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

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

<body>

<style>
    :root {
        --cash-bg-main: #020617;
        --cash-bg-surface: rgba(15, 23, 42, 0.92);
        --cash-bg-card: rgba(15, 23, 42, 0.96);
        --cash-accent: #22d3ee;
        --cash-accent-soft: rgba(34, 211, 238, 0.17);
        --cash-danger: #fb7185;
        --cash-success: #22c55e;
        --cash-warning: #facc15;
        --cash-text-main: #f9fafb;
        --cash-text-muted: #9ca3af;
        --cash-border-subtle: rgba(148, 163, 184, 0.4);
        --cash-radius-lg: 18px;
        --cash-radius-md: 14px;
        --cash-shadow-strong: 0 24px 60px rgba(15, 23, 42, 0.9);
        --cash-shadow-soft: 0 16px 40px rgba(15, 23, 42, 0.75);
    }

    body {
        background:
            radial-gradient(circle at top left, rgba(56, 189, 248, 0.14), transparent 55%),
            radial-gradient(circle at bottom right, rgba(56, 189, 248, 0.08), transparent 60%),
            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: 26px 26px 30px;
    }

    .container-box.admin-dashboard {
        max-width: 1600px;
        margin: 0 auto;
        background: linear-gradient(135deg, rgba(15, 23, 42, 0.96), rgba(15, 23, 42, 0.98));
        border-radius: var(--cash-radius-lg);
        padding: 20px 22px 26px;
        border: 1px solid rgba(148, 163, 184, 0.45);
        box-shadow: var(--cash-shadow-strong);
        backdrop-filter: blur(18px);
    }

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

    .dashboard-title-block {
        display: flex;
        flex-direction: column;
        gap: 4px;
    }

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

    .dashboard-title-dot {
        width: 9px;
        height: 9px;
        border-radius: 999px;
        background: radial-gradient(circle at 30% 30%, #a5f3fc, #22d3ee);
        box-shadow: 0 0 0 6px rgba(34, 211, 238, 0.18);
    }

    .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: 640px;
    }

    .dashboard-pill {
        padding: 7px 16px;
        border-radius: 999px;
        border: 1px solid rgba(148, 163, 184, 0.6);
        font-size: 12px;
        background:
            radial-gradient(circle at 0% 0%, rgba(34, 211, 238, 0.24), transparent 60%),
            rgba(15, 23, 42, 0.9);
        color: #e0f2fe;
        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.28);
    }

    /* Metric cards row */

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

    .metric-card {
        position: relative;
        background:
            radial-gradient(circle at top left, rgba(34, 211, 238, 0.14), transparent 60%),
            radial-gradient(circle at bottom right, rgba(56, 189, 248, 0.16), transparent 65%),
            var(--cash-bg-card);
        border-radius: 16px;
        padding: 14px 16px 14px;
        border: 1px solid rgba(148, 163, 184, 0.55);
        box-shadow: var(--cash-shadow-soft);
        overflow: hidden;
        display: flex;
        flex-direction: column;
        gap: 6px;
        transform-origin: center;
        transition:
            transform 160ms ease-out,
            box-shadow 160ms ease-out,
            border-color 160ms ease-out,
            background 180ms ease-out;
    }

    .metric-card::after {
        content: "";
        position: absolute;
        inset: 0;
        opacity: 0;
        background: radial-gradient(circle at top, rgba(248, 250, 252, 0.12), transparent 55%);
        transition: opacity 180ms ease-out;
        pointer-events: none;
    }

    .metric-card:hover {
        transform: translateY(-2px);
        box-shadow: 0 18px 50px rgba(15, 23, 42, 0.9);
        border-color: rgba(56, 189, 248, 0.65);
    }

    .metric-card:hover::after {
        opacity: 1;
    }

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

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

    .metric-icon {
        width: 30px;
        height: 30px;
        border-radius: 999px;
        display: inline-flex;
        align-items: center;
        justify-content: center;
        background: radial-gradient(circle at 30% 20%, rgba(248, 250, 252, 0.75), rgba(148, 163, 184, 0.15));
        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;
        letter-spacing: 0.02em;
    }

    .metric-value.negative {
        color: var(--cash-danger);
    }

    .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.12em;
        color: #cbd5f5;
        background: rgba(15, 23, 42, 0.85);
        display: inline-flex;
        align-items: center;
        gap: 4px;
        white-space: nowrap;
    }

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

    /* Two-column lower section */

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

    .panel-card {
        background:
            radial-gradient(circle at top left, rgba(34, 211, 238, 0.12), transparent 60%),
            linear-gradient(135deg, #020617, #020617 40%, #0f172a 100%);
        border-radius: var(--cash-radius-lg);
        padding: 16px 18px 18px;
        border: 1px solid rgba(148, 163, 184, 0.55);
        box-shadow: var(--cash-shadow-soft);
        backdrop-filter: blur(16px);
    }

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

    .panel-header h3 {
        font-size: 16px;
        font-weight: 600;
        letter-spacing: 0.02em;
    }

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

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

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

    .summary-item {
        background: rgba(15, 23, 42, 0.86);
        border-radius: 12px;
        padding: 8px 10px;
        border: 1px solid var(--cash-border-subtle);
        display: flex;
        flex-direction: column;
        gap: 2px;
    }

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

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

    /* Low stock table */

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

    .low-stock-table thead {
        background: radial-gradient(circle at top left, #0b4aa6, #0b1f51);
    }

    .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 {
        font-weight: 600;
        font-size: 12px;
        text-transform: uppercase;
        letter-spacing: 0.08em;
    }

    .low-stock-table tbody tr:hover {
        background: rgba(15, 23, 42, 0.85);
    }

    .badge-low,
    .badge-ok {
        padding: 3px 9px;
        border-radius: 999px;
        font-size: 11px;
        display: inline-flex;
        align-items: center;
        gap: 5px;
    }

    .badge-low {
        background: rgba(250, 204, 21, 0.08);
        border: 1px solid rgba(250, 204, 21, 0.9);
        color: #facc15;
    }

    .badge-ok {
        background: rgba(34, 197, 94, 0.12);
        border: 1px solid rgba(34, 197, 94, 0.85);
        color: #bbf7d0;
    }

    /* Quick links */

    .quick-links {
        margin-top: 12px;
    }

    .quick-links-title {
        font-size: 15px;
        font-weight: 600;
        margin-bottom: 8px;
        display: flex;
        align-items: center;
        gap: 6px;
    }

    .quick-links-title::before {
        content: "";
        width: 4px;
        height: 18px;
        border-radius: 999px;
        background: linear-gradient(to bottom, #22d3ee, #60a5fa);
    }

    .cards-container {
        display: grid;
        grid-template-columns: repeat(auto-fit, minmax(230px, 1fr));
        gap: 14px;
        margin-top: 6px;
    }

    .cards-container .card {
        background:
            radial-gradient(circle at top left, rgba(248, 250, 252, 0.06), transparent 60%),
            rgba(15, 23, 42, 0.95);
        border-radius: var(--cash-radius-md);
        padding: 12px 14px;
        border-left: 3px solid #2980b9;
        border-top: 1px solid rgba(148, 163, 184, 0.5);
        border-right: 1px solid rgba(15, 23, 42, 0.6);
        border-bottom: 1px solid rgba(15, 23, 42, 0.6);
        box-shadow: 0 14px 32px rgba(15, 23, 42, 0.9);
        transition:
            transform 160ms ease-out,
            box-shadow 160ms ease-out,
            border-color 160ms ease-out,
            background 160ms ease-out;
        cursor: pointer;
    }

    .cards-container .card:hover {
        transform: translateY(-2px);
        box-shadow: 0 18px 42px rgba(15, 23, 42, 0.95);
        background:
            radial-gradient(circle at top right, rgba(56, 189, 248, 0.16), transparent 60%),
            rgba(15, 23, 42, 0.98);
    }

    .cards-container .card h3 {
        font-size: 14px;
        margin-bottom: 4px;
        display: flex;
        align-items: center;
        gap: 6px;
    }

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

    .card-label {
        font-size: 10px;
        text-transform: uppercase;
        letter-spacing: 0.12em;
        color: rgba(148, 163, 184, 0.9);
        margin-bottom: 2px;
    }

    @media (max-width: 900px) {
        .main-content {
            padding: 18px 12px 24px;
        }
        .dashboard-header {
            flex-direction: column;
            align-items: flex-start;
        }
        .dashboard-pill {
            align-self: flex-start;
        }
        .lower-grid {
            grid-template-columns: minmax(0, 1fr);
        }
    }
</style>

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

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

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

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

        <div class="dashboard-header">
            <div class="dashboard-title-block">
                <div class="dashboard-title-main">
                    <span class="dashboard-title-dot"></span>
                    <h2>Admin dashboard overview</h2>
                </div>
                <p>
                    Real-time visibility into today’s performance, cash position, and inventory health for your store.
                </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 TABLE -->
        <div class="lower-grid">

            <!-- Last cash summary -->
            <section class="panel-card">
                <div class="panel-header">
                    <div>
                        <h3>Last submitted cash summary</h3>
                        <small>Most recent end-of-shift cash report from any cashier.</small>
                    </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>

            <!-- Low stock products -->
            <section class="panel-card">
                <div class="panel-header">
                    <div>
                        <h3>Low stock products</h3>
                        <small>Items at or below <?= $low_stock_threshold; ?> units (top 10).</small>
                    </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>

        <!-- QUICK NAV / SHORTCUTS -->
        <div class="quick-links">
            <div class="quick-links-title">Quick management shortcuts</div>
            <div class="cards-container">

                <div class="card" style="border-color:#2980b9;">
                    <div class="card-label">Inventory</div>
                    <h3>📦 Product Management</h3>
                    <p>Manage stock, add new products, and monitor availability.</p>
                </div>

                <div class="card" style="border-color:#27ae60;">
                    <div class="card-label">Sales</div>
                    <h3>💰 Sales Monitoring</h3>
                    <p>Analyze daily performance and overall sales trends.</p>
                </div>

                <div class="card" style="border-color:#8e44ad;">
                    <div class="card-label">Administration</div>
                    <h3>👥 User Management</h3>
                    <p>Manage user roles, staff accounts, and access permissions.</p>
                </div>

                <div class="card" style="border-color:#d35400;">
                    <div class="card-label">Customers</div>
                    <h3>📄 Customer Management</h3>
                    <p>Update customer details and track payment history.</p>
                </div>

                <div class="card" style="border-color:#c0392b;">
                    <div class="card-label">Operations</div>
                    <h3>⚠️ Damages & Expenses</h3>
                    <p>Track damaged goods and manage business expenses.</p>
                </div>

                <div class="card" style="border-color:#16a085;">
                    <div class="card-label">Debtors</div>
                    <h3>💳 Debt Management</h3>
                    <p>Monitor, update, and clear customer debts.</p>
                </div>

                <div class="card" style="border-color:#3498db;">
                    <div class="card-label">Reports</div>
                    <h3>🏆 Top 5 Products</h3>
                    <p>View the highest-selling products by quantity.</p>
                </div>

                <div class="card" style="border-color:#9b59b6;">
                    <div class="card-label">Reports</div>
                    <h3>📉 Bottom 5 Products</h3>
                    <p>See slow-moving items with the least sales.</p>
                </div>

                <div class="card" style="border-color:#e74c3c;">
                    <div class="card-label">Inventory</div>
                    <h3>🚨 Low Stock Alerts</h3>
                    <p>Monitor items with stock levels below <?= $low_stock_threshold; ?>.</p>
                </div>

            </div>
        </div>

    </div>

</div>

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

<script>
function toggleAdminSidebar() {
    const main = document.getElementById('main');
    const sidebar = document.getElementById('sidebar'); // adjust if your sidebar has different id
    if (sidebar) {
        sidebar.classList.toggle('collapsed');
    }
}
</script>

</body>
</html>
