<?php
session_start();
if (!isset($_SESSION['username']) || ($_SESSION['role'] ?? '') !== 'cashier') {
    header("Location: login.php");
    exit();
}

include("db_connect.php");

date_default_timezone_set('Africa/Nairobi');
$today      = date('Y-m-d');
$page_title = "Transactions";
$active     = 'daily_sales'; // highlight Today’s Sales in the top navigation

// -----------------------------
// Handle Entries & Pagination
// -----------------------------
$limit_options = [10, 15, 25, 50, 100];
$limit = $_GET['limit'] ?? 15;
$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;
    }
}

// Count total sales rows for today
$countResult = $conn->query("
    SELECT COUNT(*) AS total
    FROM sales
    WHERE DATE(sale_datetime) = '$today'
");
$totalRows = (int)($countResult->fetch_assoc()['total'] ?? 0);

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

// Fetch paginated sales (cashier-safe fields ONLY)
// now including id, receipt_id and refunded for the refund button
$sql = "
    SELECT
        s.id,
        s.receipt_id,
        s.sale_datetime,
        s.cashier,
        s.quantity,
        s.selling_price,
        s.discount,
        s.total_sale,
        s.refunded,
        p.name AS product_name
    FROM sales s
    JOIN products p ON s.product_id = p.id
    WHERE DATE(s.sale_datetime) = '$today'
    ORDER BY s.sale_datetime DESC
";

if (!$is_all) {
    $sql .= " LIMIT $limit OFFSET $offset";
}
$result = $conn->query($sql);

// Grand totals for all sales today (use stored total_sale)
$totalsQuery = $conn->query("
    SELECT
        SUM(total_sale) AS grand_total_sales,
        SUM(discount)   AS grand_total_discount
    FROM sales
    WHERE DATE(sale_datetime) = '$today'
");
$totalsData            = $totalsQuery->fetch_assoc();
$grand_total_sales     = (float)($totalsData['grand_total_sales'] ?? 0);
$grand_total_discount  = (float)($totalsData['grand_total_discount'] ?? 0);

// Page totals
$page_total_sales      = 0;
$page_total_discount   = 0;
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <?php include 'cashier_head.php'; ?>
    <style>
        .cashier-main {
            padding: 24px 30px 34px;
            min-width: 0;
        }

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

        /* CARD WRAPPER */

        .pos-card-outer {
            max-width: 1350px;
            margin: 0 auto;
            width: 100%;
        }

        .pos-table-card {
            background:
                radial-gradient(circle at top left, rgba(34,211,238,0.12), transparent 55%),
                var(--cash-bg-card);
            border-radius: 18px;
            padding: 18px 22px 20px;
            box-shadow: 0 20px 45px rgba(0,0,0,0.55);
            color: #E9F5FF;
            border: 1px solid var(--cash-border-soft);
            margin-bottom: 22px;
        }

        html[data-theme="light"] .pos-table-card {
            background:
                radial-gradient(circle at top left, rgba(56,189,248,0.16), transparent 55%),
                #ffffff;
            box-shadow: 0 12px 26px rgba(15,23,42,0.14);
            color: #0f172a;
            border-color: #dbeafe;
        }

        .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: var(--cash-text-muted);
            margin-top: 2px;
        }

        html[data-theme="light"] .pos-table-header p {
            color: #64748b;
        }

        /* METRIC CHIPS */

        .metric-strip {
            display: flex;
            flex-wrap: wrap;
            gap: 10px;
            margin-top: 10px;
        }

        .metric-chip {
            padding: 8px 14px;
            border-radius: 999px;
            background: rgba(15,23,42,0.85);
            border: 1px solid rgba(148,163,184,0.8);
            font-size: 12px;
        }

        html[data-theme="light"] .metric-chip {
            background: #eff6ff;
            border-color: #bfdbfe;
        }

        .metric-label {
            color: var(--cash-accent-soft);
            font-weight: 500;
            margin-right: 6px;
        }

        .metric-value {
            font-weight: 600;
        }

        /* CONTROLS (back + entries) */

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

        .back-link {
            text-decoration: none;
            font-size: 13px;
            color: var(--cash-accent-soft);
            white-space: nowrap;
        }

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

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

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

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

        .entries-form select {
            padding: 7px 11px;
            border-radius: 999px;
            border: 1px solid rgba(148,163,184,0.7);
            background: #063d8c;
            color: #E9F5FF;
            font-size: 13px;
        }

        html[data-theme="light"] .entries-form select {
            background: #ffffff;
            color: #0f172a;
            border-color: #cbd5f5;
        }

        /* TABLE */

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

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

        .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;
            text-transform: uppercase;
            letter-spacing: 0.06em;
            font-size: 12px;
        }

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

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

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

        html[data-theme="light"] .pos-table th {
            background: #eff6ff;
            color: #0f172a;
        }

        html[data-theme="light"] .pos-table td {
            color: #0f172a;
        }

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

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

        html[data-theme="light"] .pos-table tbody tr:hover {
            background: #e0f2fe;
        }

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

        html[data-theme="light"] .empty-row {
            color: #64748b;
        }

        /* REFUND BADGE + BUTTON (same as record_sales.php) */
        .badge-refunded {
            font-size: 11px;
            padding: 4px 9px;
            border-radius: 999px;
            background: rgba(16,185,129,0.14);
            color: #6ee7b7;
        }

        html[data-theme="light"] .badge-refunded {
            background: #dcfce7;
            color: #166534;
        }

        .btn-refund {
            padding: 5px 10px;
            border-radius: 999px;
            border: none;
            background: #EF4444;
            color: #FFFBF5;
            font-size: 12px;
            cursor: pointer;
        }

        .btn-refund:hover {
            background: #DC2626;
        }

        /* PAGINATION */

        .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.8);
            background: rgba(15,23,42,0.85);
            color: #E9F5FF;
            text-decoration: none;
            font-size: 12px;
            font-weight: 500;
        }

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

        .page-btn.active {
            background: linear-gradient(to right, #22d3ee, #0ea5e9);
            border-color: transparent;
            color: #011b35;
            font-weight: 700;
            box-shadow: 0 10px 24px rgba(0,0,0,0.45);
        }

        html[data-theme="light"] .page-btn {
            background: #f3f4f6;
            color: #0f172a;
            border-color: #cbd5f5;
        }

        html[data-theme="light"] .page-btn:hover {
            background: #e5e7eb;
        }

        html[data-theme="light"] .page-btn.active {
            background: linear-gradient(to right, #22d3ee, #0ea5e9);
            color: #011b35;
        }

        @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">

        <!-- TOP BAR: shared nav + theme toggle -->
        <div class="cashier-topbar">
            <div class="cashier-topbar-left">
                <h1><?= htmlspecialchars($page_title) ?></h1>
                <small>All sales recorded for <?= htmlspecialchars($today) ?>.</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="customer_debts.php" class="<?= ($active === 'debts') ? 'active' : '' ?>">Debts</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" type="button" onclick="toggleCashierSidebar()">☰</button>
            </div>
        </div>

        <!-- TRANSACTIONS CARD -->
        <div class="pos-card-outer">
            <section class="pos-table-card">
                <div class="pos-table-header">
                    <div>
                        <h3>Transactions (<?= htmlspecialchars($today) ?>)</h3>
                        <p>Full list of today’s transactions. Cashier view hides buying prices and profit.</p>

                        <div class="metric-strip">
                            <div class="metric-chip">
                                <span class="metric-label">Transactions:</span>
                                <span class="metric-value"><?= number_format($totalRows) ?></span>
                            </div>
                            <div class="metric-chip">
                                <span class="metric-label">Grand discounts:</span>
                                <span class="metric-value">KES <?= number_format($grand_total_discount, 2) ?></span>
                            </div>
                            <div class="metric-chip">
                                <span class="metric-label">Grand sales:</span>
                                <span class="metric-value">KES <?= number_format($grand_total_sales, 2) ?></span>
                            </div>
                        </div>
                    </div>

                    <div class="pos-controls">
                        <a href="cashier_dashboard.php" class="back-link">← Back to dashboard</a>

                        <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>Receipt</th>
                                <th>Date &amp; Time</th>
                                <th>Cashier</th>
                                <th>Product</th>
                                <th>Qty</th>
                                <th>Selling Price</th>
                                <th>Discount</th>
                                <th>Total Sale</th>
                                <th>Refund</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php if($result && $result->num_rows > 0): ?>
                                <?php while($row = $result->fetch_assoc()):
                                    $page_total_sales    += (float)$row['total_sale'];
                                    $page_total_discount += (float)$row['discount'];
                                ?>
                                    <tr>
                                        <td><?= htmlspecialchars($row['receipt_id']) ?></td>
                                        <td><?= htmlspecialchars($row['sale_datetime']) ?></td>
                                        <td><?= htmlspecialchars($row['cashier']) ?></td>
                                        <td class="cell-left"><?= htmlspecialchars($row['product_name']) ?></td>
                                        <td><?= htmlspecialchars($row['quantity']) ?></td>
                                        <td><?= number_format((float)$row['selling_price'], 2) ?></td>
                                        <td><?= number_format((float)$row['discount'], 2) ?></td>
                                        <td><?= number_format((float)$row['total_sale'], 2) ?></td>
                                        <td>
                                            <?php if ((int)$row['refunded'] === 0): ?>
                                                <a href="refund_sale.php?id=<?= $row['id'] ?>"
                                                   onclick="return confirm('Refund this sale?');">
                                                    <button type="button" class="btn-refund">Refund</button>
                                                </a>
                                            <?php else: ?>
                                                <span class="badge-refunded">Refunded</span>
                                            <?php endif; ?>
                                        </td>
                                    </tr>
                                <?php endwhile; ?>

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

                                <tr class="totals-row">
                                    <td colspan="6" style="text-align:right;">Grand totals (today)</td>
                                    <td><?= number_format($grand_total_discount, 2) ?></td>
                                    <td><?= number_format($grand_total_sales, 2) ?></td>
                                    <td></td>
                                </tr>
                            <?php else: ?>
                                <tr>
                                    <td colspan="9" class="empty-row">
                                        No transactions recorded for today yet.
                                    </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; ?>
            </section>
        </div>

    </main>
</div>

<?php include 'footer.php'; ?>
</body>
</html>
