<?php
/**
 * Coding facilities — master-data admin (coding.reference / coding.supervise).
 * Add / edit / activate facilities across every coding process. Linking providers to a
 * facility is done on the Hierarchy page (facility detail). Sysadmin / supervisor / manager.
 */
require_once __DIR__ . '/../includes/config.php';
$user = require_login('internal');
$pdo  = db();
$uid  = (int) $user['id'];

/* Bulk-upload template (.xlsx). */
if (($_GET['bulk_template'] ?? '') === 'xlsx') {
    require_once __DIR__ . '/../includes/xlsx.php';
    $x = new SimpleXlsx();
    $x->addSheet('Facilities',
        ['Client', 'Process', 'Facility name', 'Code (optional)', 'Status (active/inactive)'],
        [['01 Maximize', '01 Peyman Younesi', 'ABC - Main Hospital', 'AHA', 'active'],
         ['01 Maximize', '05 PY Medical',     'XYZ - Clinic',        '',    'active']]);
    $x->download('facilities-template.xlsx');
    exit;
}

/* Download the LAST facility bulk-import result as .xlsx (per-row status + reason). Stashed in the session by
   the bulk_import handler below so it survives the render→click round-trip. */
if (($_GET['download_result'] ?? '') === 'xlsx') {
    $res = $_SESSION['facility_import_result']['rows'] ?? [];
    require_once __DIR__ . '/../includes/xlsx.php';
    $x = new SimpleXlsx();
    $data = [];
    foreach ($res as $r) $data[] = [$r['row'] ?? '', $r['client'] ?? '', $r['process'] ?? '', $r['facility'] ?? '', $r['code'] ?? '', $r['status'] ?? '', $r['note'] ?? ''];
    $x->addSheet('Import result', ['Row', 'Client', 'Process', 'Facility', 'Code', 'Result', 'Reason'], $data);
    $x->download('facility-import-result-' . date('Ymd-His') . '.xlsx');
    exit;
}

$bulkReport = null;
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    csrf_check_or_die();
    $act = $_POST['action'] ?? '';
    if ($act === 'bulk_import') {
        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]??'','name'=>$r[2]??'','code'=>$r[3]??'','status'=>$r[4]??'']; }
                $rd->close();
                $bulkReport = coding_import_facilities($pdo, $rows, $uid);
                $_SESSION['facility_import_result'] = ['at' => time(), 'rows' => $bulkReport['rows'] ?? []];
            } catch (Throwable $e) { flash('error', 'Could not read the workbook: ' . (APP_DEBUG ? $e->getMessage() : 'invalid .xlsx file')); }
        }
    } else {
        try {
            if ($act === 'add') {
                coding_add_facility($pdo, (int) input('process_id'), (string) input('name'), (string) input('code'), (string) input('status'), $uid);
                flash('success', 'Facility added.');
            } elseif ($act === 'edit') {
                coding_update_facility($pdo, (int) input('id'), (string) input('name'), (string) input('code'), (string) input('status'), $uid);
                flash('success', 'Facility updated.');
            } elseif ($act === 'toggle') {
                $cur = $pdo->prepare("SELECT name,code,status FROM coding_facilities WHERE id=?"); $cur->execute([(int) input('id')]); $row = $cur->fetch();
                if ($row) { coding_update_facility($pdo, (int) input('id'), $row['name'], $row['code'], $row['status']==='active'?'inactive':'active', $uid);
                    flash('success', 'Facility ' . ($row['status']==='active'?'deactivated':'activated') . '.'); }
            }
        } catch (Throwable $e) { flash('error', $e->getMessage()); }
        redirect('/admin/coding-facilities.php?' . http_build_query(array_intersect_key($_GET, array_flip(['q','client_id','status']))));
    }
}

$q  = trim((string) ($_GET['q'] ?? ''));
$fc = (int) ($_GET['client_id'] ?? 0);
$fs = in_array($_GET['status'] ?? '', ['active','inactive'], true) ? $_GET['status'] : '';

// Coding facilities belong to Coding-vertical clients only — separate per-vertical copies (Option B), so this page
// never shows AR / Billing clients (which previously appeared as confusing same-name duplicates in the picker).
$codingV = coding_workflow_vertical_in_sql('c.vertical_id');   // all coding-workflow verticals (Coding + any module='coding')
$where = ['c.deleted_at IS NULL', 'p.deleted_at IS NULL', $codingV]; $params = [];
if ($q !== '')  { $where[] = '(f.name LIKE ? OR f.code LIKE ?)'; $params[] = "%$q%"; $params[] = "%$q%"; }
if ($fc)        { $where[] = 'c.id = ?'; $params[] = $fc; }
if ($fs !== '') { $where[] = 'f.status = ?'; $params[] = $fs; }
$wsql = 'WHERE ' . implode(' AND ', $where);

$rows = $pdo->prepare("SELECT f.id, f.name, f.code, f.status, p.name pname, c.name cname,
        (SELECT COUNT(*) FROM coding_facility_providers fp WHERE fp.facility_id=f.id) AS prov_n,
        (SELECT COUNT(*) FROM coding_cpt_validation v2 WHERE v2.facility_id=f.id AND v2.status='active') AS cpt_n
    FROM coding_facilities f
    JOIN processes p ON p.id=f.process_id
    JOIN clients c ON c.id=p.client_id
    JOIN verticals v ON v.id=c.vertical_id
    $wsql ORDER BY c.name, p.name, f.name LIMIT 2000");
$rows->execute($params); $rows = $rows->fetchAll();

$procs = $pdo->query("SELECT p.id, p.name, c.name client FROM processes p JOIN clients c ON c.id=p.client_id
    WHERE p.deleted_at IS NULL AND c.deleted_at IS NULL AND $codingV ORDER BY c.name, p.name")->fetchAll();
$clients = $pdo->query("SELECT c.id, c.name FROM clients c
    WHERE c.deleted_at IS NULL AND $codingV ORDER BY c.name")->fetchAll();
$total = (int) $pdo->query("SELECT COUNT(*) FROM coding_facilities f JOIN processes p ON p.id=f.process_id JOIN clients c ON c.id=p.client_id WHERE $codingV")->fetchColumn();

$pageTitle = 'Coding facilities';
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-building-hospital me-2 text-primary"></i>Coding facilities</h2>
        <div class="text-secondary small">Add &amp; edit facilities (<?= number_format($total) ?>). Link providers to a facility on the Hierarchy page.</div></div>
    <div class="col-auto d-flex gap-2">
        <a href="<?= e(url('/admin/coding-providers.php')) ?>" class="btn btn-outline-secondary"><i class="ti ti-user-plus me-1"></i>Providers</a>
        <a href="<?= e(url('/admin/coding-hierarchy.php')) ?>" class="btn btn-outline-secondary"><i class="ti ti-sitemap me-1"></i>Hierarchy</a>
    </div>
</div></div></div>
<div class="page-body"><div class="container-xl">

    <div class="card mb-3"><div class="card-header"><h3 class="card-title"><i class="ti ti-plus me-1"></i>Add 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="add">
            <div class="col-md-4"><label class="form-label required">Process</label>
                <select name="process_id" class="form-select" required><option value="">— client » process —</option>
                    <?php foreach ($procs as $p): ?><option value="<?= (int)$p['id'] ?>"><?= e($p['client']) ?> » <?= e($p['name']) ?></option><?php endforeach; ?></select>
                <div class="form-hint">Only processes under <strong>Coding-vertical</strong> clients appear here. Don't see a new one? On <a href="<?= e(url('/admin/processes.php')) ?>">Processes</a> make sure it's under the client shown as <em>· Coding</em>.</div></div>
            <div class="col-md-4"><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-2"><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-1"><button class="btn btn-primary w-100"><i class="ti ti-check"></i></button></div>
        </form></div>
    </div>

    <?php coding_bulk_upload_render([
        'title'        => 'Bulk upload facilities',
        'template_url' => url('/admin/coding-facilities.php?bulk_template=xlsx'),
        'action_url'   => url('/admin/coding-facilities.php'),
        'columns'      => ['Client', 'Process', 'Facility name', 'Code', 'Status'],
        'report'       => $bulkReport,
    ]); ?>

    <?php if ($bulkReport && !empty($bulkReport['rows'])):
        $rrows = $bulkReport['rows'];
        $errN = 0; foreach ($rrows as $rr) if (($rr['status'] ?? '') === 'error') $errN++; ?>
    <div class="card mb-3">
        <div class="card-header py-2">
            <h3 class="card-title mb-0">Import result — each row's outcome</h3>
            <div class="card-actions">
                <span class="badge bg-green-lt me-1"><?= (int)$bulkReport['created'] ?> created</span>
                <span class="badge bg-cyan-lt me-1"><?= (int)$bulkReport['reactivated'] ?> reactivated</span>
                <span class="badge bg-secondary-lt me-1"><?= (int)$bulkReport['skipped'] ?> skipped</span>
                <span class="badge bg-<?= $errN ? 'red' : 'secondary' ?>-lt me-2"><?= (int)$errN ?> error<?= $errN === 1 ? '' : 's' ?></span>
                <a href="<?= e(url('/admin/coding-facilities.php?download_result=xlsx')) ?>" class="btn btn-sm btn-outline-primary"><i class="ti ti-file-spreadsheet me-1"></i>Download results (.xlsx)</a>
            </div>
        </div>
        <div class="card-body py-2 text-secondary small"><i class="ti ti-info-circle me-1"></i><strong>Skipped</strong> = the facility already exists (same name in that client » process) — a re-upload is a no-op, nothing is lost. <strong>Error</strong> = the row couldn't be matched (e.g. the client » process name doesn't resolve to a Coding client). Only genuinely new facilities are <strong>created</strong>.</div>
        <div class="table-responsive" style="max-height:420px;overflow:auto">
            <table class="table table-sm table-vcenter card-table">
                <thead><tr><th class="w-1">Row</th><th>Client » Process » Facility</th><th class="w-1">Code</th><th class="w-1">Result</th><th>Reason</th></tr></thead>
                <tbody>
                <?php foreach ($rrows as $rr): $st = $rr['status'] ?? '';
                    $bc = ['created'=>'green','reactivated'=>'cyan','skipped'=>'secondary','error'=>'red'][$st] ?? 'secondary'; ?>
                    <tr class="<?= $st === 'error' ? 'table-danger' : '' ?>">
                        <td class="text-secondary"><?= (int)($rr['row'] ?? 0) ?></td>
                        <td class="small"><?= e(trim(($rr['client'] ?? '') . ' » ' . ($rr['process'] ?? '') . ' » ' . ($rr['facility'] ?? ''), ' »')) ?></td>
                        <td class="small text-nowrap"><?= e($rr['code'] ?? '') ?></td>
                        <td><span class="badge bg-<?= $bc ?>-lt"><?= e($st) ?></span></td>
                        <td class="small <?= $st === 'error' ? 'text-danger' : 'text-secondary' ?>"><?= e($rr['note'] ?? '') ?></td>
                    </tr>
                <?php endforeach; ?>
                </tbody>
            </table>
        </div>
    </div>
    <?php endif; ?>

    <div class="card">
        <div class="card-header"><form method="GET" class="row g-2 w-100">
            <div class="col"><input name="q" value="<?= e($q) ?>" class="form-control form-control-sm" placeholder="Search facility name or code…"></div>
            <div class="col-auto"><select name="client_id" class="form-select form-select-sm"><option value="">All clients</option><?php foreach($clients as $o):?><option value="<?=(int)$o['id']?>" <?=$fc===(int)$o['id']?'selected':''?>><?=e($o['name'])?></option><?php endforeach;?></select></div>
            <div class="col-auto"><select name="status" class="form-select form-select-sm"><option value="">All statuses</option>
                <option value="active" <?= $fs==='active'?'selected':'' ?>>Active</option><option value="inactive" <?= $fs==='inactive'?'selected':'' ?>>Inactive</option></select></div>
            <div class="col-auto"><button class="btn btn-sm btn-primary"><i class="ti ti-search"></i></button> <a href="<?= e(url('/admin/coding-facilities.php')) ?>" class="btn btn-sm btn-ghost-secondary">Clear</a></div>
        </form></div>
        <div class="table-responsive"><table class="table table-vcenter card-table">
            <thead><tr><th>Facility</th><th>Client » Process</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 if (!$rows): ?><tr><td colspan="7" class="text-center text-secondary py-4">No facilities match.</td></tr>
            <?php else: foreach ($rows as $r): ?>
                <tr>
                    <td><strong><?= e($r['name']) ?></strong></td>
                    <td class="small text-secondary"><?= e($r['cname']) ?> » <?= e($r['pname']) ?></td>
                    <td><?= $r['code'] ? '<code>'.e($r['code']).'</code>' : '<span class="text-secondary">—</span>' ?></td>
                    <td class="text-center"><span class="badge bg-cyan-lt"><?= (int)$r['prov_n'] ?></span></td>
                    <td class="text-center"><span class="badge bg-blue-lt"><?= (int)$r['cpt_n'] ?></span></td>
                    <td><span class="badge bg-<?= $r['status']==='active'?'success':'secondary' ?>-lt"><?= e($r['status']) ?></span></td>
                    <td><div class="btn-list flex-nowrap justify-content-end">
                        <button class="btn btn-sm" data-bs-toggle="collapse" data-bs-target="#ef<?= (int)$r['id'] ?>" title="Edit"><i class="ti ti-edit"></i></button>
                        <a href="<?= e(url('/admin/coding-hierarchy.php?facility_id='.(int)$r['id'])) ?>" class="btn btn-sm" title="Open in hierarchy (link providers)"><i class="ti ti-link"></i></a>
                        <form method="POST" class="d-inline" onsubmit="return confirm('<?= $r['status']==='active'?'Deactivate':'Activate' ?> this facility?');">
                            <?= csrf_field() ?><input type="hidden" name="action" value="toggle"><input type="hidden" name="id" value="<?= (int)$r['id'] ?>">
                            <button class="btn btn-sm btn-ghost-<?= $r['status']==='active'?'danger':'success' ?>"><i class="ti ti-<?= $r['status']==='active'?'ban':'check' ?>"></i></button></form>
                    </div></td>
                </tr>
                <tr class="collapse" id="ef<?= (int)$r['id'] ?>"><td colspan="7" class="bg-secondary-lt">
                    <form method="POST" class="row g-2 align-items-end">
                        <?= csrf_field() ?><input type="hidden" name="action" value="edit"><input type="hidden" name="id" value="<?= (int)$r['id'] ?>">
                        <div class="col-md-5"><label class="form-label">Name</label><input name="name" class="form-control form-control-sm" value="<?= e($r['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($r['code']) ?>" maxlength="60"></div>
                        <div class="col-md-2"><label class="form-label">Status</label><select name="status" class="form-select form-select-sm"><option value="active" <?= $r['status']==='active'?'selected':'' ?>>Active</option><option value="inactive" <?= $r['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 endforeach; endif; ?>
            </tbody>
        </table></div>
        <?php if (count($rows) >= 2000): ?><div class="card-footer text-secondary small">Showing first 2000 — narrow with filters.</div><?php endif; ?>
    </div>
</div></div>
<?php require __DIR__ . '/../includes/footer.php'; ?>
