<?php
session_start();

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

require 'db_connect.php';

// 🔹 Require an open cash session so that we can attach expenses to it
include 'require_cash_session.php';

date_default_timezone_set('Africa/Nairobi');

$page_title = "Expenses | Cashier POS";
$active     = 'expenses'; // for top-nav highlighting

$message = "";

// Current cashier + cash session
$cashier       = $_SESSION['username'];
$cashSessionId = $_SESSION['cash_session_id'] ?? null;

// Extra safety (require_cash_session.php should already ensure this)
if (!$cashSessionId) {
    header("Location: open_cash_session.php");
    exit();
}

/* -------------------------------
   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
--------------------------------- */
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 {

        // 🔸 Now we also store cash_session_id so close_cash_session.php can deduct
        $stmt = $conn->prepare("
            INSERT INTO expenses (expense_name, amount, cashier, cash_session_id, expense_date)
            VALUES (?, ?, ?, ?, ?)
        ");

        if ($stmt) {
            // s (string) = expense_name
            // d (double) = amount
            // s (string) = cashier
            // i (int)    = cash_session_id
            // s (string) = expense_date
            $stmt->bind_param("sdsis", $expense_name, $amount, $cashier, $cashSessionId, $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: add_expense.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
   (Still shows ALL expenses; you can later add filters by date/session)
--------------------------------- */
$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>
    <?php include 'cashier_head.php'; ?>
    <style>
        /* Layout + footer support */
        html, body {
            height: 100%;
        }
        body {
            min-height: 100vh;
            display: flex;
            flex-direction: column;
        }
        .cashier-shell {
            flex: 1;
            display: flex;
        }

        .cashier-main {
            padding: 24px 30px 34px;
        }

        @media (max-width: 900px) {
            .cashier-main {
                padding: 18px 16px 26px;
            }
        }

        /* Cards */

        .pos-card,
        .pos-table-card {
            background: linear-gradient(135deg, #064ab8 0%, #022a6b 55%, #021d53 100%);
            border-radius: 18px;
            padding: 18px 22px 22px;
            box-shadow: 0 20px 45px rgba(0,0,0,0.55);
            color: #E9F5FF;
            border: 1px solid rgba(130,238,253,0.5);
            margin-bottom: 22px;
        }

        html[data-theme="light"] .pos-card,
        html[data-theme="light"] .pos-table-card {
            background: #ffffff;
            border-color: rgba(148,163,184,0.55);
            color: #0f172a;
            box-shadow: 0 12px 26px rgba(15,23,42,0.12);
        }

        .pos-card-header h2 {
            font-size: 19px;
            font-weight: 600;
        }

        .pos-card-header p {
            font-size: 13px;
            color: #c3d8ff;
            margin-top: 4px;
        }

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

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

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

        html[data-theme="light"] .expense-form label {
            color: #0f172a;
        }

        .expense-form input[type="text"],
        .expense-form input[type="number"] {
            width: 100%;
            padding: 9px 11px;
            border-radius: 10px;
            border: 1px solid rgba(130,238,253,0.5);
            background: #0a3d87;
            color: #E9F5FF;
            font-size: 13px;
            margin-bottom: 10px;
        }

        .expense-form input::placeholder {
            color: rgba(226,232,240,0.7);
        }

        html[data-theme="light"] .expense-form input[type="text"],
        html[data-theme="light"] .expense-form input[type="number"] {
            background: #ffffff;
            border-color: rgba(148,163,184,0.55);
            color: #0f172a;
        }

        html[data-theme="light"] .expense-form input::placeholder {
            color: #9ca3af;
        }

        .expense-form input:focus {
            outline: none;
            border-color: #00FFE5;
            box-shadow: 0 0 0 1px rgba(0,255,229,0.35);
        }

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

        .btn-primary:hover {
            filter: brightness(1.08);
        }

        .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;
        }

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

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

        /* Table & header */

        .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;
        }

        html[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;
        }

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

        .entries-form select {
            padding: 7px 11px;
            border-radius: 999px;
            border: 1px solid rgba(130,238,253,0.6);
            background: #063d8c;
            color: #E9F5FF;
            font-size: 13px;
        }

        html[data-theme="light"] .entries-form select {
            background: #eff6ff;
            border-color: rgba(148,163,184,0.7);
            color: #0f172a;
        }

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

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

        .pos-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);
            color: #F9FAFF;
        }

        .pos-table th {
            background: #012a73;
            position: sticky;
            top: 0;
            z-index: 1;
            font-weight: 600;
        }

        .pos-table tbody tr:nth-child(even) { background: rgba(2,35,98,0.82); }
        .pos-table tbody tr:nth-child(odd)  { background: rgba(1,26,80,0.82); }

        .pos-table tbody tr:hover { background: rgba(130,238,253,0.16); }

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

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

        /* 🔆 Light theme overrides */

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

        html[data-theme="light"] .pos-table th {
            background: #e5f3ff;
        }

        html[data-theme="light"] .pos-table tbody tr:nth-child(even),
        html[data-theme="light"] .pos-table tbody tr:nth-child(odd) {
            background: #f9fafb;
        }

        .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);
        }

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

        .totals-row {
            background: rgba(3,4,94,0.98);
            font-weight: 600;
        }

        html[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(130,238,253,0.7);
            background: rgba(0,26,80,0.4);
            color: #E9F5FF;
            text-decoration: none;
            font-size: 12px;
            font-weight: 500;
        }

        .page-btn:hover {
            background: rgba(15,23,42,0.96);
        }

        .page-btn.active {
            background: var(--cash-accent-turquoise);
            border-color: var(--cash-accent-turquoise);
            color: #011b35;
            font-weight: 700;
        }

        html[data-theme="light"] .page-btn {
            background: #eff6ff;
            border-color: rgba(148,163,184,0.7);
            color: #0f172a;
        }

        html[data-theme="light"] .page-btn.active {
            background: #0ea5e9;
            color: #f9fafb;
        }

        .back-link {
            text-decoration: none;
            font-size: 13px;
            color: #82EEFD;
        }

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

        html[data-theme="light"] .back-link {
            color: #0369a1;
        }

        /* Footer pinned bottom */
        footer {
            background: transparent;
            text-align: center;
            font-size: 12px;
            color: var(--cash-text-muted);
            padding: 10px 18px;
            margin-top: auto;
        }

        @media (max-width: 900px) {
            .pos-controls {
                align-items: flex-start;
            }
        }
    </style>
</head>
<body>

<div class="cashier-shell">
    <?php include "cashier_sidebar.php"; ?>

    <main class="cashier-main">

        <!-- Consistent topbar with nav + theme toggle -->
        <div class="cashier-topbar">
            <div class="cashier-topbar-left">
                <h1><?= htmlspecialchars($page_title) ?></h1>
                <small>Add new expenses and review all records.</small>
            </div>

            <div class="cashier-topbar-right">
                <nav class="cashier-topnav">
                    <a href="cashier_dashboard.php" class="<?= ($active === 'dashboard') ? 'active' : '' ?>">Dashboard</a>
                    <a href="record_sales.php" class="<?= ($active === 'sales') ? 'active' : '' ?>">Sales</a>
                    <a href="cashier_view_daily_sales.php" class="<?= ($active === 'daily_sales') ? 'active' : '' ?>">Today’s Sales</a>
                    <a href="transaction_history.php" class="<?= ($active === 'transactions') ? 'active' : '' ?>">Transactions</a>
                    <a href="customers.php" class="<?= ($active === 'customers') ? 'active' : '' ?>">Customers</a>
                    <a href="add_expense.php" class="<?= ($active === 'expenses') ? 'active' : '' ?>">Expenses</a>
                </nav>

                <button type="button" class="cashier-theme-toggle" onclick="toggleCashierTheme()">
                    <span class="icon">🌓</span>
                    <span class="label">Theme</span>
                </button>

                <button class="cashier-toggle" onclick="toggleCashierSidebar()">☰</button>
            </div>
        </div>

        <!-- Add expense form -->
        <section class="pos-card">
            <div class="pos-card-header">
                <h2>Add expense</h2>
                <p>Record expenses related to operations, such as lunch, fare, fuel, etc.</p>
            </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. Lunch, Fuel, Fare"
                    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>
        </section>

        <!-- Expenses table -->
        <section class="pos-table-card">
            <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(--cash-text-muted);">entries</span>
                    </form>
                </div>
            </div>

            <div class="pos-table-wrapper">
                <table class="pos-table">
                    <thead>
                        <tr>
                            <th>ID</th>
                            <th>Expense name</th>
                            <th>Amount (KES)</th>
                            <th>Cashier</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="add_expense.php?delete=<?= (int)$row['id'] ?>"
                                           onclick="return confirm('Are you sure you want to delete this expense?');">
                                            Delete
                                        </a>
                                    </td>
                                </tr>
                            <?php endwhile; ?>

                            <!-- Page Total -->
                            <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>

                            <!-- Grand Total -->
                            <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>

            <!-- PAGINATION -->
            <?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 style="margin-top: 14px;">
                <a href="cashier_dashboard.php" class="back-link">← Back to dashboard</a>
            </div>
        </section>

    </main>
</div>

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

<script>
function toggleCashierSidebar() {
    const sidebar = document.getElementById('cashierSidebar');
    if (sidebar) {
        sidebar.classList.toggle('is-collapsed');
    }
}
</script>

</body>
</html>
