<?php
session_start();
require_once __DIR__ . '/../../includes/auth.php';
require_once __DIR__ . '/../../classes/Database.php';
require_once __DIR__ . '/../../classes/Expense.php';


$database = new Database();
$conn = $database->getConnection();


$auth = new Auth($conn);


if (!isset($_SESSION['user_id'])) {
    header('Location: ../../login.php');
    exit();
}
$auth->enforceSuperAdminPrivileges($_SESSION['user_id']);


$expense = new Expense($conn);


$startDate = isset($_GET['start_date']) ? $_GET['start_date'] : date('Y-m-d', strtotime('first day of last month'));
$endDate = isset($_GET['end_date']) ? $_GET['end_date'] : date('Y-m-d');
$branchId = isset($_GET['branch']) ? (int)$_GET['branch'] : null;
$categoryId = isset($_GET['category']) ? (int)$_GET['category'] : null;

if (empty($_SESSION['expense_export_csrf'])) {
    $_SESSION['expense_export_csrf'] = bin2hex(random_bytes(32));
}


$expenses = $expense->getExpensesForPeriod($startDate, $endDate, $categoryId, $branchId);


$totalExpenses = $expense->getTotalExpenses($startDate, $endDate, $categoryId, $branchId);


$categories = $expense->getAllCategories();


if (isset($_GET['delete']) && isset($_GET['id'])) {
    $expenseId = (int)$_GET['id'];
    if ($expense->deleteExpense($expenseId)) {
        $successMessage = "Expense deleted successfully.";

        $expenses = $expense->getExpensesForPeriod($startDate, $endDate);
        $totalExpenses = $expense->getTotalExpenses($startDate, $endDate);
    } else {
        $errorMessage = "Failed to delete expense.";
    }
}
?>

<?php include __DIR__ . '/../../includes/header.php'; ?>
<style>
    .action-buttons .btn {
        margin-right: 5px;
    }
    .filter-form {
        background-color: #f8f9fa;
        padding: 15px;
        border-radius: 10px;
        margin-bottom: 20px;
        position: relative;
        z-index: 10;
    }
    #expenseFilterForm,
    #applyExpenseFilterButton {
        position: relative;
        z-index: 11;
        pointer-events: auto;
    }
    .card {
        margin-bottom: 20px;
        box-shadow: 0 4px 6px rgba(0,0,0,0.1);
    }
    .btn-action {
        margin-right: 5px;
    }
    .table-footer {
        font-weight: bold;
    }
</style>
    <div class="container mt-4">
        <div class="row mb-3">
            <div class="col-12">
                <h2>Expense Records</h2>
            </div>
        </div>

        <div class="row mb-3">
            <div class="col-12">
                <div class="d-flex gap-2">
                    <a href="../dashboard/admin.php" class="btn btn-secondary">
                        <i class="fas fa-arrow-left"></i> Back to Dashboard
                    </a>
                    <a href="add_expense.php" class="btn btn-primary">
                        <i class="fas fa-plus"></i> Add New Expense
                    </a>
                    <a href="expense_categories.php" class="btn btn-secondary">
                        <i class="fas fa-tags"></i> Manage Categories
                    </a>
                </div>
            </div>
        </div>



                    <div class="card filter-form mb-4">
                        <div class="card-body">
                            <form id="expenseFilterForm" method="GET" action="manage_expenses.php" class="row g-3">
                                <div class="col-md-3">
                                    <label for="start_date" class="form-label">Start Date</label>
                                    <input type="date" class="form-control" id="start_date" name="start_date" value="<?php echo htmlspecialchars($startDate, ENT_QUOTES, 'UTF-8'); ?>">
                                </div>
                                <div class="col-md-3">
                                    <label for="end_date" class="form-label">End Date</label>
                                    <input type="date" class="form-control" id="end_date" name="end_date" value="<?php echo htmlspecialchars($endDate, ENT_QUOTES, 'UTF-8'); ?>">
                                </div>
                                <div class="col-md-2">
                                    <label for="branch" class="form-label">Branch</label>
                                    <select class="form-control" id="branch" name="branch">
                                        <option value="">All Branches</option>
                                        <?php
                                        $branchQuery = "SELECT branch_id, branch_name FROM branches WHERE branch_id != 7 ORDER BY branch_name";
                                        $branchStmt = $conn->prepare($branchQuery);
                                        $branchStmt->execute();
                                        $branches = $branchStmt->fetchAll(PDO::FETCH_ASSOC);

                                        $selectedBranch = isset($_GET['branch']) ? $_GET['branch'] : '';
                                        foreach ($branches as $branch) {
                                            $selected = $selectedBranch == $branch['branch_id'] ? 'selected' : '';
                                            echo "<option value=\"" . $branch['branch_id'] . "\" $selected>" .
                                                 htmlspecialchars($branch['branch_name']) . "</option>";
                                        }
                                        ?>
                                    </select>
                                </div>
                                <div class="col-md-2">
                                    <label for="category" class="form-label">Category</label>
                                    <select class="form-control" id="category" name="category">
                                        <option value="">All Categories</option>
                                        <?php
                                        $selectedCategory = isset($_GET['category']) ? $_GET['category'] : '';
                                        foreach ($categories as $category) {
                                            $selected = $selectedCategory == $category['category_id'] ? 'selected' : '';
                                            echo "<option value=\"" . $category['category_id'] . "\" $selected>" .
                                                 htmlspecialchars($category['category_name']) . "</option>";
                                        }
                                        ?>
                                    </select>
                                </div>
                                <div class="col-md-2 d-flex align-items-end">
                                    <button type="submit" id="applyExpenseFilterButton" form="expenseFilterForm" name="apply_filter" value="1" class="btn btn-primary w-100" onclick="return applyExpenseFilter(event);">Apply Filter</button>
                                </div>
                            </form>
                        </div>
                    </div>
        <?php if (isset($successMessage)): ?>
            <div class="alert alert-success"><?php echo $successMessage; ?></div>
        <?php endif; ?>

        <?php if (isset($errorMessage)): ?>
            <div class="alert alert-danger"><?php echo $errorMessage; ?></div>
        <?php endif; ?>


        <div class="card">
            <div class="card-header">
                <h5>Expenses List</h5>
            </div>
            <div class="card-body">
                <form id="expenseExportForm" method="POST" action="export_expenses.php">
                    <input type="hidden" name="csrf_token" value="<?php echo htmlspecialchars($_SESSION['expense_export_csrf'], ENT_QUOTES, 'UTF-8'); ?>">
                    <input type="hidden" name="start_date" value="<?php echo htmlspecialchars($startDate, ENT_QUOTES, 'UTF-8'); ?>">
                    <input type="hidden" name="end_date" value="<?php echo htmlspecialchars($endDate, ENT_QUOTES, 'UTF-8'); ?>">
                    <div class="d-flex flex-wrap justify-content-between align-items-center gap-2 mb-3">
                        <div class="text-muted">
                            Select the expense rows to export. The default period runs from last month through today.
                        </div>
                        <button type="submit" id="exportSelectedExpenses" class="btn btn-success">
                            <i class="fas fa-file-export"></i> Export Selected
                        </button>
                    </div>
                <table class="table table-striped">
                    <thead>
                        <tr>
                            <th style="width: 42px;">
                                <input class="form-check-input" type="checkbox" id="selectAllExpenses" aria-label="Select all visible expenses">
                            </th>
                            <th>Date</th>
                            <th>Category</th>
                            <th>Description</th>
                            <th>Amount</th>
                            <th>Branch</th>
                            <th>Actions</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php if ($expenses->rowCount() === 0): ?>
                            <tr>
                                <td colspan="7" class="text-center">No expenses found for the selected period.</td>
                            </tr>
                        <?php else: ?>
                            <?php while ($exp = $expenses->fetch(PDO::FETCH_ASSOC)): ?>
                                <tr>
                                    <td>
                                        <input class="form-check-input expense-export-checkbox" type="checkbox" name="expense_ids[]" value="<?php echo (int)$exp['expense_id']; ?>" aria-label="Select expense <?php echo (int)$exp['expense_id']; ?>">
                                    </td>
                                    <td><?php echo date('Y-m-d', strtotime($exp['expense_date'])); ?></td>
                                    <td><?php echo htmlspecialchars($exp['category_name']); ?></td>
                                    <td><?php echo htmlspecialchars($exp['description']); ?></td>
                                    <td>MWK <?php echo number_format($exp['amount'], 2); ?></td>
                                    <td><?php echo htmlspecialchars($exp['branch_name'] ?? 'N/A'); ?></td>

                                    <td class="action-buttons">
                                        <a href="edit_expense.php?id=<?php echo $exp['expense_id']; ?>" class="btn btn-sm btn-primary btn-action">
                                            <i class="fas fa-edit"></i>
                                        </a>
                                        <a href="javascript:void(0);" onclick="confirmDelete(<?php echo $exp['expense_id']; ?>)" class="btn btn-sm btn-danger btn-action">
                                            <i class="fas fa-trash"></i>
                                        </a>
                                    </td>
                                </tr>
                            <?php endwhile; ?>
                        <?php endif; ?>
                    </tbody>
                    <tfoot>
                        <tr class="table-footer">
                            <td colspan="4" class="text-end">Total:</td>
                            <td>MWK <?php echo number_format($totalExpenses, 2); ?></td>
                            <td colspan="2"></td>
                        </tr>
                    </tfoot>
                </table>
                </form>
            </div>
        </div>
    </div>

    <script>
        function applyExpenseFilter(event) {
            if (event) {
                event.preventDefault();
                event.stopPropagation();
            }

            const form = document.getElementById('expenseFilterForm');
            if (!form || !form.reportValidity()) {
                return false;
            }

            const params = new URLSearchParams(new FormData(form));
            window.location.href = form.action + '?' + params.toString();
            return false;
        }

        function confirmDelete(id) {
            if (confirm('Are you sure you want to delete this expense?')) {
                window.location.href = `?delete=1&id=${id}&start_date=<?php echo $startDate; ?>&end_date=<?php echo $endDate; ?>`;
            }
        }

        const selectAllExpenses = document.getElementById('selectAllExpenses');
        const expenseExportForm = document.getElementById('expenseExportForm');

        if (selectAllExpenses) {
            selectAllExpenses.addEventListener('change', function () {
                document.querySelectorAll('.expense-export-checkbox').forEach(function (checkbox) {
                    checkbox.checked = selectAllExpenses.checked;
                });
            });
        }

        if (expenseExportForm) {
            expenseExportForm.addEventListener('submit', function (event) {
                const selected = document.querySelectorAll('.expense-export-checkbox:checked');
                if (selected.length === 0) {
                    event.preventDefault();
                    alert('Select at least one expense to export.');
                    return;
                }

                const period = '<?php echo htmlspecialchars($startDate, ENT_QUOTES, 'UTF-8'); ?> to <?php echo htmlspecialchars($endDate, ENT_QUOTES, 'UTF-8'); ?>';
                if (!confirm('Export ' + selected.length + ' selected expense(s) for ' + period + '?')) {
                    event.preventDefault();
                }
            });
        }    </script>
<?php include __DIR__ . '/../../includes/footer.php'; ?>
