<?php
/**
 * @var string $startDate
 * @var string $endDate
 * @var array $expenses
 * @var array $categories
 * @var int|null $categoryId
 */
?>
<div class="page-title mb-4">
    <h5><i class="fas fa-file-invoice-dollar me-2 text-gold"></i>Expense Report</h5>
</div>

<div class="glass-card p-3 mb-4">
    <form class="row g-3 align-items-end" method="GET" action="<?= url('reports/expenses') ?>">
        <div class="col-md-3">
            <label class="form-label">Start Date</label>
            <input type="date" name="start_date" class="form-control" value="<?= e($startDate) ?>">
        </div>
        <div class="col-md-3">
            <label class="form-label">End Date</label>
            <input type="date" name="end_date" class="form-control" value="<?= e($endDate) ?>">
        </div>
        <div class="col-md-2">
            <label class="form-label">Category</label>
            <select name="category_id" class="form-select">
                <option value="">All</option>
                <?php foreach ($categories as $cat): ?>
                    <option value="<?= $cat->id ?>" <?= $categoryId == $cat->id ? 'selected' : '' ?>><?= e($cat->name) ?></option>
                <?php endforeach; ?>
            </select>
        </div>
        <div class="col-md-4">
            <button type="submit" class="btn btn-gold"><i class="fas fa-search me-1"></i>Generate</button>
            <a href="<?= url('reports/export/expenses?start_date=' . $startDate . '&end_date=' . $endDate . '&category_id=' . ($categoryId ?? '')) ?>" class="btn btn-outline-gold ms-2">
                <i class="fas fa-download me-1"></i>CSV
            </a>
        </div>
    </form>
</div>

<?php
$totalExpenses = array_sum(array_column($expenses, 'amount'));
$expenseByCategory = [];
foreach ($expenses as $e) {
    $cat = $e->category_name ?? 'Uncategorized';
    $expenseByCategory[$cat] = ($expenseByCategory[$cat] ?? 0) + $e->amount;
}
?>
<div class="row g-4 mb-4">
    <div class="col-md-4">
        <div class="glass-card stats-card">
            <div class="stats-icon" style="background:rgba(220,53,69,0.15);border-color:rgba(220,53,69,0.3);color:#dc3545;"><i class="fas fa-receipt"></i></div>
            <div class="stats-info">
                <span class="stats-label">Total Expenses</span>
                <span class="stats-value"><?= currency($totalExpenses) ?></span>
            </div>
        </div>
    </div>
    <div class="col-md-4">
        <div class="glass-card stats-card">
            <div class="stats-icon" style="background:rgba(13,202,240,0.15);border-color:rgba(13,202,240,0.3);color:#0dcaf0;"><i class="fas fa-tags"></i></div>
            <div class="stats-info">
                <span class="stats-label">Categories</span>
                <span class="stats-value"><?= count($expenseByCategory) ?></span>
            </div>
        </div>
    </div>
    <div class="col-md-4">
        <div class="glass-card stats-card">
            <div class="stats-icon" style="background:rgba(200,164,78,0.15);border-color:rgba(200,164,78,0.3);color:var(--gold-primary);"><i class="fas fa-file-invoice"></i></div>
            <div class="stats-info">
                <span class="stats-label">Transactions</span>
                <span class="stats-value"><?= count($expenses) ?></span>
            </div>
        </div>
    </div>
</div>

<?php if (!empty($expenseByCategory)): ?>
    <div class="row g-4 mb-4">
        <div class="col-md-6">
            <div class="glass-card p-0">
                <div class="card-header">
                    <div class="card-header-left">
                        <i class="fas fa-chart-pie card-icon"></i>
                        <h6 class="card-title">Expense by Category</h6>
                    </div>
                </div>
                <div class="card-body">
                    <canvas id="expensePieChart" height="250"></canvas>
                </div>
            </div>
        </div>
        <div class="col-md-6">
            <div class="glass-card p-0">
                <div class="card-header">
                    <div class="card-header-left">
                        <i class="fas fa-list card-icon"></i>
                        <h6 class="card-title">Category Breakdown</h6>
                    </div>
                </div>
                <div class="table-responsive">
                    <table class="table table-dark table-hover mb-0">
                        <thead><tr><th>Category</th><th class="text-end">Amount</th><th class="text-end">%</th></tr></thead>
                        <tbody>
                            <?php foreach ($expenseByCategory as $cat => $amt): ?>
                                <tr>
                                    <td><?= e($cat) ?></td>
                                    <td class="text-end"><?= currency($amt) ?></td>
                                    <td class="text-end"><?= $totalExpenses > 0 ? number_format(($amt / $totalExpenses) * 100, 1) . '%' : '0%' ?></td>
                                </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
<?php endif; ?>

<div class="glass-card p-0">
    <div class="card-header">
        <div class="card-header-left">
            <i class="fas fa-list card-icon"></i>
            <h6 class="card-title">Expense Details</h6>
        </div>
    </div>
    <div class="table-responsive">
        <table class="table table-dark table-hover mb-0">
            <thead>
                <tr>
                    <th>Date</th>
                    <th>Description</th>
                    <th>Category</th>
                    <th>Payment Method</th>
                    <th>Reference</th>
                    <th class="text-end">Amount</th>
                </tr>
            </thead>
            <tbody>
                <?php if (empty($expenses)): ?>
                    <tr><td colspan="6" class="text-center text-muted py-4">No expenses found</td></tr>
                <?php else: ?>
                    <?php foreach ($expenses as $e): ?>
                        <tr>
                            <td><?= formatDate($e->date ?? '') ?></td>
                            <td><?= e($e->description ?? '-') ?></td>
                            <td><?= e($e->category_name ?? '-') ?></td>
                            <td><?= e(ucwords(str_replace('_', ' ', $e->payment_method ?? ''))) ?></td>
                            <td><?= e($e->reference ?? '-') ?></td>
                            <td class="text-end text-danger"><?= currency($e->amount ?? 0) ?></td>
                        </tr>
                    <?php endforeach; ?>
                <?php endif; ?>
            </tbody>
        </table>
    </div>
</div>

<?php if (!empty($expenseByCategory)): ?>
    <script>
    $(function() {
        var ctx = document.getElementById('expensePieChart').getContext('2d');
        new Chart(ctx, {
            type: 'doughnut',
            data: {
                labels: <?= json_encode(array_keys($expenseByCategory)) ?>,
                datasets: [{
                    data: <?= json_encode(array_values($expenseByCategory)) ?>,
                    backgroundColor: ['#C8A44E', '#dc3545', '#0dcaf0', '#198754', '#6f42c1', '#fd7e14', '#20c997', '#0d6efd', '#ffc107', '#6610f2'],
                }]
            },
            options: {
                responsive: true,
                plugins: {
                    legend: { position: 'right', labels: { color: '#ccc', font: { size: 12 } } }
                }
            }
        });
    });
    </script>
<?php endif; ?>
