<?php
session_start();

require_once '../includes/functions.php';
require_once '../includes/db.php';

requireLogin();

$isAdmin = isAdmin();
$isManager = isManager();

if (!$isAdmin && !$isManager) {
    header('Location: /pages/dashboard.php');
    exit;
}

$accessibleBranches = getAccessibleBranches($pdo);
if (empty($accessibleBranches)) {
    die('No branch access assigned.');
}

$hasSoftDelete = dbTableHasColumn($pdo, 'expenses', 'is_deleted');
$message = '';
$error = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['delete_id'])) {
    verifyCsrf($_POST['csrf_token'] ?? null);

    $deleteId = (int)$_POST['delete_id'];
    if ($deleteId > 0) {
        $stmt = $pdo->prepare("
            SELECT expense_id, branch_id, item_name, amount
            FROM expenses
            WHERE expense_id = ?
            LIMIT 1
        ");
        $stmt->execute([$deleteId]);
        $expense = $stmt->fetch(PDO::FETCH_ASSOC);

        if (!$expense || !in_array((int)$expense['branch_id'], $accessibleBranches, true)) {
            $error = 'Unauthorized deletion attempt.';
        } else {
            if ($hasSoftDelete) {
                $stmt = $pdo->prepare("UPDATE expenses SET is_deleted = 1 WHERE expense_id = ?");
                $action = 'EXPENSE SOFT DELETED';
            } else {
                $stmt = $pdo->prepare("DELETE FROM expenses WHERE expense_id = ?");
                $action = 'EXPENSE DELETED';
            }

            $stmt->execute([$deleteId]);
            logAudit(
                $pdo,
                $action,
                'expenses',
                $deleteId,
                (int)$expense['branch_id'],
                "Removed expense: {$expense['item_name']} (Rs. {$expense['amount']})"
            );
            $message = 'Expense entry removed from the active list.';
        }
    }
}

$selectedBranch = $_GET['branch'] ?? 'all';
if ($selectedBranch !== 'all') {
    $selectedBranch = (int)$selectedBranch;
    if (!in_array($selectedBranch, $accessibleBranches, true)) {
        die('Unauthorized branch access.');
    }
}

$startDate = $_GET['start_date'] ?? '';
$endDate = $_GET['end_date'] ?? '';
$sort = $_GET['sort'] ?? 'date_desc';
$page = max(1, (int)($_GET['page'] ?? 1));
$perPage = (int)($_GET['per_page'] ?? 25);
$allowedPerPage = [10, 25, 50, 100];
if (!in_array($perPage, $allowedPerPage, true)) {
    $perPage = 25;
}

$where = [];
$params = [];

if ($hasSoftDelete) {
    $where[] = 'e.is_deleted = 0';
}

if ($startDate && preg_match('/^\d{4}-\d{2}-\d{2}$/', $startDate)) {
    $where[] = 'e.purchase_date >= ?';
    $params[] = $startDate;
}

if ($endDate && preg_match('/^\d{4}-\d{2}-\d{2}$/', $endDate)) {
    $where[] = 'e.purchase_date <= ?';
    $params[] = $endDate;
}

if ($selectedBranch === 'all') {
    $where[] = 'e.branch_id IN (' . implode(',', array_fill(0, count($accessibleBranches), '?')) . ')';
    $params = array_merge($params, $accessibleBranches);
} else {
    $where[] = 'e.branch_id = ?';
    $params[] = $selectedBranch;
}

$whereSql = $where ? 'WHERE ' . implode(' AND ', $where) : '';
$orderSql = $sort === 'date_asc'
    ? 'ORDER BY e.purchase_date ASC, e.expense_id DESC'
    : 'ORDER BY e.purchase_date DESC, e.expense_id DESC';

$countStmt = $pdo->prepare("SELECT COUNT(*) FROM expenses e $whereSql");
$countStmt->execute($params);
$totalRows = (int)$countStmt->fetchColumn();
$totalPages = max(1, (int)ceil($totalRows / $perPage));
if ($page > $totalPages) {
    $page = $totalPages;
}
$offset = ($page - 1) * $perPage;

$sumStmt = $pdo->prepare("SELECT COALESCE(SUM(e.amount), 0) FROM expenses e $whereSql");
$sumStmt->execute($params);
$totalAmount = (float)$sumStmt->fetchColumn();

$sql = "
    SELECT e.*, b.branch_name
    FROM expenses e
    JOIN branches b ON e.branch_id = b.id
    $whereSql
    $orderSql
    LIMIT ? OFFSET ?
";

$stmt = $pdo->prepare($sql);
$bindIndex = 1;
foreach ($params as $param) {
    $stmt->bindValue($bindIndex++, $param);
}
$stmt->bindValue($bindIndex++, $perPage, PDO::PARAM_INT);
$stmt->bindValue($bindIndex++, $offset, PDO::PARAM_INT);
$stmt->execute();
$expenses = $stmt->fetchAll(PDO::FETCH_ASSOC);

$branchStmt = $pdo->prepare("
    SELECT id, branch_name
    FROM branches
    WHERE id IN (" . implode(',', array_fill(0, count($accessibleBranches), '?')) . ")
    ORDER BY branch_name
");
$branchStmt->execute($accessibleBranches);
$branches = $branchStmt->fetchAll(PDO::FETCH_ASSOC);

if (isset($_GET['export']) && $_GET['export'] === 'excel') {
    header('Content-Type: application/vnd.ms-excel');
    header('Content-Disposition: attachment; filename=expenses_export.xls');

    echo "Branch\tDate\tSupplier\tItem\tCategory\tAmount\tNotes\n";
    $exportStmt = $pdo->prepare("
        SELECT e.*, b.branch_name
        FROM expenses e
        JOIN branches b ON e.branch_id = b.id
        $whereSql
        $orderSql
    ");
    $exportStmt->execute($params);

    while ($row = $exportStmt->fetch(PDO::FETCH_ASSOC)) {
        echo $row['branch_name'] . "\t";
        echo $row['purchase_date'] . "\t";
        echo $row['supplier'] . "\t";
        echo $row['item_name'] . "\t";
        echo ($row['category'] ?? '') . "\t";
        echo $row['amount'] . "\t";
        echo str_replace(["\r", "\n"], ' ', (string)$row['notes']) . "\n";
    }
    exit;
}

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

<section class="summary-strip mb-4">
    <div class="summary-card">
        <div class="label">Visible Entries</div>
        <div class="value"><?= $totalRows ?></div>
    </div>
    <div class="summary-card">
        <div class="label">Filtered Spend</div>
        <div class="value">Rs. <?= number_format($totalAmount, 2) ?></div>
    </div>
    <div class="summary-card">
        <div class="label">Branches In View</div>
        <div class="value"><?= $selectedBranch === 'all' ? count($accessibleBranches) : 1 ?></div>
    </div>
</section>

<section class="app-card p-4">
    <div class="page-toolbar">
        <div>
            <span class="app-eyebrow">Expenses</span>
            <h2 class="mb-1">Expense ledger</h2>
            <p class="text-muted mb-0">Cleaner filters, export, and live-safe soft delete where the schema already supports it.</p>
        </div>
        <div class="d-flex gap-2 flex-wrap">
            <a href="/pages/add_expense.php" class="btn btn-retro">Add Expense</a>
            <a href="?<?= http_build_query(array_merge($_GET, ['export' => 'excel'])) ?>" class="btn btn-outline-secondary rounded-pill px-4">Export Excel</a>
        </div>
    </div>

    <?php if ($message): ?>
        <div class="alert alert-success border-0 rounded-4"><?= htmlspecialchars($message) ?></div>
    <?php endif; ?>
    <?php if ($error): ?>
        <div class="alert alert-danger border-0 rounded-4"><?= htmlspecialchars($error) ?></div>
    <?php endif; ?>

    <form method="GET" class="stack-form mb-4">
        <div class="form-grid">
            <div>
                <label class="form-label fw-semibold">Branch</label>
                <select class="form-select" name="branch">
                    <option value="all">All accessible branches</option>
                    <?php foreach ($branches as $branch): ?>
                        <option value="<?= (int)$branch['id'] ?>" <?= (string)$selectedBranch === (string)$branch['id'] ? 'selected' : '' ?>>
                            <?= htmlspecialchars($branch['branch_name']) ?>
                        </option>
                    <?php endforeach; ?>
                </select>
            </div>
            <div>
                <label class="form-label fw-semibold">Start Date</label>
                <input class="form-control" type="date" name="start_date" value="<?= htmlspecialchars($startDate) ?>">
            </div>
            <div>
                <label class="form-label fw-semibold">End Date</label>
                <input class="form-control" type="date" name="end_date" value="<?= htmlspecialchars($endDate) ?>">
            </div>
            <div>
                <label class="form-label fw-semibold">Rows</label>
                <select class="form-select" name="per_page">
                    <?php foreach ($allowedPerPage as $option): ?>
                        <option value="<?= $option ?>" <?= $perPage === $option ? 'selected' : '' ?>><?= $option ?> per page</option>
                    <?php endforeach; ?>
                </select>
            </div>
            <div class="d-flex align-items-end gap-2">
                <button type="submit" class="btn btn-retro">Apply</button>
                <a href="/pages/expenses.php" class="btn btn-outline-secondary rounded-pill px-4">Reset</a>
            </div>
        </div>
    </form>

    <?php if (empty($expenses)): ?>
        <div class="empty-state">No expense entries match this filter.</div>
    <?php else: ?>
        <div class="table-responsive-wrap">
            <table class="table table-card align-middle">
                <thead>
                    <tr>
                        <th>Branch</th>
                        <th>Date</th>
                        <th>Supplier</th>
                        <th>Item</th>
                        <th>Category</th>
                        <th>Amount</th>
                        <th>Notes</th>
                        <th>Action</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($expenses as $row): ?>
                        <tr>
                            <td><?= htmlspecialchars($row['branch_name']) ?></td>
                            <td><?= htmlspecialchars($row['purchase_date']) ?></td>
                            <td><?= htmlspecialchars($row['supplier']) ?></td>
                            <td><?= htmlspecialchars($row['item_name']) ?></td>
                            <td><?= htmlspecialchars($row['category'] ?? '-') ?></td>
                            <td>Rs. <?= number_format((float)$row['amount'], 2) ?></td>
                            <td><?= htmlspecialchars($row['notes'] ?: '-') ?></td>
                            <td>
                                <form method="POST" class="m-0" onsubmit="return confirm('Remove this expense from the active list?');">
                                    <?= csrfField() ?>
                                    <input type="hidden" name="delete_id" value="<?= (int)$row['expense_id'] ?>">
                                    <button type="submit" class="button delete">Remove</button>
                                </form>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
    <?php endif; ?>

    <?php if ($totalPages > 1): ?>
        <div class="d-flex flex-wrap gap-2 mt-4">
            <?php for ($i = 1; $i <= $totalPages; $i++): ?>
                <a href="?<?= http_build_query(array_merge($_GET, ['page' => $i])) ?>" class="btn <?= $i === $page ? 'btn-retro' : 'btn-outline-secondary' ?> rounded-pill px-3">
                    <?= $i ?>
                </a>
            <?php endfor; ?>
        </div>
    <?php endif; ?>
</section>

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