<?php
session_start();

// User must be logged in as admin
if (!isset($_SESSION['username']) || ($_SESSION['role'] ?? '') !== 'admin') {
    header("Location: login.html?error=unauthorized");
    exit();
}

require 'db_connect.php';

date_default_timezone_set('Africa/Nairobi');

$page_title = "Expenses | Admin";
$username   = $_SESSION['username'];
$message    = "";

/* -------------------------------
   PAGINATION + SHOW X ENTRIES
--------------------------------- */
$limit_options = [10, 15, 25, 50, 100];
$limit = $_GET['limit'] ?? 15;
$page  = isset($_GET['page']) ? max(1, intval($_GET['page'])) : 1;

$is_all = ($limit === 'all');

if (!$is_all) {
    $limit = intval($limit);
    if (!in_array($limit, $limit_options, true)) {
        $limit = 15;
    }
    $offset = ($page - 1) * $limit;
} else {
    $offset = 0;
}

/* -------------------------------
   ADD EXPENSE (ADMIN)
   - Stored in same `expenses` table
   - cash_session_id is left NULL / default
--------------------------------- */
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $expense_name = trim($_POST['expense_name'] ?? '');
    $amount       = floatval($_POST['amount'] ?? 0);
    $date         = date('Y-m-d H:i:s');

    if ($expense_name === '' || $amount <= 0) {
        $message = "<div class='alert alert-error'>Please provide a description and a positive amount.</div>";
    } else {
        // If `cash_session_id` is nullable you can omit it here.
        // This records that the admin is the one who added it.
        $stmt = $conn->prepare("
            INSERT INTO expenses (expense_name, amount, cashier, expense_date)
            VALUES (?, ?, ?, ?)
        ");

        if ($stmt) {
            $stmt->bind_param("sdss", $expense_name, $amount, $username, $date);

            if ($stmt->execute()) {
                $message = "<div class='alert alert-success'>✔ Expense added successfully.</div>";
            } else {
                $message = "<div class='alert alert-error'>❌ Error: " . htmlspecialchars($stmt->error) . "</div>";
            }
            $stmt->close();
        } else {
            $message = "<div class='alert alert-error'>❌ Error preparing statement: " . htmlspecialchars($conn->error) . "</div>";
        }
    }
}

/* -------------------------------
   DELETE EXPENSE
--------------------------------- */
if (isset($_GET['delete'])) {
    $id = intval($_GET['delete']);
    if ($id > 0) {
        $sql = "DELETE FROM expenses WHERE id = $id";
        if ($conn->query($sql)) {
            header("Location: admin_expenses.php?deleted=1");
            exit();
        } else {
            $message = "<div class='alert alert-error'>❌ Delete failed: " . htmlspecialchars($conn->error) . "</div>";
        }
    }
}

/* -------------------------------
   COUNT TOTAL ROWS
--------------------------------- */
$countResult = $conn->query("SELECT COUNT(*) AS total FROM expenses");
$totalRows   = (int)($countResult->fetch_assoc()['total'] ?? 0);

if ($is_all) {
    $totalPages = 1;
    $page = 1;
} else {
    $totalPages = max(1, (int)ceil($totalRows / $limit));
    if ($page > $totalPages) $page = $totalPages;
}

/* -------------------------------
   FETCH PAGINATED EXPENSES
--------------------------------- */
$sql = "SELECT * FROM expenses ORDER BY expense_date DESC";
if (!$is_all) {
    $sql .= " LIMIT $limit OFFSET $offset";
}
$expenses = $conn->query($sql);

// Calculate totals
$page_total  = 0;
$grandQuery  = $conn->query("SELECT SUM(amount) AS grand_total FROM expenses");
$grand_total = (float)($grandQuery->fetch_assoc()['grand_total'] ?? 0);
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <title><?= htmlspecialchars($page_title) ?></title>
    <?php include 'head.php'; ?>
    <style>
        body {
            font-family: 'Poppins', Arial, sans-serif;
            background: var(--bg-main);
            margin: 0;
            color: var(--text-main);
        }

        .content-area {
            margin-left: 260px; /* space for admin sidebar */
            padding: 25px 30px;
        }

        @media(max-width: 768px){
            .content-area {
                margin-left: 80px;
                padding: 20px;
            }
        }

        .page-header {
            display: flex;
            flex-direction: column;
            align-items: center;
            gap: 6px;
            margin-bottom: 18px;
        }

        .page-title {
            font-size: 22px;
            font-weight: 600;
            color: var(--text-heading);
            text-align: center;
        }

        .page-subtitle {
            font-size: 13px;
            color: #f4b400;
            text-align: center;
        }

        .link-row {
            text-align: center;
            margin-bottom: 18px;
        }

        .styled-link {
            padding: 9px 18px;
            background: var(--accent-gold);
            color: var(--bg-main);
            text-decoration: none;
            border-radius: 6px;
            font-weight: 600;
            font-size: 13px;
            display: inline-block;
            border: none;
        }

        .styled-link:hover {
            background: var(--accent-gold-soft);
        }

        .page-card,
        .page-card-table {
            background: var(--bg-card);
            border-radius: 14px;
            padding: 18px 22px;
            box-shadow: 0 4px 12px rgba(0,0,0,0.35);
            border: 1px solid #0a4a85;
            color: var(--text-main);
            margin-bottom: 20px;
        }

        body[data-theme="light"] .page-card,
        body[data-theme="light"] .page-card-table {
            box-shadow: 0 12px 30px rgba(15,23,42,0.12);
            border-color: rgba(148,163,184,0.55);
        }

        .page-card-title {
            font-size: 16px;
            font-weight: 500;
            margin-bottom: 10px;
            color: var(--text-heading);
        }

        .expense-form {
            margin-top: 8px;
            max-width: 520px;
        }

        .expense-form label {
            display: block;
            font-size: 13px;
            font-weight: 500;
            margin-bottom: 4px;
        }

        .expense-form input[type="text"],
        .expense-form input[type="number"] {
            width: 100%;
            padding: 9px 11px;
            border-radius: 10px;
            border: 1px solid rgba(148,163,184,0.55);
            background: var(--bg-input);
            color: var(--text-main);
            font-size: 13px;
            margin-bottom: 10px;
        }

        .expense-form input::placeholder {
            color: #9ca3af;
        }

        .expense-form input:focus {
            outline: none;
            border-color: var(--accent-gold);
            box-shadow: 0 0 0 1px rgba(244,180,0,0.35);
        }

        .btn-primary {
            padding: 10px 18px;
            border-radius: 999px;
            border: none;
            cursor: pointer;
            font-size: 14px;
            font-weight: 600;
            background: var(--accent-gold);
            color: #111827;
            margin-top: 4px;
        }

        .btn-primary:hover {
            background: var(--accent-gold-soft);
        }

        .alert {
            margin-bottom: 10px;
            padding: 8px 10px;
            border-radius: 10px;
            font-size: 13px;
            border-left-width: 4px;
            border-left-style: solid;
        }

        .alert-success {
            background: rgba(34,197,94,0.12);
            border-left-color: rgba(34,197,94,0.9);
            color: #bbf7d0;
        }

        .alert-error {
            background: rgba(239,68,68,0.14);
            border-left-color: rgba(248,113,113,0.95);
            color: #fecaca;
        }

        body[data-theme="light"] .alert-success {
            background: #dcfce7;
            border-left-color: #16a34a;
            color: #166534;
        }

        body[data-theme="light"] .alert-error {
            background: #fee2e2;
            border-left-color: #ef4444;
            color: #b91c1c;
        }

        /* table styles */
        .pos-table-header {
            display: flex;
            justify-content: space-between;
            align-items: flex-start;
            gap: 14px;
            margin-bottom: 10px;
            flex-wrap: wrap;
        }

        .pos-table-header h3 {
            font-size: 17px;
            font-weight: 600;
        }

        .pos-table-header p {
            font-size: 12px;
            color: #c3d8ff;
            margin-top: 2px;
        }

        body[data-theme="light"] .pos-table-header p {
            color: #4b5563;
        }

        .pos-controls {
            display: flex;
            flex-direction: column;
            gap: 10px;
            align-items: flex-end;
        }

        .entries-form {
            display: flex;
            align-items: center;
            gap: 8px;
            font-size: 13px;
        }

        .entries-form label {
            color: #c3d8ff;
        }

        body[data-theme="light"] .entries-form label {
            color: #4b5563;
        }

        .entries-form select {
            padding: 7px 11px;
            border-radius: 999px;
            border: 1px solid rgba(148,163,184,0.7);
            background: var(--bg-input);
            color: var(--text-main);
            font-size: 13px;
        }

        .badge-muted {
            font-size: 11px;
            padding: 4px 9px;
            border-radius: 999px;
            background: rgba(15,23,42,0.86);
            color: #c3d8ff;
        }

        body[data-theme="light"] .badge-muted {
            background: #e5f3ff;
            color: #0f172a;
        }

        .table-wrapper {
            width: 100%;
            overflow-x: auto;
            margin-top: 6px;
        }

        table.pos-table {
            width: 100%;
            border-collapse: collapse;
            font-size: 13px;
            min-width: 850px;
        }

        .pos-table th,
        .pos-table td {
            padding: 9px 8px;
            text-align: center;
            border-bottom: 1px solid rgba(148,163,184,0.25);
        }

        .pos-table th {
            background: var(--bg-table-head);
            color: #ffffff;
            font-weight: 600;
        }

        .pos-table tbody tr {
            background: var(--bg-table-row);
        }

        .pos-table tbody tr:nth-child(even) {
            background: var(--bg-table-row);
        }

        .pos-table tbody tr:hover {
            background: var(--bg-table-hover);
            color: #ffffff;
        }

        body[data-theme="light"] .pos-table th {
            color: #111827;
            border-bottom-color: rgba(148,163,184,0.5);
        }

        body[data-theme="light"] .pos-table td {
            border-bottom-color: rgba(148,163,184,0.35);
        }

        .cell-left { text-align: left; }

        .empty-row {
            padding: 18px;
            color: #c3d8ff;
            text-align: center;
        }

        .delete-btn {
            display: inline-flex;
            align-items: center;
            justify-content: center;
            padding: 5px 10px;
            font-size: 12px;
            border-radius: 999px;
            text-decoration: none;
            border: 1px solid rgba(239,68,68,0.8);
            background: rgba(239,68,68,0.16);
            color: #fecaca;
        }

        .delete-btn:hover {
            background: rgba(239,68,68,0.3);
        }

        body[data-theme="light"] .delete-btn {
            background: #fee2e2;
            border-color: #f87171;
            color: #b91c1c;
        }

        .totals-row {
            background: rgba(15,23,42,0.9);
            font-weight: 600;
        }

        body[data-theme="light"] .totals-row {
            background: #e5f3ff;
        }

        .pagination {
            margin-top: 14px;
            display: flex;
            flex-wrap: wrap;
            gap: 8px;
            justify-content: center;
        }

        .page-btn {
            padding: 7px 12px;
            border-radius: 999px;
            border: 1px solid rgba(148,163,184,0.7);
            background: var(--bg-input);
            color: var(--text-main);
            text-decoration: none;
            font-size: 12px;
            font-weight: 500;
        }

        .page-btn:hover {
            background: var(--bg-table-hover);
            color: #ffffff;
        }

        .page-btn.active {
            background: var(--accent-gold);
            border-color: var(--accent-gold);
            color: #111827;
            font-weight: 700;
        }

        .back-link {
            text-decoration: none;
            font-size: 13px;
            color: var(--accent-gold);
        }

        .back-link:hover {
            text-decoration: underline;
        }

        footer {
            background: transparent;
        }
    </style>
</head>
<body>

<?php include 'sidebar.php'; ?>

<div class="content-area">

    <div class="page-header">
        <div class="page-title">Manage Expenses</div>
        <div class="page-subtitle">Add and review all recorded expenses.</div>
    </div>

    <div class="link-row">
        <a href="admin_dashboard.php" class="styled-link">← Return to Dashboard</a>
    </div>

    <!-- Add expense form -->
    <div class="page-card">
        <div class="page-card-title">Add expense</div>

        <?php if ($message): ?>
            <?= $message ?>
        <?php endif; ?>

        <?php if (isset($_GET['deleted'])): ?>
            <div class="alert alert-success">✔ Expense deleted successfully.</div>
        <?php endif; ?>

        <form method="post" class="expense-form">
            <label for="expense_name">Expense description</label>
            <input
                type="text"
                id="expense_name"
                name="expense_name"
                placeholder="e.g. Rent, Electricity, Bulk Purchase"
                required
            >

            <label for="amount">Amount (KES)</label>
            <input
                type="number"
                step="0.01"
                id="amount"
                name="amount"
                placeholder="0.00"
                required
            >

            <button type="submit" class="btn-primary">Add expense</button>
        </form>
    </div>

    <!-- Expenses table -->
    <div class="page-card-table">
        <div class="pos-table-header">
            <div>
                <h3>Expense history</h3>
                <p>Showing <?= $totalRows ? "page $page of $totalPages" : "no expenses yet." ?></p>
            </div>

            <div class="pos-controls">
                <span class="badge-muted">
                    Grand total: KES <?= number_format($grand_total, 2) ?>
                </span>

                <form method="GET" class="entries-form">
                    <label>Show</label>
                    <select name="limit" onchange="this.form.submit()">
                        <?php foreach($limit_options as $opt): ?>
                            <option value="<?= $opt ?>" <?= (!$is_all && (int)$limit === (int)$opt) ? 'selected' : '' ?>>
                                <?= $opt ?>
                            </option>
                        <?php endforeach; ?>
                        <option value="all" <?= $is_all ? 'selected' : '' ?>>All</option>
                    </select>
                    <span style="color:var(--text-muted);">entries</span>
                </form>
            </div>
        </div>

        <div class="table-wrapper">
            <table class="pos-table">
                <thead>
                <tr>
                    <th>ID</th>
                    <th>Expense name</th>
                    <th>Amount (KES)</th>
                    <th>Recorded by</th>
                    <th>Date</th>
                    <th>Action</th>
                </tr>
                </thead>
                <tbody>
                <?php if($expenses && $expenses->num_rows > 0): ?>
                    <?php while ($row = $expenses->fetch_assoc()):
                        $page_total += (float)$row['amount'];
                    ?>
                        <tr>
                            <td><?= (int)$row['id'] ?></td>
                            <td class="cell-left"><?= htmlspecialchars($row['expense_name']) ?></td>
                            <td><?= number_format((float)$row['amount'], 2) ?></td>
                            <td><?= htmlspecialchars($row['cashier']) ?></td>
                            <td><?= htmlspecialchars($row['expense_date']) ?></td>
                            <td>
                                <a class="delete-btn"
                                   href="admin_expenses.php?delete=<?= (int)$row['id'] ?>"
                                   onclick="return confirm('Are you sure you want to delete this expense?');">
                                    Delete
                                </a>
                            </td>
                        </tr>
                    <?php endwhile; ?>

                    <tr class="totals-row">
                        <td colspan="2" style="text-align:right;">Page total</td>
                        <td><?= number_format($page_total, 2) ?></td>
                        <td colspan="3"></td>
                    </tr>

                    <tr class="totals-row">
                        <td colspan="2" style="text-align:right;">Grand total (all expenses)</td>
                        <td><?= number_format($grand_total, 2) ?></td>
                        <td colspan="3"></td>
                    </tr>

                <?php else: ?>
                    <tr>
                        <td colspan="6" class="empty-row">No expenses found.</td>
                    </tr>
                <?php endif; ?>
                </tbody>
            </table>
        </div>

        <?php if(!$is_all && $totalPages > 1): ?>
            <div class="pagination">
                <?php for($i = 1; $i <= $totalPages; $i++): ?>
                    <a class="page-btn <?= ($i == $page) ? 'active' : '' ?>"
                       href="?page=<?= $i ?>&limit=<?= urlencode((string)$limit) ?>">
                        <?= $i ?>
                    </a>
                <?php endfor; ?>
            </div>
        <?php endif; ?>

       
    </div>

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

</div> <!-- content-area -->

</body>
</html>
