<?php  
session_start();

// Block unauthorized access
if (!isset($_SESSION['username']) || ($_SESSION['role'] ?? '') !== 'admin') {
    header("Location: login.php?error=Unauthorized access");
    exit();
}

require 'db_connect.php';

date_default_timezone_set('Africa/Nairobi');
$today      = date('Y-m-d');
$page_title = "Admin Dashboard";

/* ----------------------------------
   1. Today’s total sales & profit
----------------------------------- */
$today_total_sales  = 0.0;
$today_total_profit = 0.0;

$salesTotals = $conn->query("
    SELECT 
        COALESCE(SUM(total_sale), 0) AS total_sales,
        COALESCE(SUM(profit),     0) AS total_profit
    FROM sales
    WHERE DATE(sale_datetime) = '$today'
      AND refunded = 0
");

if ($salesTotals && $row = $salesTotals->fetch_assoc()) {
    $today_total_sales  = (float)$row['total_sales'];
    $today_total_profit = (float)$row['total_profit'];
}

/* ----------------------------------
   2. Latest cash summary (any cashier)
----------------------------------- */
$last_cash_summary = null;

$cashRes = $conn->query("
    SELECT cashier, cash_at_hand, cash_at_phone, total_cash, summary_date
    FROM cash_summary
    ORDER BY summary_date DESC
    LIMIT 1
");
if ($cashRes && $cashRes->num_rows > 0) {
    $last_cash_summary = $cashRes->fetch_assoc();
}

/* ----------------------------------
   3. Total outstanding customer debts
      (amount - sum(payments))
----------------------------------- */
$outstanding_debts = 0.0;
$debts_count       = 0;

$debtsRes = $conn->query("
    SELECT 
        COALESCE(SUM(d.amount - IFNULL(dp.total_paid, 0)), 0) AS outstanding,
        COUNT(*) AS num_debts
    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 ($debtsRes && $row = $debtsRes->fetch_assoc()) {
    $outstanding_debts = (float)$row['outstanding'];
    $debts_count       = (int)$row['num_debts'];
}

/* ----------------------------------
   4. Low stock products (qty <= 10)
----------------------------------- */
$low_stock_threshold = 10;
$low_stock_products  = [];

$lowRes = $conn->query("
    SELECT id, name, quantity, selling_price
    FROM products
    WHERE quantity <= $low_stock_threshold
    ORDER BY quantity ASC, name ASC
    LIMIT 10
");

if ($lowRes && $lowRes->num_rows > 0) {
    while ($row = $lowRes->fetch_assoc()) {
        $low_stock_products[] = $row;
    }
}

/* ----------------------------------
   5. Top & Bottom selling products
   Using the real `sales` table
----------------------------------- */

$top_selling_products    = [];
$bottom_selling_products = [];

/* TOP 5 – by quantity sold (descending) */
$topRes = $conn->query("
    SELECT 
        p.id,
        p.name,
        p.selling_price,
        COALESCE(SUM(s.quantity), 0)     AS total_qty,
        COALESCE(SUM(s.total_sale), 0)   AS total_amount
    FROM products p
    JOIN sales s ON s.product_id = p.id
    WHERE s.refunded = 0
      AND s.total_sale > 0
    GROUP BY p.id, p.name, p.selling_price
    HAVING total_qty > 0
    ORDER BY total_qty DESC
    LIMIT 5
");

if ($topRes && $topRes->num_rows > 0) {
    while ($row = $topRes->fetch_assoc()) {
        $top_selling_products[] = $row;
    }
}

/* BOTTOM 5 – by quantity sold (ascending) */
$bottomRes = $conn->query("
    SELECT 
        p.id,
        p.name,
        p.selling_price,
        COALESCE(SUM(s.quantity), 0)     AS total_qty,
        COALESCE(SUM(s.total_sale), 0)   AS total_amount
    FROM products p
    JOIN sales s ON s.product_id = p.id
    WHERE s.refunded = 0
      AND s.total_sale > 0
    GROUP BY p.id, p.name, p.selling_price
    HAVING total_qty > 0
    ORDER BY total_qty ASC
    LIMIT 5
");

if ($bottomRes && $bottomRes->num_rows > 0) {
    while ($row = $bottomRes->fetch_assoc()) {
        $bottom_selling_products[] = $row;
    }
}

include('head.php'); // outputs <!DOCTYPE html>, <head> etc.
?>

<body data-theme="dark"><!-- default theme is dark, JS will overwrite from localStorage -->

<style>
/* ============================================================
   THEME VARIABLES FOR ADMIN DASHBOARD
   ============================================================ */

/* ----- DARK THEME ----- */
body[data-theme="dark"] {
    --cash-bg-main: #001f3f;
    --cash-bg-card: #012a57;

    --cash-panel-grad-from: #064ab8;
    --cash-panel-grad-mid: #022a6b;
    --cash-panel-grad-to:   #021d53;

    --cash-text-main: #F9FAFB;
    --cash-text-muted: #9CA3AF;
    --cash-accent: #00ffef;
    --cash-border-soft: rgba(130,238,253,0.45);

    --cash-table-head-bg: #012a73;
    --cash-table-row-bg: #012a57;
    --cash-table-row-hover-bg: #001f3f;

    --bg-sidebar: #001731;
}

/* ----- LIGHT THEME (BLACK & GOLD) ----- */
body[data-theme="light"] {
    --cash-bg-main: #f5f5f4;
    --cash-bg-card: #ffffff;

    --cash-panel-grad-from: #fff7e6;
    --cash-panel-grad-mid:  #fde68a;
    --cash-panel-grad-to:   #fbbf24;

    --cash-text-main: #111827;
    --cash-text-muted: #4b5563;
    --cash-accent: #b45309;
    --cash-border-soft: rgba(180,83,9,0.45);

    /* softer golden header for tables in light mode */
    --cash-table-head-bg: #fbbf24;
    --cash-table-row-bg: #ffffff;
    --cash-table-row-hover-bg: #fef3c7;

    --bg-sidebar: #111827;
}

/* ============================================================
   SIDEBAR LAYOUT
   ============================================================ */

.sidebar {
    font-family: 'Poppins', sans-serif;
    width: 250px; /* expanded width */
    background: linear-gradient(
        180deg,
        var(--bg-sidebar, #020617) 0%,
        #021d53 40%,
        #000814 100%
    );
    height: 100vh;
    position: fixed;
    left: 0;
    top: 0;
    padding: 18px 14px 20px;
    overflow-y: auto;
    transition: width 0.25s ease, box-shadow 0.25s ease;
    box-shadow: 4px 0 18px rgba(0, 0, 0, 0.55);
    border-right: 1px solid rgba(148,163,184,0.45);
    display: flex;
    flex-direction: column;
    z-index: 999;
}

/* collapsed state */
.sidebar.collapsed {
    width: 78px;
}

/* HEADER / BRAND */
.sidebar-header {
    display: flex;
    align-items: center;
    gap: 10px;
    padding: 0 6px 14px;
    border-bottom: 1px solid rgba(148,163,184,0.35);
}

.sidebar-logo {
    width: 34px;
    height: 34px;
    border-radius: 999px;
    background: radial-gradient(circle at 30% 20%, #facc15, #b45309);
    display: flex;
    align-items: center;
    justify-content: center;
    font-weight: 700;
    font-size: 16px;
    color: #0b1020;
    box-shadow: 0 0 0 3px rgba(248, 250, 109, 0.35);
}

.sidebar-title-main {
    font-size: 15px;
    font-weight: 600;
    color: #e5e7eb;
    transition: opacity 0.2s ease, transform 0.2s ease;
}

.sidebar-title-sub {
    font-size: 11px;
    text-transform: uppercase;
    letter-spacing: 0.14em;
    color: rgba(148,163,184,0.9);
    transition: opacity 0.2s ease, transform 0.2s ease;
}

.sidebar.collapsed .sidebar-header {
    justify-content: center;
}

.sidebar.collapsed .sidebar-title-main,
.sidebar.collapsed .sidebar-title-sub {
    opacity: 0;
    transform: translateX(-8px);
    pointer-events: none;
    display: none;
}

/* MENU */
.sidebar-menu {
    margin-top: 16px;
    padding: 0;
    list-style: none;
    flex: 1; /* pushes logout to bottom */
}

.sidebar-link {
    display: flex;
    align-items: center;
    gap: 10px;
    padding: 9px 12px;
    margin: 4px 2px;
    border-radius: 9px;
    color: #e5e7eb;
    text-decoration: none;
    font-size: 14px;
    line-height: 1.2;
    position: relative;
    transition:
        background 0.2s ease,
        color 0.2s ease,
        transform 0.15s ease,
        box-shadow 0.2s ease;
}

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

/* long names: wrap instead of disappearing */
.sidebar-text {
    flex: 1;
    white-space: normal;
    word-wrap: break-word;
    transition: opacity 0.2s ease, transform 0.2s ease;
}

/* hover / active state */
.sidebar-link:hover {
    background: radial-gradient(circle at top left, rgba(56,189,248,0.18), transparent 60%);
    color: #f9fafb;
    box-shadow: 0 4px 14px rgba(15,23,42,0.9);
    transform: translateX(4px);
}

.sidebar-link.active {
    background: linear-gradient(90deg, rgba(59,130,246,0.9), rgba(56,189,248,0.95));
    color: #0b1020;
    box-shadow: 0 4px 18px rgba(37,99,235,0.75);
}

.sidebar-link.active .sidebar-icon {
    background: rgba(15,23,42,0.05);
}

/* collapsed: icons stay centered, text hidden */
.sidebar.collapsed .sidebar-link {
    justify-content: center;
    padding-inline: 10px;
}

.sidebar.collapsed .sidebar-text {
    opacity: 0;
    transform: translateX(-8px);
    pointer-events: none;
    display: none;
}

/* FOOTER / LOGOUT */
.sidebar-footer {
    margin-top: 10px;
    padding-top: 10px;
    border-top: 1px solid rgba(15,23,42,0.6);
}

.sidebar-logout {
    color: #fecaca;
}

.sidebar-logout .sidebar-icon {
    background: rgba(127,29,29,0.85);
}

.sidebar-logout:hover {
    background: radial-gradient(circle at top left, rgba(248,113,113,0.38), transparent 60%);
    color: #fee2e2;
}

/* LIGHT THEME – SIDEBAR */
body[data-theme="light"] .sidebar {
    background: linear-gradient(
        180deg,
        #fefce8 0%,
        #fef3c7 40%,
        #f9fafb 100%
    );
    border-right: 1px solid rgba(180,83,9,0.6);
    box-shadow: 4px 0 16px rgba(15,23,42,0.25);
}

body[data-theme="light"] .sidebar-title-main {
    color: #b45309;
}

body[data-theme="light"] .sidebar-title-sub {
    color: #6b7280;
}

body[data-theme="light"] .sidebar-link {
    color: #111827;
}

body[data-theme="light"] .sidebar-link:hover {
    background: rgba(254,243,199,0.95);
    color: #b45309;
    box-shadow: 0 3px 10px rgba(180,83,9,0.35);
}

body[data-theme="light"] .sidebar-link.active {
    background: linear-gradient(90deg, #fbbf24, #f59e0b);
    color: #111827;
    box-shadow: 0 4px 14px rgba(180,83,9,0.5);
}

body[data-theme="light"] .sidebar-icon {
    background: rgba(243,244,246,0.95);
}

body[data-theme="light"] .sidebar-logout {
    color: #b91c1c;
}
body[data-theme="light"] .sidebar-logout:hover {
    background: rgba(254,226,226,0.95);
}

/* ============================================================
   BASE LAYOUT
   ============================================================ */

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

.main-content {
    min-height: 100vh;
    padding: 24px 26px;
    background:
        radial-gradient(circle at top left, rgba(0,255,239,0.08), transparent 55%),
        var(--cash-bg-main);
    transition: margin-left 0.3s ease;
    margin-left: 250px; /* match expanded sidebar */
}

/* when sidebar is collapsed, pull content closer */
.sidebar.collapsed + .main-content {
    margin-left: 78px;
}

/* ============================================================
   TOPBAR
   ============================================================ */

.topbar {
    background: var(--bg-sidebar, #001731);
    padding: 14px 18px;
    margin: -10px -6px 18px;
    border-radius: 12px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    border: 1px solid rgba(184,134,11,0.65);
    box-shadow: 0 6px 18px rgba(0,0,0,0.5);
    color: #f9fafb;
}

.topbar-left {
    display: flex;
    align-items: center;
    gap: 10px;
}

.topbar-title {
    font-weight: 600;
    font-size: 15px;
    letter-spacing: 0.03em;
}

.topbar-right {
    display: flex;
    align-items: center;
    gap: 10px;
    font-size: 13px;
}

.topbar-user strong {
    font-weight: 600;
}

.menu-btn {
    font-size: 22px;
    cursor: pointer;
    color: var(--accent-gold, #f4b400);
    transition: 0.3s;
    line-height: 1;
}

.menu-btn:hover {
    color: #e6c34b;
}

.theme-toggle {
    border-radius: 999px;
    border: 1px solid rgba(184,134,11,0.7);
    padding: 6px 12px;
    background: rgba(0,0,0,0.4);
    color: #f9f9f9;
    font-size: 12px;
    cursor: pointer;
}

.theme-toggle:hover {
    background: rgba(0,0,0,0.65);
}

/* ============================================================
   DASHBOARD SHELL
   ============================================================ */

.container-box.admin-dashboard {
    max-width: 1600px;
    margin: 0 auto;
    background: rgba(0,23,48,0.92);
    border-radius: 18px;
    padding: 20px 22px 26px;
    border: 1px solid rgba(130,238,253,0.35);
    box-shadow: 0 22px 50px rgba(0,0,0,0.65);
    backdrop-filter: blur(14px);
}

/* ============================================================
   HEADER
   ============================================================ */

.dashboard-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    gap: 16px;
    margin-bottom: 22px;
    padding-bottom: 12px;
    border-bottom: 1px solid rgba(148,163,184,0.35);
}

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

.dashboard-header-title {
    display: flex;
    align-items: center;
    gap: 8px;
}

.dashboard-header-dot {
    width: 9px;
    height: 9px;
    border-radius: 999px;
    background: radial-gradient(circle at 30% 30%, #82EEFD, #00ffef);
    box-shadow: 0 0 0 6px rgba(0,255,239,0.25);
}

.dashboard-header h2 {
    font-size: 22px;
    font-weight: 600;
    letter-spacing: 0.02em;
}

.dashboard-header p {
    font-size: 13px;
    color: var(--cash-text-muted);
    max-width: 620px;
}

.dashboard-pill {
    padding: 7px 16px;
    border-radius: 999px;
    border: 1px solid rgba(130,238,253,0.6);
    font-size: 12px;
    background:
        radial-gradient(circle at 0% 0%, rgba(0,255,239,0.24), transparent 60%),
        rgba(0,23,48,0.9);
    color: #82EEFD;
    white-space: nowrap;
    display: inline-flex;
    align-items: center;
    gap: 6px;
}

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

/* ============================================================
   METRIC CARDS
   ============================================================ */

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

.metric-card {
    position: relative;
    background: linear-gradient(
        135deg,
        var(--cash-panel-grad-from) 0%,
        var(--cash-panel-grad-mid) 55%,
        var(--cash-panel-grad-to) 100%
    );
    border-radius: 16px;
    padding: 14px 16px 16px;
    border: 1px solid var(--cash-border-soft);
    box-shadow: 0 16px 40px rgba(0,0,0,0.55);
    overflow: hidden;
    display: flex;
    flex-direction: column;
    gap: 6px;
    transform-origin: center;
    transition:
        transform 0.16s ease-out,
        box-shadow 0.16s ease-out,
        border-color 0.16s ease-out;
}

.metric-card::after {
    content: "";
    position: absolute;
    left: 0;
    right: 0;
    bottom: -12px;
    height: 40px;
    background:
        linear-gradient(90deg, rgba(0,255,239,0.2), rgba(0,112,255,0.35)),
        radial-gradient(circle at top, rgba(255,255,255,0.3), transparent 60%);
    opacity: 0.45;
    pointer-events: none;
}

.metric-card:hover {
    transform: translateY(-2px);
    box-shadow: 0 20px 46px rgba(0,0,0,0.75);
    border-color: rgba(130,238,253,0.9);
}

.metric-header-row {
    display: flex;
    justify-content: space-between;
    align-items: center;
    gap: 8px;
}

.metric-label {
    font-size: 11px;
    text-transform: uppercase;
    letter-spacing: 0.12em;
    color: var(--cash-text-muted);
}

.metric-icon {
    width: 28px;
    height: 28px;
    border-radius: 999px;
    display: inline-flex;
    align-items: center;
    justify-content: center;
    background: radial-gradient(circle at 30% 20%, rgba(255,255,255,0.8), rgba(130,238,253,0.25));
    font-size: 15px;
}

.metric-main {
    display: flex;
    align-items: baseline;
    justify-content: space-between;
    gap: 8px;
    margin-top: 4px;
}

.metric-value {
    font-size: 24px;
    font-weight: 600;
}

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

.metric-chip {
    padding: 3px 9px;
    border-radius: 999px;
    border: 1px solid rgba(148,163,184,0.5);
    font-size: 10px;
    text-transform: uppercase;
    letter-spacing: 0.08em;
    color: #cbd5f5;
    background: rgba(0,23,48,0.9);
    display: inline-flex;
    align-items: center;
    gap: 4px;
    white-space: nowrap;
}

.metric-caption {
    font-size: 12px;
    color: var(--cash-text-muted);
    margin-top: 2px;
}

/* ============================================================
   LOWER GRID (PANELS)
   ============================================================ */

.lower-grid {
    display: grid;
    grid-template-columns: minmax(0, 1.1fr) minmax(0, 1.1fr);
    gap: 18px;
    margin-bottom: 22px;
}

.panel-card {
    background: linear-gradient(
        135deg,
        var(--cash-panel-grad-from) 0%,
        var(--cash-panel-grad-mid) 55%,
        var(--cash-panel-grad-to) 100%
    );
    border-radius: 18px;
    padding: 16px 18px 18px;
    border: 1px solid rgba(130,238,253,0.5);
    box-shadow: 0 20px 45px rgba(0,0,0,0.6);
}

.panel-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 10px;
    gap: 10px;
}

.panel-header-left {
    display: flex;
    align-items: center;
    gap: 8px;
}

.panel-header-icon {
    width: 20px;
    height: 20px;
    border-radius: 6px;
    background: rgba(0,0,0,0.24);
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 13px;
}

.panel-header h3 {
    font-size: 16px;
    font-weight: 600;
}

.panel-header small {
    font-size: 12px;
    color: #c3d8ff;
}

.panel-body {
    font-size: 13px;
    color: #E9F5FF;
}

.summary-grid {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
    gap: 10px;
    margin-top: 8px;
}

.summary-item {
    background: rgba(0,26,80,0.8);
    border-radius: 12px;
    padding: 8px 10px;
    border: 1px solid rgba(148,163,184,0.4);
}

.summary-label {
    font-size: 11px;
    text-transform: uppercase;
    letter-spacing: 0.06em;
    color: #9CA3AF;
    margin-bottom: 3px;
}

.summary-value {
    font-size: 13px;
    font-weight: 500;
}

/* ============================================================
   TABLE STYLES
   ============================================================ */

.low-stock-table {
    width: 100%;
    border-collapse: collapse;
    margin-top: 8px;
    font-size: 13px;
    border-radius: 12px;
    overflow: hidden;
}

.low-stock-table th,
.low-stock-table td {
    padding: 8px 8px;
    text-align: left;
    border-bottom: 1px solid rgba(148,163,184,0.35);
    color: #E9F5FF;
}

.low-stock-table th {
    background: #012a73;
    font-weight: 600;
    font-size: 12px;
    text-transform: uppercase;
    letter-spacing: 0.08em;
}

.low-stock-table tbody tr:hover {
    background: rgba(0,23,64,0.75);
}

.badge-low {
    padding: 3px 8px;
    border-radius: 999px;
    background: rgba(248, 250, 109, 0.1);
    border: 1px solid rgba(250, 204, 21, 0.8);
    font-size: 11px;
    color: #facc15;
}

.badge-ok {
    padding: 3px 8px;
    border-radius: 999px;
    background: rgba(34,197,94,0.14);
    border: 1px solid rgba(34,197,94,0.8);
    font-size: 11px;
    color: #bbf7d0;
}

/* ============================================================
   RESPONSIVE
   ============================================================ */

@media (max-width: 900px) {
    .main-content {
        padding: 18px 14px;
    }
    .dashboard-header {
        flex-direction: column;
        align-items: flex-start;
    }
    .dashboard-pill {
        align-self: flex-start;
    }
    .lower-grid {
        grid-template-columns: minmax(0,1fr);
    }
    .topbar {
        flex-direction: column;
        align-items: flex-start;
        gap: 8px;
    }
}

/* ============================================================
   LIGHT THEME – OTHER COMPONENTS
   ============================================================ */

/* 🔆 Light topbar: warm cream background, dark text */
body[data-theme="light"] .topbar {
    background: linear-gradient(90deg, #fefce8, #fef3c7);
    color: #111827;
    border-color: rgba(180,83,9,0.35);
    box-shadow: 0 6px 14px rgba(15,23,42,0.12);
}
body[data-theme="light"] .topbar-title {
    color: #b45309;
}
body[data-theme="light"] .topbar-user strong {
    color: #b45309;
}
body[data-theme="light"] .theme-toggle {
    background: #111827;
    color: #fef3c7;
    border-color: #b45309;
}

body[data-theme="light"] .container-box.admin-dashboard {
    background: #ffffff;
    border-color: rgba(180,83,9,0.45);
    box-shadow: 0 18px 40px rgba(15,23,42,0.25);
}

body[data-theme="light"] .dashboard-header h2 {
    color: #b45309;
}
body[data-theme="light"] .dashboard-header-dot {
    background: #fbbf24;
    box-shadow: 0 0 0 6px rgba(251,191,36,0.5);
}
body[data-theme="light"] .dashboard-header p {
    color: var(--cash-text-muted);
}
body[data-theme="light"] .dashboard-pill {
    background: #111827;
    color: #fef3c7;
    border-color: #b45309;
}
body[data-theme="light"] .dashboard-pill-dot {
    box-shadow: 0 0 0 4px rgba(34,197,94,0.4);
}

body[data-theme="light"] .metric-card {
    box-shadow: 0 12px 26px rgba(15,23,42,0.18);
    background:
        radial-gradient(circle at top left, rgba(251,191,36,0.14), transparent 55%),
        var(--cash-bg-card);
    border-color: rgba(180,83,9,0.4);
}
body[data-theme="light"] .metric-card::after {
    background: linear-gradient(90deg, rgba(251,191,36,0.3), rgba(217,119,6,0.35));
}
body[data-theme="light"] .metric-icon {
    background: radial-gradient(circle at 30% 20%, #fef3c7, #fbbf24);
    color: #111827;
}
body[data-theme="light"] .metric-label,
body[data-theme="light"] .metric-caption {
    color: var(--cash-text-muted);
}
body[data-theme="light"] .metric-value {
    color: #111827;
}
body[data-theme="light"] .metric-chip {
    background: #111827;
    color: #fef3c7;
    border-color: rgba(15,23,42,0.8);
}

body[data-theme="light"] .panel-card {
    box-shadow: 0 16px 30px rgba(15,23,42,0.18);
    border-color: rgba(180,83,9,0.5);
}
body[data-theme="light"] .panel-header h3 {
    color: #111827;
}
body[data-theme="light"] .panel-header small {
    color: #374151;
}
body[data-theme="light"] .panel-header-icon {
    background: rgba(0,0,0,0.2);
    color: #fbbf24;
}
body[data-theme="light"] .panel-body {
    color: #111827;
}
body[data-theme="light"] .summary-item {
    background: #fefce8;
    border-color: rgba(180,83,9,0.5);
    color: #111827;
}
body[data-theme="light"] .summary-label {
    color: #6b7280;
}

/* 🔆 Softer table header in light theme */
body[data-theme="light"] .low-stock-table th,
body[data-theme="light"] .low-stock-table td {
    color: #111827;
}
body[data-theme="light"] .low-stock-table th {
    background: #fbbf24;
    color: #111827;
    border-color: rgba(180,83,9,0.8);
}
body[data-theme="light"] .low-stock-table tbody tr {
    background: #ffffff;
}
body[data-theme="light"] .low-stock-table tbody tr:hover {
    background: var(--cash-table-row-hover-bg);
}
</style>

<?php include('sidebar.php'); ?>

<div class="main-content" id="main">

    <div class="topbar">
        <div class="topbar-left">
            <span class="menu-btn" onclick="toggleAdminSidebar()">☰</span>
            <span class="topbar-title">Admin Panel</span>
        </div>
        <div class="topbar-right">
            <button class="theme-toggle" type="button" onclick="toggleAdminTheme()">
                🌓 Theme
            </button>
            <span class="topbar-user">
                Logged in as <strong><?= htmlspecialchars($_SESSION['username'] ?? 'Admin'); ?></strong>
            </span>
        </div>
    </div>

    <div class="container-box admin-dashboard">

        <div class="dashboard-header">
            <div class="dashboard-header-left">
                <div class="dashboard-header-title">
                    <span class="dashboard-header-dot"></span>
                    <h2>Admin Dashboard</h2>
                </div>
                <p>Overview of today’s sales, profits, cash summary, and inventory health.</p>
            </div>
            <span class="dashboard-pill">
                <span class="dashboard-pill-dot"></span>
                Admin mode · <?= date('d M Y'); ?>
            </span>
        </div>

        <!-- TOP METRIC CARDS -->
        <div class="metrics-grid">

            <article class="metric-card">
                <div class="metric-header-row">
                    <div class="metric-label">Total sales (today)</div>
                    <div class="metric-icon">💵</div>
                </div>
                <div class="metric-main">
                    <div class="metric-value">
                        KES <?= number_format($today_total_sales, 2); ?>
                    </div>
                    <span class="metric-chip">
                        <span>●</span> All cashiers
                    </span>
                </div>
                <div class="metric-caption">
                    Gross value of all completed, non-refunded sales for <?= htmlspecialchars($today); ?>.
                </div>
            </article>

            <article class="metric-card">
                <div class="metric-header-row">
                    <div class="metric-label">Total profit (today)</div>
                    <div class="metric-icon">📈</div>
                </div>
                <div class="metric-main">
                    <div class="metric-value <?= $today_total_profit < 0 ? 'negative' : ''; ?>">
                        KES <?= number_format($today_total_profit, 2); ?>
                    </div>
                    <span class="metric-chip">
                        <span>✓</span> After cost
                    </span>
                </div>
                <div class="metric-caption">
                    Sum of (selling price − buying price) × quantity for today’s sales.
                </div>
            </article>

            <article class="metric-card">
                <div class="metric-header-row">
                    <div class="metric-label">Outstanding customer debts</div>
                    <div class="metric-icon">📋</div>
                </div>
                <div class="metric-main">
                    <div class="metric-value">
                        KES <?= number_format($outstanding_debts, 2); ?>
                    </div>
                    <span class="metric-chip">
                        <?= $debts_count; ?> active account<?= $debts_count == 1 ? '' : 's'; ?>
                    </span>
                </div>
                <div class="metric-caption">
                    Total unpaid balance across all customer debts.
                </div>
            </article>

            <article class="metric-card">
                <div class="metric-header-row">
                    <div class="metric-label">Low stock items</div>
                    <div class="metric-icon">📦</div>
                </div>
                <div class="metric-main">
                    <div class="metric-value">
                        <?= count($low_stock_products); ?>
                    </div>
                    <span class="metric-chip">
                        Qty ≤ <?= $low_stock_threshold; ?>
                    </span>
                </div>
                <div class="metric-caption">
                    Products at or below the reorder level and may need attention.
                </div>
            </article>

        </div>

        <!-- LOWER GRID: CASH SUMMARY + LOW STOCK -->
        <div class="lower-grid">

            <section class="panel-card">
                <div class="panel-header">
                    <div class="panel-header-left">
                        <div class="panel-header-icon">💰</div>
                        <div>
                            <h3>Last Cash Summary</h3>
                            <small>Most recent end-of-shift cash report from any cashier.</small>
                        </div>
                    </div>
                </div>

                <div class="panel-body">
                    <?php if ($last_cash_summary): ?>
                        <div class="summary-grid">
                            <div class="summary-item">
                                <div class="summary-label">Cashier</div>
                                <div class="summary-value">
                                    <?= htmlspecialchars($last_cash_summary['cashier']); ?>
                                </div>
                            </div>
                            <div class="summary-item">
                                <div class="summary-label">Cash at hand</div>
                                <div class="summary-value">
                                    KES <?= number_format($last_cash_summary['cash_at_hand'], 2); ?>
                                </div>
                            </div>
                            <div class="summary-item">
                                <div class="summary-label">Cash at phone</div>
                                <div class="summary-value">
                                    KES <?= number_format($last_cash_summary['cash_at_phone'], 2); ?>
                                </div>
                            </div>
                            <div class="summary-item">
                                <div class="summary-label">Total cash</div>
                                <div class="summary-value">
                                    KES <?= number_format($last_cash_summary['total_cash'], 2); ?>
                                </div>
                            </div>
                            <div class="summary-item">
                                <div class="summary-label">Submitted on</div>
                                <div class="summary-value">
                                    <?= date('d M Y, H:i', strtotime($last_cash_summary['summary_date'])); ?>
                                </div>
                            </div>
                        </div>
                    <?php else: ?>
                        <p style="color:#c3d8ff; margin-top:6px;">
                            No cash summary has been submitted yet.
                        </p>
                    <?php endif; ?>
                </div>
            </section>

            <section class="panel-card">
                <div class="panel-header">
                    <div class="panel-header-left">
                        <div class="panel-header-icon">📦</div>
                        <div>
                            <h3>Low Stock Products</h3>
                            <small>Items at or below <?= $low_stock_threshold; ?> units (top 10).</small>
                        </div>
                    </div>
                </div>

                <div class="panel-body">
                    <?php if (count($low_stock_products) > 0): ?>
                        <table class="low-stock-table">
                            <thead>
                                <tr>
                                    <th>Product</th>
                                    <th>Qty</th>
                                    <th>Selling price</th>
                                    <th>Status</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php foreach ($low_stock_products as $p): ?>
                                    <tr>
                                        <td><?= htmlspecialchars($p['name']); ?></td>
                                        <td><?= (int)$p['quantity']; ?></td>
                                        <td>KES <?= number_format($p['selling_price'], 2); ?></td>
                                        <td>
                                            <?php if ($p['quantity'] <= 0): ?>
                                                <span class="badge-low">Out of stock</span>
                                            <?php elseif ($p['quantity'] <= $low_stock_threshold): ?>
                                                <span class="badge-low">Low stock</span>
                                            <?php else: ?>
                                                <span class="badge-ok">OK</span>
                                            <?php endif; ?>
                                        </td>
                                    </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    <?php else: ?>
                        <p style="color:#c3d8ff; margin-top:6px;">
                            No products are currently at or below the low stock threshold.
                        </p>
                    <?php endif; ?>
                </div>
            </section>

        </div>

        <!-- LOWER GRID: TOP & BOTTOM SELLING PRODUCTS -->
        <div class="lower-grid">

            <section class="panel-card">
                <div class="panel-header">
                    <div class="panel-header-left">
                        <div class="panel-header-icon">🏆</div>
                        <div>
                            <h3>Top 5 Selling Products</h3>
                            <small>Based on cumulative quantity sold.</small>
                        </div>
                    </div>
                </div>

                <div class="panel-body">
                    <?php if (count($top_selling_products) > 0): ?>
                        <table class="low-stock-table">
                            <thead>
                                <tr>
                                    <th>Product</th>
                                    <th>Qty sold</th>
                                    <th>Unit price</th>
                                    <th>Total sales</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php foreach ($top_selling_products as $p): ?>
                                    <tr>
                                        <td><?= htmlspecialchars($p['name']); ?></td>
                                        <td><?= (int)$p['total_qty']; ?></td>
                                        <td>KES <?= number_format($p['selling_price'], 2); ?></td>
                                        <td>KES <?= number_format($p['total_amount'], 2); ?></td>
                                    </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    <?php else: ?>
                        <p style="color:#c3d8ff; margin-top:6px;">
                            No sales data available yet to compute top products.
                        </p>
                    <?php endif; ?>
                </div>
            </section>

            <section class="panel-card">
                <div class="panel-header">
                    <div class="panel-header-left">
                        <div class="panel-header-icon">📉</div>
                        <div>
                            <h3>Bottom 5 Selling Products</h3>
                            <small>Slow-moving items with the least quantity sold.</small>
                        </div>
                    </div>
                </div>

                <div class="panel-body">
                    <?php if (count($bottom_selling_products) > 0): ?>
                        <table class="low-stock-table">
                            <thead>
                                <tr>
                                    <th>Product</th>
                                    <th>Qty sold</th>
                                    <th>Unit price</th>
                                    <th>Total sales</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php foreach ($bottom_selling_products as $p): ?>
                                    <tr>
                                        <td><?= htmlspecialchars($p['name']); ?></td>
                                        <td><?= (int)$p['total_qty']; ?></td>
                                        <td>KES <?= number_format($p['selling_price'], 2); ?></td>
                                        <td>KES <?= number_format($p['total_amount'], 2); ?></td>
                                    </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    <?php else: ?>
                        <p style="color:#c3d8ff; margin-top:6px;">
                            No sales data available yet to compute bottom products.
                        </p>
                    <?php endif; ?>
                </div>
            </section>

        </div>

    </div>

</div>

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

<script>
(function () { 
    const saved = localStorage.getItem('adminTheme');
    const theme = (saved === 'light' || saved === 'dark') ? saved : 'dark';
    document.body.setAttribute('data-theme', theme);
})();

function toggleAdminTheme() {
    const current = document.body.getAttribute('data-theme') || 'dark';
    const next = current === 'dark' ? 'light' : 'dark';
    document.body.setAttribute('data-theme', next);
    localStorage.setItem('adminTheme', next);
}

// keep this if you still use the sidebar toggle button
/*function toggleAdminSidebar() {
    const sidebar = document.querySelector('.sidebar');
    const main    = document.getElementById('main');
    if (!sidebar || !main) return;

    sidebar.classList.toggle('collapsed');

    // margin handled via CSS sibling selector; this is a safety fallback
    if (sidebar.classList.contains('collapsed')) {
        main.style.marginLeft = '78px';
    } else {
        main.style.marginLeft = '250px';
    }
}*/
</script>

</body>
</html>
