<?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 = "Today's Sales | Cashier POS";

// -----------------------------
// Handle Entries & Pagination
// -----------------------------
$limit_options = [10, 15, 25, 50, 100];
$limit = $_GET['limit'] ?? 15;
$page  = isset($_GET['page']) ? max(1, intval($_GET['page'])) : 1;

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

// Count total rows today
$count_row = mysqli_fetch_assoc(mysqli_query(
    $conn,
    "SELECT COUNT(*) AS total FROM sales WHERE DATE(sale_datetime) = '$today'"
));
$totalRows  = (int)($count_row['total'] ?? 0);
$totalPages = ($limit !== 'all' && $limit > 0) ? max(1, (int)ceil($totalRows / $limit)) : 1;
if ($page > $totalPages) $page = $totalPages;

// Fetch sales for today (paginated)
$sql = "
    SELECT
        s.sale_datetime,
        s.cashier,
        s.quantity,
        s.selling_price,
        s.discount,
        s.total_sale,

        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 ($limit !== 'all') {
    $sql .= " LIMIT $limit OFFSET $offset";
}


$result = mysqli_query($conn, $sql);

// Grand totals for all sales today (matches record_sales page structure)
$totals_row = mysqli_fetch_assoc(mysqli_query($conn, "
    SELECT
        SUM(total_sale) AS grand_total_sales,
        SUM(profit)     AS grand_total_profit,
        SUM(discount)   AS grand_total_discount
    FROM sales
    WHERE DATE(sale_datetime) = '$today'
"));
$grand_total_sales    = (float)($totals_row['grand_total_sales'] ?? 0);
$grand_total_discount = (float)($totals_row['grand_total_discount'] ?? 0);

// Page totals
$page_total_sales    = 0;
$page_total_profit   = 0;
$page_total_discount = 0;
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <?php include 'cashier_head.php'; ?>
    <style>
        /* Match Record Sale POS look */

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

        .pos-table-card {
            background: linear-gradient(135deg, #064ab8 0%, #022a6b 55%, #021d53 100%);
            border-radius: 18px;
            padding: 18px 22px 20px;
            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;
        }

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

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

        .metric-chip {
            padding: 8px 14px;
            border-radius: 999px;
            background: rgba(1,22,61,0.75);
            border: 1px solid rgba(130,238,253,0.8);
            font-size: 12px;
        }

        .metric-label {
            color: #82EEFD;
            font-weight: 500;
            margin-right: 6px;
        }

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

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

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

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

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

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

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

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

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

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

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

        @media (max-width: 900px) {
            .cashier-main {
                padding: 18px 16px 26px;
            }
        }
    </style>
</head>
<body>

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

    <main class="cashier-main">

        <div class="cashier-topbar">
            <div>
                <h1>Today sales</h1>
                <small>Sales summary for <?= htmlspecialchars($today) ?>.</small>
            </div>
            <button class="cashier-toggle" onclick="toggleCashierSidebar()">Menu</button>
        </div>

        <section class="pos-table-card">

            <div class="pos-table-header">
                <div>
                    <h3>Sales summary (<?= htmlspecialchars($today) ?>)</h3>
                    <p>Live summary of transactions recorded during this shift.</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 sales:</span>
                            <span class="metric-value">KES <?= number_format($grand_total_sales, 2) ?></span>
                        </div>
                        <div class="metric-chip">
                            <span class="metric-label">Grand profit:</span>
                            </span>
                        </div>
                        <div class="metric-chip">
                            <span class="metric-label">Discounts:</span>
                            <span class="metric-value">KES <?= number_format($grand_total_discount, 2) ?></span>
                        </div>
                    </div>
                </div>

                <div style="display:flex; flex-direction:column; gap:10px; align-items:flex-end;">
                    <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 $option): ?>
                                <option value="<?= $option ?>" <?= ($limit == $option) ? 'selected' : '' ?>>
                                    <?= $option ?>
                                </option>
                            <?php endforeach; ?>
                            <option value="all" <?= ($limit === 'all') ? 'selected' : '' ?>>All</option>
                        </select>
                        <span style="color:var(--cash-text-muted);">entries</span>

                        <?php if($limit !== 'all'): ?>
                            <input type="hidden" name="page" value="1">
                        <?php endif; ?>
                    </form>
                </div>
            </div>

            <div class="pos-table-wrapper">
                <table class="pos-table">
                    <thead>
                        <tr>
                            <th>Date & Time</th>
                            <th>Cashier</th>
                            <th>Product</th>
                            <th>Qty</th>
            
                            <th>Selling price</th>
                            <th>Discount</th>
                            <th>Total sale</th>
                    
                        </tr>
                    </thead>
                    <tbody>
                        <?php if($result && mysqli_num_rows($result) > 0): ?>
                            <?php while($row = mysqli_fetch_assoc($result)):
                                $page_total_sales    += (float)$row['total_sale'];
                                
                                $page_total_discount += (float)$row['discount'];
                            ?>
                                <tr>
                                    <td><?= htmlspecialchars($row['sale_datetime']) ?></td>
                                    <td><?= htmlspecialchars($row['cashier']) ?></td>
                                    <td style="text-align: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>
                                  
                                </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><?= number_format($page_total_profit, 2) ?></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>
                                
                            </tr>

                        <?php else: ?>
                            <tr>
                                <td colspan="9" style="padding: 18px; color:#c3d8ff;">
                                    No sales recorded for today yet.
                                </td>
                            </tr>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>

            <?php if($limit !== '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>

    </main>
</div>

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