<?php
/**
 * Coding hierarchy browser — Vertical ▸ Client ▸ Process ▸ Facility ▸ Provider.
 * Read-only drill-down; CPT validation is managed on coding-cpt.php.
 * Gated: coding.supervise OR coding.reference (see admin_route_permissions).
 */
require_once __DIR__ . '/../includes/config.php';
$user = require_login('internal');
$pdo  = db();
$uid  = (int) $user['id'];
$canEdit = can('coding.reference') || can('coding.supervise');   // page is already gated to these

/* Bulk-upload template (.xlsx) — link providers to facilities. */
if (($_GET['bulk_template'] ?? '') === 'xlsx') {
    require_once __DIR__ . '/../includes/xlsx.php';
    $x = new SimpleXlsx();
    $x->addSheet('Provider links',
        ['Client', 'Process', 'Facility', 'Provider'],
        [['01 Maximize', '01 Peyman Younesi', 'ABC - Main Hospital', 'Smith, John MD'],
         ['01 Maximize', '01 Peyman Younesi', 'ABC - Main Hospital', 'Jones, Mary NP']]);
    $x->download('provider-facility-links-template.xlsx');
    exit;
}

$bulkReport = null;

/* ----------------------------------------------------------- POST handlers (master-data edits) */
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    csrf_check_or_die();
    if (!$canEdit) { flash('error', 'You are not allowed to edit master data.'); redirect('/admin/coding-hierarchy.php'); }
    $act = $_POST['action'] ?? '';
    if ($act === 'bulk_import') {                       // sets $bulkReport, falls through to render (no redirect)
        if (empty($_FILES['file']['tmp_name']) || !is_uploaded_file($_FILES['file']['tmp_name'])) {
            flash('error', 'Choose an .xlsx file to upload.');
        } else {
            try {
                require_once __DIR__ . '/../includes/xlsx-reader.php';
                $rd = new XlsxReader($_FILES['file']['tmp_name']); $rows = []; $i = 0;
                foreach ($rd->rows(0) as $r) { if (++$i === 1) continue; $rows[] = ['client'=>$r[0]??'','process'=>$r[1]??'','facility'=>$r[2]??'','provider'=>$r[3]??'']; }
                $rd->close();
                $bulkReport = coding_import_facility_providers($pdo, $rows, $uid);
            } catch (Throwable $e) { flash('error', 'Could not read the workbook: ' . (APP_DEBUG ? $e->getMessage() : 'invalid .xlsx file')); }
        }
    } else {
    $backProc = (int) input('process_id');
    $backFac  = (int) input('facility_id');
    $back = $backFac ? ('/admin/coding-hierarchy.php?facility_id=' . $backFac) : ($backProc ? ('/admin/coding-hierarchy.php?process_id=' . $backProc) : '/admin/coding-hierarchy.php');
    try {
        if ($act === 'add_facility') {
            coding_add_facility($pdo, $backProc, (string) input('name'), (string) input('code'), (string) input('status'), $uid);
            flash('success', 'Facility added.');
        } elseif ($act === 'edit_facility') {
            coding_update_facility($pdo, $backFac, (string) input('name'), (string) input('code'), (string) input('status'), $uid);
            flash('success', 'Facility updated.');
        } elseif ($act === 'link_provider') {
            coding_link_provider($pdo, $backFac, (int) input('provider_id'), $uid);
            flash('success', 'Provider linked to this facility.');
        } elseif ($act === 'create_link_provider') {
            $pid = coding_add_provider($pdo, (string) input('name'), (string) input('npi'), 'active', $uid);
            coding_link_provider($pdo, $backFac, $pid, $uid);
            flash('success', 'Provider created and linked.');
        } elseif ($act === 'unlink_provider') {
            coding_unlink_provider($pdo, $backFac, (int) input('provider_id'), $uid);
            flash('success', 'Provider unlinked from this facility.');
        } elseif ($act === 'delete_facility') {
            if (!is_sysadmin()) throw new RuntimeException('Only a SysAdmin can delete facilities.');
            $pr = $pdo->prepare("SELECT process_id FROM coding_facilities WHERE id=?"); $pr->execute([$backFac]); $procForBack = (int) $pr->fetchColumn();
            $res = coding_delete_facility($pdo, $backFac, $uid);
            $extra = array_sum($res) > 0 ? " (also removed {$res['provider_links']} provider link(s), {$res['cpt_validation']} CPT row(s), {$res['user_scope']} alignment(s), {$res['upload_batches']} upload batch(es))" : '';
            flash('success', 'Facility deleted' . $extra . '.');
            $back = $procForBack ? ('/admin/coding-hierarchy.php?process_id=' . $procForBack) : '/admin/coding-hierarchy.php';   // facility is gone — go to its process
        }
    } catch (Throwable $e) { flash('error', $e->getMessage()); }
    redirect($back);
    }
}

$clientId   = (int) ($_GET['client_id'] ?? 0);
$processId  = (int) ($_GET['process_id'] ?? 0);
$facilityId = (int) ($_GET['facility_id'] ?? 0);

$pageTitle = 'Coding hierarchy';
require __DIR__ . '/../includes/header.php';

/* Resolve breadcrumb context from whichever id is deepest. */
$crumbs = [['Hierarchy', url('/admin/coding-hierarchy.php')]];
$facility = $process = $client = null;
if ($facilityId) {
    $facility = $pdo->prepare("SELECT f.*, p.id pid, p.name pname, c.id cid, c.name cname
        FROM coding_facilities f JOIN processes p ON p.id=f.process_id JOIN clients c ON c.id=p.client_id WHERE f.id=?");
    $facility->execute([$facilityId]); $facility = $facility->fetch();
    if ($facility) { $processId = (int)$facility['pid']; $clientId = (int)$facility['cid']; }
}
if ($processId && !$process) {
    $process = $pdo->prepare("SELECT p.*, c.id cid, c.name cname FROM processes p JOIN clients c ON c.id=p.client_id WHERE p.id=?");
    $process->execute([$processId]); $process = $process->fetch();
    if ($process) $clientId = (int)$process['cid'];
}
if ($clientId && !$client) {
    $client = $pdo->prepare("SELECT * FROM clients WHERE id=?"); $client->execute([$clientId]); $client = $client->fetch();
}
if ($client)   $crumbs[] = [$client['name'],   url('/admin/coding-hierarchy.php?client_id=' . $clientId)];
if ($process)  $crumbs[] = [$process['name'],  url('/admin/coding-hierarchy.php?process_id=' . $processId)];
if ($facility) $crumbs[] = [$facility['name'], url('/admin/coding-hierarchy.php?facility_id=' . $facilityId)];
?>
<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-sitemap me-2 text-primary"></i>Coding hierarchy</h2>
        <nav class="text-secondary small mt-1">
            <?php foreach ($crumbs as $i => $cb): ?>
                <?php if ($i) echo ' <span class="opacity-50">/</span> '; ?>
                <a href="<?= e($cb[1]) ?>" class="text-reset text-decoration-none"><?= e($cb[0]) ?></a>
            <?php endforeach; ?>
        </nav>
    </div>
</div></div></div>
<div class="page-body"><div class="container-xl">
<?php
/* ---------- LEVEL 4: facility detail (providers + CPT counts) ---------- */
if ($facility) {
    $provs = $pdo->prepare("SELECT pr.id, pr.name, pr.status AS pstatus,
            (SELECT COUNT(*) FROM coding_cpt_validation v WHERE v.facility_id=? AND v.provider_id=pr.id AND v.status='active') AS cpt_n,
            (SELECT COUNT(*) FROM coding_cpt_validation v WHERE v.facility_id=? AND v.provider_id=pr.id AND v.source='coder') AS added_n
        FROM coding_facility_providers fp JOIN coding_providers pr ON pr.id=fp.provider_id
        WHERE fp.facility_id=? ORDER BY pr.name");
    $provs->execute([$facilityId, $facilityId, $facilityId]);
    $provs = $provs->fetchAll();
    $unlinked = $canEdit ? $pdo->prepare("SELECT id,name FROM coding_providers WHERE status='active' AND provider_type='billing' AND id NOT IN (SELECT provider_id FROM coding_facility_providers WHERE facility_id=?) ORDER BY name") : null;
    if ($unlinked) { $unlinked->execute([$facilityId]); $unlinked = $unlinked->fetchAll(); }
    /* SysAdmin delete gating: a facility can only be hard-deleted when no chart / billing sheet references it. */
    $facChartN = 0; $facSheetN = 0;
    if (is_sysadmin()) {
        $cq = $pdo->prepare("SELECT COUNT(*) FROM coding_inventory WHERE facility_id=?"); $cq->execute([$facilityId]); $facChartN = (int) $cq->fetchColumn();
        $sq = $pdo->prepare("SELECT COUNT(*) FROM coding_billing_sheets WHERE facility_id=?"); $sq->execute([$facilityId]); $facSheetN = (int) $sq->fetchColumn();
    }
    ?>
    <?php if ($canEdit): ?>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/tom-select@2.3.1/dist/css/tom-select.bootstrap5.min.css">
    <script src="https://cdn.jsdelivr.net/npm/tom-select@2.3.1/dist/js/tom-select.complete.min.js"></script>
    <div class="card mb-3"><div class="card-header"><h3 class="card-title"><i class="ti ti-edit me-1"></i>Edit facility</h3></div>
        <div class="card-body"><form method="POST" class="row g-2 align-items-end">
            <?= csrf_field() ?><input type="hidden" name="action" value="edit_facility"><input type="hidden" name="facility_id" value="<?= $facilityId ?>">
            <div class="col-md-5"><label class="form-label required">Name</label><input name="name" class="form-control" value="<?= e($facility['name']) ?>" required></div>
            <div class="col-md-3"><label class="form-label">Code</label><input name="code" class="form-control" value="<?= e($facility['code']) ?>" maxlength="60"></div>
            <div class="col-md-2"><label class="form-label">Status</label><select name="status" class="form-select"><option value="active" <?= $facility['status']==='active'?'selected':'' ?>>Active</option><option value="inactive" <?= $facility['status']==='inactive'?'selected':'' ?>>Inactive</option></select></div>
            <div class="col-md-2"><button class="btn btn-primary w-100"><i class="ti ti-device-floppy me-1"></i>Save</button></div>
        </form></div>
        <?php if (is_sysadmin()): ?>
        <div class="card-footer d-flex flex-wrap align-items-center gap-2">
            <div class="text-secondary small"><i class="ti ti-alert-triangle me-1 text-danger"></i>Delete this facility permanently (SysAdmin) — also removes its provider links &amp; CPT validation. Cannot be undone.</div>
            <div class="ms-auto">
            <?php if ($facChartN + $facSheetN > 0): ?>
                <button class="btn btn-outline-secondary btn-sm" disabled title="In use by <?= $facChartN ?> chart(s) &amp; <?= $facSheetN ?> billing sheet(s) — deactivate the facility or clear the data first"><i class="ti ti-trash-off me-1"></i>Delete facility</button>
            <?php else: ?>
                <form method="POST" onsubmit="return confirm('Delete this facility permanently? This also removes its provider links and CPT validation, and cannot be undone.');">
                    <?= csrf_field() ?><input type="hidden" name="action" value="delete_facility"><input type="hidden" name="facility_id" value="<?= $facilityId ?>">
                    <button class="btn btn-danger btn-sm"><i class="ti ti-trash me-1"></i>Delete facility</button>
                </form>
            <?php endif; ?>
            </div>
        </div>
        <?php endif; ?>
    </div>
    <div class="card mb-3"><div class="card-header"><h3 class="card-title"><i class="ti ti-link me-1"></i>Add a provider to this facility</h3></div>
        <div class="card-body"><div class="row g-3">
            <div class="col-md-6">
                <form method="POST" class="row g-2 align-items-end">
                    <?= csrf_field() ?><input type="hidden" name="action" value="link_provider"><input type="hidden" name="facility_id" value="<?= $facilityId ?>">
                    <div class="col"><label class="form-label">Link an existing provider</label>
                        <select name="provider_id" id="linkProv" required><option value="">— choose a provider —</option>
                            <?php foreach (($unlinked ?: []) as $u): ?><option value="<?= (int)$u['id'] ?>"><?= e($u['name']) ?></option><?php endforeach; ?></select></div>
                    <div class="col-auto"><button class="btn btn-outline-primary"><i class="ti ti-link me-1"></i>Link</button></div>
                </form>
            </div>
            <div class="col-md-6 border-start">
                <form method="POST" class="row g-2 align-items-end">
                    <?= csrf_field() ?><input type="hidden" name="action" value="create_link_provider"><input type="hidden" name="facility_id" value="<?= $facilityId ?>">
                    <div class="col"><label class="form-label">…or create a new provider</label><input name="name" class="form-control" placeholder="LASTNAME, FIRSTNAME" required></div>
                    <div class="col-auto"><label class="form-label">NPI</label><input name="npi" class="form-control" style="width:120px" placeholder="optional" maxlength="10"></div>
                    <div class="col-auto"><button class="btn btn-primary"><i class="ti ti-plus me-1"></i>Create &amp; link</button></div>
                </form>
            </div>
        </div></div>
    </div>
    <?php endif; ?>
    <div class="card">
        <div class="card-header"><h3 class="card-title"><i class="ti ti-user-check me-1"></i>Providers at <?= e($facility['name']) ?> <span class="badge bg-blue-lt ms-2"><?= count($provs) ?></span></h3>
            <?php if (!in_array($facility['status'],['active'],true)): ?><div class="card-actions"><span class="badge bg-secondary-lt">facility inactive</span></div><?php endif; ?></div>
        <div class="table-responsive"><table class="table table-vcenter card-table">
            <thead><tr><th>Provider</th><th class="text-center">CPTs (active)</th><th class="text-center">Coder-added</th><th class="w-1"></th></tr></thead>
            <tbody>
            <?php foreach ($provs as $pr): ?>
                <tr>
                    <td><strong><?= e($pr['name']) ?></strong><?php if ($pr['pstatus']!=='active'): ?> <span class="badge bg-secondary-lt">inactive</span><?php endif; ?></td>
                    <td class="text-center"><span class="badge bg-blue-lt"><?= (int)$pr['cpt_n'] ?></span></td>
                    <td class="text-center"><?= (int)$pr['added_n'] ? '<span class="badge bg-orange-lt">'.(int)$pr['added_n'].'</span>' : '<span class="text-secondary">—</span>' ?></td>
                    <td><div class="btn-list flex-nowrap justify-content-end">
                        <?php if (can('coding.cpt.manage')): ?><a href="<?= e(url('/admin/coding-cpt.php?facility_id='.$facilityId.'&provider_id='.$pr['id'])) ?>" class="btn btn-sm btn-outline-primary" title="Add / manage this provider's CPT validation set"><i class="ti ti-list-numbers me-1"></i>CPTs</a><?php endif; ?>
                        <?php if ($canEdit): ?>
                        <form method="POST" class="d-inline" onsubmit="return confirm('Unlink <?= e(addslashes($pr['name'])) ?> from this facility?');">
                            <?= csrf_field() ?><input type="hidden" name="action" value="unlink_provider"><input type="hidden" name="facility_id" value="<?= $facilityId ?>"><input type="hidden" name="provider_id" value="<?= (int)$pr['id'] ?>">
                            <button class="btn btn-sm btn-ghost-danger" title="Unlink from this facility"><i class="ti ti-unlink"></i></button></form>
                        <?php endif; ?>
                    </div></td>
                </tr>
            <?php endforeach; ?>
            <?php if (!$provs): ?><tr><td colspan="4" class="text-center text-secondary py-4">No providers linked.</td></tr><?php endif; ?>
            </tbody>
        </table></div>
    </div>
    <?php if ($canEdit): ?><script>document.addEventListener('DOMContentLoaded',function(){ if(window.TomSelect){ try{ new TomSelect('#linkProv',{maxOptions:5000}); }catch(e){} } });</script><?php endif; ?>
<?php
/* ---------- LEVEL 3: facilities under a process ---------- */
} elseif ($process) {
    $facs = $pdo->prepare("SELECT f.id, f.name, f.code, f.status,
            (SELECT COUNT(*) FROM coding_facility_providers fp WHERE fp.facility_id=f.id) AS prov_n,
            (SELECT COUNT(*) FROM coding_cpt_validation v WHERE v.facility_id=f.id AND v.status='active') AS cpt_n
        FROM coding_facilities f WHERE f.process_id=? ORDER BY f.name");
    $facs->execute([$processId]); $facs = $facs->fetchAll();
    ?>
    <?php if ($canEdit): ?>
    <div class="card mb-3"><div class="card-header"><h3 class="card-title"><i class="ti ti-plus me-1"></i>Add facility to <?= e($process['name']) ?></h3></div>
        <div class="card-body"><form method="POST" class="row g-2 align-items-end">
            <?= csrf_field() ?><input type="hidden" name="action" value="add_facility"><input type="hidden" name="process_id" value="<?= $processId ?>">
            <div class="col-md-6"><label class="form-label required">Facility name</label><input name="name" class="form-control" placeholder="e.g. ABC - Main Hospital" required></div>
            <div class="col-md-3"><label class="form-label">Code</label><input name="code" class="form-control" placeholder="optional" maxlength="60"></div>
            <div class="col-md-1"><label class="form-label">Status</label><select name="status" class="form-select"><option value="active">Active</option><option value="inactive">Inactive</option></select></div>
            <div class="col-md-2"><button class="btn btn-primary w-100"><i class="ti ti-check me-1"></i>Add</button></div>
        </form></div>
    </div>
    <?php endif; ?>
    <div class="card">
        <div class="card-header"><h3 class="card-title"><i class="ti ti-building-hospital me-1"></i>Facilities in <?= e($process['name']) ?> <span class="badge bg-blue-lt ms-2"><?= count($facs) ?></span></h3></div>
        <div class="table-responsive"><table class="table table-vcenter card-table" id="dt">
            <thead><tr><th>Facility</th><th>Code</th><th class="text-center">Providers</th><th class="text-center">CPTs</th><th>Status</th><th class="w-1"></th></tr></thead>
            <tbody>
            <?php foreach ($facs as $f): ?>
                <tr>
                    <td><strong><?= e($f['name']) ?></strong></td>
                    <td><?= $f['code'] ? '<code>'.e($f['code']).'</code>' : '<span class="text-secondary">—</span>' ?></td>
                    <td class="text-center"><span class="badge bg-cyan-lt"><?= (int)$f['prov_n'] ?></span></td>
                    <td class="text-center"><span class="badge bg-blue-lt"><?= (int)$f['cpt_n'] ?></span></td>
                    <td><span class="badge bg-<?= $f['status']==='active'?'success':'secondary' ?>-lt"><?= e($f['status']) ?></span></td>
                    <td><div class="btn-list flex-nowrap justify-content-end">
                        <?php if ($canEdit): ?><button class="btn btn-sm" data-bs-toggle="collapse" data-bs-target="#ef<?= (int)$f['id'] ?>" title="Edit"><i class="ti ti-edit"></i></button><?php endif; ?>
                        <a href="<?= e(url('/admin/coding-hierarchy.php?facility_id='.$f['id'])) ?>" class="btn btn-sm">Open <i class="ti ti-chevron-right"></i></a>
                    </div></td>
                </tr>
                <?php if ($canEdit): ?>
                <tr class="collapse" id="ef<?= (int)$f['id'] ?>"><td colspan="6" class="bg-secondary-lt">
                    <form method="POST" class="row g-2 align-items-end">
                        <?= csrf_field() ?><input type="hidden" name="action" value="edit_facility"><input type="hidden" name="facility_id" value="<?= (int)$f['id'] ?>"><input type="hidden" name="process_id" value="<?= $processId ?>">
                        <div class="col-md-6"><label class="form-label">Name</label><input name="name" class="form-control form-control-sm" value="<?= e($f['name']) ?>" required></div>
                        <div class="col-md-3"><label class="form-label">Code</label><input name="code" class="form-control form-control-sm" value="<?= e($f['code']) ?>" maxlength="60"></div>
                        <div class="col-md-1"><label class="form-label">Status</label><select name="status" class="form-select form-select-sm"><option value="active" <?= $f['status']==='active'?'selected':'' ?>>Active</option><option value="inactive" <?= $f['status']==='inactive'?'selected':'' ?>>Inactive</option></select></div>
                        <div class="col-md-2"><button class="btn btn-sm btn-primary w-100"><i class="ti ti-device-floppy me-1"></i>Save</button></div>
                    </form>
                </td></tr>
                <?php endif; ?>
            <?php endforeach; ?>
            <?php if (!$facs): ?><tr><td colspan="6" class="text-center text-secondary py-4">No facilities yet<?= $canEdit ? ' — add one above.' : '.' ?></td></tr><?php endif; ?>
            </tbody>
        </table></div>
    </div>
<?php
/* ---------- LEVEL 2: processes under a client ---------- */
} elseif ($client) {
    $procs = $pdo->prepare("SELECT p.id, p.name, p.code,
            (SELECT COUNT(*) FROM coding_facilities f WHERE f.process_id=p.id) AS fac_n
        FROM processes p WHERE p.client_id=? AND p.deleted_at IS NULL ORDER BY p.name");
    $procs->execute([$clientId]); $procs = $procs->fetchAll();
    ?>
    <div class="card">
        <div class="card-header"><h3 class="card-title"><i class="ti ti-list-tree me-1"></i>Processes for <?= e($client['name']) ?> <span class="badge bg-blue-lt ms-2"><?= count($procs) ?></span></h3></div>
        <div class="table-responsive"><table class="table table-vcenter card-table">
            <thead><tr><th>Process</th><th>Code</th><th class="text-center">Facilities</th><th class="w-1"></th></tr></thead>
            <tbody>
            <?php foreach ($procs as $p): ?>
                <tr>
                    <td><strong><?= e($p['name']) ?></strong></td>
                    <td><code><?= e($p['code']) ?></code></td>
                    <td class="text-center"><span class="badge bg-blue-lt"><?= (int)$p['fac_n'] ?></span></td>
                    <td><a href="<?= e(url('/admin/coding-hierarchy.php?process_id='.$p['id'])) ?>" class="btn btn-sm">Open <i class="ti ti-chevron-right"></i></a></td>
                </tr>
            <?php endforeach; ?>
            </tbody>
        </table></div>
    </div>
<?php
/* ---------- LEVEL 1: clients (Coding vertical only — coding users never see AR / Billing clients) ---------- */
} else {
    $hq = trim((string) ($_GET['q'] ?? ''));
    // Master data is SHARED across all verticals — the Hierarchy manages the one global client»process»facility»provider tree.
    // Coding hierarchy lists Coding-vertical clients only (separate per-vertical copies — Option B), so AR / Billing
    // clients don't appear here as confusing same-name duplicates.
    $hw = ['c.deleted_at IS NULL', coding_workflow_vertical_in_sql('c.vertical_id')]; $hp = [];
    if ($hq !== '') { $hw[] = '(c.name LIKE ? OR c.code LIKE ?)'; $hp[] = "%$hq%"; $hp[] = "%$hq%"; }
    $cst = $pdo->prepare("SELECT c.id, c.name, c.code,
            (SELECT COUNT(*) FROM processes p WHERE p.client_id=c.id AND p.deleted_at IS NULL) AS proc_n,
            (SELECT COUNT(*) FROM coding_facilities f JOIN processes p ON p.id=f.process_id WHERE p.client_id=c.id) AS fac_n
        FROM clients c JOIN verticals v ON v.id=c.vertical_id AND v.deleted_at IS NULL
        WHERE " . implode(' AND ', $hw) . " ORDER BY c.name");
    $cst->execute($hp); $clients = $cst->fetchAll();
    ?>
    <?php if ($canEdit) coding_bulk_upload_render([
        'title'        => 'Bulk link providers to facilities',
        'template_url' => url('/admin/coding-hierarchy.php?bulk_template=xlsx'),
        'action_url'   => url('/admin/coding-hierarchy.php'),
        'columns'      => ['Client', 'Process', 'Facility', 'Provider'],
        'report'       => $bulkReport,
    ]); ?>

    <div class="card mb-3"><div class="card-body"><form method="GET" class="row g-2 align-items-end">
        <div class="col-md-5"><label class="form-label small mb-1">Client</label><input name="q" value="<?= e($hq) ?>" class="form-control form-control-sm" placeholder="Search client name or code…"></div>
        <div class="col-auto"><button class="btn btn-sm btn-primary"><i class="ti ti-filter me-1"></i>Filter</button> <a href="<?= e(url('/admin/coding-hierarchy.php')) ?>" class="btn btn-sm btn-ghost-secondary">Clear</a></div>
    </form></div></div>
    <div class="card">
        <div class="card-header"><h3 class="card-title"><i class="ti ti-building me-1"></i>Clients <span class="badge bg-blue-lt ms-2"><?= count($clients) ?></span></h3>
            <div class="card-actions text-secondary small">Coding vertical</div>
        </div>
        <div class="table-responsive"><table class="table table-vcenter card-table">
            <thead><tr><th>Client</th><th>Code</th><th class="text-center">Processes</th><th class="text-center">Facilities</th><th class="w-1"></th></tr></thead>
            <tbody>
            <?php foreach ($clients as $c): ?>
                <tr>
                    <td><strong><?= e($c['name']) ?></strong></td>
                    <td><code><?= e($c['code']) ?></code></td>
                    <td class="text-center"><span class="badge bg-cyan-lt"><?= (int)$c['proc_n'] ?></span></td>
                    <td class="text-center"><span class="badge bg-blue-lt"><?= (int)$c['fac_n'] ?></span></td>
                    <td><a href="<?= e(url('/admin/coding-hierarchy.php?client_id='.$c['id'])) ?>" class="btn btn-sm">Open <i class="ti ti-chevron-right"></i></a></td>
                </tr>
            <?php endforeach; ?>
            <?php if (!$clients): ?><tr><td colspan="5" class="text-center text-secondary py-4">No clients yet.</td></tr><?php endif; ?>
            </tbody>
        </table></div>
    </div>
<?php } ?>
</div></div>
<?php require __DIR__ . '/../includes/footer.php'; ?>
