<?php
/**
 * Client portal shell — HEAD + sidebar + top bar.  client-portal-v2
 *
 * Used by client-facing pages that REUSE internal renderers (the AR collection dashboard in
 * "client mode") and the client overall dashboard. It loads the SAME front-end assets as
 * includes/header.php AND the full --m-* design-token set, so internal markup renders identically.
 *
 * It mirrors the INTERNAL sidebar look (Tabler navbar-vertical, dark) — but the menu is built ONLY
 * from the client's OWN accessible dashboards (home client's reports UNION report_access grants),
 * grouped by client. NO internal admin nav is ever exposed to a client.
 *
 * Expects (set before include): $cp_title, $cp_primary, $cp_brand, $cp_slug, optional $cp_back_url.
 * Falls back to current_user() + sensible defaults if unset.
 */
if (!function_exists('e')) { require_once __DIR__ . '/config.php'; }
$cp_user     = $cp_user     ?? current_user();
$cp_primary  = $cp_primary  ?? '#206bc4';
$cp_brand    = $cp_brand    ?? 'Reports';
$cp_title    = $cp_title    ?? $cp_brand;
$cp_slug     = $cp_slug     ?? '';
$cp_back_url = $cp_back_url ?? ('/client/overall.php' . ($cp_slug !== '' ? ('?slug=' . $cp_slug) : ''));

/* ---- Build the client's OWN navigation: every active dashboard they can open, grouped by client.
   Same visibility rule as the dashboards themselves: home client's reports UNION report_access grants. ---- */
$cp_nav = [];
try {
    $cp_db    = db();
    $cp_uid   = (int) ($cp_user['id'] ?? 0);
    $cp_home  = (int) ($cp_user['client_id'] ?? 0);
    $cp_grant = function_exists('accessible_report_ids') ? accessible_report_ids($cp_uid) : null;
    $cp_gcl   = (is_array($cp_grant) && $cp_grant) ? (' OR r.id IN (' . implode(',', array_map('intval', $cp_grant)) . ')') : '';
    $cp_q = $cp_db->prepare("SELECT r.id, r.name, r.handler, c.name client_name
        FROM reports r JOIN processes p ON p.id = r.process_id JOIN clients c ON c.id = p.client_id
        WHERE r.deleted_at IS NULL AND r.status='active' AND (p.client_id = ?" . $cp_gcl . ")
        ORDER BY c.name, r.name");
    $cp_q->execute([$cp_home]);
    foreach ($cp_q->fetchAll() as $r) { $cp_nav[(string) $r['client_name']][] = $r; }
} catch (Throwable $e) { $cp_nav = []; }
$cp_multi    = count($cp_nav) > 1;                         // group under client headers only when >1 client
$cp_script   = basename((string) ($_SERVER['SCRIPT_NAME'] ?? $_SERVER['PHP_SELF'] ?? ''));
$cp_curId    = (int) ($_GET['id'] ?? 0);
$cp_isOverall = ($cp_script === 'overall.php');
$cp_repHref  = fn($r) => (($r['handler'] ?? '') === 'collection_dashboard')
    ? ('/admin/collection.php?id=' . (int) $r['id'])
    : ('/client/report.php?id=' . (int) $r['id']);
?><!doctype html>
<html lang="en">
<head>
<meta charset="utf-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<meta name="theme-color" content="<?= e($cp_primary) ?>"/>
<title><?= e($cp_title) ?></title>
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700;800&family=JetBrains+Mono:wght@400;500&display=swap" rel="stylesheet"/>
<link href="https://cdn.jsdelivr.net/npm/@tabler/core@1.0.0-beta20/dist/css/tabler.min.css" rel="stylesheet"/>
<link href="https://cdn.jsdelivr.net/npm/@tabler/icons-webfont@2.47.0/tabler-icons.min.css" rel="stylesheet"/>
<link href="https://cdn.datatables.net/1.13.8/css/dataTables.bootstrap5.min.css" rel="stylesheet"/>
<link href="https://cdn.datatables.net/buttons/2.4.2/css/buttons.bootstrap5.min.css" rel="stylesheet"/>
<link href="https://cdn.datatables.net/rowgroup/1.5.0/css/rowGroup.bootstrap5.min.css" rel="stylesheet"/>
<link href="https://cdn.datatables.net/fixedheader/3.4.0/css/fixedHeader.bootstrap5.min.css" rel="stylesheet"/>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
<script src="https://cdn.datatables.net/1.13.8/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/1.13.8/js/dataTables.bootstrap5.min.js"></script>
<script src="https://cdn.datatables.net/buttons/2.4.2/js/dataTables.buttons.min.js"></script>
<script src="https://cdn.datatables.net/buttons/2.4.2/js/buttons.html5.min.js"></script>
<script src="https://cdn.datatables.net/buttons/2.4.2/js/buttons.print.min.js"></script>
<script src="https://cdn.datatables.net/rowgroup/1.5.0/js/dataTables.rowGroup.min.js"></script>
<script src="https://cdn.datatables.net/fixedheader/3.4.0/js/dataTables.fixedHeader.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/jszip@3.10.1/dist/jszip.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/apexcharts@3.45.2/dist/apexcharts.min.js"></script>
<style>
    :root {
        --tblr-primary: <?= e($cp_primary) ?>;
        --m-bg: #f4f6fb; --m-bg-elev: #ffffff; --m-surface: #ffffff; --m-surface-2: #f8fafc;
        --m-border: #e6eaf0; --m-border-strong: #d8dee8; --m-text: #1a2332; --m-text-soft: #6c7a89;
        --m-side-bg: linear-gradient(180deg, #1a2332 0%, #0f1825 100%); --m-side-text: #cfd6e4;
        --m-shadow-sm: 0 1px 2px rgba(15,23,37,.04), 0 1px 3px rgba(15,23,37,.04);
        --m-shadow-md: 0 4px 14px rgba(15,23,37,.08);
        --m-accent: #206bc4; --m-accent-2: #4f46e5; --m-good: #16a34a; --m-warn: #f59e0b; --m-bad: #dc2626;
    }
    html[data-bs-theme="dark"] {
        --m-bg: #0b1220; --m-bg-elev: #111a2c; --m-surface: #131e34; --m-surface-2: #0e1729;
        --m-border: #1e2a44; --m-border-strong: #28365a; --m-text: #e7ecf5; --m-text-soft: #97a2b6;
        --m-side-bg: linear-gradient(180deg, #0a1220 0%, #060c18 100%); --m-side-text: #cfd6e4;
        --m-shadow-sm: 0 1px 2px rgba(0,0,0,.3); --m-shadow-md: 0 6px 24px rgba(0,0,0,.45);
        --tblr-body-bg: var(--m-bg); --tblr-body-color: var(--m-text);
        --tblr-card-bg: var(--m-surface); --tblr-border-color: var(--m-border);
    }
    body { background: var(--m-bg); color: var(--m-text); font-family: 'Inter', -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif; }
    code, pre, .text-code, .font-mono { font-family: 'JetBrains Mono', ui-monospace, SFMono-Regular, Consolas, monospace; }

    .navbar-vertical.navbar-expand-lg { background: var(--m-side-bg) !important; border-right: 0; }
    .navbar-vertical .navbar-brand { padding: 1rem 1rem .5rem; }
    .navbar-vertical .nav-link { transition: all .15s ease; color: var(--m-side-text); border-radius: 6px; margin: 1px 8px; padding: .4rem .75rem; font-size: .9rem; }
    .navbar-vertical .nav-link:hover { background: rgba(255,255,255,.06); color: #fff; }
    .navbar-vertical .nav-item.active .nav-link, .navbar-vertical .nav-link.active {
        background: linear-gradient(90deg, rgba(32,107,196,.22) 0%, rgba(32,107,196,.05) 100%) !important;
        border-left: 3px solid var(--tblr-primary); padding-left: calc(.75rem - 3px); color: #fff;
        box-shadow: inset 0 0 0 1px rgba(255,255,255,.04);
    }
    .navbar-vertical .nav-link-icon { color: rgba(255,255,255,.55); font-size: 1.05rem; }
    .navbar-vertical .nav-link.active .nav-link-icon, .navbar-vertical .nav-link:hover .nav-link-icon { color: #38bdf8; }
    .navbar-vertical .nav-header { letter-spacing: .12em; padding: .7rem .95rem .15rem; opacity: .5; font-size: .66rem; font-weight: 700; color: var(--m-side-text); text-transform: uppercase; }
    .cp-brand-ico { width:34px; height:34px; border-radius:9px; background: color-mix(in srgb, <?= e($cp_primary) ?> 85%, #1e1b4b); display:inline-flex; align-items:center; justify-content:center; color:#fff; }
    .cp-pill { display:inline-flex; align-items:center; gap:6px; background: var(--m-surface-2); border:1px solid var(--m-border); padding:4px 10px; border-radius:999px; font-size:.8rem; color: var(--m-text-soft); }
</style>
<?php require __DIR__ . '/compact-css.php'; ?>
</head>
<body>
<div class="page">

    <aside class="navbar navbar-vertical navbar-expand-lg" data-bs-theme="dark">
        <div class="container-fluid">
            <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#cp-sidebar">
                <span class="navbar-toggler-icon"></span>
            </button>
            <h1 class="navbar-brand">
                <a href="<?= e(url('/client/overall.php')) ?>" class="d-flex align-items-center text-white text-decoration-none">
                    <span class="cp-brand-ico me-2"><i class="ti ti-building-skyscraper" style="font-size:1.15rem"></i></span>
                    <span style="font-weight:700; letter-spacing:.01em"><?= e($cp_brand) ?></span>
                </a>
            </h1>
            <div class="collapse navbar-collapse" id="cp-sidebar">
                <ul class="navbar-nav pt-lg-2">
                    <li class="nav-item<?= $cp_isOverall ? ' active' : '' ?>">
                        <a class="nav-link" href="<?= e(url('/client/overall.php')) ?>">
                            <span class="nav-link-icon"><i class="ti ti-layout-dashboard"></i></span>
                            <span class="nav-link-title">Overall dashboard</span>
                        </a>
                    </li>
                    <?php if (!$cp_nav): ?>
                        <li class="nav-item"><span class="nav-link text-secondary" style="cursor:default">No dashboards yet</span></li>
                    <?php else: foreach ($cp_nav as $cpClient => $cpReps): ?>
                        <?php if ($cp_multi): ?><li class="nav-header"><span><?= e($cpClient) ?></span></li><?php endif; ?>
                        <?php foreach ($cpReps as $r): $cpAct = !$cp_isOverall && (int) $r['id'] === $cp_curId; ?>
                            <li class="nav-item<?= $cpAct ? ' active' : '' ?>">
                                <a class="nav-link" href="<?= e(url($cp_repHref($r))) ?>">
                                    <span class="nav-link-icon"><i class="ti ti-chart-bar"></i></span>
                                    <span class="nav-link-title"><?= e($r['name']) ?></span>
                                </a>
                            </li>
                        <?php endforeach; ?>
                    <?php endforeach; endif; ?>

                    <li class="nav-header"><span>Account</span></li>
                    <li class="nav-item">
                        <a class="nav-link" href="<?= e(url('/change-password.php')) ?>">
                            <span class="nav-link-icon"><i class="ti ti-key"></i></span><span class="nav-link-title">Change password</span>
                        </a>
                    </li>
                    <li class="nav-item">
                        <form method="POST" action="<?= e(url('/logout.php')) ?>" class="m-0"><?= csrf_field() ?>
                            <button class="nav-link border-0 bg-transparent w-100 text-start" type="submit">
                                <span class="nav-link-icon"><i class="ti ti-logout"></i></span><span class="nav-link-title">Sign out</span>
                            </button>
                        </form>
                    </li>
                </ul>
            </div>
        </div>
    </aside>

    <div class="page-wrapper">

    <header class="navbar navbar-expand-md d-print-none" style="background: var(--m-surface); border-bottom: 1px solid var(--m-border);">
        <div class="container-xl">
            <div class="navbar-nav flex-row order-md-last ms-auto align-items-center gap-2">
                <span class="cp-pill d-none d-md-inline-flex"><i class="ti ti-clock"></i> <?= e(date('D, M j')) ?></span>
                <div class="nav-item dropdown">
                    <a href="#" class="nav-link d-flex align-items-center gap-2 dropdown-toggle text-reset" data-bs-toggle="dropdown">
                        <span class="avatar avatar-sm" style="background: var(--tblr-primary); color:#fff; font-weight:600;"><?= e(strtoupper(substr((string) ($cp_user['name'] ?? 'U'), 0, 2))) ?></span>
                        <span class="d-none d-md-inline" style="font-size:.9rem; color: var(--m-text)"><?= e($cp_user['name'] ?? '') ?></span>
                    </a>
                    <div class="dropdown-menu dropdown-menu-end">
                        <div class="dropdown-header text-secondary small"><?= e($cp_user['email'] ?? '') ?></div>
                        <div class="dropdown-divider"></div>
                        <a href="<?= e(url('/change-password.php')) ?>" class="dropdown-item"><i class="ti ti-key me-2"></i>Change password</a>
                        <form method="POST" action="<?= e(url('/logout.php')) ?>"><?= csrf_field() ?>
                            <button class="dropdown-item text-danger"><i class="ti ti-logout me-2"></i>Sign out</button>
                        </form>
                    </div>
                </div>
            </div>
        </div>
    </header>

    <?php if (function_exists('is_impersonating') && is_impersonating()): ?>
    <div class="bg-warning text-dark py-2 px-3 d-flex align-items-center">
        <i class="ti ti-eye me-2"></i><strong>Sysadmin view-as: <?= e($cp_user['name'] ?? '') ?></strong>
        <span class="ms-2 small">(client of <?= e($cp_brand) ?>)</span>
        <form method="POST" action="<?= e(url('/admin/impersonate.php')) ?>" class="ms-auto">
            <?= csrf_field() ?><input type="hidden" name="stop" value="1">
            <button class="btn btn-sm btn-dark"><i class="ti ti-x me-1"></i>Back to admin</button>
        </form>
    </div>
    <?php endif; ?>

    <div class="page-body">
