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

require 'db_connect.php';
date_default_timezone_set('Africa/Nairobi');

$page_title = "Products | Cashier POS";

/* -----------------------------
   Search + pagination
------------------------------*/
$search_raw = $_GET['q'] ?? '';
$search     = trim($search_raw);

$limit_options = [10, 25, 50, 100, 'all'];
$limit = $_GET['limit'] ?? 25;
$page  = isset($_GET['page']) ? max(1, intval($_GET['page'])) : 1;

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

if (!$is_all) {
    $limit = intval($limit);
    if (!in_array($limit, [10, 25, 50, 100], true)) {
        $limit = 25;
    }
}

/* WHERE clause for search (name or barcode) */
$search_sql = '';
if ($search !== '') {
    $safe = $conn->real_escape_string($search);
    $search_sql = " WHERE name LIKE '%$safe%' OR barcode LIKE '%$safe%'";
}

/* Count products (filtered) */
$countResult = $conn->query("SELECT COUNT(*) AS total FROM products $search_sql");
$totalRows   = (int)($countResult->fetch_assoc()['total'] ?? 0);

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

/* Fetch paginated products (filtered) */
$sql = "
    SELECT id, name, barcode, category, selling_price, quantity, date_added
    FROM products
    $search_sql
    ORDER BY name ASC
";
if (!$is_all) {
    $sql .= " LIMIT $limit OFFSET $offset";
}
$products = $conn->query($sql);

/* Grand totals (ALL products, not filtered) */
$grandQuery = $conn->query("
    SELECT 
        SUM(quantity) AS grand_qty,
        SUM(quantity * selling_price) AS grand_value
    FROM products
");
$grandData   = $grandQuery->fetch_assoc();
$grand_qty   = (int)($grandData['grand_qty'] ?? 0);
$grand_value = (float)($grandData['grand_value'] ?? 0);
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <?php include 'cashier_head.php'; ?>
    <style>
        /* ====== Layout & sticky footer ====== */
        html, body { height: 100%; }
        body {
            min-height: 100vh;
            margin: 0;
            display: flex;
            flex-direction: column;
        }
        .cashier-shell {
            flex: 1;
            display: flex;
            min-height: 0;
        }
        .cashier-main {
            flex: 1;
            min-width: 0;
            padding: 24px 30px 34px;
        }
        footer {
            position: relative !important;
            bottom: auto !important;
            width: 100%;
            margin-top: auto;
        }

        /* ====== HERO TOP BAR ====== */
        .cashier-hero-bar {
            background:
                radial-gradient(circle at top left, rgba(56,189,248,0.28), transparent 60%),
                radial-gradient(circle at bottom right, rgba(30,64,175,0.55), transparent 60%),
                #020617;
            border-radius: 14px;
            padding: 14px 22px;
            margin-bottom: 18px;
            display: flex;
            align-items: center;
            justify-content: space-between;
            gap: 20px;
            border: 1px solid rgba(30,64,175,0.8);
            box-shadow: 0 18px 40px rgba(0,0,0,0.7);
            color: #E9F5FF;
        }
        .hero-left h1 {
            font-size: 20px;
            font-weight: 600;
            margin: 0;
            color: #F9FAFF;
        }
        .hero-left p {
            margin: 2px 0 0;
            font-size: 13px;
            color: #cbd5f5;
        }
        .hero-nav {
            display: flex;
            align-items: center;
            gap: 16px;
            flex-wrap: wrap;
        }
        .hero-actions {
            display: flex;
            align-items: center;
            gap: 10px;
        }
        .hero-menu-btn {
            width: 36px;
            height: 36px;
            border-radius: 999px;
            border: none;
            background: #06b6d4;
            color: #f9fafb;
            font-size: 18px;
            display: flex;
            align-items: center;
            justify-content: center;
            cursor: pointer;
        }

        /* ====== Theme toggle pill ====== */
        .theme-toggle-pill {
            display: inline-flex;
            align-items: center;
            gap: 6px;
            border-radius: 999px;
            padding: 4px 10px;
            background: #020617;
            color: #e5e7eb;
            font-size: 12px;
            cursor: pointer;
            border: 1px solid rgba(148,163,184,0.8);
        }
        .theme-toggle-pill-circle {
            width: 16px;
            height: 16px;
            border-radius: 999px;
            background: linear-gradient(135deg, #facc15, #fb923c);
        }

        /* ====== Card / table styles (dark base) ====== */
        .pos-table-card {
            background: radial-gradient(circle at top left, rgba(56,189,248,0.12), transparent 60%), #021428;
            border-radius: 18px;
            padding: 18px 22px 22px;
            box-shadow: 0 20px 45px rgba(0,0,0,0.7);
            color: #E9F5FF;
            border: 1px solid rgba(30,64,175,0.9);
        }
        .pos-table-header {
            display: flex;
            justify-content: space-between;
            align-items: flex-start;
            gap: 14px;
            margin-bottom: 10px;
            flex-wrap: wrap;
        }
        .pos-table-header h2 {
            font-size: 18px;
            font-weight: 600;
            margin: 0;
        }
        .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: 7px 12px;
            border-radius: 999px;
            background: rgba(1,22,61,0.9);
            border: 1px solid rgba(130,238,253,0.8);
            font-size: 12px;
        }
        .metric-label {
            color: #82EEFD;
            font-weight: 500;
            margin-right: 4px;
        }
        .metric-value {
            font-weight: 600;
        }

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

        /* search bar */
        .product-search {
            display: flex;
            align-items: stretch;
            gap: 8px;
        }
        .product-search input[type="text"] {
            padding: 8px 12px;
            border-radius: 999px;
            border: 1px solid rgba(130,238,253,0.7);
            background: rgba(15,23,42,0.9);
            color: #E9F5FF;
            font-size: 13px;
            min-width: 220px;
        }
        .product-search input::placeholder {
            color: #9ca3af;
        }
        .product-search button {
            padding: 8px 16px;
            border-radius: 999px;
            border: none;
            background: #06b6d4;
            color: #020617;
            font-weight: 600;
            font-size: 13px;
            cursor: pointer;
        }
        .product-search button:hover {
            background: #22d3ee;
        }

        /* CLEAR button */
        .product-search .clear-btn {
            padding: 8px 14px;
            border-radius: 999px;
            border: 1px solid rgba(148,163,184,0.8);
            background: transparent;
            color: #e5e7eb;
            font-size: 13px;
            text-decoration: none;
            display: inline-flex;
            align-items: center;
            justify-content: center;
        }
        .product-search .clear-btn:hover {
            background: rgba(148,163,184,0.2);
        }

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

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

        /* LOW STOCK: text color only (works on dark + light) */
        .pos-table tr.low-stock td {
            color: red;
            font-weight: 600;
        }
        html[data-theme="light"] .pos-table tr.low-stock td,
        body[data-theme="light"] .pos-table tr.low-stock td,
        body.light-theme .pos-table tr.low-stock td {
            color: #b91c1c;
        }

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

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

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

        @media (max-width: 960px) {
            .cashier-main {
                padding: 18px 16px 26px;
            }
            .cashier-hero-bar {
                flex-direction: column;
                align-items: flex-start;
            }
            .hero-nav {
                width: 100%;
                justify-content: space-between;
            }
            .pos-controls {
                align-items: flex-start;
            }
        }

        /* ====== LIGHT THEME overrides ====== */
        html[data-theme="light"] .cashier-hero-bar,
        body[data-theme="light"] .cashier-hero-bar,
        body.light-theme .cashier-hero-bar {
            background: linear-gradient(90deg, #f1fbff 0%, #ffffff 40%, #f5fbff 100%);
            border-color: rgba(148,163,184,0.4);
            box-shadow: 0 10px 26px rgba(148,163,184,0.45);
            color: #0f172a;
        }
        html[data-theme="light"] .hero-left h1,
        body[data-theme="light"] .hero-left h1,
        body.light-theme .hero-left h1 {
            color: #020617;
        }
        html[data-theme="light"] .hero-left p,
        body[data-theme="light"] .hero-left p,
        body.light-theme .hero-left p {
            color: #64748b;
        }

        html[data-theme="light"] .theme-toggle-pill,
        body[data-theme="light"] .theme-toggle-pill,
        body.light-theme .theme-toggle-pill {
            background: #e2e8f0;
            color: #0f172a;
            border-color: rgba(148,163,184,0.9);
        }

        html[data-theme="light"] .pos-table-card,
        body[data-theme="light"] .pos-table-card,
        body.light-theme .pos-table-card {
            background: #ffffff !important;
            color: #0f172a !important;
            border-color: rgba(148,163,184,0.6) !important;
            box-shadow: 0 8px 22px rgba(15,23,42,0.12);
        }
        html[data-theme="light"] .pos-table-header p,
        body[data-theme="light"] .pos-table-header p,
        body.light-theme .pos-table-header p {
            color: #64748b !important;
        }

        html[data-theme="light"] .entries-form label,
        body[data-theme="light"] .entries-form label,
        body.light-theme .entries-form label {
            color: #0f172a !important;
        }
        html[data-theme="light"] .entries-form select,
        body[data-theme="light"] .entries-form select,
        body.light-theme .entries-form select {
            background: #e5f2ff;
            color: #0f172a;
            border-color: rgba(148,163,184,0.9);
        }

        html[data-theme="light"] .product-search input[type="text"],
        body[data-theme="light"] .product-search input[type="text"],
        body.light-theme .product-search input[type="text"] {
            background: #ffffff;
            color: #0f172a;
            border-color: rgba(148,163,184,0.8);
        }

        html[data-theme="light"] .product-search .clear-btn,
        body[data-theme="light"] .product-search .clear-btn,
        body.light-theme .product-search .clear-btn {
            color: #0f172a;
            border-color: rgba(148,163,184,0.9);
        }

        /* metric chips: keep high contrast on light theme */
        html[data-theme="light"] .metric-chip,
        body[data-theme="light"] .metric-chip,
        body.light-theme .metric-chip {
            background: #0f172a;
            border-color: rgba(15,23,42,0.7);
            color: #e0f2fe;
        }
        html[data-theme="light"] .metric-label,
        body[data-theme="light"] .metric-label,
        body.light-theme .metric-label {
            color: #bfdbfe;
        }
        html[data-theme="light"] .metric-value,
        body[data-theme="light"] .metric-value,
        body.light-theme .metric-value {
            color: #e0f2fe;
        }

        html[data-theme="light"] table.pos-table,
        body[data-theme="light"] table.pos-table,
        body.light-theme table.pos-table {
            background: #ffffff;
        }
        html[data-theme="light"] .pos-table th,
        body[data-theme="light"] .pos-table th,
        body.light-theme .pos-table th {
            background: #e5f2ff;
            color: #0f172a;
            border-bottom-color: rgba(148,163,184,0.6);
        }
        html[data-theme="light"] .pos-table td,
        body[data-theme="light"] .pos-table td,
        body.light-theme .pos-table td {
            color: #0f172a;
            border-bottom-color: rgba(148,163,184,0.35);
        }
        html[data-theme="light"] .pos-table tbody tr:nth-child(even),
        body[data-theme="light"] .pos-table tbody tr:nth-child(even),
        body.light-theme .pos-table tbody tr:nth-child(even) {
            background: #f8fafc;
        }
        html[data-theme="light"] .pos-table tbody tr:nth-child(odd),
        body[data-theme="light"] .pos-table tbody tr:nth-child(odd),
        body.light-theme .pos-table tbody tr:nth-child(odd) {
            background: #ffffff;
        }
        html[data-theme="light"] .pos-table tbody tr:hover,
        body[data-theme="light"] .pos-table tbody tr:hover,
        body.light-theme .pos-table tbody tr:hover {
            background: #e2f3ff;
        }
        html[data-theme="light"] .totals-row,
        body[data-theme="light"] .totals-row,
        body.light-theme .totals-row {
            background: #e5f2ff;
        }

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

        html[data-theme="light"] .back-link,
        body[data-theme="light"] .back-link,
        body.light-theme .back-link {
            color: #0369a1;
        }
    </style>
</head>
<body>

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

    <main class="cashier-main">

        <!-- HERO TOP BAR -->
        <header class="cashier-hero-bar">
            <div class="hero-left">
                <h1>Products | Cashier POS</h1>
                <p>View available products, quantities, and total value at selling price.</p>
            </div>

            <div class="hero-nav">
                <div class="hero-actions">
                    <button type="button" class="theme-toggle-pill" id="themeToggle">
                        <span class="theme-toggle-pill-circle"></span>
                        <span id="themeToggleLabel">Dark</span>
                    </button>
                    <button class="hero-menu-btn" type="button" onclick="toggleCashierSidebar()">
                        ☰
                    </button>
                </div>
            </div>
        </header>

        <!-- PRODUCTS TABLE -->
        <section class="pos-table-card">
            <div class="pos-table-header">
                <div>
                    <h2>Product inventory</h2>
                    <p>
                        <?= $totalRows ? "Showing page $page of $totalPages" : "No products found." ?>
                    </p>

                    <div class="metric-strip">
                        <div class="metric-chip">
                            <span class="metric-label">Products (filtered):</span>
                            <span class="metric-value"><?= number_format($totalRows) ?></span>
                        </div>
                        <div class="metric-chip">
                            <span class="metric-label">Total quantity (all):</span>
                            <span class="metric-value"><?= number_format($grand_qty) ?></span>
                        </div>
                        <div class="metric-chip">
                            <span class="metric-label">Total value (all, selling):</span>
                            <span class="metric-value">KES <?= number_format($grand_value, 2) ?></span>
                        </div>
                    </div>
                </div>

                <div class="pos-controls">
                    <!-- SEARCH + CLEAR -->
                    <form method="GET" class="product-search">
                        <input
                            type="text"
                            name="q"
                            placeholder="Search by name or barcode"
                            value="<?= htmlspecialchars($search_raw) ?>"
                        >
                        <!-- Keep current limit when searching -->
                        <input type="hidden" name="limit"
                               value="<?= htmlspecialchars($is_all ? 'all' : (string)$limit, ENT_QUOTES) ?>">
                        <button type="submit">Search</button>

                        <?php if ($search !== ''): ?>
                            <a href="<?= htmlspecialchars($_SERVER['PHP_SELF']) ?>" class="clear-btn">Clear</a>
                        <?php endif; ?>
                    </form>

                    <!-- SHOW ENTRIES -->
                    <form method="GET" class="entries-form">
                        <?php if ($search !== ''): ?>
                            <input type="hidden" name="q" value="<?= htmlspecialchars($search_raw) ?>">
                        <?php endif; ?>
                        <label>Show</label>
                        <select name="limit" onchange="this.form.submit()">
                            <?php foreach ($limit_options as $opt): ?>
                                <option value="<?= $opt ?>"
                                    <?= ($is_all && $opt === 'all') || (!$is_all && (int)$limit === (int)$opt) ? 'selected' : '' ?>>
                                    <?= $opt === 'all' ? 'All' : $opt ?>
                                </option>
                            <?php endforeach; ?>
                        </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>Product</th>
                            <th>Barcode</th>
                            <th>Category</th>
                            <th>Quantity</th>
                            <th>Selling price (KES)</th>
                            <th>Total value (KES)</th>
                            <th>Created</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php
                        $page_qty   = 0;
                        $page_value = 0.0;

                        if ($products && $products->num_rows > 0):
                            while ($row = $products->fetch_assoc()):
                                $qty       = (int)$row['quantity'];
                                $price     = (float)$row['selling_price'];
                                $row_total = $qty * $price;

                                $page_qty   += $qty;
                                $page_value += $row_total;

                                $low_class = ($qty < 5) ? 'low-stock' : '';
                        ?>
                            <tr class="<?= $low_class ?>">
                                <td><?= (int)$row['id'] ?></td>
                                <td class="cell-left"><?= htmlspecialchars($row['name']) ?></td>
                                <td><?= htmlspecialchars($row['barcode']) ?></td>
                                <td class="cell-left"><?= htmlspecialchars($row['category']) ?></td>
                                <td><?= number_format($qty) ?></td>
                                <td><?= number_format($price, 2) ?></td>
                                <td><?= number_format($row_total, 2) ?></td>
                                <td><?= htmlspecialchars($row['date_added']) ?></td>
                            </tr>
                        <?php
                            endwhile;
                        ?>

                            <!-- Page totals -->
                            <tr class="totals-row">
                                <td colspan="4" style="text-align:right;">Page totals</td>
                                <td><?= number_format($page_qty) ?></td>
                                <td></td>
                                <td>KES <?= number_format($page_value, 2) ?></td>
                                <td></td>
                            </tr>

                            <!-- Grand totals -->
                            <tr class="totals-row">
                                <td colspan="4" style="text-align:right;">Grand totals (all products)</td>
                                <td><?= number_format($grand_qty) ?></td>
                                <td></td>
                                <td>KES <?= number_format($grand_value, 2) ?></td>
                                <td></td>
                            </tr>

                        <?php else: ?>
                            <tr>
                                <td colspan="8" class="empty-row">No products 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=<?= htmlspecialchars((string)$limit, ENT_QUOTES) ?>&q=<?= urlencode($search_raw) ?>">
                            <?= $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>

<script>
    // Theme toggler (same pattern as other cashier pages)
    (function () {
        const root = document.documentElement;
        const body = document.body;
        const toggleBtn = document.getElementById('themeToggle');
        const label = document.getElementById('themeToggleLabel');

        function applyTheme(theme) {
            root.setAttribute('data-theme', theme);
            body.setAttribute('data-theme', theme);
            body.classList.toggle('light-theme', theme === 'light');
            localStorage.setItem('cashierTheme', theme);
            if (label) {
                label.textContent = theme === 'light' ? 'Light' : 'Dark';
            }
        }

        function initTheme() {
            const saved = localStorage.getItem('cashierTheme');
            const initial = saved === 'light' || saved === 'dark' ? saved : 'dark';
            applyTheme(initial);
        }

        if (toggleBtn) {
            toggleBtn.addEventListener('click', function () {
                const current = root.getAttribute('data-theme') === 'light' ? 'light' : 'dark';
                const next = current === 'light' ? 'dark' : 'light';
                applyTheme(next);
            });
        }

        document.addEventListener('DOMContentLoaded', initTheme);
    })();
</script>

</body>
</html>
