<?php
/**
 * Coding chart — READ-ONLY detail (coding-chart-view-v1).
 *
 * A quick "what's in this chart" view reachable from every coding-inventory row (incl. pending charts that
 * have no Resume/View action in the editor). Shows demographics, the coder's coded lines (DOS · CPT · Units ·
 * Modifiers · ICDs), any audit findings, and the event log. No edits happen here — the full editor is
 * admin/coding-chart.php.
 *
 * Visibility fence MIRRORS the inventory list: a coder sees their OWN charts; a supervisor/manager sees their
 * TEAM's (coding_team_scope); SysAdmin sees all. The route gate is a coarse allow-list; THIS is the real fence.
 */
require_once __DIR__ . '/../includes/config.php';
$user = require_login('internal');
$pdo  = db();
$uid  = (int) $user['id'];

$id = (int) ($_GET['id'] ?? 0);
if (!$id) { redirect('/admin/coding-inventory.php'); }

$chart = $pdo->prepare("SELECT ci.*, c.name cn, p.name pn, f.name fn, pr.name uploaded_provider, cp.name coded_provider
    FROM coding_inventory ci
    JOIN clients c ON c.id=ci.client_id JOIN processes p ON p.id=ci.process_id
    JOIN coding_facilities f ON f.id=ci.facility_id JOIN coding_providers pr ON pr.id=ci.provider_id
    LEFT JOIN coding_providers cp ON cp.id=ci.coded_provider_id
    WHERE ci.id=?");
$chart->execute([$id]);
$chart = $chart->fetch();
if (!$chart) { flash('error', 'Chart not found.'); redirect('/admin/coding-inventory.php'); }

// Same visibility fence as coding-inventory: own chart, or a supervisor/manager within their team, or sysadmin.
$team  = coding_team_scope($pdo, $uid);                       // null = sysadmin (unrestricted)
$owner = (int) ($chart['assigned_to'] ?? 0);
$coder = (int) ($chart['coder_id'] ?? 0);
$canView = $owner === $uid || $coder === $uid
    || (can('coding.supervise') && ($team === null || in_array($owner, $team, true) || in_array($coder, $team, true)))
    // Auditors / validators are vertical-wide reviewers (matching the editor's auditor policy and this page's
    // route gate) — they may read any chart's detail. The route gate already admits them; keep the two in sync.
    || can('coding.audit') || can('coding.validate');
if (!$canView) { http_response_code(403); flash('error', 'That chart is not in your scope.'); redirect('/admin/coding-inventory.php'); }

$lines  = coding_chart_lines($pdo, $id);
$audit  = array_values(array_filter(coding_audit_codes($pdo, $id), fn($a) => empty($a['superseded_at'])));
$events = $pdo->prepare("SELECT ev.*, u.name actor FROM coding_chart_events ev LEFT JOIN users u ON u.id=ev.actor_id
    WHERE ev.inventory_id=? ORDER BY ev.created_at DESC, ev.id DESC LIMIT 40");
$events->execute([$id]);
$events = $events->fetchAll();

// A supervisor/owner can jump to the full editor; others just get the read-only view + Back.
$canEdit = ($owner === $uid) || can('coding.supervise') || can('coding.audit');

$statusBadge = ['pending'=>'secondary','in_progress'=>'blue','hold'=>'orange','completed'=>'green','rfi'=>'yellow','disregard'=>'red'];
$auditBadge  = ['correct'=>'green','incorrect'=>'red','extra'=>'orange','missing'=>'purple'];
$backUrl = $_GET['back'] ?? '/admin/coding-inventory.php';
if (!is_string($backUrl) || strpos($backUrl, '/admin/') !== 0) $backUrl = '/admin/coding-inventory.php';   // only same-app paths

$pageTitle = 'Chart details';
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-file-text me-2 text-primary"></i>Chart details
        <span class="badge bg-<?= $statusBadge[$chart['status']] ?? 'secondary' ?>-lt ms-2"><?= e(str_replace('_',' ', $chart['status'])) ?></span></h2>
        <div class="text-secondary small">Read-only view of the chart's demographics, coded lines and audit history.</div>
    </div>
    <div class="col-auto d-flex gap-2">
        <a href="<?= e(url($backUrl)) ?>" class="btn btn-outline-secondary"><i class="ti ti-arrow-left me-1"></i>Back</a>
        <?php if ($canEdit): ?><a href="<?= e(url('/admin/coding-chart.php?id=' . $id)) ?>" class="btn btn-primary"><i class="ti ti-external-link me-1"></i>Open in editor</a><?php endif; ?>
    </div>
</div></div></div>

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

    <!-- Demographics -->
    <div class="card mb-3"><div class="card-body">
        <div class="row g-3">
            <?php
            $demo = [
                ['Patient', $chart['patient_name']],
                ['MRN', $chart['patient_mrn'] ?? '—'],
                ['DOB', fmt_date($chart['patient_dob'])],
                ['DOS', fmt_date($chart['dos'] ?? null)],
                ['Record sign', fmt_date($chart['record_sign_date'] ?? null)],
                ['Client', $chart['cn']],
                ['Process', $chart['pn']],
                ['Facility', $chart['fn']],
                ['Rendering provider', $chart['uploaded_provider']],
                ['Coded provider', $chart['coded_provider'] ?: '—'],
            ];
            foreach ($demo as [$lbl, $val]): ?>
                <div class="col-6 col-md-3">
                    <div class="text-secondary small text-uppercase" style="font-size:.7rem;letter-spacing:.03em"><?= e($lbl) ?></div>
                    <div class="fw-medium"><?= e((string) ($val ?? '')) ?: '<span class="text-secondary">—</span>' ?></div>
                </div>
            <?php endforeach; ?>
        </div>
    </div></div>

    <!-- Coded lines -->
    <div class="card mb-3">
        <div class="card-header py-2"><h3 class="card-title mb-0">Coded lines <span class="text-secondary fw-normal small">(<?= count($lines) ?>)</span></h3></div>
        <div class="table-responsive"><table class="table table-sm table-vcenter card-table">
            <thead><tr><th class="text-nowrap">DOS</th><th>CPT</th><th class="text-center">Units</th><th>Modifier(s)</th><th>ICD(s)</th></tr></thead>
            <tbody>
            <?php foreach ($lines as $ln): ?>
                <tr>
                    <td class="text-nowrap"><?= e(fmt_date($ln['dos'] ?? null)) ?: '—' ?></td>
                    <td class="fw-bold"><?= e($ln['cpt_code'] ?? $ln['cpt'] ?? '') ?></td>
                    <td class="text-center"><?= (int) ($ln['units'] ?? 1) ?></td>
                    <td><?= e(implode(', ', $ln['mods'] ?? [])) ?: '<span class="text-secondary">—</span>' ?></td>
                    <td><?= e(implode(', ', $ln['icds'] ?? [])) ?: '<span class="text-secondary">—</span>' ?></td>
                </tr>
            <?php endforeach; ?>
            <?php if (!$lines): ?><tr><td colspan="5" class="text-center text-secondary py-3">No coded lines on this chart yet.</td></tr><?php endif; ?>
            </tbody>
        </table></div>
    </div>

    <!-- Audit findings -->
    <?php if ($audit): ?>
    <div class="card mb-3">
        <div class="card-header py-2"><h3 class="card-title mb-0">Audit findings <span class="text-secondary fw-normal small">(<?= count($audit) ?>)</span></h3></div>
        <div class="table-responsive"><table class="table table-sm table-vcenter card-table">
            <thead><tr><th>Type</th><th>Coded value</th><th>Result</th><th>Correct value</th><th>Category</th><th>Comment</th></tr></thead>
            <tbody>
            <?php foreach ($audit as $a): $res = (string) ($a['result'] ?? ''); ?>
                <tr>
                    <td class="text-uppercase small"><?= e($a['code_type'] ?? '') ?></td>
                    <td><?= e($a['code_value'] ?? '') ?: '<span class="text-secondary">—</span>' ?></td>
                    <td><span class="badge bg-<?= $auditBadge[$res] ?? 'secondary' ?>-lt"><?= e($res) ?: '—' ?></span></td>
                    <td><?= e($a['correct_value'] ?? '') ?: '<span class="text-secondary">—</span>' ?></td>
                    <td class="small"><?= e($a['error_category'] ?? '') ?></td>
                    <td class="small text-secondary"><?= e($a['comment'] ?? '') ?></td>
                </tr>
            <?php endforeach; ?>
            </tbody>
        </table></div>
    </div>
    <?php endif; ?>

    <!-- Event log -->
    <div class="card">
        <div class="card-header py-2"><h3 class="card-title mb-0">History <span class="text-secondary fw-normal small">(last <?= count($events) ?>)</span></h3></div>
        <div class="table-responsive"><table class="table table-sm table-vcenter card-table">
            <thead><tr><th class="text-nowrap">When</th><th>Event</th><th>By</th><th>Note</th></tr></thead>
            <tbody>
            <?php foreach ($events as $ev): ?>
                <tr>
                    <td class="text-nowrap small text-secondary"><?= e(fmt_dt($ev['created_at'] ?? null)) ?></td>
                    <td class="small"><?= e(str_replace('_', ' ', (string) ($ev['event_type'] ?? ''))) ?>
                        <?php if (!empty($ev['from_state']) || !empty($ev['to_state'])): ?><span class="text-secondary">(<?= e((string)($ev['from_state'] ?? '')) ?> → <?= e((string)($ev['to_state'] ?? '')) ?>)</span><?php endif; ?></td>
                    <td class="small"><?= e($ev['actor'] ?? '—') ?></td>
                    <td class="small text-secondary"><?= e($ev['note'] ?? '') ?></td>
                </tr>
            <?php endforeach; ?>
            <?php if (!$events): ?><tr><td colspan="4" class="text-center text-secondary py-3">No history yet.</td></tr><?php endif; ?>
            </tbody>
        </table></div>
    </div>

</div></div>
<?php require __DIR__ . '/../includes/footer.php'; ?>
