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

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

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

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

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

/* =========================
   DASHBOARD COUNTS
========================= */
$dossier_count = fetchOne(
    $conn,
    "SELECT COUNT(*) AS total 
     FROM admin_product_approval 
     WHERE status='Pending'",
    'total',
    0
);
$renewal_products = fetchOne(
    $conn,
    "SELECT COUNT(*) AS total 
     FROM admin_product_approval 
     WHERE type='variation' 
     AND status='Pending'",
    'total',
    0
);
$sample_products = fetchOne(
    $conn,
    "SELECT COUNT(*) AS total FROM sample_products",
    'total',
    0
);
$admin_requests_total = fetchOne($conn, "SELECT COUNT(*) AS total FROM admin_product_approval", 'total', 0);
$admin_requests_pending = fetchOne($conn, "SELECT COUNT(*) AS total FROM admin_product_approval WHERE status='Pending'", 'total', 0);
$total_products = fetchOne($conn, "SELECT COUNT(*) AS total FROM products", 'total', 0);
$pending        = fetchOne($conn, "SELECT COUNT(*) AS total FROM products WHERE status='pending'", 'total', 0);
$approved       = fetchOne($conn, "SELECT COUNT(*) AS total FROM products WHERE status='approved'", 'total', 0);
$rejected       = fetchOne($conn, "SELECT COUNT(*) AS total FROM products WHERE status='rejected'", 'total', 0);
$total_qty      = fetchOne($conn, "SELECT COALESCE(SUM(qty),0) AS total FROM products", 'total', 0);
$today_added    = fetchOne($conn, "SELECT COUNT(*) AS total FROM products WHERE DATE(created_at)=CURDATE()", 'total', 0);
$week_added     = fetchOne($conn, "SELECT COUNT(*) AS total FROM products WHERE created_at >= DATE_SUB(CURDATE(), INTERVAL 6 DAY)", 'total', 0);

/* =========================
   RECENT PRODUCTS
========================= */
$recent_requests = $conn->query("
    SELECT * FROM admin_product_approval
    ORDER BY created_at DESC
    LIMIT 8
");


/* Top brands */
$brands = $conn->query("
    SELECT brand_name, COUNT(*) AS total
    FROM products
    WHERE brand_name IS NOT NULL AND brand_name <> ''
    GROUP BY brand_name
    ORDER BY total DESC
    LIMIT 6
");

/* =========================
   CHART DATA
========================= */
$status_labels = ["Pending", "Approved", "Rejected"];
$status_values = [(int)$pending, (int)$approved, (int)$rejected];

$daily = [];
$trend_res = $conn->query("
    SELECT DATE(created_at) AS day, COUNT(*) AS total
    FROM products
    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()) {
        $daily[$row['day']] = (int)$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[] = $daily[$day] ?? 0;
}

$labels_json = json_encode($labels, JSON_UNESCAPED_UNICODE);
$values_json = json_encode($values, JSON_UNESCAPED_UNICODE);
$status_labels_json = json_encode($status_labels, JSON_UNESCAPED_UNICODE);
$status_values_json = json_encode($status_values, JSON_UNESCAPED_UNICODE);

$pending_pct  = $total_products > 0 ? round(($pending / $total_products) * 100) : 0;
$approved_pct = $total_products > 0 ? round(($approved / $total_products) * 100) : 0;
$rejected_pct = $total_products > 0 ? round(($rejected / $total_products) * 100) : 0;
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>RA Dashboard</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.0/css/all.min.css">
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>

    <style>
        :root{
            --bg:#f4f7fb;
            --card:#ffffff;
            --text:#0f172a;
            --muted:#64748b;
            --border:#e5e7eb;
            --primary:#374155;
            --primary-soft:#eef2f7;
            --success:#16a34a;
            --warning:#f59e0b;
            --danger:#ef4444;
            --info:#2563eb;
            --shadow:0 12px 32px rgba(15,23,42,.08);
            --radius:18px;
            --sidebar-width:260px;
            --header-height:70px;
        }

        *{ box-sizing:border-box; }
        html, body{
            max-width:100%;
            overflow-x:hidden;
        }

        body{
            margin:0;
            font-family:Inter, Arial, Helvetica, sans-serif;
            background:
                radial-gradient(circle at top left, rgba(55,65,85,.08), transparent 30%),
                radial-gradient(circle at bottom right, rgba(37,99,235,.06), transparent 28%),
                var(--bg);
            color:var(--text);
        }

        .content-area{
            margin-left:var(--sidebar-width);
            width:calc(100% - var(--sidebar-width));
            padding:calc(var(--header-height) + 24px) 24px 24px;
            overflow-x:hidden;
        }

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

        .title{
            margin-bottom:18px;
        }

        .title h1{
            margin:0;
            font-size:30px;
            font-weight:900;
            display:flex;
            align-items:center;
            gap:12px;
            color:var(--primary);
            letter-spacing:-.04em;
        }

        .title h1 i{
            color:#374155;
            background:#eaf2ff;
            width:42px;
            height:42px;
            display:inline-flex;
            align-items:center;
            justify-content:center;
            border-radius:14px;
            box-shadow:inset 0 0 0 1px rgba(37,99,235,.08);
        }

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

        .grid{
            display:grid;
            gap:16px;
        }

        .metrics{
            grid-template-columns:repeat(auto-fit,minmax(200px,1fr));
            margin-bottom:18px;
            align-items:stretch;
        }

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

       .metric{
    padding:16px;
    border-radius:16px;
    background:#fff;
    border:1px solid #e2e8f0;
    box-shadow:0 4px 12px rgba(0,0,0,0.04);
    min-height:auto;
}
        .metric:nth-child(1) .value{color:#111827;}
        .metric:nth-child(2) .value{color:#f59e0b;}
        .metric:nth-child(3) .value{color:#16a34a;}
        .metric:nth-child(4) .value{color:#ef4444;}
        .metric:nth-child(5) .value{color:#2563eb;}
        .metric:nth-child(6) .value{color:#8b5cf6;}
        .metric:nth-child(7) .value{color:#14b8a6;}
        .metric:nth-child(8) .value{color:#64748b;}
        .metric::before{
            content:"";
            position:absolute;
            inset:0 auto auto 0;
            width:100%;
            height:4px;
            background:linear-gradient(90deg, var(--primary), #64748b);
        }

        .metric:nth-child(1)::before{ background:linear-gradient(90deg,#2563eb,#60a5fa); }
        .metric:nth-child(2)::before{ background:linear-gradient(90deg,#f59e0b,#fbbf24); }
        .metric:nth-child(3)::before{ background:linear-gradient(90deg,#16a34a,#4ade80); }
        .metric:nth-child(4)::before{ background:linear-gradient(90deg,#ef4444,#fb7185); }
        .metric:nth-child(5)::before{ background:linear-gradient(90deg,#0ea5e9,#38bdf8); }
        .metric:nth-child(6)::before{ background:linear-gradient(90deg,#8b5cf6,#a78bfa); }
        .metric:nth-child(7)::before{ background:linear-gradient(90deg,#14b8a6,#5eead4); }
        .metric:nth-child(8)::before{ background:linear-gradient(90deg,#64748b,#94a3b8); }

            .metric .label{
            font-size:11px;
            color:#94a3b8;
            font-weight:700;
        }

        .metric .value{
            font-size:22px;
            font-weight:800;
            margin-top:6px;
        }

        .metric .sub{
            font-size:12px;
            color:#64748b;
        }
        .metrics{
        gap:14px;
        }
                .layout-2{
            display:grid;
            grid-template-columns:1fr 1fr;
            gap:16px;
            margin-bottom:16px;
            align-items:start;
        }

        .layout-3{
            display:grid;
            grid-template-columns:repeat(auto-fit, minmax(280px,1fr));
            gap:16px;
            margin-bottom:16px;
            align-items:start;
        }

        .panel{
            padding:18px;
            min-width:0;
            display:flex;
            flex-direction:column;
            height:100%;
        }

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

        .section-title h2{
            margin:0;
            font-size:18px;
            font-weight:900;
            color:var(--primary);
            letter-spacing:-.02em;
            display:flex;
            align-items:center;
            gap:10px;
        }

        .section-title h2 i{
            color:var(--info);
        }

        .section-title .note{
            font-size:13px;
            color:var(--muted);
        }

        .chart-box{
            width:100%;
            height:320px;
            border-radius:16px;
            background:linear-gradient(180deg,#fbfdff,#f8fbff);
        }

        .card, .panel{
            min-width:0;
        }

        .table-wrap{
            width:100%;
            overflow-x:auto;
        }

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

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

        th{
            color:#334155;
            font-size:13px;
            font-weight:800;
            background:#f8fafc;
        }

        td{
            color:var(--text);
            font-size:14px;
        }

        .center{
            text-align:center;
        }

        .chip{
            display:inline-flex;
            align-items:center;
            padding:6px 12px;
            border-radius:999px;
            font-size:12px;
            font-weight:700;
            text-transform:capitalize;
        }

        .pending{background:#fef3c7;color:#92400e;}
        .approved{background:#dcfce7;color:#166534;}
        .rejected{background:#fee2e2;color:#991b1b;}

        .product-cell{
            display:flex;
            flex-direction:column;
            gap:4px;
        }

        .product-name{
            font-weight:800;
            color:var(--primary);
        }

        .meta-small{
            font-size:12px;
            color:var(--muted);
        }

        .stats-list{
            display:grid;
            gap:12px;
        }

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

        .stat-row:last-child{
            border-bottom:none;
        }

        .stat-row strong,
        .stat-row span{
            color:var(--primary);
        }

        .progress{
            height:10px;
            background:#e5e7eb;
            border-radius:999px;
            overflow:hidden;
            margin-top:10px;
        }

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

        .progress .pending-bar{background:var(--warning);}
        .progress .approved-bar{background:var(--success);}
        .progress .rejected-bar{background:var(--danger);}
        .progress .blue-bar{background:var(--info);}
        .progress .approved-bar{
            background:#374155 !important;
        }
        .mini-info{
            display:grid;
            gap:10px;
        }

        .mini-card{
            background:#f8fafc;
            border:1px solid var(--border);
            border-radius:14px;
            padding:14px;
            display:flex;
            justify-content:space-between;
            align-items:center;
            gap:10px;
        }

        .mini-card strong{
            color:var(--primary);
        }

        .mini-card span{
            color:var(--info);
            font-weight:800;
        }

        .empty{
            padding:18px;
            text-align:center;
            color:var(--muted);
        }
        .metric::before{
    display:none !important;
}

        @media (max-width:1100px){
            .layout-3{
                grid-template-columns:1fr;
            }
        }

        @media (max-width:992px){
            .content-area{
                margin-left:0;
                width:100%;
            }

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

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

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

            .metric .value{
                font-size:24px;
            }
        }
/* ================= FINAL MOBILE RESPONSIVE ================= */
@media (max-width: 768px){

    .content-area{
        margin-left:0 !important;
        width:100% !important;
        padding:80px 12px 12px;
    }

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

    .title h1 i{
        width:36px;
        height:36px;
        font-size:14px;
    }

    .title p{
        font-size:12px;
    }

    /* ðŸ”¥ METRICS */
    .metrics{
        grid-template-columns:1fr 1fr;
        gap:10px;
    }

    .metric{
        padding:14px;
        min-height:auto;
    }

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

    /* ðŸ”¥ LAYOUT */
    .layout-2,
    .layout-3{
        grid-template-columns:1fr;
        gap:12px;
    }

    .panel{
        padding:14px;
    }

    /* ðŸ”¥ CHART */
    .chart-box{
        height:240px;
    }

}
    </style>
</head>
<body>

<?php
if (file_exists('rasidebar.php')) {
    include 'rasidebar.php';
}
if (file_exists('../header.php')) {
    include '../header.php';
}
?>

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

        <!-- TITLE -->
        <div class="title">
            <h1><i class="fa-solid fa-clipboard-list"></i> RA Dashboard</h1>
            <p>Product overview, stock alerts, approvals, and recent activity in one place.</p>
        </div>

        <!-- METRICS -->
        <div class="grid metrics">
            <div class="card metric">
                <div class="label">Total Products</div>
                <div class="value"><?= (int)$total_products ?></div>
                <div class="sub">All products in system</div>
            </div>

            <div class="card metric">
                <div class="label">Pending</div>
                <div class="value"><?= (int)$pending ?></div>
                <div class="sub"><?= (int)$pending_pct ?>%</div>
            </div>

            <div class="card metric">
                <div class="label">Registered </div>
                <div class="value"><?= (int)$approved ?></div>
                <div class="sub"><?= (int)$approved_pct ?>%</div>
            </div>

            <div class="card metric">
                <div class="label">Rejected</div>
                <div class="value"><?= (int)$rejected ?></div>
                <div class="sub"><?= (int)$rejected_pct ?>%</div>
            </div>

            <div class="card metric">
                <div class="label">Total Qty</div>
                <div class="value"><?= (int)$total_qty ?></div>
            </div>

            <div class="card metric">
                <div class="label">Today Added</div>
                <div class="value"><?= (int)$today_added ?></div>
            </div>

            <div class="card metric">
                <div class="label">This Week</div>
                <div class="value"><?= (int)$week_added ?></div>
            </div>
            <div class="card metric">
    <div class="label">Admin Requests</div>
    <div class="value"><?= (int)$admin_requests_total ?></div>
    <div class="sub"><?= (int)$admin_requests_pending ?> Pending</div>
</div>
<div class="card metric">
    <div class="label">Dossier Under Preparation</div>
    <div class="value"><?= (int)$dossier_count ?></div>
    <div class="sub">In progress</div>
</div>
<div class="card metric">
    <div class="label">Renewal Products</div>
    <div class="value"><?= (int)$renewal_products ?></div>
    <div class="sub">Renewal started</div>
</div>
<div class="card metric">
    <div class="label">Samples</div>
    <div class="value"><?= (int)$sample_products ?></div>
    <div class="sub">Available samples</div>
</div>
        </div>

        <!-- CHARTS -->
        <div class="layout-2">
            <!-- STATUS -->
            <div class="card panel">
                <div class="section-title">
                    <h2><i class="fa-solid fa-chart-pie"></i> Status Overview</h2>
                </div>
                <div class="chart-box">
                    <canvas id="statusChart"></canvas>
                </div>
            </div>

            <!-- WEEKLY -->
            <div class="card panel">
                <div class="section-title">
                    <h2><i class="fa-solid fa-chart-line"></i> Weekly Trend</h2>
                </div>
                <div class="chart-box">
                    <canvas id="weeklyChart"></canvas>
                </div>
            </div>
        </div>

        <!-- 🔥 TOP BRANDS + RECENT PRODUCTS SIDE BY SIDE -->
        <div class="layout-2">

            <!-- TOP BRANDS -->
            <div class="card panel">
                <div class="section-title">
                    <h2><i class="fa-solid fa-crown"></i> Top Brands</h2>
                </div>

                <div class="table-wrap">
                    <table>
                        <thead>
                            <tr>
                                <th>Brand</th>
                                <th class="center">Count</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php if ($brands && $brands->num_rows > 0): ?>
                                <?php while($b = $brands->fetch_assoc()): ?>
                                    <tr>
                                        <td><?= esc($b['brand_name']) ?></td>
                                        <td class="center">
                                            <span class="chip approved"><?= (int)$b['total'] ?></span>
                                        </td>
                                    </tr>
                                <?php endwhile; ?>
                            <?php else: ?>
                                <tr>
                                    <td colspan="2" class="empty">No brand data found.</td>
                                </tr>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>

            <!-- ✅ RECENT PRODUCTS (RIGHT SIDE) -->
            <div class="card panel">
                <div class="section-title">
                    <h2><i class="fa-solid fa-clock"></i> Recent Requests</h2>
                </div>

                <div class="table-wrap">
                    <table>
                        <thead>
                            <tr>
                                <th>Product</th>
                                <th class="center">Qty</th>
                            </tr>
                        </thead>
                        <tbody>
                           <?php if ($recent_requests && $recent_requests->num_rows > 0): ?>
    <?php while($row = $recent_requests->fetch_assoc()): ?>
        <?php
            $data = json_decode($row['request_data'], true);
            $name = $data['form']['product_name'] ?? 'Product';
        ?>
        <tr>
            <td class="product-cell">
                <div class="product-name"><?= esc($name) ?></div>
<div class="meta-small">
<?= ($row['status'] === 'Pending') 
    ? 'Dossier under preparation' 
    : esc($row['type']) ?>
</div>
            </td>
            <td class="center">
                <span class="chip <?= strtolower($row['status']) ?>">
                    <?= esc($row['status']) ?>
                </span>
            </td>
        </tr>
    <?php endwhile; ?>
<?php else: ?>
    <tr>
        <td colspan="2" class="empty">No requests found.</td>
    </tr>
<?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>

        </div>

        <!-- ACTION NOTES -->
        <div class="layout-2">
            <div class="card panel">
                <div class="section-title">
                    <h2><i class="fa-solid fa-list-check"></i> Action Notes</h2>
                </div>

                <div class="mini-info">
                    <div class="mini-card">
                        <strong>Pending</strong>
                        <span><?= (int)$pending ?></span>
                    </div>
                    <div class="mini-card">
                        <strong>Approved</strong>
                        <span><?= (int)$approved ?></span>
                    </div>
                    <div class="mini-card">
                        <strong>Rejected</strong>
                        <span><?= (int)$rejected ?></span>
                    </div>
                </div>
            </div>
        </div>

    </div>
</main>

<script>
const statusCtx = document.getElementById('statusChart').getContext('2d');
new Chart(statusCtx, {
    type: 'doughnut',
    data: {
        labels: <?= $status_labels_json ?>,
        datasets: [{
            data: <?= $status_values_json ?>,
            backgroundColor: [
  '#eab308',  // subtle yellow
  '#334155',  // dark slate (best corporate)
  '#ef4444'   // clean red
],
            borderWidth: 0
        }]
    },
    options: {
        responsive: true,
        maintainAspectRatio: false,
        plugins: {
            legend: {
                display: true,
                position: 'bottom'
            }
        },
        cutout: '68%'
    }
});

const weeklyCtx = document.getElementById('weeklyChart').getContext('2d');
const weeklyGradient = weeklyCtx.createLinearGradient(0, 0, 0, 320);
weeklyGradient.addColorStop(0, 'rgba(55,65,85,0.28)');
weeklyGradient.addColorStop(1, 'rgba(55,65,85,0.03)');

new Chart(weeklyCtx, {
    type: 'line',
    data: {
        labels: <?= $labels_json ?>,
        datasets: [{
            label: 'Products Added',
            data: <?= $values_json ?>,
            tension: 0.35,
            fill: true,
            backgroundColor: weeklyGradient,
            borderColor: '#374155',
            borderWidth: 3,
            pointRadius: 4,
            pointHoverRadius: 6,
            pointBackgroundColor: '#ffffff',
            pointBorderColor: '#374155',
            pointBorderWidth: 2
        }]
    },
    options: {
        responsive: true,
        maintainAspectRatio: false,
        plugins: {
            legend: { display: false }
        },
        scales: {
            y: {
                beginAtZero: true,
                grid: { color: '#e5e7eb' },
                ticks: { color: '#64748b' }
            },
            x: {
                grid: { display: false },
                ticks: { color: '#64748b' }
            }
        }
    }
});
</script>

</body>
</html>