<?php
// admin/accounts/transactions.php
require_once __DIR__ . '/../../includes/config.php';
require_once __DIR__ . '/../../includes/functions.php';

if (!isAdmin()) {
    header('Location: ../login.php');
    exit;
}

// Get filters
$type_filter = isset($_GET['type']) ? $_GET['type'] : 'all';
$date_from = isset($_GET['date_from']) ? $_GET['date_from'] : date('Y-m-01');
$date_to = isset($_GET['date_to']) ? $_GET['date_to'] : date('Y-m-d');

// Build transactions array from all sources
$transactions = [];

// 1. Income Transactions
$stmt = $pdo->prepare("SELECT 
    'income' as source,
    id,
    income_no as reference_no,
    customer_name as party_name,
    amount,
    payment_method,
    reference_no as transaction_ref,
    payment_date as transaction_date,
    note,
    created_at
    FROM income 
    WHERE DATE(payment_date) BETWEEN ? AND ?");
$stmt->execute([$date_from, $date_to]);
$income = $stmt->fetchAll();
foreach ($income as $row) {
    $row['type'] = 'income';
    $row['status'] = 'completed';
    $transactions[] = $row;
}

// 2. Expenses
$stmt = $pdo->prepare("SELECT 
    'expense' as source,
    id,
    expense_no as reference_no,
    category as party_name,
    amount,
    payment_method,
    reference_no as transaction_ref,
    expense_date as transaction_date,
    note,
    created_at
    FROM expenses 
    WHERE DATE(expense_date) BETWEEN ? AND ?");
$stmt->execute([$date_from, $date_to]);
$expenses = $stmt->fetchAll();
foreach ($expenses as $row) {
    $row['type'] = 'expense';
    $row['status'] = 'completed';
    $transactions[] = $row;
}

// 3. PO Payments
$stmt = $pdo->prepare("SELECT 
    'po_payment' as source,
    pp.id,
    pp.payment_no as reference_no,
    v.name as party_name,
    pp.amount,
    pp.payment_method,
    pp.reference_no as transaction_ref,
    pp.payment_date as transaction_date,
    pp.note,
    pp.created_at
    FROM po_payments pp
    LEFT JOIN vendors v ON pp.vendor_id = v.id
    WHERE DATE(pp.payment_date) BETWEEN ? AND ?");
$stmt->execute([$date_from, $date_to]);
$po_payments = $stmt->fetchAll();
foreach ($po_payments as $row) {
    $row['type'] = 'po_payment';
    $row['status'] = 'completed';
    $transactions[] = $row;
}

// 4. Invoice Payments (Income from invoices)
$stmt = $pdo->prepare("SELECT 
    'invoice_payment' as source,
    i.id,
    i.invoice_no as reference_no,
    i.customer_name as party_name,
    i.total as amount,
    'invoice' as payment_method,
    i.invoice_no as transaction_ref,
    i.invoice_date as transaction_date,
    i.note,
    i.created_at,
    i.status
    FROM invoices i
    WHERE DATE(i.invoice_date) BETWEEN ? AND ? AND i.status = 'paid'");
$stmt->execute([$date_from, $date_to]);
$invoices = $stmt->fetchAll();
foreach ($invoices as $row) {
    $row['type'] = 'income';
    $row['source'] = 'invoice';
    $row['reference_no'] = $row['invoice_no'];
    $row['payment_method'] = 'invoice';
    $row['status'] = $row['status'] == 'paid' ? 'completed' : 'pending';
    $transactions[] = $row;
}

// 5. Order Payments (Income from orders)
$stmt = $pdo->prepare("SELECT 
    'order_payment' as source,
    o.id,
    o.invoice_no as reference_no,
    o.name as party_name,
    o.total as amount,
    o.payment_method,
    o.invoice_no as transaction_ref,
    o.created_at as transaction_date,
    o.note,
    o.created_at,
    o.order_status as status
    FROM orders o
    WHERE DATE(o.created_at) BETWEEN ? AND ? AND o.payment_status = 'paid'");
$stmt->execute([$date_from, $date_to]);
$orders = $stmt->fetchAll();
foreach ($orders as $row) {
    $row['type'] = 'income';
    $row['source'] = 'order';
    $row['reference_no'] = $row['invoice_no'];
    $row['payment_method'] = $row['payment_method'] ?: 'cod';
    $row['status'] = $row['status'] == 'delivered' ? 'completed' : 'pending';
    $transactions[] = $row;
}

// Sort transactions by date (newest first)
usort($transactions, function($a, $b) {
    return strtotime($b['transaction_date']) - strtotime($a['transaction_date']);
});

// Apply type filter
if ($type_filter != 'all') {
    $transactions = array_filter($transactions, function($t) use ($type_filter) {
        return $t['type'] == $type_filter;
    });
}

// Calculate totals
$total_income = 0;
$total_expense = 0;
$total_po_payment = 0;
$net_balance = 0;

foreach ($transactions as $t) {
    if ($t['type'] == 'income' || $t['source'] == 'invoice' || $t['source'] == 'order') {
        $total_income += $t['amount'];
    } elseif ($t['type'] == 'expense') {
        $total_expense += $t['amount'];
    } elseif ($t['type'] == 'po_payment') {
        $total_po_payment += $t['amount'];
    }
}
$net_balance = $total_income - ($total_expense + $total_po_payment);

include '../header.php';
?>

<style>
.transaction-stats {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(180px, 1fr));
    gap: 15px;
    margin-bottom: 25px;
}

.stat-box {
    background: #fff;
    border-radius: 12px;
    padding: 18px 20px;
    text-align: center;
    box-shadow: 0 1px 3px rgba(0,0,0,0.08);
    transition: all 0.3s ease;
}

.stat-box:hover {
    transform: translateY(-3px);
    box-shadow: 0 4px 15px rgba(0,0,0,0.1);
}

.stat-box .stat-number {
    font-size: 24px;
    font-weight: 700;
}

.stat-box .stat-label {
    font-size: 13px;
    color: #64748b;
    margin-top: 2px;
}

.stat-box .stat-icon {
    font-size: 24px;
    margin-bottom: 5px;
}

.transaction-filter {
    background: #fff;
    border-radius: 12px;
    padding: 15px 20px;
    box-shadow: 0 1px 3px rgba(0,0,0,0.08);
    margin-bottom: 20px;
}

.transaction-filter .filter-group {
    display: flex;
    flex-wrap: wrap;
    gap: 15px;
    align-items: center;
}

.transaction-filter .filter-group .form-control {
    width: auto;
    min-width: 150px;
}

.type-badge {
    padding: 4px 12px;
    border-radius: 20px;
    font-size: 12px;
    font-weight: 500;
}

.type-badge.income { background: #86efac; color: #166534; }
.type-badge.expense { background: #fca5a5; color: #991b1b; }
.type-badge.po_payment { background: #fcd34d; color: #92400e; }
.type-badge.invoice { background: #93c5fd; color: #1e40af; }
.type-badge.order { background: #c4b5fd; color: #5b21b6; }

.transaction-table td {
    vertical-align: middle;
}

.amount-positive {
    color: #22c55e;
    font-weight: 600;
}

.amount-negative {
    color: #ef4444;
    font-weight: 600;
}

.action-btns {
    display: flex;
    gap: 4px;
    flex-wrap: wrap;
}

.alert-container {
    margin-bottom: 20px;
}

@media (max-width: 768px) {
    .transaction-filter .filter-group {
        flex-direction: column;
        align-items: stretch;
    }
    
    .transaction-filter .filter-group .form-control {
        width: 100%;
    }
}
</style>

<div class="admin-content">
    <div class="d-flex justify-content-between align-items-center mb-4">
        <h2><i class="fa-solid fa-arrow-right-arrow-left me-2"></i> Transactions</h2>
        <div>
            <button onclick="window.print()" class="btn btn-secondary">
                <i class="fa-solid fa-print"></i> Print
            </button>
            <button onclick="exportTransactions()" class="btn btn-success">
                <i class="fa-solid fa-file-export"></i> Export
            </button>
        </div>
    </div>
    
    <!-- Stats -->
    <div class="transaction-stats">
        <div class="stat-box">
            <div class="stat-icon text-success"><i class="fa-solid fa-arrow-down"></i></div>
            <div class="stat-number text-success"><?php echo number_format($total_income); ?> TK</div>
            <div class="stat-label">Total Income</div>
        </div>
        <div class="stat-box">
            <div class="stat-icon text-danger"><i class="fa-solid fa-arrow-up"></i></div>
            <div class="stat-number text-danger"><?php echo number_format($total_expense); ?> TK</div>
            <div class="stat-label">Total Expenses</div>
        </div>
        <div class="stat-box">
            <div class="stat-icon text-warning"><i class="fa-solid fa-hand-holding-dollar"></i></div>
            <div class="stat-number text-warning"><?php echo number_format($total_po_payment); ?> TK</div>
            <div class="stat-label">PO Payments</div>
        </div>
        <div class="stat-box">
            <div class="stat-icon text-primary"><i class="fa-solid fa-coins"></i></div>
            <div class="stat-number text-<?php echo $net_balance >= 0 ? 'success' : 'danger'; ?>">
                <?php echo number_format($net_balance); ?> TK
            </div>
            <div class="stat-label">Net Balance</div>
        </div>
    </div>
    
    <!-- Filter -->
    <div class="transaction-filter">
        <form method="GET" class="filter-group">
            <div>
                <label class="form-label mb-0">Type</label>
                <select name="type" class="form-control" onchange="this.form.submit()">
                    <option value="all" <?php echo $type_filter == 'all' ? 'selected' : ''; ?>>All Transactions</option>
                    <option value="income" <?php echo $type_filter == 'income' ? 'selected' : ''; ?>>Income</option>
                    <option value="expense" <?php echo $type_filter == 'expense' ? 'selected' : ''; ?>>Expenses</option>
                    <option value="po_payment" <?php echo $type_filter == 'po_payment' ? 'selected' : ''; ?>>PO Payments</option>
                </select>
            </div>
            <div>
                <label class="form-label mb-0">Date From</label>
                <input type="date" name="date_from" class="form-control" value="<?php echo $date_from; ?>" onchange="this.form.submit()">
            </div>
            <div>
                <label class="form-label mb-0">Date To</label>
                <input type="date" name="date_to" class="form-control" value="<?php echo $date_to; ?>" onchange="this.form.submit()">
            </div>
            <div>
                <label class="form-label mb-0">&nbsp;</label>
                <a href="transactions.php" class="btn btn-secondary">Clear</a>
            </div>
        </form>
    </div>
    
    <!-- Alert Container -->
    <div id="alertContainer" class="alert-container"></div>
    
    <!-- Transactions Table -->
    <div class="admin-card">
        <div class="table-responsive">
            <table class="table table-hover transaction-table">
                <thead>
                    <tr>
                        <th>Date</th>
                        <th>Reference</th>
                        <th>Type</th>
                        <th>Party</th>
                        <th>Method</th>
                        <th>Amount</th>
                        <th>Status</th>
                        <th>Actions</th>
                    </tr>
                </thead>
                <tbody>
                    <?php if (empty($transactions)): ?>
                    <tr>
                        <td colspan="8" class="text-center py-4">
                            <i class="fa-regular fa-receipt fa-2x text-muted d-block mb-2"></i>
                            No transactions found for the selected period
                        </td>
                    </tr>
                    <?php else: ?>
                    <?php foreach ($transactions as $transaction): ?>
                    <tr>
                        <td><?php echo date('d M Y', strtotime($transaction['transaction_date'])); ?></td>
                        <td>
                            <code><?php echo htmlspecialchars($transaction['reference_no']); ?></code>
                            <?php if ($transaction['source'] == 'invoice' || $transaction['source'] == 'order'): ?>
                            <br><small class="text-muted"><?php echo ucfirst($transaction['source']); ?></small>
                            <?php endif; ?>
                        </td>
                        <td>
                            <span class="type-badge <?php echo $transaction['type']; ?>">
                                <?php echo ucfirst(str_replace('_', ' ', $transaction['type'])); ?>
                            </span>
                        </td>
                        <td><?php echo htmlspecialchars($transaction['party_name'] ?? 'N/A'); ?></td>
                        <td>
                            <span class="badge bg-secondary">
                                <?php echo ucfirst(str_replace('_', ' ', $transaction['payment_method'] ?? 'N/A')); ?>
                            </span>
                        </td>
                        <td>
                            <span class="<?php echo ($transaction['type'] == 'income' || $transaction['source'] == 'invoice' || $transaction['source'] == 'order') ? 'amount-positive' : 'amount-negative'; ?>">
                                <?php echo ($transaction['type'] == 'income' || $transaction['source'] == 'invoice' || $transaction['source'] == 'order') ? '+' : '-'; ?>
                                <?php echo number_format($transaction['amount']); ?> TK
                            </span>
                        </td>
                        <td>
                            <span class="badge bg-<?php echo $transaction['status'] == 'completed' ? 'success' : 'warning'; ?>">
                                <?php echo ucfirst($transaction['status']); ?>
                            </span>
                        </td>
                        <td>
                            <div class="action-btns">
                                <?php if ($transaction['source'] == 'income'): ?>
                                <a href="view-income.php?id=<?php echo $transaction['id']; ?>" class="btn btn-sm btn-primary">
                                    <i class="fa-solid fa-eye"></i>
                                </a>
                                <?php elseif ($transaction['source'] == 'expense'): ?>
                                <a href="view-expense.php?id=<?php echo $transaction['id']; ?>" class="btn btn-sm btn-primary">
                                    <i class="fa-solid fa-eye"></i>
                                </a>
                                <?php elseif ($transaction['source'] == 'po_payment'): ?>
                                <a href="view-po-payment.php?id=<?php echo $transaction['id']; ?>" class="btn btn-sm btn-primary">
                                    <i class="fa-solid fa-eye"></i>
                                </a>
                                <?php elseif ($transaction['source'] == 'invoice'): ?>
                                <a href="view-invoice.php?id=<?php echo $transaction['id']; ?>" class="btn btn-sm btn-primary">
                                    <i class="fa-solid fa-eye"></i>
                                </a>
                                <?php elseif ($transaction['source'] == 'order'): ?>
                                <a href="order-details.php?id=<?php echo $transaction['id']; ?>" class="btn btn-sm btn-primary">
                                    <i class="fa-solid fa-eye"></i>
                                </a>
                                <?php else: ?>
                                <span class="text-muted">-</span>
                                <?php endif; ?>
                            </div>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                    <?php endif; ?>
                </tbody>
                <tfoot>
                    <tr class="fw-bold">
                        <td colspan="5" class="text-end">Total</td>
                        <td>
                            <span class="text-success">+<?php echo number_format($total_income); ?> TK</span>
                            <br>
                            <span class="text-danger">-<?php echo number_format($total_expense + $total_po_payment); ?> TK</span>
                            <br>
                            <span class="text-primary"><?php echo number_format($net_balance); ?> TK</span>
                        </td>
                        <td colspan="2"></td>
                    </tr>
                </tfoot>
            </table>
        </div>
    </div>
</div>

<script>
// ========================================
// EXPORT TRANSACTIONS
// ========================================
function exportTransactions() {
    var type = document.querySelector('select[name="type"]').value;
    var date_from = document.querySelector('input[name="date_from"]').value;
    var date_to = document.querySelector('input[name="date_to"]').value;
    
    window.open('export-transactions.php?type=' + type + '&date_from=' + date_from + '&date_to=' + date_to, '_blank');
}

// ========================================
// SHOW TOAST
// ========================================
function showToast(message, type) {
    var colors = {
        success: '#22c55e',
        error: '#ef4444',
        warning: '#f59e0b',
        info: '#3b82f6'
    };
    
    var toast = document.createElement('div');
    toast.style.cssText = `
        position: fixed;
        top: 20px;
        right: 20px;
        padding: 12px 24px;
        background: ${colors[type] || colors.info};
        color: #fff;
        border-radius: 8px;
        z-index: 9999;
        animation: slideIn 0.3s ease;
        max-width: 400px;
        font-size: 14px;
        font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
        box-shadow: 0 5px 20px rgba(0,0,0,0.15);
    `;
    toast.textContent = message;
    document.body.appendChild(toast);
    
    setTimeout(function() {
        toast.style.opacity = '0';
        toast.style.transition = 'opacity 0.3s ease';
        setTimeout(function() { toast.remove(); }, 300);
    }, 3000);
}

// Add CSS animation
var style = document.createElement('style');
style.textContent = `
    @keyframes slideIn {
        from { transform: translateX(100%); opacity: 0; }
        to { transform: translateX(0%); opacity: 1; }
    }
`;
document.head.appendChild(style);
</script>

<?php include '../footer.php'; ?>