<?php
/**
 * Client portal dashboard. Reports scoped to user's client_id.
 * Modern card grid with sparklines, search, and freshness indicators.
 */
require_once __DIR__ . '/../includes/config.php';
$user = require_login('client');

// The card-list landing has been replaced by the OVERALL dashboard — clients go straight there.
redirect('/client/overall.php' . (trim((string)($_GET['slug'] ?? '')) !== '' ? '?slug=' . urlencode(trim((string)$_GET['slug'])) : ''));

$pdo = db();
$slug = trim((string) ($_GET['slug'] ?? ''));
if ($slug === '') $slug = $pdo->query("SELECT login_slug FROM client_branding WHERE client_id = " . (int)$user['client_id'])->fetchColumn() ?: '';

// Branding is OPTIONAL — a client created outside admin/clients.php (seed/import/coding vertical) may have NO
// client_branding row. Fall back to the client name + default colour so the portal still loads. Previously a
// missing branding row logged the user straight back out, so a brand-less client user could never sign in.
$brand = $pdo->prepare('SELECT c.name AS client_name, cb.primary_color, cb.login_slug, cb.login_message
    FROM clients c LEFT JOIN client_branding cb ON cb.client_id = c.id
    WHERE c.id = ? AND c.deleted_at IS NULL');
$brand->execute([$user['client_id']]); $brand = $brand->fetch();
if (!$brand) { logout(); redirect('/login.php'); }   // client row genuinely missing/deleted → cannot proceed
$brand['primary_color'] = $brand['primary_color'] ?: '#206bc4';

$primary = $brand['primary_color'] ?? '#206bc4';
$q = trim((string) ($_GET['q'] ?? ''));

/* A client portal user sees the reports/dashboards for the CLIENT they are assigned to (scoped by client_id).
   Visibility is client-assignment-based — no per-report grant needed — since a client user belongs to exactly
   one client. (Cross-client is impossible: every query is fenced by p.client_id = the user's client_id, and the
   collection rollup mirror enforces a same-client fence. Raw-row data + downloads remain opt-in per client.) */
$sqlParams = [(int) $user['client_id']];
$qSql = '';
if ($q !== '') { $qSql = ' AND (r.name LIKE ? OR p.name LIKE ?)'; $sqlParams[] = "%$q%"; $sqlParams[] = "%$q%"; }
$reports = $pdo->prepare('SELECT r.*, p.name AS process_name,
        (SELECT COUNT(*) FROM report_data rd WHERE rd.report_id = r.id AND rd.is_active = 1) AS row_count,
        (SELECT MAX(created_at) FROM report_uploads ru WHERE ru.report_id = r.id AND ru.status = "completed") AS last_upload,
        (SELECT COUNT(*) FROM report_uploads ru WHERE ru.report_id = r.id AND ru.created_at > NOW() - INTERVAL 7 DAY) AS uploads_7d
    FROM reports r
    JOIN processes p ON p.id = r.process_id
    WHERE p.client_id = ? AND r.deleted_at IS NULL AND r.status = "active"' . $qSql . '
    ORDER BY r.name');
$reports->execute($sqlParams);
$reports = $reports->fetchAll();

$totalRows = 0; $freshCount = 0; $hasCollection = false;
foreach ($reports as $r) {
    $totalRows += (int) $r['row_count'];
    if ($r['last_upload'] && strtotime($r['last_upload']) > strtotime('-7 days')) $freshCount++;
    if (($r['handler'] ?? '') === 'collection_dashboard') $hasCollection = true;
}
?><!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($primary) ?>"/>
<title><?= e($brand['client_name']) ?> &mdash; Reports</title>
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700;800&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"/>
<style>
    :root { --tblr-primary: <?= e($primary) ?>; --m-bg: #f4f6fb; --m-border: #e6eaf0; --m-text-soft: #6c7a89; }
    body { font-family: 'Inter', -apple-system, sans-serif; background: var(--m-bg); }
    .c-topbar {
        background: linear-gradient(135deg, <?= e($primary) ?> 0%, color-mix(in srgb, <?= e($primary) ?> 80%, #1e1b4b) 100%);
        color: #fff; padding: 18px 0; position: relative; overflow: hidden;
    }
    .c-topbar::before {
        content:''; position:absolute; inset:0;
        background:
          radial-gradient(600px 200px at 0% 0%, rgba(255,255,255,.12), transparent 60%),
          radial-gradient(400px 200px at 100% 100%, rgba(255,255,255,.08), transparent 60%);
    }
    .c-topbar > * { position: relative; }
    .c-brand { display:inline-flex; align-items:center; gap:12px; font-weight:700; font-size:1.2rem; }
    .c-brand .ico {
        width:38px; height:38px; border-radius:10px; display:inline-flex; align-items:center; justify-content:center;
        background: rgba(255,255,255,.18); backdrop-filter: blur(8px);
    }
    .c-hero { padding: 28px 0 32px; color:#fff; }
    .c-hero h1 { font-weight: 800; font-size: 1.9rem; margin: 0 0 6px; }
    .c-hero p  { color: rgba(255,255,255,.78); margin: 0; }
    .pill {
        display:inline-flex; align-items:center; gap:6px;
        background: rgba(255,255,255,.12); border:1px solid rgba(255,255,255,.18);
        padding: 4px 10px; border-radius: 999px; font-size: .8rem; color: #fff;
    }

    .c-stat-strip {
        margin-top: -36px; margin-bottom: 18px; position: relative; z-index: 5;
    }
    .c-stat-card {
        background: #fff; border-radius: 14px;
        box-shadow: 0 6px 24px rgba(15,23,37,.08);
        padding: 16px 18px; transition: all .15s;
    }
    .c-stat-card:hover { transform: translateY(-2px); box-shadow: 0 10px 32px rgba(15,23,37,.12); }
    .c-stat-card .lbl { font-size:.7rem; text-transform: uppercase; color: var(--m-text-soft); letter-spacing: .04em; }
    .c-stat-card .val { font-size: 1.7rem; font-weight: 700; color:#0f172a; line-height: 1.1; margin-top: 4px; font-variant-numeric: tabular-nums; }
    .c-stat-card .ico {
        width: 38px; height: 38px; border-radius: 10px; display: inline-flex; align-items: center; justify-content: center;
        background: color-mix(in srgb, var(--tblr-primary) 15%, transparent); color: var(--tblr-primary); margin-bottom: 8px;
    }

    .c-search {
        background:#fff; border:1px solid var(--m-border); border-radius: 10px;
        padding: 8px 14px; display:flex; align-items:center; gap:10px;
        box-shadow: 0 1px 2px rgba(15,23,37,.04);
    }
    .c-search input { border: 0; outline: 0; flex-grow: 1; font-size: .92rem; background: transparent; }

    .c-report-card {
        background:#fff; border:1px solid var(--m-border); border-radius: 12px;
        padding: 16px; cursor: pointer; transition: all .15s;
        position: relative; overflow: hidden;
        height: 100%; display: flex; flex-direction: column;
    }
    .c-report-card:hover { border-color: var(--tblr-primary); transform: translateY(-3px); box-shadow: 0 8px 24px rgba(15,23,37,.1); }
    .c-report-card .ico {
        width: 38px; height: 38px; border-radius: 10px; display: inline-flex; align-items: center; justify-content: center;
        background: color-mix(in srgb, var(--tblr-primary) 12%, transparent); color: var(--tblr-primary); margin-bottom: 10px;
    }
    .c-report-card h3 { font-size: 1rem; font-weight: 600; margin: 0 0 4px; line-height: 1.3; color: #0f172a; }
    .c-report-card .sub { font-size: .82rem; color: var(--m-text-soft); margin-bottom: 12px; }
    .c-report-card .meta {
        margin-top: auto; padding-top: 12px; border-top: 1px solid var(--m-border);
        display: flex; justify-content: space-between; font-size: .8rem; color: var(--m-text-soft);
    }
    .c-report-card .meta .rows { font-weight: 600; color: #0f172a; }
    .c-report-card .badge-fresh {
        position: absolute; top: 12px; right: 12px;
        background: #dcfce7; color: #166534; font-size: .7rem; padding: 2px 8px; border-radius: 99px;
        display:inline-flex; align-items:center; gap:4px;
    }
    .c-report-card .badge-fresh::before {
        content: ''; width: 6px; height: 6px; background: #16a34a; border-radius: 50%;
        box-shadow: 0 0 0 3px rgba(22,163,74,.2);
        animation: pulse 2s infinite;
    }
    @keyframes pulse { 0%, 100% { opacity: 1 } 50% { opacity: .4 } }

    .empty-state { text-align: center; padding: 60px 20px; color: var(--m-text-soft); }
    .empty-state .icon { font-size: 4rem; opacity: .3; margin-bottom: 16px; }
</style>
<?php require __DIR__ . '/../includes/compact-css.php'; ?>
</head>
<body>
<div class="page">

<header class="c-topbar">
    <div class="container-xl d-flex align-items-center">
        <span class="c-brand">
            <span class="ico"><i class="ti ti-building-skyscraper" style="font-size:1.2rem"></i></span>
            <span><?= e($brand['client_name']) ?></span>
        </span>
        <div class="ms-auto d-flex align-items-center gap-3">
            <span class="pill"><i class="ti ti-clock"></i> <?= e(date('D, M j')) ?></span>
            <div class="dropdown">
                <a href="#" class="text-decoration-none text-white d-flex align-items-center gap-2 dropdown-toggle" data-bs-toggle="dropdown">
                    <span class="avatar avatar-sm" style="background:rgba(255,255,255,.2); color:#fff; font-weight:600;"><?= e(strtoupper(substr($user['name'],0,2))) ?></span>
                    <span class="d-none d-md-inline" style="font-size:.9rem"><?= e($user['name']) ?></span>
                </a>
                <div class="dropdown-menu dropdown-menu-end">
                    <div class="dropdown-header text-secondary small"><?= e($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>

    <div class="container-xl c-hero">
        <h1>Welcome, <?= e(explode(' ', $user['name'])[0]) ?> 👋</h1>
        <p>Your reports for <?= e($brand['client_name']) ?></p>
        <?php if ($hasCollection): ?>
            <a href="<?= e(url('/client/overall.php?slug='.$slug)) ?>" class="btn btn-light btn-sm mt-3"><i class="ti ti-chart-area-line me-1"></i>Overall dashboard</a>
        <?php endif; ?>
    </div>
</header>

<?php if (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($user['name']) ?></strong>
        <span class="ms-2 small">(client of <?= e($brand['client_name']) ?>)</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-wrapper">
    <div class="container-xl">

        <!-- ====== STATS STRIP ====== -->
        <div class="row row-cards c-stat-strip">
            <div class="col-md-3 col-6">
                <div class="c-stat-card">
                    <div class="ico"><i class="ti ti-report-analytics"></i></div>
                    <div class="lbl">Available reports</div>
                    <div class="val"><?= count($reports) ?></div>
                </div>
            </div>
            <div class="col-md-3 col-6">
                <div class="c-stat-card">
                    <div class="ico" style="background:rgba(34,197,94,.12); color:#16a34a"><i class="ti ti-database"></i></div>
                    <div class="lbl">Total active rows</div>
                    <div class="val"><?= number_format($totalRows) ?></div>
                </div>
            </div>
            <div class="col-md-3 col-6">
                <div class="c-stat-card">
                    <div class="ico" style="background:rgba(247,103,7,.12); color:#f76707"><i class="ti ti-flame"></i></div>
                    <div class="lbl">Updated this week</div>
                    <div class="val"><?= $freshCount ?></div>
                </div>
            </div>
            <div class="col-md-3 col-6">
                <div class="c-stat-card">
                    <div class="ico" style="background:rgba(124,58,237,.12); color:#7c3aed"><i class="ti ti-shield-check"></i></div>
                    <div class="lbl">Last sign-in</div>
                    <div class="val" style="font-size:1rem"><?= e(fmt_dt($user['last_login_at'], 'Just now')) ?></div>
                </div>
            </div>
        </div>

        <!-- ====== SEARCH ====== -->
        <form method="GET" class="c-search mb-4">
            <i class="ti ti-search text-secondary"></i>
            <input type="text" name="q" placeholder="Search your reports..." value="<?= e($q) ?>" autocomplete="off">
            <input type="hidden" name="slug" value="<?= e($slug) ?>">
            <?php if ($q !== ''): ?>
                <a href="?slug=<?= e($slug) ?>" class="btn btn-sm btn-ghost-secondary"><i class="ti ti-x"></i></a>
            <?php endif; ?>
            <button class="btn btn-sm btn-primary"><i class="ti ti-search me-1"></i>Search</button>
        </form>

        <!-- ====== REPORT GRID ====== -->
        <?php if (!$reports): ?>
            <div class="card"><div class="empty-state">
                <div class="icon"><i class="ti ti-folder-open"></i></div>
                <h3>No reports available</h3>
                <p>Your account manager will publish reports here when they're ready.</p>
            </div></div>
        <?php else: ?>
            <div class="row row-cards">
                <?php foreach ($reports as $r):
                    $isFresh = $r['last_upload'] && strtotime($r['last_upload']) > strtotime('-7 days');
                    // AR collection dashboards open the rich (read-only) collection view in client mode;
                    // everything else opens the standard report-builder viewer.
                    $cardHref = (($r['handler'] ?? '') === 'collection_dashboard')
                        ? url('/admin/collection.php?id=' . (int)$r['id'])
                        : url('/client/report.php?slug=' . $slug . '&id=' . (int)$r['id']);
                ?>
                    <div class="col-md-6 col-lg-4">
                        <a href="<?= e($cardHref) ?>" class="text-decoration-none">
                            <div class="c-report-card">
                                <?php if ($isFresh): ?><span class="badge-fresh">FRESH</span><?php endif; ?>
                                <div class="ico"><i class="ti ti-chart-pie-2" style="font-size:1.2rem"></i></div>
                                <h3><?= e($r['name']) ?></h3>
                                <div class="sub"><?= e($r['process_name']) ?></div>
                                <div class="meta">
                                    <span><span class="rows"><?= number_format($r['row_count']) ?></span> rows</span>
                                    <span>
                                        <?php if ($r['last_upload']): ?>
                                            <i class="ti ti-clock me-1"></i><?= e(fmt_date($r['last_upload'])) ?>
                                        <?php else: ?>
                                            <i class="ti ti-circle-dashed me-1"></i>No data yet
                                        <?php endif; ?>
                                    </span>
                                </div>
                            </div>
                        </a>
                    </div>
                <?php endforeach; ?>
            </div>
        <?php endif; ?>

    </div>
</div>

</div>
<script src="https://cdn.jsdelivr.net/npm/@tabler/core@1.0.0-beta20/dist/js/tabler.min.js" defer></script>
</body>
</html>
