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

include 'db_connect.php';

$page_title = "Sales Report";
$active     = 'sales'; // highlights the Sales tab in the top nav

/* ------------------------------
   PAGINATION
------------------------------ */
$limit = isset($_GET['limit']) ? intval($_GET['limit']) : 10;
if ($limit <= 0) {
    $limit = 10;
}

$page = isset($_GET['page']) ? intval($_GET['page']) : 1;
$page = max(1, $page);

/* ------------------------------
   DATE FILTER LOGIC
   mode:
     - today
     - last7
     - thismonth
     - all
     - custom (requires start_date & end_date)
------------------------------ */
$mode  = $_GET['mode'] ?? 'today';
$today = date('Y-m-d');

$start_date = null;
$end_date   = null;

switch ($mode) {
    case 'last7':
        $end_date   = $today;
        $start_date = date('Y-m-d', strtotime($today . ' -6 days')); // last 7 days including today
        break;

    case 'thismonth':
        $start_date = date('Y-m-01');
        $end_date   = date('Y-m-t');
        break;

    case 'custom':
        $start_date = !empty($_GET['start_date']) ? $_GET['start_date'] : $today;
        $end_date   = !empty($_GET['end_date'])   ? $_GET['end_date']   : $start_date;
        break;

    case 'all':
        // No date filter
        $start_date = null;
        $end_date   = null;
        break;

    case 'today':
    default:
        $start_date = $today;
        $end_date   = $today;
        $mode       = 'today';
        break;
}

/* Build WHERE clause (alias s for sales) */
$base_where = " WHERE 1=1 ";
if ($start_date && $end_date) {
    $sd = $conn->real_escape_string($start_date);
    $ed = $conn->real_escape_string($end_date);
    $base_where .= " AND DATE(s.sale_datetime) BETWEEN '$sd' AND '$ed'";
}

/* Filter label for UI */
if ($mode === 'all') {
    $filter_label = "All time";
} elseif ($start_date && $end_date && $start_date === $end_date) {
    $filter_label = "Date: $start_date";
} elseif ($start_date && $end_date) {
    $filter_label = "From $start_date to $end_date";
} else {
    $filter_label = "All time";
}

/* ------------------------------
   COUNT TOTAL ROWS (for pagination)
------------------------------ */
$totalRows = 0;
$countSql  = "SELECT COUNT(*) AS total FROM sales s $base_where";
$countResult = $conn->query($countSql);
if ($countResult) {
    $rowCount  = $countResult->fetch_assoc();
    $totalRows = (int)($rowCount['total'] ?? 0);
}

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

/* ------------------------------
   SALES QUERY (cashier-safe)
   - NO buying price, NO profit
   - includes receipt_id + refunded + id (for Refund button)
------------------------------ */
$sql = "
    SELECT 
        s.id,
        s.receipt_id,
        s.sale_datetime,
        s.cashier,
        s.quantity,
        s.selling_price,
        s.discount,
        s.refunded,
        p.name AS product_name
    FROM sales s
    JOIN products p ON s.product_id = p.id
    $base_where
    ORDER BY s.sale_datetime DESC
    LIMIT $limit OFFSET $offset
";
$result = $conn->query($sql);

/* Page totals */
$total_sales_net     = 0;  // selling*qty - discount
$total_discount_page = 0;

/* ------------------------------
   GRAND TOTALS (for selected range)
------------------------------ */
$grand_total_discount  = 0;
$grand_total_sales_net = 0;

$grandSql = "
    SELECT 
        SUM(s.discount) AS grand_total_discount,
        SUM(s.selling_price * s.quantity - s.discount) AS grand_total_sales_net
    FROM sales s
    $base_where
";
$grandQuery = $conn->query($grandSql);
if ($grandQuery) {
    $grand                 = $grandQuery->fetch_assoc();
    $grand_total_discount  = (float)($grand['grand_total_discount']  ?? 0);
    $grand_total_sales_net = (float)($grand['grand_total_sales_net'] ?? 0);
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <title><?= htmlspecialchars($page_title) ?> | Cashier</title>
    <?php include 'cashier_head.php'; ?>

    <style>
        /* ---------- LAYOUT & FOOTER PIN ---------- */
        html,
        body {
            height: 100%;
        }

        body {
            margin: 0;
            display: flex;
            flex-direction: column;
            background: var(--cash-bg-main);
            color: var(--cash-text-main);
            font-family: "Poppins", system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
            -webkit-font-smoothing: antialiased;
        }

        .cashier-shell {
            flex: 1 0 auto;
            display: flex;
            min-height: 0;
        }

        footer,
        footer.footer {
            margin-top: auto;
            background: transparent;
            border-top: none;
            text-align: center;
            font-size: 13px;
            padding: 10px 16px;
            color: var(--cash-text-muted);
        }

        /* ---------- PAGE-SPECIFIC STYLES ---------- */

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

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

        .sales-report-wrapper {
            max-width: 1650px;
            margin: 0 auto;
            width: 100%;
        }

        .sales-report-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 22px;
            border: 1px solid var(--cash-border-soft);
            box-shadow: 0 20px 45px rgba(0,0,0,0.55);
            color: var(--cash-text-main);
        }

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

        .sales-header {
            display: flex;
            justify-content: space-between;
            align-items: flex-start;
            gap: 14px;
            flex-wrap: wrap;
            margin-bottom: 14px;
        }

        .sales-header-left {
            display: flex;
            flex-direction: column;
            gap: 4px;
        }

        .sales-header-left h2 {
            font-size: 18px;
            font-weight: 600;
        }

        .sales-header-left p {
            font-size: 12px;
            color: var(--cash-text-muted);
        }

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

        .sales-subtitle {
            font-size: 13px;
            color: var(--cash-text-muted);
        }

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

        /* Controls (filter + limit) */
        .sales-controls {
            display: flex;
            flex-direction: column;
            align-items: flex-end;
            gap: 10px;
            font-size: 13px;
        }

        .date-filter-form {
            display: flex;
            flex-wrap: wrap;
            align-items: center;
            gap: 8px;
            justify-content: flex-end;
        }

        .date-filter-form label {
            color: #cbd5f5;
            font-size: 13px;
        }

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

        .date-filter-form select,
        .date-filter-form input[type="date"] {
            padding: 6px 10px;
            border-radius: 999px;
            border: 1px solid rgba(148,163,184,0.7);
            background: #001b3a;
            color: #e5e7eb;
            font-size: 12px;
        }

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

        .date-filter-form button {
            padding: 6px 12px;
            border-radius: 999px;
            border: none;
            font-size: 12px;
            cursor: pointer;
            background: linear-gradient(to right, #22d3ee, #0ea5e9);
            color: #011b35;
            font-weight: 600;
        }

        .limit-form {
            display: flex;
            align-items: center;
            gap: 8px;
        }

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

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

        .limit-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"] .limit-form select {
            background: #ffffff;
            color: #0f172a;
            border-color: #cbd5f5;
        }

        .sales-kpi {
            margin-top: 2px;
            font-size: 12px;
            color: var(--cash-text-muted);
            text-align: right;
        }

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

        /* Table */

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

        table.sales-table {
            width: 100%;
            min-width: 1100px;
            border-collapse: collapse;
            border-radius: 12px;
            overflow: hidden;
        }

        .sales-table th,
        .sales-table td {
            padding: 9px 10px;
            border-bottom: 1px solid rgba(148,163,184,0.35);
            font-size: 13px;
            text-align: center;
        }

        .sales-table th {
            background: #012a73;
            color: #E5F0FF;
            font-weight: 600;
            text-transform: uppercase;
            letter-spacing: 0.06em;
            font-size: 12px;
        }

        .sales-table tbody tr:nth-child(even) {
            background: rgba(2,35,98,0.82);
        }

        .sales-table tbody tr:nth-child(odd) {
            background: rgba(1,26,80,0.82);
        }

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

        .sales-table td {
            color: #F9FAFF;
        }

        .numeric {
            text-align: right;
        }

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

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

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

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

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

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

        .page-btn {
            padding: 7px 12px;
            background: rgba(15,23,42,0.9);
            color: #E9F5FF;
            border-radius: 999px;
            text-decoration: none;
            border: 1px solid rgba(148,163,184,0.8);
            font-size: 13px;
            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;
            font-weight: 700;
            color: #011b35;
            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;
        }

        /* Totals section */

        .totals-box {
            margin-top: 18px;
            text-align: right;
            font-weight: 600;
            font-size: 14px;
        }

        .totals-box span.label {
            color: var(--cash-text-main);
        }

        .totals-box span.value {
            color: var(--cash-accent-soft);
        }

        html[data-theme="light"] .totals-box span.label {
            color: #0f172a;
        }

        .grand-totals-box {
            margin-top: 14px;
            padding: 12px 16px;
            background: rgba(2,24,71,0.98);
            border-left: 4px solid var(--cash-accent-soft);
            border-radius: 12px;
            text-align: right;
            font-weight: 600;
            font-size: 14px;
            box-shadow: 0 8px 20px rgba(0,0,0,0.45);
        }

        .grand-totals-box span.label {
            color: #e5e7eb;
        }

        .grand-totals-box span.value {
            color: var(--cash-accent-soft);
        }

        html[data-theme="light"] .grand-totals-box {
            background: #eff6ff;
            border-left-color: #0ea5e9;
            box-shadow: 0 8px 20px rgba(15,23,42,0.12);
        }

        html[data-theme="light"] .grand-totals-box span.label {
            color: #0f172a;
        }

        @media (max-width: 900px) {
            .sales-controls {
                align-items: flex-start;
            }
        }

        /* Refund styling (same style as record_sales page) */
        .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;
        }
    </style>
</head>
<body>

<div class="cashier-shell">

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

    <main class="cashier-main">

        <!-- Top bar -->
        <div class="cashier-topbar">
            <div class="cashier-topbar-left">
                <h1><?= htmlspecialchars($page_title) ?></h1>
                <small>
                    Page <?= $page ?> of <?= $totalPages ?> (showing <?= $limit ?> entries per page)
                </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>

        <!-- SALES REPORT CARD -->
        <div class="sales-report-wrapper">
            <section class="sales-report-card">

                <div class="sales-header">
                    <div class="sales-header-left">
                        <h2>Sales detail</h2>
                        <p>Paginated history of all sales for the selected period. Cashier view hides buying prices and profit.</p>
                        <div class="sales-subtitle">
                            Filter: <?= htmlspecialchars($filter_label) ?> · Records: <?= number_format($totalRows) ?>
                        </div>
                    </div>

                    <div class="sales-controls">
                        <!-- Date filter -->
                        <form method="GET" class="date-filter-form">
                            <label for="mode">Filter by</label>
                            <select name="mode" id="mode">
                                <option value="today"     <?= $mode === 'today'     ? 'selected' : '' ?>>Today</option>
                                <option value="last7"     <?= $mode === 'last7'     ? 'selected' : '' ?>>Last 7 days</option>
                                <option value="thismonth" <?= $mode === 'thismonth' ? 'selected' : '' ?>>This month</option>
                                <option value="all"       <?= $mode === 'all'       ? 'selected' : '' ?>>All time</option>
                                <option value="custom"    <?= $mode === 'custom'    ? 'selected' : '' ?>>Custom range</option>
                            </select>

                            <input
                                type="date"
                                name="start_date"
                                value="<?= htmlspecialchars($start_date ?? '') ?>"
                                <?= ($mode !== 'custom') ? 'disabled' : '' ?>
                            >
                            <input
                                type="date"
                                name="end_date"
                                value="<?= htmlspecialchars($end_date ?? '') ?>"
                                <?= ($mode !== 'custom') ? 'disabled' : '' ?>
                            >

                            <input type="hidden" name="limit" value="<?= $limit ?>">

                            <button type="submit">Apply</button>
                        </form>

                        <!-- Limit select -->
                        <form method="GET" class="limit-form">
                            <label for="limit">Show</label>
                            <select name="limit" id="limit" onchange="this.form.submit()">
                                <option value="10"  <?= $limit == 10  ? 'selected' : '' ?>>10</option>
                                <option value="25"  <?= $limit == 25  ? 'selected' : '' ?>>25</option>
                                <option value="50"  <?= $limit == 50  ? 'selected' : '' ?>>50</option>
                                <option value="100" <?= $limit == 100 ? 'selected' : '' ?>>100</option>
                            </select>
                            <span style="color:var(--cash-text-muted);">entries</span>

                            <!-- preserve current filter -->
                            <input type="hidden" name="mode" value="<?= htmlspecialchars($mode) ?>">
                            <input type="hidden" name="start_date" value="<?= htmlspecialchars($start_date ?? '') ?>">
                            <input type="hidden" name="end_date" value="<?= htmlspecialchars($end_date ?? '') ?>">
                        </form>

                        <div class="sales-kpi">
                            Page <?= $page ?> / <?= $totalPages ?>
                        </div>
                    </div>
                </div>

                <div class="table-wrapper">
                    <table class="sales-table">
                        <thead>
                            <tr>
                                <th>Receipt</th>
                                <th>Date &amp; Time</th>
                                <th>Cashier</th>
                                <th>Product</th>
                                <th>Quantity Sold</th>
                                <th>Selling Price (KES)</th>
                                <th>Discount (KES)</th>
                                <th>Total Sale (KES)</th>
                                <th>Refund</th>
                            </tr>
                        </thead>
                        <tbody>
                        <?php if ($result && $result->num_rows > 0): ?>
                            <?php while ($row = $result->fetch_assoc()):
                                $discount = (float)($row['discount'] ?? 0);
                                $total    = ((float)$row['selling_price'] * (int)$row['quantity']) - $discount;

                                $total_sales_net     += $total;
                                $total_discount_page += $discount;
                            ?>
                                <tr>
                                    <td><?= htmlspecialchars($row['receipt_id']) ?></td>
                                    <td><?= htmlspecialchars($row['sale_datetime']) ?></td>
                                    <td><?= htmlspecialchars($row['cashier']) ?></td>
                                    <td><?= htmlspecialchars($row['product_name']) ?></td>
                                    <td class="numeric"><?= (int)$row['quantity'] ?></td>
                                    <td class="numeric"><?= number_format((float)$row['selling_price'], 2) ?></td>
                                    <td class="numeric"><?= number_format($discount, 2) ?></td>
                                    <td class="numeric"><?= number_format($total, 2) ?></td>
                                    <td>
                                        <?php if ((int)$row['refunded'] === 0): ?>
                                            <a href="refund_sale.php?id=<?= (int)$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; ?>
                        <?php else: ?>
                            <tr>
                                <td colspan="9" style="padding:14px; text-align:center;">
                                    No sales found for this period.
                                </td>
                            </tr>
                        <?php endif; ?>
                        </tbody>
                    </table>
                </div>

                <div class="pagination">
                    <?php for ($i = 1; $i <= $totalPages; $i++): ?>
                        <a class="page-btn <?= ($i == $page) ? 'active' : '' ?>"
                           href="?page=<?= $i ?>&limit=<?= $limit ?>&mode=<?= urlencode($mode) ?>&start_date=<?= urlencode($start_date ?? '') ?>&end_date=<?= urlencode($end_date ?? '') ?>">
                            <?= $i ?>
                        </a>
                    <?php endfor; ?>
                </div>

                <!-- Page totals -->
                <div class="totals-box">
                    <div>
                        <span class="label">Page Total Discount:</span>
                        <span class="value">KES <?= number_format($total_discount_page, 2) ?></span>
                    </div>
                    <div>
                        <span class="label">Page Total Sales (Net):</span>
                        <span class="value">KES <?= number_format($total_sales_net, 2) ?></span>
                    </div>
                </div>

                <!-- Grand totals (for selected filter) -->
                <div class="grand-totals-box">
                    <div>
                        <span class="label">Grand Total Discount (Filtered):</span>
                        <span class="value">KES <?= number_format($grand_total_discount, 2) ?></span>
                    </div>
                    <div>
                        <span class="label">Grand Total Sales (Net, Filtered):</span>
                        <span class="value">KES <?= number_format($grand_total_sales_net, 2) ?></span>
                    </div>
                </div>

            </section>
        </div>

    </main>
</div>

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