<?php
/**
 * Coding providers — master-data admin (coding.reference / coding.supervise).
 * Add / edit / activate providers (global). Linking a provider to a facility is done
 * on the Hierarchy page (facility detail). Providers added here become selectable there.
 */
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('Providers',
        ['Provider name', 'NPI (optional)', 'Type (billing/scribe)', 'Billing route (internal/external)', 'Vendor name (if external)', 'Movement date (YYYY-MM-DD, optional)'],
        [['Smith, John MD', '1234567890', 'billing', 'internal', '', ''],
         ['Acme Billing LLC', '', 'billing', 'external', 'Acme Billing', '2026-01-01'],
         ['Doe, Jane (scribe)', '', 'scribe', 'internal', '', '']]);
    $x->download('providers-template.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[] = ['name'=>$r[0]??'','npi'=>$r[1]??'','type'=>$r[2]??'','route'=>$r[3]??'','vendor'=>$r[4]??'','movement'=>$r[5]??'']; }
                $rd->close();
                $bulkReport = coding_import_providers($pdo, $rows, $uid);
            } catch (Throwable $e) { flash('error', 'Could not read the workbook: ' . (APP_DEBUG ? $e->getMessage() : 'invalid .xlsx file')); }
        }
    } else {
        try {
            if ($act === 'add') {
                coding_add_provider($pdo, (string) input('name'), (string) input('npi'), (string) input('status'), $uid, (string) input('billing_route'), (string) input('vendor_name'), (string) input('movement_date'), (string) input('provider_type'));
                flash('success', 'Provider added.');
            } elseif ($act === 'edit') {
                coding_update_provider($pdo, (int) input('id'), (string) input('name'), (string) input('npi'), (string) input('status'), $uid, (string) input('billing_route'), (string) input('vendor_name'), (string) input('movement_date'), (string) input('provider_type'));
                flash('success', 'Provider updated.');
            } elseif ($act === 'toggle') {
                $cur = $pdo->prepare("SELECT name,npi,status,provider_type,billing_route,vendor_name,movement_date FROM coding_providers WHERE id=?"); $cur->execute([(int) input('id')]); $row = $cur->fetch();
                if ($row) { coding_update_provider($pdo, (int) input('id'), $row['name'], $row['npi'], $row['status']==='active'?'inactive':'active', $uid, (string) $row['billing_route'], $row['vendor_name'], $row['movement_date'], (string) $row['provider_type']);
                    flash('success', 'Provider ' . ($row['status']==='active'?'deactivated':'activated') . '.'); }
            } elseif ($act === 'delete') {
                if (!is_sysadmin()) { flash('error', 'Only a SysAdmin can delete providers.'); }
                else {
                    $res = coding_delete_provider($pdo, (int) input('id'), $uid);
                    $extra = array_sum($res) > 0 ? " (also removed {$res['facility_links']} facility link(s), {$res['cpt_validation']} CPT row(s), {$res['user_scope']} alignment(s), {$res['upload_batches']} upload batch(es))" : '';
                    flash('success', 'Provider deleted' . $extra . '.');
                }
            }
        } catch (Throwable $e) { flash('error', $e->getMessage()); }
        redirect('/admin/coding-providers.php?' . http_build_query(array_intersect_key($_GET, array_flip(['q','status','provider_type','billing_route']))));
    }
}

$q  = trim((string) ($_GET['q'] ?? ''));
$fs = in_array($_GET['status'] ?? '', ['active','inactive'], true) ? $_GET['status'] : '';
$ftype  = in_array($_GET['provider_type'] ?? '', ['billing','scribe'], true) ? $_GET['provider_type'] : '';
$froute = in_array($_GET['billing_route'] ?? '', ['internal','external'], true) ? $_GET['billing_route'] : '';
$where = []; $params = [];
if ($q !== '')      { $where[] = '(pr.name LIKE ? OR pr.npi LIKE ?)'; $params[] = "%$q%"; $params[] = "%$q%"; }
if ($fs !== '')     { $where[] = 'pr.status = ?'; $params[] = $fs; }
if ($ftype !== '')  { $where[] = "COALESCE(pr.provider_type,'billing') = ?"; $params[] = $ftype; }
if ($froute !== '') { $where[] = "COALESCE(pr.billing_route,'internal') = ?"; $params[] = $froute; }
$wsql = $where ? ('WHERE ' . implode(' AND ', $where)) : '';
$rows = $pdo->prepare("SELECT pr.*, (SELECT COUNT(*) FROM coding_facility_providers fp WHERE fp.provider_id=pr.id) AS fac_n
    FROM coding_providers pr $wsql ORDER BY pr.name LIMIT 1000");
$rows->execute($params); $rows = $rows->fetchAll();
$total = (int) $pdo->query("SELECT COUNT(*) FROM coding_providers")->fetchColumn();

/* Client » Process » Facility mappings per listed provider (which facilities each provider is linked to). Fetched in
   one grouped query so the Facilities badge can expand to show the actual c»p»f list. */
$mapByProv = [];
if ($rows) {
    $pin = implode(',', array_map(fn($r) => (int) $r['id'], $rows));
    foreach ($pdo->query("SELECT fp.provider_id, c.name cn, p.name pn, f.name fn, f.status fstatus
            FROM coding_facility_providers fp
            JOIN coding_facilities f ON f.id=fp.facility_id
            JOIN processes p ON p.id=f.process_id
            JOIN clients c ON c.id=p.client_id
            WHERE fp.provider_id IN ($pin)
            ORDER BY c.name, p.name, f.name") as $m) {
        $mapByProv[(int) $m['provider_id']][] = $m;
    }
}

/* Which provider ids are referenced by real work data (any chart role OR a billing sheet as provider/scribe) — used
   only to gate the SysAdmin hard-delete button. Computed in bulk (a handful of scans) rather than a correlated
   subquery per row; the delete function re-checks authoritatively before deleting. */
$provInUse = [];
if (is_sysadmin()) {
    $u = "SELECT provider_id id FROM coding_inventory WHERE provider_id IS NOT NULL
          UNION SELECT coded_provider_id FROM coding_inventory WHERE coded_provider_id IS NOT NULL
          UNION SELECT rendering_provider_id FROM coding_inventory WHERE rendering_provider_id IS NOT NULL
          UNION SELECT billing_provider_id FROM coding_inventory WHERE billing_provider_id IS NOT NULL
          UNION SELECT pcp_provider_id FROM coding_inventory WHERE pcp_provider_id IS NOT NULL
          UNION SELECT provider_id FROM coding_billing_sheets WHERE provider_id IS NOT NULL
          UNION SELECT scribe_id FROM coding_billing_sheets WHERE scribe_id IS NOT NULL";
    foreach ($pdo->query($u) as $r) $provInUse[(int) $r['id']] = 1;
}

$pageTitle = 'Coding providers';
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-user-plus me-2 text-primary"></i>Coding providers</h2>
        <div class="text-secondary small">Master list of providers (<?= number_format($total) ?>). Link them to facilities on the Hierarchy page.</div></div>
    <div class="col-auto"><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 provider</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">Name</label><input name="name" class="form-control" placeholder="LASTNAME, FIRSTNAME" required></div>
            <div class="col-md-2"><label class="form-label">NPI</label><input name="npi" class="form-control" placeholder="10 digits" maxlength="10" inputmode="numeric"></div>
            <div class="col-md-2"><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"><label class="form-label">Type</label><select name="provider_type" class="form-select"><option value="billing">Billing provider</option><option value="scribe">Scribe</option></select></div>
            <div class="col-md-2"><label class="form-label">Billing route</label><select name="billing_route" class="form-select"><option value="internal">Internal billing</option><option value="external">External vendor</option></select></div>
            <div class="col-md-2"><label class="form-label">Vendor <span class="text-secondary small">(if external)</span></label><input name="vendor_name" class="form-control" placeholder="Vendor name"></div>
            <div class="col-md-2"><label class="form-label">Movement date <span class="text-secondary small">(optional)</span></label><input type="date" name="movement_date" class="form-control" title="Date this provider moved to internal billing. Charts with a DOS before this date route to the External vendor."></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 class="card-footer text-secondary small py-2"><i class="ti ti-info-circle me-1"></i><strong>Type</strong>: a <em>Billing provider</em> is linked to facilities on the Hierarchy page; a <em>Scribe</em> is global (works under any client / process / facility) and is tagged under a billing provider on the billing-sheet uploader and the chart. &nbsp;·&nbsp; <strong>Movement date</strong>: the date the provider switched to internal billing — on <em>Send to billing</em>, any chart whose <strong>DOS is before</strong> this date routes to the <strong>External vendor</strong> tab; DOS on/after follows the billing route.</div></div>
    </div>

    <?php coding_bulk_upload_render([
        'title'        => 'Bulk upload providers',
        'template_url' => url('/admin/coding-providers.php?bulk_template=xlsx'),
        'action_url'   => url('/admin/coding-providers.php'),
        'columns'      => ['Name', 'NPI', 'Type', 'Billing route', 'Vendor', 'Movement date'],
        'report'       => $bulkReport,
    ]); ?>

    <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 name or NPI…"></div>
            <div class="col-auto"><select name="provider_type" class="form-select form-select-sm"><option value="">All types</option>
                <option value="billing" <?= $ftype==='billing'?'selected':'' ?>>Billing</option><option value="scribe" <?= $ftype==='scribe'?'selected':'' ?>>Scribe</option></select></div>
            <div class="col-auto"><select name="billing_route" class="form-select form-select-sm"><option value="">All routes</option>
                <option value="internal" <?= $froute==='internal'?'selected':'' ?>>Internal</option><option value="external" <?= $froute==='external'?'selected':'' ?>>External</option></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-providers.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>Provider</th><th>Type</th><th>NPI</th><th class="text-center">Facilities</th><th>Billing route</th><th>Movement date</th><th>Status</th><th class="w-1"></th></tr></thead>
            <tbody>
            <?php if (!$rows): ?><tr><td colspan="8" class="text-center text-secondary py-4">No providers match.</td></tr>
            <?php else: foreach ($rows as $r): ?>
                <tr>
                    <td><strong><?= e($r['name']) ?></strong></td>
                    <td><?php if (($r['provider_type'] ?? 'billing')==='scribe'): ?><span class="badge bg-purple-lt"><i class="ti ti-pencil me-1"></i>Scribe</span><?php else: ?><span class="badge bg-blue-lt">Billing</span><?php endif; ?></td>
                    <td class="small"><?= e($r['npi'] ?: '—') ?></td>
                    <td class="text-center"><?php if ((int)$r['fac_n'] > 0): ?><button type="button" class="btn btn-sm btn-ghost-secondary py-0" data-bs-toggle="collapse" data-bs-target="#map<?= (int)$r['id'] ?>" title="Show which client » process » facility this provider is mapped under"><span class="badge bg-cyan-lt"><?= (int)$r['fac_n'] ?></span> <i class="ti ti-chevron-down"></i></button><?php else: ?><span class="badge bg-secondary-lt" title="Not linked to any facility">0</span><?php endif; ?></td>
                    <td><?php if (($r['billing_route'] ?? 'internal')==='external'): ?><span class="badge bg-orange-lt" title="Charts route to an external vendor"><i class="ti ti-external-link me-1"></i><?= e($r['vendor_name'] ?: 'Vendor') ?></span><?php else: ?><span class="badge bg-secondary-lt">Internal</span><?php endif; ?></td>
                    <td class="small"><?php if (!empty($r['movement_date'])): ?><span title="Charts with a DOS before this date route to the External vendor"><i class="ti ti-calendar-event me-1 text-secondary"></i><?= e(fmt_date($r['movement_date'])) ?></span><?php else: ?><span class="text-secondary">—</span><?php endif; ?></td>
                    <td><span class="badge bg-<?= $r['status']==='active'?'success':'secondary' ?>-lt"><?= e($r['status']) ?></span></td>
                    <td>
                        <div class="btn-list flex-nowrap">
                            <button class="btn btn-sm" data-bs-toggle="collapse" data-bs-target="#ep<?= (int)$r['id'] ?>"><i class="ti ti-edit"></i></button>
                            <form method="POST" class="d-inline" onsubmit="return confirm('<?= $r['status']==='active'?'Deactivate':'Activate' ?> this provider?');">
                                <?= 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>
                            <?php if (is_sysadmin()): ?>
                                <?php if (isset($provInUse[(int)$r['id']])): ?>
                                    <button class="btn btn-sm btn-ghost-secondary" disabled title="In use by chart(s) or billing sheet(s) — deactivate the provider or clear the data first"><i class="ti ti-trash-off"></i></button>
                                <?php else: ?>
                                    <form method="POST" class="d-inline" onsubmit="return confirm('Delete this provider permanently? This also removes its facility links and CPT validation, and cannot be undone.');">
                                        <?= csrf_field() ?><input type="hidden" name="action" value="delete"><input type="hidden" name="id" value="<?= (int)$r['id'] ?>">
                                        <button class="btn btn-sm btn-ghost-danger" title="Delete provider (SysAdmin)"><i class="ti ti-trash"></i></button>
                                    </form>
                                <?php endif; ?>
                            <?php endif; ?>
                        </div>
                    </td>
                </tr>
                <tr class="collapse" id="map<?= (int)$r['id'] ?>"><td colspan="8" class="bg-cyan-lt bg-opacity-10">
                    <div class="small"><i class="ti ti-sitemap me-1 text-cyan"></i><strong>Mapped under (Client » Process » Facility):</strong>
                        <?php $maps = $mapByProv[(int)$r['id']] ?? []; if (!$maps): ?><span class="text-secondary ms-1">Not linked to any facility.</span>
                        <?php else: ?>
                        <div class="row g-1 mt-1">
                            <?php foreach ($maps as $m): ?>
                            <div class="col-md-6 col-lg-4"><i class="ti ti-point text-secondary"></i> <?= e($m['cn']) ?> <span class="text-secondary">»</span> <?= e($m['pn']) ?> <span class="text-secondary">»</span> <strong><?= e($m['fn']) ?></strong><?php if (($m['fstatus'] ?? 'active')!=='active'): ?> <span class="badge bg-secondary-lt">facility inactive</span><?php endif; ?></div>
                            <?php endforeach; ?>
                        </div>
                        <?php endif; ?>
                    </div>
                </td></tr>
                <tr class="collapse" id="ep<?= (int)$r['id'] ?>"><td colspan="8" 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-4"><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-2"><label class="form-label">Type</label><select name="provider_type" class="form-select form-select-sm"><option value="billing" <?= ($r['provider_type']??'billing')==='billing'?'selected':'' ?>>Billing provider</option><option value="scribe" <?= ($r['provider_type']??'')==='scribe'?'selected':'' ?>>Scribe</option></select></div>
                        <div class="col-md-2"><label class="form-label">NPI</label><input name="npi" class="form-control form-control-sm" value="<?= e($r['npi']) ?>" maxlength="10" inputmode="numeric"></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"><label class="form-label">Billing route</label><select name="billing_route" class="form-select form-select-sm"><option value="internal" <?= ($r['billing_route']??'internal')==='internal'?'selected':'' ?>>Internal billing</option><option value="external" <?= ($r['billing_route']??'')==='external'?'selected':'' ?>>External vendor</option></select></div>
                        <div class="col-md-2"><label class="form-label">Vendor <span class="text-secondary small">(if external)</span></label><input name="vendor_name" class="form-control form-control-sm" value="<?= e($r['vendor_name'] ?? '') ?>"></div>
                        <div class="col-md-2"><label class="form-label">Movement date</label><input type="date" name="movement_date" class="form-control form-control-sm" value="<?= e($r['movement_date'] ?? '') ?>" title="DOS before this date route to External vendor"></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) >= 1000): ?><div class="card-footer text-secondary small">Showing first 1000 — narrow with search.</div><?php endif; ?>
    </div>
</div></div>
<?php require __DIR__ . '/../includes/footer.php'; ?>
