<?php
require_once __DIR__ . '/includes/config.php';
$user = require_login('internal');

if (!empty($_SESSION['must_change_pw'])) redirect('/change-password.php');

/* SysAdmin gets the full platform dashboard below; every other (report-viewer) role
   uses the Workspace home (admin/workspace.php), which carries the all-client KPIs.
   Coding-only users (no billing report access) land on the coding home instead. */
if (!is_sysadmin()) {
    if (is_coding_user() && !can('report.view'))  redirect(coding_home_url());
    if (is_billing_user() && !can('report.view')) redirect(can('billing.allocate') ? '/admin/billing-allocation.php' : '/admin/my-billing.php');
    if (is_ar_user() && !can('report.view'))      redirect(ar_home_url());   // AR/Collections staff → their module home
    if (can('report.view'))                       redirect('/admin/workspace.php');
    // No module + no report access yet (truly unassigned user).
    // Render a minimal landing HERE — never bounce to workspace.php (it requires report.view
    // and would redirect back, causing ERR_TOO_MANY_REDIRECTS).
    $pageTitle = 'Home';
    require __DIR__ . '/includes/header.php';
    ?>
    <div class="page-body"><div class="container-xl"><div class="card"><div class="card-body text-center py-5">
        <div style="font-size:2.2rem">👋</div>
        <h3 class="mt-2">Welcome, <?= e(explode(' ', $user['name'])[0]) ?></h3>
        <p class="text-secondary mb-0">Your workspace isn’t set up yet — your module is being prepared.<br>Please contact your administrator if you need access.</p>
    </div></div></div></div>
    <?php
    require __DIR__ . '/includes/footer.php';
    exit;
}

$pdo = db();

/* ============================================================
   MANAGER VIEW — overall ALL-CLIENT collection dashboard.
   SysAdmin falls through to the full platform dashboard below.
   ============================================================ */
if (false) {   // superseded by admin/workspace.php — kept for reference, never runs
    $rows = [];
    try {
        $rows = $pdo->query("
            SELECT cr.report_id,
                   COALESCE(c.name,'(unknown)') AS client,
                   rep.name AS report_name,
                   COUNT(DISTINCT cr.visit_id) AS claims,
                   COUNT(DISTINCT CASE WHEN cr.primary_ins_paid > 0 THEN cr.visit_id END) AS paid_n,
                   SUM(cr.charge_amount) AS charge,
                   SUM(cr.expected_payment) AS expected,
                   SUM(cr.primary_ins_paid + cr.secondary_ins_paid + cr.tertiary_ins_paid + cr.patient_payment_amount) AS paid,
                   SUM(cr.insurance_balance) AS ins_balance,
                   SUM(cr.patient_balance) AS pat_balance,
                   COUNT(DISTINCT CASE WHEN cr.insurance_balance > 0 OR cr.patient_balance > 0 THEN cr.visit_id END) AS outst_n
            FROM collection_raw cr
            JOIN reports rep ON rep.id = cr.report_id AND rep.deleted_at IS NULL
            JOIN processes p ON p.id   = rep.process_id
            JOIN clients   c ON c.id   = p.client_id
            GROUP BY cr.report_id
            ORDER BY charge DESC
        ")->fetchAll();
    } catch (Throwable $e) { /* schema not applied yet */ }

    $g = ['claims'=>0,'paid_n'=>0,'charge'=>0,'expected'=>0,'paid'=>0,'ins_balance'=>0,'pat_balance'=>0,'outst_n'=>0];
    foreach ($rows as $r) foreach ($g as $k=>$_) $g[$k] += (float) $r[$k];
    // Collection % = paid claims ÷ total claims
    $gColl   = $g['claims'] > 0 ? $g['paid_n']/$g['claims']*100 : 0;
    $clientCt = count(array_unique(array_map(fn($r)=>$r['client'], $rows)));
    $money  = fn($v) => '$'.number_format((float)$v, 2);
    // Tiles show the FULL accurate amount (client requirement — not K/M abbreviated).
    $moneyS = function($v){ return '$' . number_format((float)$v, 2); };
    $collColor = fn($p) => $p>=70 ? 'green' : ($p>=40 ? 'orange' : 'red');

    $pageTitle = 'Clients Overview';
    require __DIR__ . '/includes/header.php';
    ?>
    <div class="page-header"><div class="container-xl"><div class="row align-items-center">
        <div class="col">
            <h2 class="page-title"><i class="ti ti-building-bank me-2 text-primary"></i>All-Clients Collection Overview</h2>
            <div class="text-secondary">Aggregate A/R across every client's collection report &middot; <?= (int)$clientCt ?> client(s), <?= count($rows) ?> report(s)</div>
        </div>
    </div></div></div>
    <div class="page-body"><div class="container-xl">
    <?php if (!$rows): ?>
        <div class="card"><div class="card-body text-center text-secondary py-5">
            <div style="font-size:2.5rem">📊</div>
            <h3 class="mt-2">No collection data yet</h3>
            <p class="mb-0">Collection reports will appear here once data has been uploaded.</p>
        </div></div>
    <?php else: ?>
        <div class="row row-cards mb-3">
            <div class="col-6 col-lg-3"><div class="card card-sm"><div class="card-body">
                <div class="text-secondary small">Total Charge</div><div class="h2 mb-0"><?= $moneyS($g['charge']) ?></div></div></div></div>
            <div class="col-6 col-lg-3"><div class="card card-sm"><div class="card-body">
                <div class="text-secondary small">Total Expected Payment</div><div class="h2 mb-0"><?= $moneyS($g['expected']) ?></div></div></div></div>
            <div class="col-6 col-lg-3"><div class="card card-sm"><div class="card-body">
                <div class="text-secondary small">Total Paid</div><div class="h2 mb-0 text-green"><?= $moneyS($g['paid']) ?></div></div></div></div>
            <div class="col-6 col-lg-3"><div class="card card-sm"><div class="card-body">
                <div class="text-secondary small">Insurance Balance</div><div class="h2 mb-0 text-orange"><?= $moneyS($g['ins_balance']) ?></div></div></div></div>
            <div class="col-6 col-lg-3"><div class="card card-sm"><div class="card-body">
                <div class="text-secondary small">Patient Balance</div><div class="h2 mb-0 text-purple"><?= $moneyS($g['pat_balance']) ?></div></div></div></div>
            <div class="col-6 col-lg-3"><div class="card card-sm"><div class="card-body">
                <div class="text-secondary small">Collection %</div><div class="h2 mb-0 text-<?= $collColor($gColl) ?>"><?= number_format($gColl,1) ?>%</div>
                <div class="small text-secondary">Paid claims &divide; Total claims</div></div></div></div>
            <div class="col-6 col-lg-3"><div class="card card-sm"><div class="card-body">
                <div class="text-secondary small">Total Claims</div><div class="h2 mb-0"><?= number_format($g['claims']) ?></div></div></div></div>
            <div class="col-6 col-lg-3"><div class="card card-sm"><div class="card-body">
                <div class="text-secondary small">Open-balance Claims</div><div class="h2 mb-0"><?= number_format($g['outst_n']) ?></div></div></div></div>
            <div class="col-6 col-lg-3"><div class="card card-sm"><div class="card-body">
                <div class="text-secondary small">Clients</div><div class="h2 mb-0"><?= (int)$clientCt ?></div></div></div></div>
        </div>

        <div class="card">
            <div class="card-header"><h3 class="card-title"><i class="ti ti-users me-1"></i>By client</h3></div>
            <div class="table-responsive"><table class="table table-vcenter card-table">
                <thead><tr>
                    <th>Client</th><th>Report</th><th class="text-end">Claims</th>
                    <th class="text-end">Charge</th><th class="text-end">Expected</th>
                    <th class="text-end">Total Paid</th>
                    <th class="text-end">Insurance Balance</th>
                    <th class="text-end">Patient Balance</th>
                    <th class="text-end">Collection %</th><th></th>
                </tr></thead>
                <tbody>
                <?php foreach ($rows as $r):
                    // Collection % = paid claims ÷ total claims
                    $cp = (int)$r['claims'] > 0 ? (int)$r['paid_n']/(int)$r['claims']*100 : 0; ?>
                    <tr>
                        <td class="fw-medium"><?= e($r['client']) ?></td>
                        <td class="text-secondary"><?= e($r['report_name']) ?></td>
                        <td class="text-end"><?= number_format((int)$r['claims']) ?></td>
                        <td class="text-end"><?= $money($r['charge']) ?></td>
                        <td class="text-end"><?= $money($r['expected']) ?></td>
                        <td class="text-end text-green"><?= $money($r['paid']) ?></td>
                        <td class="text-end text-orange"><?= $money($r['ins_balance']) ?></td>
                        <td class="text-end text-purple"><?= $money($r['pat_balance']) ?></td>
                        <td class="text-end"><span class="text-<?= $collColor($cp) ?> fw-bold"><?= number_format($cp,1) ?>%</span></td>
                        <td class="text-end"><a href="<?= e(url('/admin/collection.php?id='.(int)$r['report_id'])) ?>" class="btn btn-sm btn-outline-primary">Open</a></td>
                    </tr>
                <?php endforeach; ?>
                </tbody>
                <tfoot><tr class="fw-bold" style="background:var(--m-surface-2)">
                    <td colspan="2">TOTAL &mdash; <?= (int)$clientCt ?> client(s)</td>
                    <td class="text-end"><?= number_format($g['claims']) ?></td>
                    <td class="text-end"><?= $money($g['charge']) ?></td>
                    <td class="text-end"><?= $money($g['expected']) ?></td>
                    <td class="text-end text-green"><?= $money($g['paid']) ?></td>
                    <td class="text-end text-orange"><?= $money($g['ins_balance']) ?></td>
                    <td class="text-end text-purple"><?= $money($g['pat_balance']) ?></td>
                    <td class="text-end"><span class="text-<?= $collColor($gColl) ?>"><?= number_format($gColl,1) ?>%</span></td>
                    <td></td>
                </tr></tfoot>
            </table></div>
        </div>
    <?php endif; ?>
    </div></div>
    <?php
    require __DIR__ . '/includes/footer.php';
    exit;
}

/* ============= COUNTS ============= */
$counts = [
    'verticals'   => (int) $pdo->query('SELECT COUNT(*) FROM verticals  WHERE deleted_at IS NULL')->fetchColumn(),
    'clients'     => (int) $pdo->query('SELECT COUNT(*) FROM clients    WHERE deleted_at IS NULL')->fetchColumn(),
    'processes'   => (int) $pdo->query('SELECT COUNT(*) FROM processes  WHERE deleted_at IS NULL')->fetchColumn(),
    'reports'     => (int) $pdo->query('SELECT COUNT(*) FROM reports    WHERE deleted_at IS NULL')->fetchColumn(),
    'users_int'   => (int) $pdo->query("SELECT COUNT(*) FROM users WHERE user_type='internal' AND status='active'")->fetchColumn(),
    'users_cli'   => (int) $pdo->query("SELECT COUNT(*) FROM users WHERE user_type='client'   AND status='active'")->fetchColumn(),
    'uploads_24h' => (int) $pdo->query("SELECT COUNT(*) FROM report_uploads WHERE created_at > NOW() - INTERVAL 1 DAY")->fetchColumn(),
    'uploads_7d'  => (int) $pdo->query("SELECT COUNT(*) FROM report_uploads WHERE created_at > NOW() - INTERVAL 7 DAY")->fetchColumn(),
    'uploads_prev_7d' => (int) $pdo->query("SELECT COUNT(*) FROM report_uploads WHERE created_at BETWEEN NOW() - INTERVAL 14 DAY AND NOW() - INTERVAL 7 DAY")->fetchColumn(),
    'logins_24h'  => (int) $pdo->query("SELECT COUNT(*) FROM login_logs WHERE status='success' AND created_at > NOW() - INTERVAL 1 DAY")->fetchColumn(),
    'logins_7d'   => (int) $pdo->query("SELECT COUNT(*) FROM login_logs WHERE status='success' AND created_at > NOW() - INTERVAL 7 DAY")->fetchColumn(),
    'logins_prev_7d' => (int) $pdo->query("SELECT COUNT(*) FROM login_logs WHERE status='success' AND created_at BETWEEN NOW() - INTERVAL 14 DAY AND NOW() - INTERVAL 7 DAY")->fetchColumn(),
    'failed_24h'  => (int) $pdo->query("SELECT COUNT(*) FROM login_logs WHERE status IN ('failed','locked') AND created_at > NOW() - INTERVAL 1 DAY")->fetchColumn(),
    'data_rows'   => (int) $pdo->query("SELECT COUNT(*) FROM report_data WHERE is_active = 1")->fetchColumn(),
    'audit_24h'   => (int) $pdo->query("SELECT COUNT(*) FROM audit_logs WHERE created_at > NOW() - INTERVAL 1 DAY")->fetchColumn(),
];

/* Growth deltas */
function pctDelta($cur, $prev): array {
    if ($prev <= 0) return ['v' => $cur > 0 ? 100 : 0, 'arrow' => $cur > 0 ? 'up' : 'flat'];
    $d = (($cur - $prev) / $prev) * 100;
    return ['v' => $d, 'arrow' => $d > 1 ? 'up' : ($d < -1 ? 'down' : 'flat')];
}
$dUploads = pctDelta($counts['uploads_7d'], $counts['uploads_prev_7d']);
$dLogins  = pctDelta($counts['logins_7d'],  $counts['logins_prev_7d']);

/* ============= RECENT UPLOADS ============= */
$recentUploads = $pdo->query("SELECT u.*, r.name AS report_name, c.name AS client_name, usr.name AS user_name
    FROM report_uploads u
    LEFT JOIN reports r ON r.id = u.report_id
    LEFT JOIN processes p ON p.id = r.process_id
    LEFT JOIN clients c ON c.id = p.client_id
    LEFT JOIN users usr ON usr.id = u.uploaded_by
    ORDER BY u.created_at DESC LIMIT 8")->fetchAll();

$recentLogins = $pdo->query("SELECT created_at, email_attempted, status, ip
    FROM login_logs ORDER BY created_at DESC LIMIT 8")->fetchAll();

/* ============= ACTIVITY (last 14 days, daily) ============= */
$days = [];
for ($i = 13; $i >= 0; $i--) {
    $d = date('Y-m-d', strtotime("-$i days"));
    $days[$d] = ['logins' => 0, 'uploads' => 0];
}
foreach ($pdo->query("SELECT DATE(created_at) AS d, COUNT(*) AS c FROM login_logs
                      WHERE status='success' AND created_at > NOW() - INTERVAL 14 DAY
                      GROUP BY DATE(created_at)")->fetchAll() as $r) {
    if (isset($days[$r['d']])) $days[$r['d']]['logins'] = (int)$r['c'];
}
foreach ($pdo->query("SELECT DATE(created_at) AS d, COUNT(*) AS c FROM report_uploads
                      WHERE created_at > NOW() - INTERVAL 14 DAY
                      GROUP BY DATE(created_at)")->fetchAll() as $r) {
    if (isset($days[$r['d']])) $days[$r['d']]['uploads'] = (int)$r['c'];
}

/* ============= TOP REPORTS BY UPLOADS (last 30 days) ============= */
$topReports = $pdo->query("SELECT r.id, r.name, c.name AS cname, COUNT(u.id) AS upl, MAX(u.created_at) AS last_upload,
                                  SUM(u.valid_rows) AS rows_total
    FROM reports r
    LEFT JOIN processes p ON p.id = r.process_id
    LEFT JOIN clients c ON c.id = p.client_id
    LEFT JOIN report_uploads u ON u.report_id = r.id AND u.created_at > NOW() - INTERVAL 30 DAY
    WHERE r.deleted_at IS NULL
    GROUP BY r.id ORDER BY upl DESC, last_upload DESC LIMIT 6")->fetchAll();

/* ============= SYSTEM HEALTH ============= */
$lastBackup = '--';
$dbSize = 0;
try {
    $dbName = DB_NAME;
    $sz = $pdo->prepare("SELECT ROUND(SUM(data_length + index_length)/1024/1024, 1) AS mb
                         FROM information_schema.tables WHERE table_schema=?");
    $sz->execute([$dbName]);
    $dbSize = (float) $sz->fetchColumn();
} catch (Throwable $e) {}

/* Smart insights — auto-generated narrative */
$insights = [];
$activeClients = (int) $pdo->query("SELECT COUNT(DISTINCT c.id) FROM clients c
    JOIN processes p ON p.client_id=c.id JOIN reports r ON r.process_id=p.id
    JOIN report_uploads u ON u.report_id=r.id
    WHERE u.created_at > NOW() - INTERVAL 30 DAY AND c.deleted_at IS NULL")->fetchColumn();
$insights[] = ['icon' => 'users', 'color' => 'blue',
    'text' => "<strong>$activeClients</strong> of <strong>{$counts['clients']}</strong> clients had uploads in the last 30 days."];

if ($dUploads['arrow'] === 'up') {
    $insights[] = ['icon' => 'trending-up', 'color' => 'green',
        'text' => 'Upload volume is up <strong>'.number_format(abs($dUploads['v']),1).'%</strong> week-over-week.'];
} elseif ($dUploads['arrow'] === 'down') {
    $insights[] = ['icon' => 'trending-down', 'color' => 'red',
        'text' => 'Upload volume is down <strong>'.number_format(abs($dUploads['v']),1).'%</strong> week-over-week.'];
}
if ($counts['failed_24h'] > 5) {
    $insights[] = ['icon' => 'alert-triangle', 'color' => 'orange',
        'text' => "<strong>{$counts['failed_24h']}</strong> failed sign-in attempts in the last 24 hours."];
}
$idleReports = (int) $pdo->query("SELECT COUNT(*) FROM reports r WHERE r.deleted_at IS NULL
    AND NOT EXISTS (SELECT 1 FROM report_uploads u WHERE u.report_id=r.id AND u.created_at > NOW() - INTERVAL 30 DAY)")->fetchColumn();
if ($idleReports > 0) {
    $insights[] = ['icon' => 'moon', 'color' => 'yellow',
        'text' => "<strong>$idleReports</strong> report(s) haven't received any uploads in 30 days."];
}

$pageTitle = 'Dashboard';
require __DIR__ . '/includes/header.php';
?>
<style>
.welcome-hero {
    background: linear-gradient(135deg, #1e3a8a 0%, #312e81 50%, #581c87 100%);
    color:#fff; border-radius: 12px; padding: 22px 26px;
    margin: 16px 0;
    position: relative; overflow: hidden;
}
.welcome-hero::before {
    content:''; position:absolute; inset:0;
    background:
      radial-gradient(600px 200px at 0% 0%, rgba(56,189,248,.25), transparent 60%),
      radial-gradient(400px 200px at 100% 100%, rgba(168,85,247,.25), transparent 60%);
    pointer-events:none;
}
.welcome-hero > * { position: relative; z-index: 1; }
.welcome-hero .hi { font-size: 1.6rem; font-weight: 700; line-height: 1.2; }
.welcome-hero .sub { color: rgba(255,255,255,.7); font-size: .92rem; margin-top: 4px; }
.welcome-hero .btn-light:hover { background: #fff; }
.welcome-hero .pill {
    display:inline-flex; align-items:center; gap:6px;
    background: rgba(255,255,255,.08); border:1px solid rgba(255,255,255,.18);
    padding: 4px 12px; border-radius:999px; font-size:.8rem;
}
.delta-up   { color:#22c55e; font-weight:600; }
.delta-down { color:#ef4444; font-weight:600; }
.delta-flat { color: var(--m-text-soft); font-weight:600; }
.kpi-tile .ti { font-size: 1.05rem; }
.insight-row {
    display:flex; gap:10px; align-items:center;
    padding: 10px 12px; border-bottom: 1px solid var(--m-border);
    font-size: .9rem;
}
.insight-row:last-child { border-bottom: 0; }
.insight-row .icon-ball {
    width:30px; height:30px; border-radius:8px;
    display:inline-flex; align-items:center; justify-content:center;
    flex-shrink:0;
}
</style>

<div class="container-xl">
    <!-- ============= WELCOME HERO ============= -->
    <div class="welcome-hero">
        <div class="row align-items-center g-3">
            <div class="col">
                <div class="hi">Welcome back, <?= e(explode(' ', $user['name'])[0]) ?> 👋</div>
                <div class="sub">
                    <span class="pill"><i class="ti ti-shield-check"></i> <?= e(ucfirst($user['user_type'])) ?></span>
                    <span class="pill"><i class="ti ti-clock"></i> <?= e(date('D, M j · H:i')) ?></span>
                    <?php if ($user['last_login_at']): ?>
                        <span class="pill"><i class="ti ti-history"></i> Last sign-in <?= e(fmt_dt($user['last_login_at'])) ?></span>
                    <?php endif; ?>
                </div>
            </div>
            <div class="col-auto">
                <div class="d-flex gap-2 flex-wrap justify-content-end">
                    <a href="<?= e(url('/admin/report-builder.php')) ?>" class="btn btn-light"><i class="ti ti-template me-1"></i>Build a report</a>
                    <a href="<?= e(url('/admin/reports.php')) ?>" class="btn btn-outline-light"><i class="ti ti-search me-1"></i>Browse reports</a>
                </div>
            </div>
        </div>
    </div>
</div>

<div class="page-body">
<div class="container-xl">

    <!-- ============= INSIGHTS PANEL ============= -->
    <?php if ($insights): ?>
    <div class="card mb-3">
        <div class="card-header py-2">
            <h3 class="card-title small mb-0"><i class="ti ti-bulb me-1 text-warning"></i>Smart insights</h3>
            <span class="ms-auto small text-secondary">Auto-generated · refreshes hourly</span>
        </div>
        <div class="card-body p-0">
            <?php foreach ($insights as $ins): ?>
                <div class="insight-row">
                    <span class="icon-ball bg-<?= e($ins['color']) ?>-lt text-<?= e($ins['color']) ?>"><i class="ti ti-<?= e($ins['icon']) ?>"></i></span>
                    <div><?= $ins['text'] ?></div>
                </div>
            <?php endforeach; ?>
        </div>
    </div>
    <?php endif; ?>

    <!-- ============= KPI TILES ============= -->
    <div class="row row-deck row-cards mb-3">
        <div class="col-6 col-md-3">
            <a href="<?= e(url('/admin/verticals.php')) ?>" class="text-decoration-none">
                <div class="card kpi-tile"><div class="card-body py-3">
                    <div class="d-flex align-items-center mb-2"><span class="bg-blue-lt text-blue avatar avatar-sm me-2"><i class="ti ti-building"></i></span><div class="stat-label">Verticals</div></div>
                    <div class="stat-value"><?= $counts['verticals'] ?></div>
                </div></div>
            </a>
        </div>
        <div class="col-6 col-md-3">
            <a href="<?= e(url('/admin/clients.php')) ?>" class="text-decoration-none">
                <div class="card kpi-tile"><div class="card-body py-3">
                    <div class="d-flex align-items-center mb-2"><span class="bg-green-lt text-green avatar avatar-sm me-2"><i class="ti ti-users"></i></span><div class="stat-label">Clients</div></div>
                    <div class="stat-value"><?= $counts['clients'] ?></div>
                    <div class="small text-secondary mt-1"><?= $activeClients ?> active in 30d</div>
                </div></div>
            </a>
        </div>
        <div class="col-6 col-md-3">
            <a href="<?= e(url('/admin/processes.php')) ?>" class="text-decoration-none">
                <div class="card kpi-tile"><div class="card-body py-3">
                    <div class="d-flex align-items-center mb-2"><span class="bg-cyan-lt text-cyan avatar avatar-sm me-2"><i class="ti ti-list-tree"></i></span><div class="stat-label">Processes</div></div>
                    <div class="stat-value"><?= $counts['processes'] ?></div>
                </div></div>
            </a>
        </div>
        <div class="col-6 col-md-3">
            <a href="<?= e(url('/admin/reports.php')) ?>" class="text-decoration-none">
                <div class="card kpi-tile"><div class="card-body py-3">
                    <div class="d-flex align-items-center mb-2"><span class="bg-orange-lt text-orange avatar avatar-sm me-2"><i class="ti ti-report"></i></span><div class="stat-label">Reports</div></div>
                    <div class="stat-value"><?= $counts['reports'] ?></div>
                    <?php if ($idleReports): ?><div class="small text-warning mt-1"><i class="ti ti-moon"></i> <?= $idleReports ?> idle 30d</div><?php endif; ?>
                </div></div>
            </a>
        </div>

        <div class="col-6 col-md-3">
            <div class="card kpi-tile"><div class="card-body py-3">
                <div class="d-flex align-items-center mb-2"><span class="bg-indigo-lt text-indigo avatar avatar-sm me-2"><i class="ti ti-upload"></i></span><div class="stat-label">Uploads (7d)</div></div>
                <div class="stat-value"><?= $counts['uploads_7d'] ?></div>
                <div class="small mt-1">
                    <span class="delta-<?= $dUploads['arrow'] ?>">
                        <i class="ti ti-trending-<?= $dUploads['arrow'] === 'flat' ? 'flat' : $dUploads['arrow'] ?>"></i>
                        <?= number_format($dUploads['v'], 1) ?>%
                    </span>
                    <span class="text-secondary">vs prev week</span>
                </div>
            </div></div>
        </div>
        <div class="col-6 col-md-3">
            <a href="<?= e(url('/admin/login-logs.php')) ?>" class="text-decoration-none">
                <div class="card kpi-tile"><div class="card-body py-3">
                    <div class="d-flex align-items-center mb-2"><span class="bg-teal-lt text-teal avatar avatar-sm me-2"><i class="ti ti-login"></i></span><div class="stat-label">Sign-ins (7d)</div></div>
                    <div class="stat-value"><?= $counts['logins_7d'] ?></div>
                    <div class="small mt-1">
                        <span class="delta-<?= $dLogins['arrow'] ?>">
                            <i class="ti ti-trending-<?= $dLogins['arrow'] === 'flat' ? 'flat' : $dLogins['arrow'] ?>"></i>
                            <?= number_format($dLogins['v'], 1) ?>%
                        </span>
                        <span class="text-secondary">vs prev week</span>
                    </div>
                </div></div>
            </a>
        </div>
        <div class="col-6 col-md-3">
            <div class="card kpi-tile"><div class="card-body py-3">
                <div class="d-flex align-items-center mb-2"><span class="bg-yellow-lt text-yellow avatar avatar-sm me-2"><i class="ti ti-database"></i></span><div class="stat-label">Active rows</div></div>
                <div class="stat-value"><?= number_format($counts['data_rows']) ?></div>
                <?php if ($dbSize > 0): ?><div class="small text-secondary mt-1"><i class="ti ti-server"></i> <?= number_format($dbSize, 1) ?> MB DB</div><?php endif; ?>
            </div></div>
        </div>
        <div class="col-6 col-md-3">
            <a href="<?= e(url('/admin/audit.php')) ?>" class="text-decoration-none">
                <div class="card kpi-tile"><div class="card-body py-3">
                    <div class="d-flex align-items-center mb-2"><span class="bg-pink-lt text-pink avatar avatar-sm me-2"><i class="ti ti-history"></i></span><div class="stat-label">Audit events (24h)</div></div>
                    <div class="stat-value"><?= number_format($counts['audit_24h']) ?></div>
                </div></div>
            </a>
        </div>
    </div>

    <!-- ============= ACTIVITY CHART + INSIGHTS ============= -->
    <div class="row row-deck row-cards mb-3">
        <div class="col-lg-8">
            <div class="card">
                <div class="card-header py-2" style="flex-wrap:wrap;gap:6px">
                    <h3 class="card-title small mb-0"><i class="ti ti-activity me-1 text-primary"></i>Activity · last 14 days</h3>
                    <div class="card-actions" style="flex-shrink:0">
                        <span class="legend small text-secondary" style="white-space:nowrap">
                            <span style="display:inline-block;width:10px;height:10px;background:#206bc4;border-radius:2px;margin-right:4px"></span>Sign-ins
                            <span style="display:inline-block;width:10px;height:10px;background:#2fb344;border-radius:2px;margin:0 4px 0 12px"></span>Uploads
                        </span>
                    </div>
                </div>
                <div class="card-body p-2"><div id="chart_activity_14d" style="min-height:240px"></div></div>
            </div>
        </div>
        <div class="col-lg-4">
            <div class="card">
                <div class="card-header py-2">
                    <h3 class="card-title small mb-0"><i class="ti ti-flame me-1 text-danger"></i>Top reports · 30 days</h3>
                </div>
                <div class="list-group list-group-flush">
                    <?php if (!$topReports): ?>
                        <div class="list-group-item text-secondary text-center py-4 small">No upload activity yet.</div>
                    <?php else: foreach ($topReports as $i => $r): ?>
                        <a href="<?= e(url('/admin/report-view.php?id='.$r['id'])) ?>" class="list-group-item list-group-item-action py-2">
                            <div class="d-flex align-items-center">
                                <div class="me-2 text-secondary" style="font-variant-numeric:tabular-nums; width:18px;">#<?= $i+1 ?></div>
                                <div class="flex-grow-1 text-truncate">
                                    <div class="fw-medium small text-truncate"><?= e($r['name']) ?></div>
                                    <div class="text-secondary text-truncate" style="font-size:.75rem"><?= e($r['cname']) ?></div>
                                </div>
                                <div class="text-end ms-2">
                                    <div class="badge bg-blue-lt text-blue"><?= (int)$r['upl'] ?> uploads</div>
                                    <?php if ($r['rows_total']): ?>
                                        <div class="small text-secondary mt-1"><?= number_format((int)$r['rows_total']) ?> rows</div>
                                    <?php endif; ?>
                                </div>
                            </div>
                        </a>
                    <?php endforeach; endif; ?>
                </div>
            </div>
        </div>
    </div>

    <!-- ============= RECENT UPLOADS + LOGINS ============= -->
    <div class="row row-deck row-cards">
        <div class="col-lg-7">
            <div class="card">
                <div class="card-header py-2">
                    <h3 class="card-title small mb-0"><i class="ti ti-upload me-1 text-primary"></i>Recent uploads</h3>
                    <div class="card-actions"><a href="<?= e(url('/admin/reports.php')) ?>" class="btn btn-sm btn-ghost-primary">All reports</a></div>
                </div>
                <div class="table-responsive"><table class="table card-table table-vcenter table-sm">
                    <thead><tr><th>When</th><th>Report</th><th>Client</th><th>By</th><th>Mode</th><th class="text-end">Rows</th><th>Status</th></tr></thead>
                    <tbody>
                    <?php if (!$recentUploads): ?>
                        <tr><td colspan="7" class="text-center text-secondary py-4">No uploads yet.</td></tr>
                    <?php else: foreach ($recentUploads as $u): ?>
                        <tr>
                            <td class="small text-secondary text-nowrap"><?= e(fmt_dt($u['created_at'])) ?></td>
                            <td><a href="<?= e(url('/admin/report-view.php?id='.$u['report_id'].'&upload='.$u['id'])) ?>" class="text-truncate d-inline-block" style="max-width:240px;"><?= e($u['report_name']) ?></a></td>
                            <td class="small text-secondary text-truncate" style="max-width:160px"><?= e($u['client_name'] ?? '--') ?></td>
                            <td class="small"><?= e($u['user_name'] ?? '--') ?></td>
                            <td><span class="badge bg-secondary-lt"><?= e($u['upload_mode_used']) ?></span></td>
                            <td class="text-end"><?= number_format((int)$u['valid_rows']) ?></td>
                            <td><span class="badge bg-<?= ['completed'=>'success','failed'=>'danger','processing'=>'info'][$u['status']] ?? 'secondary' ?>-lt"><?= e($u['status']) ?></span></td>
                        </tr>
                    <?php endforeach; endif; ?>
                    </tbody>
                </table></div>
            </div>
        </div>

        <div class="col-lg-5">
            <div class="card">
                <div class="card-header py-2">
                    <h3 class="card-title small mb-0"><i class="ti ti-shield-lock me-1 text-info"></i>Recent sign-ins</h3>
                    <div class="card-actions"><a href="<?= e(url('/admin/login-logs.php')) ?>" class="btn btn-sm btn-ghost-secondary">All</a></div>
                </div>
                <div class="table-responsive"><table class="table card-table table-sm">
                    <thead><tr><th>When</th><th>Email</th><th>IP</th><th>Status</th></tr></thead>
                    <tbody>
                    <?php foreach ($recentLogins as $l): ?>
                        <tr>
                            <td class="small text-secondary text-nowrap"><?= e(fmt_dt($l['created_at'])) ?></td>
                            <td class="small text-truncate" style="max-width:160px"><?= e($l['email_attempted']) ?></td>
                            <td class="small text-secondary"><?= e($l['ip']) ?></td>
                            <td>
                                <?php $cls = ['success'=>'success','failed'=>'warning','locked'=>'danger'][$l['status']] ?? 'secondary'; ?>
                                <span class="badge bg-<?= $cls ?>-lt"><?= e($l['status']) ?></span>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                    </tbody>
                </table></div>
            </div>
        </div>
    </div>

</div>
</div>

<script>
/* ============= ACTIVITY CHART (14d) ============= */
(function(){
    var dayLabels = <?= json_encode(array_map(fn($d) => date('M j', strtotime($d)), array_keys($days))) ?>;
    var loginSeries  = <?= json_encode(array_values(array_map(fn($d) => $d['logins'],  $days))) ?>;
    var uploadSeries = <?= json_encode(array_values(array_map(fn($d) => $d['uploads'], $days))) ?>;

    function buildChart(theme) {
        var dark = theme === 'dark';
        return {
            chart: { type: 'area', height: 240, toolbar: { show: false }, fontFamily: 'inherit', background: 'transparent' },
            theme: { mode: dark ? 'dark' : 'light' },
            series: [
                { name: 'Sign-ins', data: loginSeries },
                { name: 'Uploads',  data: uploadSeries },
            ],
            colors: ['#206bc4', '#2fb344'],
            stroke: { curve: 'smooth', width: 2 },
            fill: {
                type: 'gradient',
                gradient: { shadeIntensity: 1, opacityFrom: 0.45, opacityTo: 0.05, stops: [0, 100] },
            },
            dataLabels: { enabled: false },
            xaxis: { categories: dayLabels, axisBorder: { show: false }, labels: { style: { colors: dark ? '#97a2b6' : '#6c7a89' } } },
            yaxis: { labels: { style: { colors: dark ? '#97a2b6' : '#6c7a89' }, formatter: v => Math.round(v) } },
            tooltip: { shared: true },
            grid: { borderColor: dark ? '#1e2a44' : '#eef0f3' },
            legend: { show: false },
        };
    }
    var chart = new ApexCharts(document.querySelector('#chart_activity_14d'),
        buildChart(document.documentElement.getAttribute('data-bs-theme')));
    chart.render();
    window.addEventListener('m-theme-change', function(e){ chart.updateOptions(buildChart(e.detail.theme), false, true); });
})();
</script>
<?php require __DIR__ . '/includes/footer.php'; ?>
