<?php
/**
 * Client-side report viewer. Same materialized output rendering as admin,
 * but with strict client_id scoping enforced. Modern UI with charts and KPIs.
 */
require_once __DIR__ . '/../includes/config.php';
$user = require_login('client');

$pdo = db();
$reportId = (int) ($_GET['id'] ?? 0);
$tab      = $_GET['tab'] ?? '';
$slug     = trim((string) ($_GET['slug'] ?? ''));

$rep = $pdo->prepare('SELECT r.*, p.name AS pname, c.name AS cname, c.id AS report_client_id, cb.primary_color
    FROM reports r
    JOIN processes p ON p.id = r.process_id
    JOIN clients c ON c.id = p.client_id
    LEFT JOIN client_branding cb ON cb.client_id = c.id
    WHERE r.id = ? AND r.deleted_at IS NULL AND r.status = "active"');
$rep->execute([$reportId]);
$report = $rep->fetch();
// Visible if the report is under the user's HOME client OR explicitly granted to them (report_access) — a client
// contact may oversee several clients.
if (!$report || ((int)$report['report_client_id'] !== (int)$user['client_id'] && !user_can_view_report((int)$user['id'], $reportId))) {
    http_response_code(404); exit('Report not available.');
}

$primary = $report['primary_color'] ?? '#206bc4';

$outputs = $pdo->prepare('SELECT * FROM report_outputs WHERE report_id=? ORDER BY display_order, id');
$outputs->execute([$reportId]); $outputs = $outputs->fetchAll();

$activeOutput = null;
foreach ($outputs as $o) { if ((string)$o['id'] === $tab) { $activeOutput = $o; break; } }
if (!$activeOutput && $outputs) $activeOutput = $outputs[0];

$lastUpload = $pdo->prepare("SELECT * FROM report_uploads WHERE report_id=? AND status='completed' ORDER BY created_at DESC LIMIT 1");
$lastUpload->execute([$reportId]); $lastUpload = $lastUpload->fetch();

$data = null;
if ($activeOutput) {
    $st = $pdo->prepare('SELECT data_json FROM generated_outputs WHERE report_id=? AND output_id=? ORDER BY generated_at DESC LIMIT 1');
    $st->execute([$reportId, (int)$activeOutput['id']]);
    $row = $st->fetch();
    $data = $row ? json_decode($row['data_json'], true) : null;
}

/* Client wants the FULL accurate $ amount everywhere — not K/M abbreviated. */
function fmt_money_short($v) {
    return '$' . number_format((float) $v, 2);
}
?><!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($report['name']) ?> &mdash; <?= e($report['cname']) ?></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"/>
<link href="https://cdn.datatables.net/1.13.8/css/dataTables.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.jsdelivr.net/npm/apexcharts@3.45.2/dist/apexcharts.min.js"></script>
<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: 14px 0; }
    .c-brand { display:inline-flex; align-items:center; gap:12px; font-weight:700; font-size:1.15rem; }
    .c-brand .ico { width:34px; height:34px; border-radius:9px; background:rgba(255,255,255,.18); display:inline-flex; align-items:center; justify-content:center; }
    .c-title-bar { background: #fff; border-bottom: 1px solid var(--m-border); padding: 18px 0 12px; }
    .c-title-bar h2 { margin: 0; font-weight: 700; font-size: 1.4rem; color:#0f172a; }
    .c-title-bar .crumbs { font-size: .82rem; color: var(--m-text-soft); margin-top: 4px; }
    .c-title-bar .snap { display:inline-flex; align-items:center; gap:6px; font-size:.78rem; padding:3px 10px; border-radius:99px; background:#f1f5f9; color:#475569; }

    .c-tabs { display: flex; gap: 4px; padding: 8px 0 0; border-bottom: 2px solid var(--m-border); }
    .c-tab { padding: 9px 16px; font-size:.88rem; color: var(--m-text-soft); border-radius: 6px 6px 0 0; text-decoration:none; }
    .c-tab:hover { color: #0f172a; background: rgba(0,0,0,.03); }
    .c-tab.active { color: var(--tblr-primary); border-bottom: 2px solid var(--tblr-primary); margin-bottom: -2px; font-weight: 600; background:#fff; }

    .c-kpi { background:#fff; border:1px solid var(--m-border); border-radius:12px; padding: 16px 18px; transition: all .12s; }
    .c-kpi:hover { transform: translateY(-2px); box-shadow: 0 8px 24px rgba(15,23,37,.08); border-color: var(--tblr-primary); }
    .c-kpi .lbl { font-size:.7rem; text-transform:uppercase; letter-spacing:.04em; color: var(--m-text-soft); }
    .c-kpi .val { font-size: 1.7rem; font-weight: 700; color:#0f172a; line-height:1.1; margin-top: 4px; font-variant-numeric: tabular-nums; }

    .data-table { font-size: .85rem; }
    .data-table thead th { background: #475569; color:#fff; font-weight: 600; padding: 8px 10px; font-size: .72rem; text-transform: uppercase; letter-spacing:.04em; border-color: #334155; }
    .data-table tbody td { padding: 6px 10px; border-color: #e2e8f0; vertical-align: middle; }
    .data-table tbody tr:nth-child(even) td { background: #f8fafc; }
    .data-table .num { text-align: right; font-variant-numeric: tabular-nums; }
</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">
        <a href="<?= e(url('/client/overall.php?slug='.$slug)) ?>" class="c-brand text-decoration-none text-white">
            <span class="ico"><i class="ti ti-building-skyscraper"></i></span>
            <span><?= e($report['cname']) ?></span>
        </a>
        <div class="ms-auto d-flex align-items-center gap-2">
            <a href="<?= e(url('/client/overall.php?slug='.$slug)) ?>" class="btn btn-sm btn-light"><i class="ti ti-arrow-left me-1"></i>Dashboard</a>
            <form method="POST" action="<?= e(url('/logout.php')) ?>" class="d-inline"><?= csrf_field() ?>
                <button class="btn btn-sm btn-outline-light"><i class="ti ti-logout"></i></button>
            </form>
        </div>
    </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</strong>
        <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="c-title-bar">
    <div class="container-xl">
        <div class="row align-items-end">
            <div class="col">
                <h2><?= e($report['name']) ?></h2>
                <div class="crumbs">
                    <i class="ti ti-list-tree me-1"></i><?= e($report['pname']) ?>
                    <?php if ($lastUpload): ?>
                        <span class="ms-2 snap"><i class="ti ti-clock"></i> Updated <?= e(fmt_dt($lastUpload['completed_at'] ?? $lastUpload['created_at'])) ?></span>
                    <?php endif; ?>
                </div>
            </div>
            <div class="col-auto">
                <button onclick="window.print()" class="btn btn-sm btn-outline-secondary"><i class="ti ti-printer me-1"></i>Print</button>
            </div>
        </div>
        <?php if ($outputs): ?>
        <div class="c-tabs mt-3">
            <?php foreach ($outputs as $o): ?>
                <a class="c-tab <?= (string)$o['id']===(string)$activeOutput['id']?'active':'' ?>" href="?slug=<?= e($slug) ?>&id=<?= $reportId ?>&tab=<?= $o['id'] ?>">
                    <i class="ti ti-<?= ['dashboard'=>'chart-pie-2','kpi'=>'chart-pie-2','summary'=>'table','pivot'=>'list-tree','detail'=>'database'][$o['output_type']] ?? 'file-analytics' ?> me-1"></i>
                    <?= e($o['output_name']) ?>
                </a>
            <?php endforeach; ?>
        </div>
        <?php endif; ?>
    </div>
</div>

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

<?php if (!$activeOutput || !$data): ?>
    <div class="card text-center p-5">
        <div style="font-size: 3rem; opacity: .3">📊</div>
        <h3 class="mt-3">No data available yet</h3>
        <p class="text-secondary">This report hasn't been populated yet. Please check back soon.</p>
    </div>
<?php else: $type = $activeOutput['output_type']; ?>

    <?php if ($type === 'dashboard' || $type === 'kpi'): ?>
        <div class="row row-cards mb-4">
            <?php foreach (($data['kpis'] ?? []) as $k):
                $v = $k['value']; $fmt = $k['format'] ?? 'number';
                $vfmt = $fmt==='currency' ? fmt_money_short($v) : (is_numeric($v) ? number_format((float)$v, $v==(int)$v?0:2) : (string)$v); ?>
                <div class="col-md-6 col-lg-3">
                    <div class="c-kpi">
                        <div class="lbl"><?= e($k['label']) ?></div>
                        <div class="val"><?= $vfmt ?></div>
                    </div>
                </div>
            <?php endforeach; ?>
        </div>

        <?php if (!empty($data['chart'])): $chart = $data['chart']; ?>
        <div class="card mb-3">
            <div class="card-header py-2"><h3 class="card-title small mb-0"><i class="ti ti-chart-line me-1" style="color:var(--tblr-primary)"></i><?= e($chart['title'] ?? 'Trend') ?></h3></div>
            <div class="card-body p-2"><div id="c_main_chart" style="min-height:300px"></div></div>
        </div>
        <script>
        new ApexCharts(document.querySelector('#c_main_chart'), {
            chart: { type: '<?= e($chart['type'] ?? 'line') ?>', height: 300, fontFamily: 'inherit', toolbar: { show: false } },
            series: <?= json_encode($chart['series'] ?? []) ?>,
            xaxis: { categories: <?= json_encode($chart['categories'] ?? []) ?> },
            stroke: { curve: 'smooth', width: 2 },
            colors: ['<?= e($primary) ?>', '#16a34a', '#f59e0b', '#dc2626'],
            grid: { borderColor: '#eef0f3' },
            legend: { position: 'top' },
        }).render();
        </script>
        <?php endif; ?>

    <?php elseif ($type === 'detail'): ?>
        <?php $rows = $data['rows'] ?? []; $hdr = $rows ? array_keys($rows[0]) : []; ?>
        <div class="card">
            <div class="card-header py-2">
                <h3 class="card-title small mb-0"><i class="ti ti-database me-1" style="color:var(--tblr-primary)"></i>Detail · <?= number_format(count($rows)) ?> rows</h3>
            </div>
            <div class="card-body p-0">
            <table id="c_dt" class="table table-sm data-table mb-0">
                <thead><tr><?php foreach ($hdr as $h): ?><th class="text-nowrap"><?= e($h) ?></th><?php endforeach; ?></tr></thead>
                <tbody>
                <?php foreach (array_slice($rows, 0, 1000) as $r): ?>
                    <tr><?php foreach ($hdr as $h): ?>
                        <?php $v = $r[$h] ?? ''; $isNum = is_numeric($v); ?>
                        <td class="<?= $isNum ? 'num' : '' ?> text-nowrap"><?= e(is_scalar($v) ? (string)$v : '') ?></td>
                    <?php endforeach; ?></tr>
                <?php endforeach; ?>
                </tbody>
            </table></div>
        </div>
        <script>$(function(){ $('#c_dt').DataTable({ pageLength: 25, order: [], dom: 'frtip' }); });</script>

    <?php else: /* summary or pivot */ ?>
        <?php $rows = $data['rows'] ?? []; $groupBy = $data['group_by'] ?? []; $aggCols = $data['agg_cols'] ?? []; ?>
        <div class="card">
            <div class="card-header py-2"><h3 class="card-title small mb-0"><i class="ti ti-table me-1" style="color:var(--tblr-primary)"></i><?= e($activeOutput['output_name']) ?></h3></div>
            <div class="card-body p-0"><div class="table-responsive">
            <table class="table table-sm data-table mb-0">
                <thead><tr>
                    <?php foreach ($groupBy as $g): ?><th><?= e($g) ?></th><?php endforeach; ?>
                    <?php foreach ($aggCols as $a): ?><th class="text-end"><?= e($a['label'] ?? $a['col']) ?></th><?php endforeach; ?>
                </tr></thead>
                <tbody>
                <?php foreach ($rows as $r): ?>
                    <tr>
                        <?php foreach ($groupBy as $g): ?><td><?= e((string)($r[$g] ?? '')) ?></td><?php endforeach; ?>
                        <?php foreach ($aggCols as $a):
                            $alias = $a['label'] ?? $a['col']; $v = $r[$alias] ?? 0;
                            $disp = is_numeric($v) ? number_format((float)$v, $v==(int)$v?0:2) : (string)$v; ?>
                            <td class="num"><?= $disp ?></td>
                        <?php endforeach; ?>
                    </tr>
                <?php endforeach; ?>
                </tbody>
            </table>
            </div></div>
        </div>
    <?php endif; ?>

<?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>
