<?php
// ════════════════════════════════════════════════════════════
//  SSBS-ISCMS — Main Admin Dashboard
// ════════════════════════════════════════════════════════════
ob_start();
session_start();
date_default_timezone_set('Africa/Juba');   // South Sudan timezone (EAT = UTC+3)

require_once 'layouts/dbconn.php';

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

$user_id    = $_SESSION['user_id'];
$role_code  = $_SESSION['role_code']  ?? '';
$full_name  = $_SESSION['full_name']  ?? 'User';
$first_name = $_SESSION['first_name'] ?? 'User';
$user_type  = $_SESSION['user_type']  ?? '';
$dept_name  = $_SESSION['dept_name']  ?? '';
$today      = date('Y-m-d');

// ── AJAX endpoint ───────────────────────────────────────────
if (isset($_GET['ajax'])) {
    ob_end_clean();
    header('Content-Type: application/json; charset=utf-8');

    if ($_GET['ajax'] === 'charts') {
        // Applications submitted over last 12 months
        $app_trend = $conn->query("
            SELECT DATE_FORMAT(submitted_at, '%Y-%m') AS month,
                   COUNT(*) AS total
            FROM   applications
            WHERE  submitted_at >= DATE_SUB(CURDATE(), INTERVAL 12 MONTH)
              AND  submitted_at IS NOT NULL
            GROUP  BY DATE_FORMAT(submitted_at, '%Y-%m')
            ORDER  BY month
        ")->fetch_all(MYSQLI_ASSOC);

        // Applications by type
        $app_by_type = $conn->query("
            SELECT application_type, COUNT(*) AS cnt
            FROM   applications
            WHERE  status NOT IN ('draft','withdrawn')
            GROUP  BY application_type
            ORDER  BY cnt DESC
        ")->fetch_all(MYSQLI_ASSOC);

        // Certifications by status
        $cert_status = $conn->query("
            SELECT status, COUNT(*) AS cnt
            FROM   certifications
            GROUP  BY status
        ")->fetch_all(MYSQLI_ASSOC);

        // Inspections by outcome (last 6 months)
        $insp_outcomes = $conn->query("
            SELECT COALESCE(outcome, 'pending') AS outcome, COUNT(*) AS cnt
            FROM   inspections
            WHERE  conducted_date >= DATE_SUB(CURDATE(), INTERVAL 6 MONTH)
            GROUP  BY outcome
        ")->fetch_all(MYSQLI_ASSOC);

        echo json_encode(compact('app_trend','app_by_type','cert_status','insp_outcomes'));
    }
    exit();
}

// ── Dashboard KPI queries ────────────────────────────────────

// Active certifications
$kpi_active_certs = (int)($conn->query("
    SELECT COUNT(*) AS n FROM certifications WHERE status = 'issued'"
)->fetch_assoc()['n'] ?? 0);

// Certificates expiring within 90 days
$kpi_expiring_certs = (int)($conn->query("
    SELECT COUNT(*) AS n FROM certifications
    WHERE  status = 'issued'
      AND  expiry_date BETWEEN CURDATE() AND DATE_ADD(CURDATE(), INTERVAL 90 DAY)"
)->fetch_assoc()['n'] ?? 0);

// Pending / in-progress applications
$kpi_pending_apps = (int)($conn->query("
    SELECT COUNT(*) AS n FROM applications
    WHERE  status IN ('submitted','under_review','in_progress',
                      'awaiting_inspection','awaiting_lab','awaiting_decision')"
)->fetch_assoc()['n'] ?? 0);

// Open inspections (scheduled or in progress)
$kpi_open_inspections = (int)($conn->query("
    SELECT COUNT(*) AS n FROM inspections
    WHERE  status IN ('scheduled','in_progress')"
)->fetch_assoc()['n'] ?? 0);

// Open non-conformances
$kpi_open_ncs = (int)($conn->query("
    SELECT COUNT(*) AS n FROM non_conformances
    WHERE  status NOT IN ('closed','escalated')"
)->fetch_assoc()['n'] ?? 0);

// Pending lab requests
$kpi_pending_lab = (int)($conn->query("
    SELECT COUNT(*) AS n FROM lab_test_requests
    WHERE  status IN ('pending','received','in_progress')"
)->fetch_assoc()['n'] ?? 0);

// Registered organisations
$kpi_orgs = (int)($conn->query("
    SELECT COUNT(*) AS n FROM organizations WHERE status = 'active'"
)->fetch_assoc()['n'] ?? 0);

// Overdue NCs
$kpi_overdue_ncs = (int)($conn->query("
    SELECT COUNT(*) AS n FROM non_conformances
    WHERE  status NOT IN ('closed')
      AND  response_due_date < CURDATE()"
)->fetch_assoc()['n'] ?? 0);

// ── Recent applications (last 10) ────────────────────────────
$recent_apps_result = $conn->query("
    SELECT a.id, a.application_number, a.application_type,
           a.status, a.priority, a.submitted_at, a.due_date,
           o.org_name,
           CONCAT(u.first_name,' ',u.last_name) AS submitted_by
    FROM   applications a
    LEFT   JOIN organizations o ON a.org_id      = o.id
    LEFT   JOIN users u         ON a.submitted_by = u.id
    WHERE  a.status NOT IN ('draft','closed','withdrawn')
    ORDER  BY a.submitted_at DESC
    LIMIT  10
");
$recent_apps = $recent_apps_result ? $recent_apps_result->fetch_all(MYSQLI_ASSOC) : [];

// ── Upcoming inspections (next 14 days) ──────────────────────
$upcoming_inspections_result = $conn->query("
    SELECT i.inspection_number, i.inspection_type,
           i.scheduled_date, i.location, i.status,
           CONCAT(u.first_name,' ',u.last_name) AS inspector_name,
           o.org_name
    FROM   inspections i
    LEFT   JOIN users         u ON i.inspector_id = u.id
    LEFT   JOIN applications  a ON i.application_id = a.id
    LEFT   JOIN organizations o ON a.org_id = o.id
    WHERE  i.status    = 'scheduled'
      AND  i.scheduled_date BETWEEN CURDATE() AND DATE_ADD(CURDATE(), INTERVAL 14 DAY)
    ORDER  BY i.scheduled_date
    LIMIT  8
");
$upcoming_inspections = $upcoming_inspections_result ? $upcoming_inspections_result->fetch_all(MYSQLI_ASSOC) : [];

// ── Certificates expiring soon ───────────────────────────────
$expiring_certs_result = $conn->query("
    SELECT c.certificate_number, c.expiry_date,
           DATEDIFF(c.expiry_date, CURDATE()) AS days_left,
           o.org_name, p.product_name, ct.type_name
    FROM   certifications c
    LEFT   JOIN organizations   o  ON c.org_id      = o.id
    LEFT   JOIN products        p  ON c.product_id  = p.id
    LEFT   JOIN certificate_types ct ON c.cert_type_id = ct.id
    WHERE  c.status      = 'issued'
      AND  c.expiry_date BETWEEN CURDATE() AND DATE_ADD(CURDATE(), INTERVAL 90 DAY)
    ORDER  BY c.expiry_date
    LIMIT  8
");
$expiring_certs = $expiring_certs_result ? $expiring_certs_result->fetch_all(MYSQLI_ASSOC) : [];

// ── Open non-conformances (critical & major first) ───────────
$open_ncs_result = $conn->query("
    SELECT nc.nc_number, nc.severity, nc.nc_source, nc.status,
           nc.response_due_date,
           DATEDIFF(CURDATE(), nc.response_due_date) AS days_overdue,
           o.org_name
    FROM   non_conformances nc
    LEFT   JOIN organizations o ON nc.org_id = o.id
    WHERE  nc.status NOT IN ('closed')
    ORDER  BY FIELD(nc.severity,'critical','major','minor','informational'),
              nc.response_due_date
    LIMIT  8
");
$open_ncs = $open_ncs_result ? $open_ncs_result->fetch_all(MYSQLI_ASSOC) : [];

$conn->close();

// ── Helpers ──────────────────────────────────────────────────
function status_badge(string $status): string {
    return match($status) {
        'submitted','in_progress'       => '<span class="badge bg-primary-subtle text-primary">'.ucwords(str_replace('_',' ',$status)).'</span>',
        'approved','issued','completed' => '<span class="badge bg-success-subtle text-success">'.ucwords(str_replace('_',' ',$status)).'</span>',
        'rejected','revoked'            => '<span class="badge bg-danger-subtle text-danger">'.ucwords(str_replace('_',' ',$status)).'</span>',
        'under_review','awaiting_decision','awaiting_lab','awaiting_inspection'
                                        => '<span class="badge bg-warning-subtle text-warning">'.ucwords(str_replace('_',' ',$status)).'</span>',
        'on_hold','pending_payment','payment_confirmed'
                                        => '<span class="badge bg-secondary-subtle text-secondary">'.ucwords(str_replace('_',' ',$status)).'</span>',
        default                         => '<span class="badge bg-light text-dark">'.ucwords(str_replace('_',' ',$status)).'</span>',
    };
}

function severity_badge(string $sev): string {
    return match($sev) {
        'critical' => '<span class="badge bg-danger">Critical</span>',
        'major'    => '<span class="badge bg-warning text-dark">Major</span>',
        'minor'    => '<span class="badge bg-info text-dark">Minor</span>',
        default    => '<span class="badge bg-secondary">Info</span>',
    };
}

function priority_label(int $p): string {
    return match($p) {
        1 => '<span class="badge bg-danger">Critical</span>',
        2 => '<span class="badge bg-warning text-dark">High</span>',
        3 => '<span class="badge bg-info text-dark">Normal</span>',
        4 => '<span class="badge bg-secondary">Low</span>',
        default => '<span class="badge bg-secondary">—</span>',
    };
}

ob_end_flush();
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Dashboard — SSBS-ISCMS</title>
    <meta name="robots" content="noindex, nofollow">

    <!-- Bootstrap 5 -->
    <link rel="stylesheet" href="assets/libs/bootstrap/css/bootstrap.min.css">
    <!-- Remix Icons -->
    <link rel="stylesheet" href="assets/libs/remixicon/remixicon.css">
    <!-- ApexCharts -->
    <script src="assets/libs/apexcharts/apexcharts.min.js" defer></script>

    <style>
        :root {
            --ssbs-blue:       #1a3a6b;
            --ssbs-blue-light: #2a5298;
            --ssbs-blue-dark:  #0d1f3c;
            --ssbs-gold:       #c8a92b;
            --ssbs-gold-light: #e6c84a;
            --ssbs-green:      #1a6e2e;
            --ssbs-green-light:#28a745;
            --ssbs-red:        #c0392b;
            --sidebar-w:       240px;
            --topbar-h:        64px;
        }

        * { box-sizing: border-box; }

        body {
            font-family: 'Segoe UI', system-ui, sans-serif;
            background: #f0f4f8;
            color: #1c2b4a;
            margin: 0;
        }

        /* ── Sidebar ────────────────────────────── */
        .sidebar {
            position: fixed;
            top: 0; left: 0;
            width: var(--sidebar-w);
            height: 100vh;
            background: linear-gradient(175deg, var(--ssbs-blue-dark) 0%, var(--ssbs-blue) 100%);
            display: flex;
            flex-direction: column;
            z-index: 1000;
            overflow-y: auto;
            transition: transform .3s;
        }

        .sidebar-brand {
            padding: 20px 16px 16px;
            border-bottom: 1px solid rgba(255,255,255,.1);
            text-decoration: none;
        }
        .sidebar-brand .brand-logo {
            font-size: 28px;
            display: block;
            margin-bottom: 4px;
        }
        .sidebar-brand .brand-name {
            font-size: .85rem;
            font-weight: 700;
            color: var(--white, #fff);
            line-height: 1.2;
        }
        .sidebar-brand .brand-sub {
            font-size: .65rem;
            color: rgba(255,255,255,.55);
        }

        .flag-bar {
            display: flex;
            height: 3px;
            margin: 0 16px 12px;
        }
        .flag-bar span { flex: 1; }
        .flag-bar .f-black { background: #000; }
        .flag-bar .f-red   { background: #DD1C1A; }
        .flag-bar .f-green { background: #007A3D; }
        .flag-bar .f-blue  { background: #003893; }

        .sidebar-nav { flex: 1; padding: 6px 0; }

        .nav-section-title {
            font-size: .62rem;
            font-weight: 700;
            letter-spacing: 1px;
            text-transform: uppercase;
            color: rgba(255,255,255,.35);
            padding: 12px 20px 4px;
        }

        .nav-item a {
            display: flex;
            align-items: center;
            gap: 10px;
            padding: 9px 20px;
            color: rgba(255,255,255,.75);
            text-decoration: none;
            font-size: .82rem;
            font-weight: 500;
            border-left: 3px solid transparent;
            transition: all .2s;
        }
        .nav-item a i { font-size: 17px; flex-shrink: 0; }
        .nav-item a:hover,
        .nav-item a.active {
            color: #fff;
            background: rgba(255,255,255,.08);
            border-left-color: var(--ssbs-gold);
        }
        .nav-item a .badge {
            margin-left: auto;
            font-size: .65rem;
        }

        .sidebar-footer {
            padding: 14px 16px;
            border-top: 1px solid rgba(255,255,255,.1);
            font-size: .75rem;
            color: rgba(255,255,255,.4);
            text-align: center;
        }

        /* ── Topbar ─────────────────────────────── */
        .topbar {
            position: fixed;
            top: 0; left: var(--sidebar-w); right: 0;
            height: var(--topbar-h);
            background: #fff;
            border-bottom: 1px solid #e2e8f0;
            display: flex;
            align-items: center;
            padding: 0 24px;
            gap: 16px;
            z-index: 900;
            box-shadow: 0 1px 4px rgba(0,0,0,.06);
        }

        .topbar-title {
            font-size: 1rem;
            font-weight: 700;
            color: var(--ssbs-blue);
            flex: 1;
        }

        .topbar-user {
            display: flex;
            align-items: center;
            gap: 10px;
            cursor: pointer;
        }
        .topbar-user .avatar {
            width: 36px; height: 36px;
            border-radius: 50%;
            background: var(--ssbs-blue);
            color: #fff;
            display: flex;
            align-items: center;
            justify-content: center;
            font-weight: 700;
            font-size: .85rem;
            flex-shrink: 0;
        }
        .topbar-user .user-info .name {
            font-size: .82rem;
            font-weight: 600;
            color: var(--ssbs-blue);
        }
        .topbar-user .user-info .role {
            font-size: .7rem;
            color: #6b7280;
        }

        .topbar-bell {
            position: relative;
            width: 36px; height: 36px;
            border-radius: 50%;
            border: none;
            background: #f0f4f8;
            color: var(--ssbs-blue);
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 18px;
            cursor: pointer;
            transition: background .2s;
        }
        .topbar-bell:hover { background: #e2e8f0; }
        .topbar-bell .dot {
            position: absolute;
            top: 4px; right: 4px;
            width: 8px; height: 8px;
            background: #ef4444;
            border-radius: 50%;
            border: 2px solid #fff;
        }

        /* ── Main content ───────────────────────── */
        .main-content {
            margin-left: var(--sidebar-w);
            margin-top: var(--topbar-h);
            padding: 24px;
            min-height: calc(100vh - var(--topbar-h));
        }

        /* ── Page header ────────────────────────── */
        .page-header {
            margin-bottom: 24px;
        }
        .page-header h1 {
            font-size: 1.35rem;
            font-weight: 700;
            color: var(--ssbs-blue);
            margin: 0 0 2px;
        }
        .page-header p {
            font-size: .82rem;
            color: #6b7280;
            margin: 0;
        }

        /* ── KPI Cards ──────────────────────────── */
        .kpi-grid {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
            gap: 16px;
            margin-bottom: 24px;
        }

        .kpi-card {
            background: #fff;
            border-radius: 14px;
            padding: 20px;
            display: flex;
            align-items: center;
            gap: 16px;
            box-shadow: 0 1px 4px rgba(0,0,0,.06);
            border-top: 3px solid var(--card-color, var(--ssbs-blue));
            transition: transform .2s, box-shadow .2s;
        }
        .kpi-card:hover {
            transform: translateY(-2px);
            box-shadow: 0 4px 16px rgba(0,0,0,.1);
        }
        .kpi-card .kpi-icon {
            width: 48px; height: 48px;
            border-radius: 12px;
            background: var(--card-color-light, #e8f0fb);
            display: flex; align-items: center; justify-content: center;
            font-size: 22px;
            color: var(--card-color, var(--ssbs-blue));
            flex-shrink: 0;
        }
        .kpi-card .kpi-value {
            font-size: 1.75rem;
            font-weight: 800;
            color: var(--ssbs-blue);
            line-height: 1;
        }
        .kpi-card .kpi-label {
            font-size: .72rem;
            color: #6b7280;
            margin-top: 4px;
        }

        /* ── Section cards ──────────────────────── */
        .section-card {
            background: #fff;
            border-radius: 14px;
            box-shadow: 0 1px 4px rgba(0,0,0,.06);
            overflow: hidden;
            margin-bottom: 24px;
        }
        .section-header {
            padding: 16px 20px;
            border-bottom: 1px solid #f1f5f9;
            display: flex;
            align-items: center;
            justify-content: space-between;
        }
        .section-header h2 {
            font-size: .95rem;
            font-weight: 700;
            color: var(--ssbs-blue);
            margin: 0;
            display: flex;
            align-items: center;
            gap: 8px;
        }
        .section-header h2 i { color: var(--ssbs-gold); }
        .section-header a {
            font-size: .75rem;
            color: var(--ssbs-blue);
            text-decoration: none;
        }
        .section-header a:hover { text-decoration: underline; }

        /* ── Table tweaks ───────────────────────── */
        .ssbs-table {
            width: 100%;
            font-size: .8rem;
            border-collapse: collapse;
        }
        .ssbs-table thead th {
            background: #f8fafc;
            color: #6b7280;
            font-weight: 700;
            font-size: .72rem;
            text-transform: uppercase;
            letter-spacing: .5px;
            padding: 10px 14px;
            border-bottom: 1px solid #e2e8f0;
        }
        .ssbs-table tbody td {
            padding: 10px 14px;
            border-bottom: 1px solid #f1f5f9;
            vertical-align: middle;
        }
        .ssbs-table tbody tr:last-child td { border-bottom: none; }
        .ssbs-table tbody tr:hover td { background: #f8fafc; }

        .empty-row td {
            text-align: center;
            color: #9ca3af;
            padding: 28px !important;
            font-size: .82rem;
        }

        /* ── Alert-row highlighting ─────────────── */
        .row-critical td { background: #fff1f0; }
        .row-warn     td { background: #fffbeb; }

        /* ── Quick actions ──────────────────────── */
        .quick-actions {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(130px, 1fr));
            gap: 12px;
            padding: 16px 20px;
        }
        .qa-btn {
            display: flex;
            flex-direction: column;
            align-items: center;
            gap: 8px;
            padding: 16px 12px;
            border-radius: 12px;
            background: #f8fafc;
            border: 1px solid #e2e8f0;
            color: var(--ssbs-blue);
            text-decoration: none;
            font-size: .75rem;
            font-weight: 600;
            transition: all .2s;
            text-align: center;
        }
        .qa-btn i { font-size: 24px; }
        .qa-btn:hover {
            background: var(--ssbs-blue);
            color: #fff;
            border-color: var(--ssbs-blue);
            transform: translateY(-2px);
            box-shadow: 0 4px 12px rgba(26,58,107,.25);
        }

        /* ── Expiry badge ───────────────────────── */
        .expiry-badge {
            display: inline-block;
            padding: 2px 8px;
            border-radius: 10px;
            font-size: .7rem;
            font-weight: 700;
        }
        .expiry-critical { background: #fee2e2; color: #991b1b; }
        .expiry-warn     { background: #fef3c7; color: #92400e; }
        .expiry-ok       { background: #d1fae5; color: #065f46; }

        /* ── Chart wrapper ──────────────────────── */
        .chart-wrap { padding: 16px 20px 20px; }

        /* ── Responsive ─────────────────────────── */
        @media (max-width: 991px) {
            .sidebar { transform: translateX(-100%); }
            .sidebar.open { transform: translateX(0); }
            .topbar, .main-content { margin-left: 0; left: 0; }
        }
    </style>
</head>
<body>

<!-- ═══════════════════════════════════════════════════════════
     SIDEBAR
════════════════════════════════════════════════════════════ -->
<nav class="sidebar" id="sidebar">
    <a href="index.php" class="sidebar-brand text-decoration-none">
        <span class="brand-logo">🏛️</span>
        <span class="brand-name">SSBS-ISCMS</span>
        <span class="brand-sub">South Sudan Bureau of Standards</span>
    </a>

    <div class="flag-bar">
        <span class="f-black"></span>
        <span class="f-red"></span>
        <span class="f-green"></span>
        <span class="f-blue"></span>
    </div>

    <div class="sidebar-nav">
        <div class="nav-section-title">Main</div>
        <div class="nav-item">
            <a href="index.php" class="active">
                <i class="ri-dashboard-3-line"></i> Dashboard
            </a>
        </div>

        <div class="nav-section-title">Operations</div>
        <div class="nav-item">
            <a href="applications.php">
                <i class="ri-file-list-3-line"></i> Applications
                <?php if ($kpi_pending_apps > 0): ?>
                    <span class="badge bg-warning text-dark"><?= $kpi_pending_apps ?></span>
                <?php endif; ?>
            </a>
        </div>
        <div class="nav-item">
            <a href="inspections.php">
                <i class="ri-search-2-line"></i> Inspections
                <?php if ($kpi_open_inspections > 0): ?>
                    <span class="badge bg-primary"><?= $kpi_open_inspections ?></span>
                <?php endif; ?>
            </a>
        </div>
        <div class="nav-item">
            <a href="laboratory.php">
                <i class="ri-flask-line"></i> Laboratory
                <?php if ($kpi_pending_lab > 0): ?>
                    <span class="badge bg-info text-dark"><?= $kpi_pending_lab ?></span>
                <?php endif; ?>
            </a>
        </div>
        <div class="nav-item">
            <a href="certifications.php">
                <i class="ri-shield-star-line"></i> Certifications
                <?php if ($kpi_expiring_certs > 0): ?>
                    <span class="badge bg-danger"><?= $kpi_expiring_certs ?></span>
                <?php endif; ?>
            </a>
        </div>
        <div class="nav-item">
            <a href="import_export.php">
                <i class="ri-ship-line"></i> Import / Export
            </a>
        </div>

        <div class="nav-section-title">Compliance</div>
        <div class="nav-item">
            <a href="non_conformances.php">
                <i class="ri-error-warning-line"></i> Non-Conformances
                <?php if ($kpi_open_ncs > 0): ?>
                    <span class="badge bg-danger"><?= $kpi_open_ncs ?></span>
                <?php endif; ?>
            </a>
        </div>
        <div class="nav-item">
            <a href="enforcement.php">
                <i class="ri-scales-3-line"></i> Enforcement
            </a>
        </div>
        <div class="nav-item">
            <a href="market_surveillance.php">
                <i class="ri-store-2-line"></i> Market Surveillance
            </a>
        </div>
        <div class="nav-item">
            <a href="complaints.php">
                <i class="ri-feedback-line"></i> Complaints
            </a>
        </div>

        <div class="nav-section-title">Standards</div>
        <div class="nav-item">
            <a href="standards.php">
                <i class="ri-book-2-line"></i> Standards Library
            </a>
        </div>
        <div class="nav-item">
            <a href="products.php">
                <i class="ri-box-3-line"></i> Products Register
            </a>
        </div>
        <div class="nav-item">
            <a href="organizations.php">
                <i class="ri-building-2-line"></i> Organisations
            </a>
        </div>

        <?php if (in_array($role_code, ['SUPER_ADMIN','ADMIN'])): ?>
        <div class="nav-section-title">Administration</div>
        <div class="nav-item">
            <a href="users.php">
                <i class="ri-team-line"></i> Users
            </a>
        </div>
        <div class="nav-item">
            <a href="audit_logs.php">
                <i class="ri-file-code-line"></i> Audit Logs
            </a>
        </div>
        <div class="nav-item">
            <a href="settings.php">
                <i class="ri-settings-3-line"></i> System Settings
            </a>
        </div>
        <?php endif; ?>
    </div>

    <div class="sidebar-footer">
        SSBS-ISCMS v2.0 &bull; <?php echo date('Y'); ?>
    </div>
</nav>

<!-- ═══════════════════════════════════════════════════════════
     TOPBAR
════════════════════════════════════════════════════════════ -->
<header class="topbar">
    <!-- Mobile toggle -->
    <button class="d-lg-none btn btn-sm btn-light me-2" id="sidebar-toggle" style="border:none">
        <i class="ri-menu-line" style="font-size:18px"></i>
    </button>

    <div class="topbar-title">Dashboard</div>

    <div class="d-flex align-items-center gap-2">
        <!-- Date/time -->
        <div class="d-none d-md-block text-end me-2" style="font-size:.72rem; color:#6b7280; line-height:1.4">
            <div id="topbar-date" style="font-weight:600; color:var(--ssbs-blue)"></div>
            <div id="topbar-time"></div>
        </div>

        <!-- Notifications -->
        <button class="topbar-bell" title="Notifications">
            <i class="ri-notification-3-line"></i>
            <?php if (($kpi_expiring_certs + $kpi_overdue_ncs) > 0): ?>
                <span class="dot"></span>
            <?php endif; ?>
        </button>

        <!-- User dropdown -->
        <div class="dropdown">
            <div class="topbar-user dropdown-toggle" data-bs-toggle="dropdown">
                <div class="avatar">
                    <?php echo strtoupper(substr($first_name, 0, 1) . substr($_SESSION['last_name'] ?? '', 0, 1)); ?>
                </div>
                <div class="user-info d-none d-sm-block">
                    <div class="name"><?php echo htmlspecialchars($full_name); ?></div>
                    <div class="role"><?php echo htmlspecialchars($_SESSION['role_name'] ?? $role_code); ?></div>
                </div>
            </div>
            <ul class="dropdown-menu dropdown-menu-end" style="min-width:180px; font-size:.83rem">
                <li><a class="dropdown-item" href="profile.php"><i class="ri-user-line me-2"></i>My Profile</a></li>
                <li><a class="dropdown-item" href="change_password.php"><i class="ri-lock-password-line me-2"></i>Change Password</a></li>
                <li><hr class="dropdown-divider"></li>
                <li><a class="dropdown-item text-danger" href="logout.php"><i class="ri-logout-box-line me-2"></i>Sign Out</a></li>
            </ul>
        </div>
    </div>
</header>

<!-- ═══════════════════════════════════════════════════════════
     MAIN CONTENT
════════════════════════════════════════════════════════════ -->
<main class="main-content">

    <!-- Page header -->
    <div class="page-header">
        <h1>Good <?php
            $h = (int)date('H');
            echo $h < 12 ? 'Morning' : ($h < 17 ? 'Afternoon' : 'Evening');
        ?>, <?php echo htmlspecialchars($first_name); ?>!</h1>
        <p>
            <?php echo date('l, d F Y'); ?> &mdash; <?php echo htmlspecialchars($_SESSION['role_name'] ?? $role_code); ?>
            <?php if ($dept_name): ?>&nbsp;&bull;&nbsp;<?php echo htmlspecialchars($dept_name); ?><?php endif; ?>
        </p>
    </div>

    <!-- ── Alerts banner ───────────────────────────────────── -->
    <?php if ($kpi_expiring_certs > 0 || $kpi_overdue_ncs > 0): ?>
    <div class="alert alert-warning d-flex align-items-center gap-2 mb-4" style="border-radius:12px; font-size:.83rem">
        <i class="ri-alarm-warning-line" style="font-size:20px; flex-shrink:0"></i>
        <div>
            <?php if ($kpi_expiring_certs > 0): ?>
                <strong><?= $kpi_expiring_certs ?> certificate(s)</strong> expire within 90 days.
            <?php endif; ?>
            <?php if ($kpi_overdue_ncs > 0): ?>
                &nbsp;&bull;&nbsp; <strong><?= $kpi_overdue_ncs ?> non-conformance(s)</strong> are overdue for response.
            <?php endif; ?>
            &nbsp;<a href="certifications.php?filter=expiring" class="alert-link ms-1">View details &rarr;</a>
        </div>
    </div>
    <?php endif; ?>

    <!-- ── KPI Cards ───────────────────────────────────────── -->
    <div class="kpi-grid">
        <div class="kpi-card" style="--card-color:#1a3a6b; --card-color-light:#e8f0fb">
            <div class="kpi-icon"><i class="ri-shield-star-line"></i></div>
            <div>
                <div class="kpi-value"><?= number_format($kpi_active_certs) ?></div>
                <div class="kpi-label">Active Certificates</div>
            </div>
        </div>
        <div class="kpi-card" style="--card-color:#c8a92b; --card-color-light:#fef9e7">
            <div class="kpi-icon"><i class="ri-time-line"></i></div>
            <div>
                <div class="kpi-value"><?= number_format($kpi_expiring_certs) ?></div>
                <div class="kpi-label">Expiring (90 days)</div>
            </div>
        </div>
        <div class="kpi-card" style="--card-color:#2a5298; --card-color-light:#e8f0fb">
            <div class="kpi-icon"><i class="ri-file-list-3-line"></i></div>
            <div>
                <div class="kpi-value"><?= number_format($kpi_pending_apps) ?></div>
                <div class="kpi-label">Pending Applications</div>
            </div>
        </div>
        <div class="kpi-card" style="--card-color:#0d6efd; --card-color-light:#e7f1ff">
            <div class="kpi-icon"><i class="ri-search-2-line"></i></div>
            <div>
                <div class="kpi-value"><?= number_format($kpi_open_inspections) ?></div>
                <div class="kpi-label">Open Inspections</div>
            </div>
        </div>
        <div class="kpi-card" style="--card-color:#198754; --card-color-light:#d1e7dd">
            <div class="kpi-icon"><i class="ri-flask-line"></i></div>
            <div>
                <div class="kpi-value"><?= number_format($kpi_pending_lab) ?></div>
                <div class="kpi-label">Lab Requests Active</div>
            </div>
        </div>
        <div class="kpi-card" style="--card-color:#dc3545; --card-color-light:#f8d7da">
            <div class="kpi-icon"><i class="ri-error-warning-line"></i></div>
            <div>
                <div class="kpi-value"><?= number_format($kpi_open_ncs) ?></div>
                <div class="kpi-label">Open Non-Conformances</div>
            </div>
        </div>
        <div class="kpi-card" style="--card-color:#6f42c1; --card-color-light:#e9e0f8">
            <div class="kpi-icon"><i class="ri-building-2-line"></i></div>
            <div>
                <div class="kpi-value"><?= number_format($kpi_orgs) ?></div>
                <div class="kpi-label">Active Organisations</div>
            </div>
        </div>
        <div class="kpi-card" style="--card-color:#fd7e14; --card-color-light:#ffe5d0">
            <div class="kpi-icon"><i class="ri-alarm-warning-line"></i></div>
            <div>
                <div class="kpi-value"><?= number_format($kpi_overdue_ncs) ?></div>
                <div class="kpi-label">Overdue NCs</div>
            </div>
        </div>
    </div>

    <!-- ── Charts row ──────────────────────────────────────── -->
    <div class="row g-4 mb-4">
        <div class="col-lg-8">
            <div class="section-card h-100">
                <div class="section-header">
                    <h2><i class="ri-bar-chart-2-line"></i> Applications Trend (12 months)</h2>
                </div>
                <div class="chart-wrap">
                    <div id="chart-app-trend" style="min-height:240px"></div>
                </div>
            </div>
        </div>
        <div class="col-lg-4">
            <div class="section-card h-100">
                <div class="section-header">
                    <h2><i class="ri-pie-chart-2-line"></i> Certifications</h2>
                </div>
                <div class="chart-wrap">
                    <div id="chart-cert-status" style="min-height:240px"></div>
                </div>
            </div>
        </div>
    </div>

    <!-- ── Quick Actions ───────────────────────────────────── -->
    <div class="section-card mb-4">
        <div class="section-header">
            <h2><i class="ri-flashlight-line"></i> Quick Actions</h2>
        </div>
        <div class="quick-actions">
            <a href="applications.php?action=new" class="qa-btn">
                <i class="ri-file-add-line"></i> New Application
            </a>
            <a href="inspections.php?action=schedule" class="qa-btn">
                <i class="ri-calendar-check-line"></i> Schedule Inspection
            </a>
            <a href="certifications.php?action=new" class="qa-btn">
                <i class="ri-award-line"></i> Issue Certificate
            </a>
            <a href="laboratory.php?action=new" class="qa-btn">
                <i class="ri-test-tube-line"></i> New Lab Request
            </a>
            <a href="import_export.php?action=new" class="qa-btn">
                <i class="ri-ship-2-line"></i> New Permit
            </a>
            <a href="non_conformances.php?action=new" class="qa-btn">
                <i class="ri-error-warning-line"></i> Log Non-Conformance
            </a>
            <a href="complaints.php?action=new" class="qa-btn">
                <i class="ri-customer-service-2-line"></i> Log Complaint
            </a>
            <a href="reports.php" class="qa-btn">
                <i class="ri-file-chart-line"></i> Reports
            </a>
        </div>
    </div>

    <!-- ── Recent Applications ─────────────────────────────── -->
    <div class="section-card mb-4">
        <div class="section-header">
            <h2><i class="ri-file-list-3-line"></i> Recent Applications</h2>
            <a href="applications.php">View all &rarr;</a>
        </div>
        <div class="table-responsive">
            <table class="ssbs-table">
                <thead>
                    <tr>
                        <th>App No.</th>
                        <th>Organisation</th>
                        <th>Type</th>
                        <th>Status</th>
                        <th>Priority</th>
                        <th>Submitted</th>
                        <th>Due</th>
                        <th>Submitted By</th>
                    </tr>
                </thead>
                <tbody>
                    <?php if (empty($recent_apps)): ?>
                        <tr class="empty-row"><td colspan="8"><i class="ri-inbox-line me-2"></i>No pending applications</td></tr>
                    <?php else: ?>
                        <?php foreach ($recent_apps as $app): ?>
                        <tr>
                            <td><a href="applications.php?id=<?= htmlspecialchars($app['id']) ?>" style="color:var(--ssbs-blue); font-weight:600; font-size:.78rem">
                                <?= htmlspecialchars($app['application_number']) ?>
                            </a></td>
                            <td><?= htmlspecialchars($app['org_name'] ?? '—') ?></td>
                            <td><small><?= htmlspecialchars(str_replace('_',' ', $app['application_type'])) ?></small></td>
                            <td><?= status_badge($app['status']) ?></td>
                            <td><?= priority_label((int)$app['priority']) ?></td>
                            <td><small><?= $app['submitted_at'] ? date('d M Y', strtotime($app['submitted_at'])) : '—' ?></small></td>
                            <td>
                                <?php if ($app['due_date']): ?>
                                    <?php $days = (int)((strtotime($app['due_date']) - time()) / 86400); ?>
                                    <small class="<?= $days < 3 ? 'text-danger fw-bold' : ($days < 7 ? 'text-warning fw-semibold' : '') ?>">
                                        <?= date('d M Y', strtotime($app['due_date'])) ?>
                                    </small>
                                <?php else: ?>—<?php endif; ?>
                            </td>
                            <td><small><?= htmlspecialchars($app['submitted_by'] ?? '—') ?></small></td>
                        </tr>
                        <?php endforeach; ?>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
    </div>

    <!-- ── Two-column: Inspections + Expiring Certs ────────── -->
    <div class="row g-4 mb-4">

        <!-- Upcoming Inspections -->
        <div class="col-xl-6">
            <div class="section-card h-100">
                <div class="section-header">
                    <h2><i class="ri-search-2-line"></i> Upcoming Inspections (14 days)</h2>
                    <a href="inspections.php">View all &rarr;</a>
                </div>
                <div class="table-responsive">
                    <table class="ssbs-table">
                        <thead>
                            <tr>
                                <th>No.</th>
                                <th>Organisation</th>
                                <th>Type</th>
                                <th>Date</th>
                                <th>Inspector</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php if (empty($upcoming_inspections)): ?>
                                <tr class="empty-row"><td colspan="5"><i class="ri-calendar-check-line me-2"></i>No upcoming inspections</td></tr>
                            <?php else: ?>
                                <?php foreach ($upcoming_inspections as $ins): ?>
                                <tr>
                                    <td style="font-size:.75rem; font-weight:600; color:var(--ssbs-blue)"><?= htmlspecialchars($ins['inspection_number']) ?></td>
                                    <td><small><?= htmlspecialchars($ins['org_name'] ?? '—') ?></small></td>
                                    <td><small><?= htmlspecialchars(str_replace('_',' ', $ins['inspection_type'])) ?></small></td>
                                    <td><small><?= date('d M', strtotime($ins['scheduled_date'])) ?></small></td>
                                    <td><small><?= htmlspecialchars($ins['inspector_name'] ?? '—') ?></small></td>
                                </tr>
                                <?php endforeach; ?>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>

        <!-- Expiring Certifications -->
        <div class="col-xl-6">
            <div class="section-card h-100">
                <div class="section-header">
                    <h2><i class="ri-timer-flash-line"></i> Certificates Expiring Soon</h2>
                    <a href="certifications.php?filter=expiring">View all &rarr;</a>
                </div>
                <div class="table-responsive">
                    <table class="ssbs-table">
                        <thead>
                            <tr>
                                <th>Cert No.</th>
                                <th>Organisation</th>
                                <th>Product</th>
                                <th>Expires</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php if (empty($expiring_certs)): ?>
                                <tr class="empty-row"><td colspan="4"><i class="ri-checkbox-circle-line me-2"></i>No certificates expiring soon</td></tr>
                            <?php else: ?>
                                <?php foreach ($expiring_certs as $cert): ?>
                                <?php
                                    $days_left = (int)$cert['days_left'];
                                    $ex_class  = $days_left <= 30 ? 'expiry-critical' : ($days_left <= 60 ? 'expiry-warn' : 'expiry-ok');
                                ?>
                                <tr>
                                    <td style="font-size:.75rem; font-weight:600; color:var(--ssbs-blue)"><?= htmlspecialchars($cert['certificate_number']) ?></td>
                                    <td><small><?= htmlspecialchars($cert['org_name'] ?? '—') ?></small></td>
                                    <td><small><?= htmlspecialchars($cert['product_name'] ?? '—') ?></small></td>
                                    <td>
                                        <span class="expiry-badge <?= $ex_class ?>">
                                            <?= $days_left ?>d — <?= date('d M Y', strtotime($cert['expiry_date'])) ?>
                                        </span>
                                    </td>
                                </tr>
                                <?php endforeach; ?>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>

    </div>

    <!-- ── Open Non-Conformances ───────────────────────────── -->
    <div class="section-card mb-4">
        <div class="section-header">
            <h2><i class="ri-error-warning-line"></i> Open Non-Conformances</h2>
            <a href="non_conformances.php">View all &rarr;</a>
        </div>
        <div class="table-responsive">
            <table class="ssbs-table">
                <thead>
                    <tr>
                        <th>NC No.</th>
                        <th>Organisation</th>
                        <th>Severity</th>
                        <th>Source</th>
                        <th>Status</th>
                        <th>Response Due</th>
                        <th>Overdue</th>
                    </tr>
                </thead>
                <tbody>
                    <?php if (empty($open_ncs)): ?>
                        <tr class="empty-row"><td colspan="7"><i class="ri-checkbox-circle-line me-2"></i>No open non-conformances</td></tr>
                    <?php else: ?>
                        <?php foreach ($open_ncs as $nc): ?>
                        <?php $is_overdue = $nc['days_overdue'] > 0 && !empty($nc['response_due_date']); ?>
                        <tr class="<?= $nc['severity'] === 'critical' ? 'row-critical' : ($is_overdue ? 'row-warn' : '') ?>">
                            <td style="font-size:.75rem; font-weight:600; color:var(--ssbs-blue)"><?= htmlspecialchars($nc['nc_number']) ?></td>
                            <td><small><?= htmlspecialchars($nc['org_name'] ?? '—') ?></small></td>
                            <td><?= severity_badge($nc['severity']) ?></td>
                            <td><small><?= htmlspecialchars(str_replace('_',' ', $nc['nc_source'])) ?></small></td>
                            <td><?= status_badge($nc['status']) ?></td>
                            <td><small><?= $nc['response_due_date'] ? date('d M Y', strtotime($nc['response_due_date'])) : '—' ?></small></td>
                            <td>
                                <?php if ($is_overdue): ?>
                                    <span class="text-danger fw-bold" style="font-size:.75rem">+<?= $nc['days_overdue'] ?>d</span>
                                <?php else: ?>
                                    <span class="text-muted" style="font-size:.75rem">—</span>
                                <?php endif; ?>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
    </div>

</main>

<!-- Bootstrap JS -->
<script src="assets/libs/bootstrap/js/bootstrap.bundle.min.js"></script>

<script>
// ── Live clock ──────────────────────────────────────────────
(function tick() {
    const now = new Date();
    const opts = { weekday:'long', year:'numeric', month:'long', day:'numeric' };
    const dateEl = document.getElementById('topbar-date');
    const timeEl = document.getElementById('topbar-time');
    if (dateEl) dateEl.textContent = now.toLocaleDateString('en-SS', opts);
    if (timeEl) timeEl.textContent = now.toLocaleTimeString('en-SS', { hour:'2-digit', minute:'2-digit', hour12:false }) + ' EAT';
    setTimeout(tick, 10000);
})();

// ── Mobile sidebar ──────────────────────────────────────────
document.getElementById('sidebar-toggle')?.addEventListener('click', function () {
    document.getElementById('sidebar').classList.toggle('open');
});

// ── Charts (loaded after DOMContentLoaded) ──────────────────
document.addEventListener('DOMContentLoaded', function () {
    if (typeof ApexCharts === 'undefined') return;

    fetch('index.php?ajax=charts')
        .then(r => r.json())
        .then(data => {

            // ── Application trend (area chart) ────────────────
            if (data.app_trend && document.getElementById('chart-app-trend')) {
                const labels = data.app_trend.map(r => r.month);
                const values = data.app_trend.map(r => parseInt(r.total));

                new ApexCharts(document.getElementById('chart-app-trend'), {
                    chart:  { type: 'area', height: 240, toolbar: { show: false }, sparkline: { enabled: false } },
                    series: [{ name: 'Applications', data: values }],
                    xaxis:  { categories: labels, labels: { style: { fontSize: '10px' } } },
                    yaxis:  { labels: { style: { fontSize: '10px' } } },
                    colors: ['#1a3a6b'],
                    fill:   { type: 'gradient', gradient: { shadeIntensity: 1, opacityFrom: .4, opacityTo: .05 } },
                    stroke: { curve: 'smooth', width: 2 },
                    tooltip: { theme: 'light' },
                    grid:  { borderColor: '#f1f5f9' },
                    dataLabels: { enabled: false },
                }).render();
            }

            // ── Certifications donut ───────────────────────────
            if (data.cert_status && document.getElementById('chart-cert-status')) {
                const colorMap = {
                    issued:         '#1a3a6b',
                    pending_review: '#c8a92b',
                    approved:       '#28a745',
                    expired:        '#dc3545',
                    suspended:      '#fd7e14',
                    revoked:        '#6c757d',
                    surrendered:    '#adb5bd',
                };
                const labels = data.cert_status.map(r => r.status.replace(/_/g,' '));
                const values = data.cert_status.map(r => parseInt(r.cnt));
                const colors = data.cert_status.map(r => colorMap[r.status] || '#adb5bd');

                new ApexCharts(document.getElementById('chart-cert-status'), {
                    chart:     { type: 'donut', height: 240, toolbar: { show: false } },
                    series:    values,
                    labels:    labels,
                    colors:    colors,
                    legend:    { position: 'bottom', fontSize: '11px' },
                    dataLabels:{ style: { fontSize: '10px' } },
                    tooltip:   { theme: 'light' },
                }).render();
            }
        })
        .catch(() => { /* Chart data unavailable — silent fail */ });
});
</script>

</body>
</html>
