<?php
require_once __DIR__ . '/../config/auth.php';
require_once __DIR__ . '/../includes/functions.php';
requirePermission('report_view');

$pdo = getDB();
$from = $_GET['from'] ?? date('Y-m-01');
$to = $_GET['to'] ?? date('Y-m-d');

$stmt = $pdo->prepare("SELECT e.*, ec.category_name as category_name FROM expenses e LEFT JOIN expense_categories ec ON e.expense_category_id = ec.id WHERE DATE(e.expense_date) BETWEEN ? AND ? ORDER BY e.expense_date DESC");
$stmt->execute([$from, $to]);
$expenses = $stmt->fetchAll();

$stmt = $pdo->prepare("SELECT SUM(amount) as total FROM expenses WHERE DATE(expense_date) BETWEEN ? AND ?");
$stmt->execute([$from, $to]);
$total_expense = $stmt->fetchColumn();

include __DIR__ . '/../includes/header.php';
include __DIR__ . '/../includes/sidebar.php';
?>
<div class="content-wrapper">
    <div class="container-fluid">
        <h4 class="page-title"><i class="fas fa-receipt me-2"></i>Expense Report</h4>
        <div class="card">
            <div class="card-body">
                <form method="GET" class="row g-3 mb-3">
                    <div class="col-md-4"><input type="date" name="from" class="form-control" value="<?= $from ?>"></div>
                    <div class="col-md-4"><input type="date" name="to" class="form-control" value="<?= $to ?>"></div>
                    <div class="col-md-4"><button type="submit" class="btn btn-primary"><i class="fas fa-filter me-1"></i>Filter</button></div>
                </form>
                <div class="row mb-3">
                    <div class="col-md-4"><div class="stat-card bg-danger-gradient"><div class="stat-value"><?= formatCurrency($total_expense) ?></div><div class="stat-label">Total Expenses</div></div></div>
                </div>
                <div class="table-responsive">
                    <table id="expenseReportTable" class="table table-hover datatable">
                        <thead><tr><th>Date</th><th>Category</th><th>Description</th><th>Amount</th><th>Method</th></tr></thead>
                        <tbody>
                            <?php foreach ($expenses as $e): ?>
                            <tr>
                                <td><?= formatDate($e['expense_date']) ?></td>
                                <td><?= htmlspecialchars($e['category_name'] ?? 'Other') ?></td>
                                <td><?= htmlspecialchars($e['description'] ?? '-') ?></td>
                                <td><strong><?= formatCurrency($e['amount']) ?></strong></td>
                                <td><?= $e['payment_method'] ?></td>
                            </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
</div>
<?php include __DIR__ . '/../includes/footer.php'; ?>
