<?php
session_start();
require_once '../config.php';

if (!isset($_SESSION['user_id']) || ($_SESSION['role'] ?? '') !== 'admin') {
    header('Location: ../login.php');
    exit;
}

function money($amt) {
    return "₹" . number_format((float)$amt, 2);
}

function esc($value) {
    return htmlspecialchars((string)$value, ENT_QUOTES, 'UTF-8');
}

function fetchOne(mysqli $conn, string $sql, string $key, $default = 0) {
    $res = $conn->query($sql);
    if ($res && ($row = $res->fetch_assoc())) {
        return $row[$key] ?? $default;
    }
    return $default;
}

/* =========================
   BASIC STATS
========================= */
$total_sales = fetchOne(
    $conn,
    "SELECT COALESCE(SUM(total_amount),0) AS total FROM bills",
    'total',
    0
);

$total_bills = fetchOne(
    $conn,
    "SELECT COUNT(*) AS total FROM bills",
    'total',
    0
);

$total_users = fetchOne(
    $conn,
    "SELECT COUNT(*) AS total FROM users",
    'total',
    0
);

$total_products = fetchOne(
    $conn,
    "SELECT COUNT(*) AS total FROM products",
    'total',
    0
);

$today_sales = fetchOne(
    $conn,
    "SELECT COALESCE(SUM(total_amount),0) AS total
     FROM bills
     WHERE DATE(created_at) = CURDATE()",
    'total',
    0
);

$week_sales = fetchOne(
    $conn,
    "SELECT COALESCE(SUM(total_amount),0) AS total
     FROM bills
     WHERE created_at >= DATE_SUB(CURDATE(), INTERVAL 6 DAY)",
    'total',
    0
);

$overdue_amount = fetchOne(
    $conn,
    "SELECT COALESCE(SUM(GREATEST(total_amount, 0)),0) AS total
     FROM bills
     WHERE due_date < CURDATE()
       AND GREATEST(total_amount, 0) > 0",
    'total',
    0
);

$overdue_count = fetchOne(
    $conn,
    "SELECT COUNT(*) AS total
     FROM bills
     WHERE due_date < CURDATE()
       AND GREATEST(total_amount, 0) > 0",
    'total',
    0
);

$pending_due = max(0, (float)$total_sales - 0);

/* =========================
   RECENT DATA
========================= */
$recent_bills = $conn->query("
    SELECT b.*, u.name AS user_name
    FROM bills b
    JOIN users u ON b.created_by = u.id
    ORDER BY b.id DESC
    LIMIT 8
");

$overdue_list = $conn->query("
    SELECT b.*, u.name AS user_name
    FROM bills b
    JOIN users u ON b.created_by = u.id
    WHERE b.due_date < CURDATE()
      AND GREATEST(b.total_amount, 0) > 0
    ORDER BY b.due_date ASC, b.id DESC
    LIMIT 8
");

$latest_users = $conn->query("
    SELECT id, name, role, created_at
    FROM users
    ORDER BY id DESC
    LIMIT 6
");

$top_products = $conn->query("
    SELECT
        p.product_name AS name,
        COALESCE(SUM(bi.qty),0) AS qty_sold,
        COALESCE(SUM(bi.qty * bi.price),0) AS value_sold
    FROM bill_items bi
    JOIN bills b ON bi.bill_id = b.id
    JOIN products p ON bi.product_id = p.id
    GROUP BY p.id, p.product_name
    ORDER BY qty_sold DESC
    LIMIT 6
");

/* =========================
   CHART DATA
========================= */
$sales_trend = [];
$trend_res = $conn->query("
    SELECT DATE(created_at) AS day, COALESCE(SUM(total_amount),0) AS total
    FROM bills
    WHERE created_at >= DATE_SUB(CURDATE(), INTERVAL 6 DAY)
    GROUP BY DATE(created_at)
    ORDER BY day ASC
");

if ($trend_res) {
    while ($row = $trend_res->fetch_assoc()) {
        $sales_trend[$row['day']] = (float)$row['total'];
    }
}

$labels = [];
$values = [];
for ($i = 6; $i >= 0; $i--) {
    $day = date('Y-m-d', strtotime("-$i days"));
    $labels[] = date('d M', strtotime($day));
    $values[] = $sales_trend[$day] ?? 0;
}

$labels_json = json_encode($labels);
$values_json = json_encode($values);

$summary_labels = json_encode(["Total Sales", "Overdue", "Today Sales"]);
$summary_values = json_encode([(float)$total_sales, (float)$overdue_amount, (float)$today_sales]);

?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Admin Dashboard</title>
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.0/css/all.min.css">
<style>
:root{
    --bg:#eef3f9;
    --card:#ffffff;
    --text:#0f172a;
    --muted:#7b8aa4;
    --border:#dbe3ee;
    --primary:#1f3b73;
    --primary-2:#0f172a;
    --accent:#2563eb;
    --green:#16a34a;
    --orange:#f59e0b;
    --red:#ef4444;
    --shadow:0 10px 24px rgba(15,23,42,.08);
    --shadow-soft:0 6px 16px rgba(15,23,42,.05);
    --radius:18px;
    --sidebar-width:260px;
    --header-height:72px;
}

*{
    box-sizing:border-box;
}

html, body{
    max-width:100%;
    overflow-x:hidden;
}

body{
    margin:0;
    font-family:Inter, Arial, Helvetica, sans-serif;
    background:var(--bg);
    color:var(--text);
}

/* =========================
   MAIN CONTENT AREA
========================= */
.content-area{
    margin-left:var(--sidebar-width);
    width:calc(100% - var(--sidebar-width));
    padding:calc(var(--header-height) + 20px) 20px 20px;
    overflow-x:hidden;
}

.wrap{
    max-width:1600px;
    margin:0 auto;
}

/* =========================
   TOP TITLE CARD
========================= */
.header{
    display:flex;
    justify-content:space-between;
    align-items:flex-start;
    gap:14px;
    margin-bottom:18px;
    flex-wrap:wrap;
}

.title{
    width:100%;
    background:#fff;
    border:1px solid var(--border);
    border-radius:20px;
    padding:18px 20px;
    box-shadow:var(--shadow-soft);
}

.title h1{
    margin:0;
    font-size:22px;
    font-weight:800;
    letter-spacing:-.03em;
    display:flex;
    align-items:center;
    gap:12px;
    color:var(--text);
}

.title h1 i{
    width:34px;
    height:34px;
    display:inline-flex;
    align-items:center;
    justify-content:center;
    border-radius:10px;
    background:#f3f6fb;
    color:#111827;
    font-size:16px;
    border:1px solid var(--border);
}

.title p{
    margin:8px 0 0;
    color:var(--muted);
    font-size:14px;
    line-height:1.45;
}

/* =========================
   BUTTONS
========================= */
.header-actions{
    display:flex;
    gap:10px;
    flex-wrap:wrap;
}

.btn{
    display:inline-flex;
    align-items:center;
    gap:8px;
    text-decoration:none;
    border:none;
    cursor:pointer;
    padding:10px 14px;
    border-radius:12px;
    font-weight:700;
    background:#fff;
    color:var(--text);
    box-shadow:var(--shadow-soft);
    transition:transform .18s ease, box-shadow .18s ease, background .18s ease;
}

.btn:hover{
    transform:translateY(-1px);
    box-shadow:0 12px 24px rgba(15,23,42,.10);
}

.btn.primary{
    background:#111827;
    color:#fff;
}

.btn.primary:hover{
    background:#0f172a;
}

/* =========================
   GRID / CARDS
========================= */
.grid{
    display:grid;
    gap:14px;
}

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

.card{
    background:#fff;
    border:1px solid var(--border);
    border-radius:var(--radius);
    box-shadow:var(--shadow);
    min-width:0;
    overflow:hidden;
}

/* =========================
   METRIC CARDS
========================= */
.metric{
    padding:10px 12px;
    position:relative;
    min-height:80px;
}



.metric:nth-child(2)::before{ background:linear-gradient(90deg, #0ea5e9, #2563eb); }
.metric:nth-child(3)::before{ background:linear-gradient(90deg, #10b981, #16a34a); }
.metric:nth-child(4)::before{ background:linear-gradient(90deg, #ef4444, #f97316); }
.metric:nth-child(5)::before{ background:linear-gradient(90deg, #8b5cf6, #6366f1); }
.metric:nth-child(6)::before{ background:linear-gradient(90deg, #14b8a6, #0f766e); }
.metric:nth-child(7)::before{ background:linear-gradient(90deg, #f59e0b, #fb7185); }

.metric .label{
    color:#94a3b8;
    font-size:8px;
    font-weight:800;
    text-transform:uppercase;
    letter-spacing:.08em;
}

.metric .value{
    margin-top:12px;
    font-size:20px;
    font-weight:800;
    line-height:1.05;
    letter-spacing:-.04em;
    color:var(--text);
}

.metric .sub{
    margin-top:10px;
    color:var(--muted);
    font-size:13px;
    line-height:1.45;
}

/* =========================
   PANELS / LAYOUT
========================= */
.layout-2{
    display:grid;
    grid-template-columns:minmax(0,1.2fr) minmax(0,.8fr);
    gap:14px;
    margin-bottom:14px;
    align-items:start;
}

.panel{
    padding:16px;
    min-width:0;
}

.panel h2{
    margin:0 0 12px;
    font-size:17px;
    font-weight:800;
    letter-spacing:-.02em;
    color:var(--text);
}

/* =========================
   CHART
========================= */
.chart-box{
    width:100%;
    height:320px;
}

/* =========================
   TABLES
========================= */
.table-wrap{
    overflow-x:auto;
    width:100%;
    border-radius:14px;
    border:1px solid var(--border);
    background:#fff;
}

table{
    width:100%;
    border-collapse:collapse;
    min-width:700px;
}

th, td{
    padding:12px 12px;
    border-bottom:1px solid var(--border);
    text-align:left;
    white-space:nowrap;
    vertical-align:middle;
}

th{
    color:#64748b;
    font-size:11px;
    font-weight:800;
    text-transform:uppercase;
    letter-spacing:.08em;
    background:#f8fafc;
}

td{
    color:var(--text);
    font-size:13px;
    background:#fff;
}

tbody tr{
    transition:background .18s ease;
}

tbody tr:hover td{
    background:#f8fafc;
}

tbody tr:last-child td{
    border-bottom:none;
}

/* =========================
   BADGES
========================= */
.badge{
    display:inline-flex;
    align-items:center;
    padding:5px 9px;
    border-radius:999px;
    font-size:11px;
    font-weight:800;
    line-height:1;
    border:1px solid transparent;
}

.badge.success{
    background:#dcfce7;
    color:#166534;
    border-color:#bbf7d0;
}

.badge.warning{
    background:#fef3c7;
    color:#92400e;
    border-color:#fde68a;
}

.badge.danger{
    background:#fee2e2;
    color:#991b1b;
    border-color:#fecaca;
}

.badge.neutral{
    background:#e2e8f0;
    color:#334155;
    border-color:#cbd5e1;
}

/* =========================
   SMALL BLOCKS / LISTS
========================= */
.mini{
    padding-top:10px;
}

.progress{
    height:10px;
    background:#e5e7eb;
    border-radius:999px;
    overflow:hidden;
    margin-top:10px;
    box-shadow:inset 0 1px 2px rgba(15,23,42,.05);
}

.progress > div{
    height:100%;
    border-radius:999px;
}

.progress .paid{
    background:linear-gradient(90deg, #22c55e, #16a34a);
}

.progress .due{
    background:linear-gradient(90deg, #f59e0b, #f97316);
}

.section-title{
    display:flex;
    justify-content:space-between;
    align-items:center;
    gap:10px;
    margin:0 0 12px;
    flex-wrap:wrap;
}

.section-title h2{
    margin:0;
    font-size:17px;
    font-weight:800;
    letter-spacing:-.02em;
}

.note{
    color:var(--muted);
    font-size:12px;
    background:#f8fafc;
    padding:7px 10px;
    border-radius:999px;
    border:1px solid var(--border);
}

.empty{
    padding:22px 18px;
    text-align:center;
    color:var(--muted);
    font-size:13px;
}

.stack{
    display:grid;
    gap:10px;
    margin-bottom:14px;
}

.list-item{
    display:flex;
    justify-content:space-between;
    align-items:center;
    gap:12px;
    padding:11px 0;
    border-bottom:1px solid var(--border);
}

.list-item:last-child{
    border-bottom:none;
}

.muted{
    color:var(--muted);
}

/* =========================
   SCROLLBAR
========================= */
.table-wrap::-webkit-scrollbar{
    height:10px;
}

.table-wrap::-webkit-scrollbar-track{
    background:#eef2f7;
}

.table-wrap::-webkit-scrollbar-thumb{
    background:#cbd5e1;
    border-radius:999px;
}

.table-wrap::-webkit-scrollbar-thumb:hover{
    background:#94a3b8;
}
.value.green{ color:#16a34a; }
.value.red{ color:#ef4444; }
.value.orange{ color:#f59e0b; }
/* =========================
   RESPONSIVE
========================= */
@media (max-width: 992px){
    .content-area{
        margin-left:0;
        width:100%;
        padding:18px 16px 16px;
    }

    .layout-2{
        grid-template-columns:1fr;
    }

    .title{
        padding:16px;
    }

    .title h1{
        font-size:20px;
    }

    .chart-box{
        height:280px;
    }
}

@media (max-width: 640px){
    .content-area{
        padding:14px;
    }

    .title h1{
        font-size:18px;
    }

    .title h1 i{
        width:32px;
        height:32px;
        font-size:14px;
        border-radius:10px;
    }

    .metric{
        min-height:auto;
    }

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

    .panel{
        padding:14px;
    }

    .chart-box{
        height:250px;
    }

    .btn{
        width:100%;
        justify-content:center;
    }
}
</style>
</head>
<body>

<?php include 'adminsidebar.php'; ?>
<?php include '../header.php'; ?>

<main class="content-area">
    <div class="wrap">

       
            <div class="title">
                <h1><i class="fa-solid fa-user-shield"></i> Admin Dashboard</h1>
                <p>Complete business overview, collections, users, products, and recent activity.</p>
            </div>
         <br>
    

        <div class="grid metrics">
            <div class="card metric">
                <div class="label">Total Sales</div>
                <div class="value 
<?= $total_sales > 0 ? 'green' : ($total_sales < 0 ? 'red' : '') ?>">
<?= money($total_sales) ?>
</div>
                <div class="sub">All billing amount in the system</div>
            </div>

            <div class="card metric">
                <div class="label">Today Sales</div>
                <div class="value 
<?= $today_sales > 0 ? 'green' : ($today_sales < 0 ? 'red' : '') ?>">
<?= money($today_sales) ?>
</div>
                <div class="sub">Sales created today</div>
            </div>

            <div class="card metric">
                <div class="label">Total Bills</div>
                <div class="value"><?= (int)$total_bills ?></div>
                <div class="sub">All created bills</div>
            </div>

            <div class="card metric">
                <div class="label">Overdue Amount</div>
                <div class="value orange">
<?= money($overdue_amount) ?>
</div>
                <div class="sub"><?= (int)$overdue_count ?> overdue bills</div>
            </div>

            <div class="card metric">
                <div class="label">Total Users</div>
                <div class="value"><?= (int)$total_users ?></div>
                <div class="sub">All registered users</div>
            </div>

            <div class="card metric">
                <div class="label">Total Products</div>
                <div class="value"><?= (int)$total_products ?></div>
                <div class="sub">Available products</div>
            </div>

            <div class="card metric">
                <div class="label">7 Day Sales</div>
                <div class="value 
<?= $week_sales > 0 ? 'green' : ($week_sales < 0 ? 'red' : '') ?>">
<?= money($week_sales) ?>
</div>
                <div class="sub">Last 7 days total</div>
            </div>
<?php

$new_orders = fetchOne(
    $conn,
    "SELECT COUNT(*) AS total
     FROM orders             
     WHERE status='Pending'",
    'total',
    0
);

?>

<div class="card metric">

    <div class="label">
        New Orders
    </div>

    <div class="value orange">
        <?= (int)$new_orders ?>
    </div>

    <div class="sub">
        Pending order requests
    </div>

</div>
          
        </div>

        <div class="layout-2">
            <div class="card panel">
                <h2>Sales Trend (Last 7 Days)</h2>
                <div class="chart-box">
                    <canvas id="salesTrendChart"></canvas>
                </div>
            </div>

            <div class="card panel">
                <h2>Quick Summary</h2>

                <div class="stack">
                    <div class="list-item">
                        <strong>Total Sales</strong>
                        <span><?= money($total_sales) ?></span>
                    </div>
                    <div class="list-item">
                        <strong>Today Sales</strong>
                        <span><?= money($today_sales) ?></span>
                    </div>
                    <div class="list-item">
                        <strong>Overdue</strong>
                        <span><?= money($overdue_amount) ?></span>
                    </div>
                    <div class="list-item">
                        <strong>Users</strong>
                        <span><?= (int)$total_users ?></span>
                    </div>
                    <div class="list-item">
                        <strong>Products</strong>
                        <span><?= (int)$total_products ?></span>
                    </div>
                </div>

                <div class="mini">
                    <div style="display:flex;justify-content:space-between;gap:10px;">
                        <strong>Sales Collection View</strong>
                        <span><?= money($total_sales) ?></span>
                    </div>
                    <div class="progress">
                        <div class="paid" style="width:100%;"></div>
                    </div>
                </div>
            </div>
        </div>

        <div class="layout-2">
            <div class="card panel">
                <div class="section-title">
                    <h2>Recent Bills</h2>
                    <div class="note">Latest transactions</div>
                </div>
                <div class="table-wrap">
                    <table>
                        <thead>
                            <tr>
                                <th>ID</th>
                                <th>User</th>
                                <th>Total</th>
                                <th>Due</th>
                                <th>Date</th>
                            </tr>
                        </thead>
                        <tbody>
                        <?php if ($recent_bills && $recent_bills->num_rows > 0): ?>
                            <?php while($b = $recent_bills->fetch_assoc()): ?>
                                <?php $due_amt = max(0, (float)$b['total_amount']); ?>
                                <tr>
                                    <td><?= (int)$b['id'] ?></td>
                                    <td><?= esc($b['user_name']) ?></td>
                                    <td><?= money($b['total_amount']) ?></td>
                                    <td><span class="badge <?= $due_amt > 0 ? 'warning' : 'success' ?>"><?= money($due_amt) ?></span></td>
                                    <td><?= esc($b['created_at']) ?></td>
                                </tr>
                            <?php endwhile; ?>
                        <?php else: ?>
                            <tr><td colspan="5" class="empty">No bills found.</td></tr>
                        <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>

            <div class="card panel">
                <div class="section-title">
                    <h2>Latest Users</h2>
                    <div class="note">Newest accounts</div>
                </div>
                <div class="table-wrap">
                    <table>
                        <thead>
                            <tr>
                                <th>Name</th>
                                <th>Role</th>
                                <th>Date</th>
                            </tr>
                        </thead>
                        <tbody>
                        <?php if ($latest_users && $latest_users->num_rows > 0): ?>
                            <?php while($u = $latest_users->fetch_assoc()): ?>
                                <tr>
                                    <td><?= esc($u['name']) ?></td>
                                    <td><span class="badge neutral"><?= esc($u['role']) ?></span></td>
                                    <td><?= esc($u['created_at']) ?></td>
                                </tr>
                            <?php endwhile; ?>
                        <?php else: ?>
                            <tr><td colspan="3" class="empty">No users found.</td></tr>
                        <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>

        <div class="layout-2">
            <div class="card panel">
                <div class="section-title">
                    <h2>Overdue Bills</h2>
                    <div class="note">Needs attention</div>
                </div>
                <div class="table-wrap">
                    <table>
                        <thead>
                            <tr>
                                <th>ID</th>
                                <th>User</th>
                                <th>Due Date</th>
                                <th>Amount</th>
                            </tr>
                        </thead>
                        <tbody>
                        <?php if ($overdue_list && $overdue_list->num_rows > 0): ?>
                            <?php while($o = $overdue_list->fetch_assoc()): ?>
                                <tr>
                                    <td><?= (int)$o['id'] ?></td>
                                    <td><?= esc($o['user_name']) ?></td>
                                    <td><?= esc($o['due_date']) ?></td>
                                    <td><span class="badge danger"><?= money($o['total_amount']) ?></span></td>
                                </tr>
                            <?php endwhile; ?>
                        <?php else: ?>
                            <tr><td colspan="4" class="empty">No overdue bills.</td></tr>
                        <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>

            <div class="card panel">
                <div class="section-title">
                    <h2>Top Products</h2>
                    <div class="note">Best sellers</div>
                </div>
                <div class="table-wrap">
                    <table>
                        <thead>
                            <tr>
                                <th>Product</th>
                                <th>Qty Sold</th>
                                <th>Value</th>
                            </tr>
                        </thead>
                        <tbody>
                        <?php if ($top_products && $top_products->num_rows > 0): ?>
                            <?php while($p = $top_products->fetch_assoc()): ?>
                                <tr>
                                    <td><?= esc($p['name']) ?></td>
                                    <td><span class="badge neutral"><?= (int)$p['qty_sold'] ?></span></td>
                                    <td><?= money($p['value_sold']) ?></td>
                                </tr>
                            <?php endwhile; ?>
                        <?php else: ?>
                            <tr><td colspan="3" class="empty">No product sales found.</td></tr>
                        <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>

    </div>
</main>

<script>
const labels = <?= $labels_json ?>;
const values = <?= $values_json ?>;
const summaryLabels = <?= $summary_labels ?>;
const summaryValues = <?= $summary_values ?>;

new Chart(document.getElementById('salesTrendChart').getContext('2d'), {
    type: 'line',
    data: {
        labels: labels,
        datasets: [{
            label: 'Sales',
            data: values,
            tension: 0.35,
            fill: true,
            borderWidth: 2,
            pointRadius: 4
        }]
    },
    options: {
        responsive: true,
        maintainAspectRatio: false,
        plugins: {
            legend: { display: false }
        },
        scales: {
            y: {
                beginAtZero: true,
                grid: { color: '#e5e7eb' }
            },
            x: {
                grid: { display: false }
            }
        }
    }
});
</script>
</body>
</html>