<?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');

$username   = $_SESSION['username'] ?? 'User';
$page_title = "Cashier Dashboard";
$active     = 'dashboard'; // for top-nav highlight

$today = date('Y-m-d');

/* ----------------------------------------
   1. Today’s sales + receipts (this cashier)
----------------------------------------- */
$today_sales_total   = 0.0;
$today_receipt_count = 0;

$salesStmt = $conn->prepare("
    SELECT 
        COALESCE(SUM(total_sale), 0)  AS total_sales,
        COUNT(DISTINCT receipt_id)    AS receipts_count
    FROM sales
    WHERE DATE(sale_datetime) = ?
      AND cashier = ?
      AND refunded = 0
");
if ($salesStmt) {
    $salesStmt->bind_param("ss", $today, $username);
    $salesStmt->execute();
    $salesResult = $salesStmt->get_result();
    if ($row = $salesResult->fetch_assoc()) {
        $today_sales_total   = (float)$row['total_sales'];
        $today_receipt_count = (int)$row['receipts_count'];
    }
    $salesStmt->close();
}

/* ----------------------------------------
   2. Pending debts (all customers)
----------------------------------------- */
$pending_debts_total = 0.0;

$debtsQuery = $conn->query("
    SELECT COALESCE(SUM(amount - COALESCE(dp.total_paid, 0)), 0) AS outstanding
    FROM customer_debts d
    LEFT JOIN (
        SELECT debt_id, SUM(amount_paid) AS total_paid
        FROM debt_payments
        GROUP BY debt_id
    ) dp ON d.id = dp.debt_id
");
if ($debtsQuery && ($row = $debtsQuery->fetch_assoc())) {
    $pending_debts_total = (float)$row['outstanding'];
}

/* ----------------------------------------
   3. Shift status (cash summary for today)
----------------------------------------- */
$shift_status_label   = "Open";
$shift_status_caption = "Remember to submit cash summary before leaving.";
$shift_status_chip    = "Active shift";

$cashStmt = $conn->prepare("
    SELECT total_cash, summary_date
    FROM cash_summary
    WHERE cashier = ?
      AND DATE(summary_date) = ?
    ORDER BY summary_date DESC
    LIMIT 1
");
if ($cashStmt) {
    $cashStmt->bind_param("ss", $username, $today);
    $cashStmt->execute();
    $cashResult = $cashStmt->get_result();
    if ($row = $cashResult->fetch_assoc()) {
        $shift_status_label   = "Summary submitted";
        $shift_status_caption = "Last cash summary: KES " . number_format((float)$row['total_cash'], 2);
        $shift_status_chip    = "Shift closing done";
    }
    $cashStmt->close();
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <?php include 'cashier_head.php'; ?>

    <style>
        /* ensure accent vars exist even if not set in cashier_head */
        :root {
            --cash-accent-main: var(--cash-accent-main, #22d3ee);
            --cash-accent-soft: var(--cash-accent-soft, #7dd3fc);
        }

        /* wrapper around page content */
        .cashier-main {
            flex: 1;
            padding: 20px 24px 30px;
            min-width: 0;
        }

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

        .dashboard-inner {
            max-width: 1400px;
            margin: 0 auto;
            width: 100%;
            background:
                radial-gradient(circle at top left, rgba(34,211,238,0.10), transparent 55%),
                var(--cash-bg-card);
            border-radius: 16px;
            padding: 16px 18px 22px;
            border: 1px solid var(--cash-border-soft);
            box-shadow: 0 18px 40px rgba(0,0,0,0.55);
        }

        html[data-theme="light"] .dashboard-inner {
            background:
                radial-gradient(circle at top left, rgba(56,189,248,0.12), transparent 55%),
                var(--cash-bg-card);
            box-shadow: 0 10px 24px rgba(15,23,42,0.12);
            border-color: #dbeafe;
        }

        /* OVERVIEW HEADER */

        .overview-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 16px;
        }

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

        .overview-left h2 {
            font-size: 17px;
            font-weight: 600;
        }

        .overview-sub {
            font-size: 12px;
            color: var(--cash-text-muted);
        }

        html[data-theme="light"] .overview-sub {
            color: #475569; /* brighter content text */
        }

        .overview-pill {
            padding: 6px 14px;
            border-radius: 999px;
            border: 1px solid rgba(148,163,184,0.6);
            font-size: 11px;
            background:
                radial-gradient(circle at 0% 0%, rgba(34,211,238,0.28), transparent 60%),
                rgba(15,23,42,0.96);
            color: var(--cash-accent-soft);
            white-space: nowrap;
            display: inline-flex;
            align-items: center;
            gap: 6px;
        }

        html[data-theme="light"] .overview-pill {
            background:
                radial-gradient(circle at 0% 0%, rgba(56,189,248,0.20), transparent 60%),
                #eff6ff;
            color: #0369a1;
            border-color: rgba(148,163,184,0.8);
        }

        .overview-pill-dot {
            width: 7px;
            height: 7px;
            border-radius: 999px;
            background: #22c55e;
            box-shadow: 0 0 0 4px rgba(34,197,94,0.22);
        }

        @media (max-width: 700px) {
            .overview-header {
                flex-direction: column;
                align-items: flex-start;
                gap: 8px;
            }
        }

        /* STAT CARDS */

        .stat-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(230px, 1fr));
            gap: 14px;
            margin-bottom: 18px;
        }

        .stat-card {
            position: relative;
            background:
                radial-gradient(circle at 0 0, rgba(34,211,238,0.20), transparent 55%),
                var(--cash-bg-card);
            border-radius: 16px;
            padding: 12px 14px 14px;
            border: 1px solid rgba(148,163,184,0.40);
            box-shadow: 0 14px 30px rgba(0,0,0,0.55);
            overflow: hidden;
            transform-origin: center;
            transition:
                transform 0.15s ease-out,
                box-shadow 0.15s ease-out,
                border-color 0.15s ease-out;
        }

        html[data-theme="light"] .stat-card {
            box-shadow: 0 10px 22px rgba(15,23,42,0.12);
            border-color: rgba(148,163,184,0.55);
        }

        .stat-card:hover {
            transform: translateY(-2px);
            box-shadow: 0 18px 38px rgba(0,0,0,0.70);
            border-color: var(--cash-accent-soft);
        }

        html[data-theme="light"] .stat-card:hover {
            box-shadow: 0 16px 34px rgba(15,23,42,0.16);
        }

        .stat-header-row {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 2px;
        }

        .stat-label {
            font-size: 10px;
            text-transform: uppercase;
            letter-spacing: 0.1em;
            color: var(--cash-text-muted);
        }

        .stat-icon {
            width: 24px;
            height: 24px;
            border-radius: 999px;
            display: inline-flex;
            align-items: center;
            justify-content: center;
            font-size: 14px;
            background: rgba(15,23,42,0.65);
        }

        html[data-theme="light"] .stat-icon {
            background: #e5f3ff;
        }

        .stat-value-row {
            display: flex;
            align-items: baseline;
            gap: 6px;
        }

        .stat-value {
            font-size: 21px;
            font-weight: 600;
        }

        .stat-value.negative {
            color: #fecaca;
        }

        html[data-theme="light"] .stat-value.negative {
            color: #b91c1c;
        }

        .stat-chip {
            padding: 2px 7px;
            border-radius: 999px;
            border: 1px solid rgba(148,163,184,0.5);
            font-size: 9px;
            text-transform: uppercase;
            letter-spacing: 0.08em;
            color: var(--cash-text-muted);
            white-space: nowrap;
            background: rgba(15,23,42,0.85);
        }

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

        .stat-caption {
            font-size: 11px;
            color: var(--cash-text-muted);
            margin-top: 3px;
        }

        html[data-theme="light"] .stat-caption {
            color: #4b5563; /* clearer content text */
        }

        /* QUICK ACTIONS */

        .cashier-section-title {
            font-size: 14px;
            font-weight: 600;
            margin-bottom: 8px;
            display: flex;
            align-items: center;
            gap: 6px;
        }

        .cashier-section-title::before {
            content: "";
            width: 3px;
            height: 16px;
            border-radius: 999px;
            background: linear-gradient(to bottom, var(--cash-accent-main), var(--cash-accent-soft));
        }

        .cashier-cards {
            display: grid;
            grid-template-columns: repeat(3, minmax(0, 1fr));
            gap: 14px;
            align-items: stretch;
        }

        @media (max-width: 1100px) {
            .cashier-cards {
                grid-template-columns: repeat(2, minmax(0, 1fr));
            }
        }

        @media (max-width: 700px) {
            .cashier-cards {
                grid-template-columns: minmax(0, 1fr);
            }
        }

        .cash-card {
            background: var(--cash-bg-card);
            border-radius: 16px;
            padding: 12px 14px;
            border-left: 3px solid var(--cash-accent-main);
            box-shadow: 0 10px 24px rgba(0,0,0,0.45);
            display: flex;
            flex-direction: column;
            gap: 4px;
            min-height: 140px;
            transition:
                transform 0.15s ease-out,
                box-shadow 0.15s ease-out,
                border-color 0.15s ease-out,
                background 0.15s ease-out;
        }

        html[data-theme="light"] .cash-card {
            box-shadow: 0 8px 20px rgba(15,23,42,0.10);
        }

        .cash-card:hover {
            transform: translateY(-2px);
            box-shadow: 0 16px 32px rgba(0,0,0,0.65);
            border-color: var(--cash-accent-soft);
        }

        html[data-theme="light"] .cash-card:hover {
            box-shadow: 0 14px 30px rgba(15,23,42,0.16);
            background: #f9fafb;
        }

        .cash-card-title {
            display: flex;
            align-items: center;
            gap: 8px;
        }

        .cash-card-title span.icon {
            width: 26px;
            height: 26px;
            border-radius: 999px;
            display: inline-flex;
            align-items: center;
            justify-content: center;
            font-size: 15px;
            background: rgba(34,211,238,0.24);
        }

        html[data-theme="light"] .cash-card-title span.icon {
            background: #e0f7ff;
        }

        .cash-card-title h3 {
            font-size: 13px;
            margin: 0;
        }

        .cash-card p {
            margin: 0;
            font-size: 12px;
            color: var(--cash-text-muted);
        }

        html[data-theme="light"] .cash-card p {
            color: #475569; /* stronger for readability */
        }

        .cash-card a {
            margin-top: 6px;
            font-size: 11px;
            color: var(--cash-accent-soft);
            text-decoration: none;
            align-self: flex-start;
        }

        .cash-card a:hover {
            text-decoration: underline;
        }
    </style>
</head>
<body>

<div class="cashier-shell">

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

    <main class="cashier-main">
        <!-- TOP BAR (shared style from cashier_head.php) -->
        <div class="cashier-topbar">
            <div class="cashier-topbar-left">
                <h1><?= htmlspecialchars($page_title) ?></h1>
                <small>Quick snapshot of your sales and shift activity.</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 type="button" class="cashier-toggle" onclick="toggleCashierSidebar()">
                    ☰
                </button>
            </div>
        </div>

        <!-- DASHBOARD CONTENT -->
        <div class="dashboard-inner">

            <section>
                <div class="overview-header">
                    <div class="overview-left">
                        <h2>Welcome, <?= htmlspecialchars($username); ?></h2>
                        <p class="overview-sub">
                            Monitor your sales, receipts, cash summary, and important tasks for this shift.
                        </p>
                    </div>
                    <span class="overview-pill">
                        <span class="overview-pill-dot"></span>
                        Cashier mode · <?= date('d M Y'); ?>
                    </span>
                </div>

                <!-- LIVE stats row -->
                <div class="stat-grid">
                    <article class="stat-card">
                        <div class="stat-header-row">
                            <div class="stat-label">Today’s sales</div>
                            <div class="stat-icon">💵</div>
                        </div>
                        <div class="stat-value-row">
                            <div class="stat-value">
                                KES <?= number_format($today_sales_total, 2); ?>
                            </div>
                            <span class="stat-chip">Your shift</span>
                        </div>
                        <div class="stat-caption">
                            Live total from all your completed transactions today.
                        </div>
                    </article>

                    <article class="stat-card">
                        <div class="stat-header-row">
                            <div class="stat-label">Receipts issued</div>
                            <div class="stat-icon">🧾</div>
                        </div>
                        <div class="stat-value-row">
                            <div class="stat-value">
                                <?= $today_receipt_count; ?>
                            </div>
                            <span class="stat-chip">Distinct receipts</span>
                        </div>
                        <div class="stat-caption">
                            Number of unique receipts completed under your login today.
                        </div>
                    </article>

                    <article class="stat-card">
                        <div class="stat-header-row">
                            <div class="stat-label">Pending debts</div>
                            <div class="stat-icon">💳</div>
                        </div>
                        <div class="stat-value-row">
                            <div class="stat-value <?= $pending_debts_total > 0 ? 'negative' : ''; ?>">
                                KES <?= number_format($pending_debts_total, 2); ?>
                            </div>
                            <span class="stat-chip">All customers</span>
                        </div>
                        <div class="stat-caption">
                            Outstanding customer balances across the shop.
                        </div>
                    </article>

                    <article class="stat-card">
                        <div class="stat-header-row">
                            <div class="stat-label">Shift status</div>
                            <div class="stat-icon">⏱️</div>
                        </div>
                        <div class="stat-value-row">
                            <div class="stat-value">
                                <?= htmlspecialchars($shift_status_label); ?>
                            </div>
                            <span class="stat-chip">
                                <?= htmlspecialchars($shift_status_chip); ?>
                            </span>
                        </div>
                        <div class="stat-caption">
                            <?= htmlspecialchars($shift_status_caption); ?>
                        </div>
                    </article>
                </div>

                <!-- Feature shortcuts -->
                <h3 class="cashier-section-title">Quick cashier actions</h3>
                <div class="cashier-cards">

                    <article class="cash-card">
                        <div class="cash-card-title">
                            <span class="icon">🧾</span>
                            <h3>Record sales</h3>
                        </div>
                        <p>Open the sales screen, select products, adjust quantities or discounts, and issue receipts.</p>
                        <a href="record_sales.php">Go to record sales →</a>
                    </article>

                    <article class="cash-card">
                        <div class="cash-card-title">
                            <span class="icon">📅</span>
                            <h3>Today’s sales summary</h3>
                        </div>
                        <p>Review all sales recorded today, including totals, payment methods, and refunds.</p>
                        <a href="cashier_view_daily_sales.php">View today’s sales →</a>
                    </article>

                    <article class="cash-card">
                        <div class="cash-card-title">
                            <span class="icon">📂</span>
                            <h3>Transaction history</h3>
                        </div>
                        <p>Search previous receipts when customers or managers need clarifications.</p>
                        <a href="transaction_history.php">Browse history →</a>
                    </article>

                    <article class="cash-card">
                        <div class="cash-card-title">
                            <span class="icon">💵</span>
                            <h3>Cash summary</h3>
                        </div>
                        <p>Submit cash at hand and mobile money to reconcile the till for this shift.</p>
                        <a href="submit_cash_summary.php">Submit cash summary →</a>
                    </article>

                    <article class="cash-card">
                        <div class="cash-card-title">
                            <span class="icon">⚠️</span>
                            <h3>Damaged products</h3>
                        </div>
                        <p>Log damaged or expired stock so inventory and loss reports stay accurate.</p>
                        <a href="add_damages.php">Record damages →</a>
                    </article>

                    <article class="cash-card">
                        <div class="cash-card-title">
                            <span class="icon">💳</span>
                            <h3>Customer debts</h3>
                        </div>
                        <p>Create new customer debts and record repayments when they clear their balances.</p>
                        <a href="customer_debts.php">Manage debts →</a>
                    </article>

                </div>

            </section>

        </div>
    </main>
</div>

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

</body>
</html>
