<?php
/**
 * Upload inventory (coding.upload).
 *  1. Coder picks Client ▸ Process ▸ Facility ▸ Provider (scoped to their access).
 *  2. "Download template" → xlsx with the 4 context columns prefilled + blank
 *     patient columns (MRN/PRN, Name, DOB, Record Sign Date).
 *  3. "Upload" → rows are parsed, stamped with uploaded_at, and AUTO-ALLOCATED
 *     to the uploading coder (FIFO by uploaded_at when worked).
 */
require_once __DIR__ . '/../includes/config.php';
$user = require_login('internal');
$pdo  = db();
$uid  = (int) $user['id'];

/* ---- resolve a selected combo + scope check (shared by template + upload) ---- */
function _combo(PDO $pdo): array {
    $ids = ['client_id'=>(int)input('client_id'),'process_id'=>(int)input('process_id'),
            'facility_id'=>(int)input('facility_id'),'provider_id'=>(int)input('provider_id')];
    return $ids;
}

$do = $_POST['do'] ?? $_GET['do'] ?? '';

/* ---------- TEMPLATE DOWNLOAD (POST do=template) ---------- */
if ($do === 'template' && $_SERVER['REQUEST_METHOD'] === 'POST') {
    csrf_check_or_die();
    $c = _combo($pdo);
    if (!$c['client_id'] || !$c['process_id'] || !$c['facility_id'] || !$c['provider_id']
        || !coding_user_can_tuple($uid, $c['client_id'], $c['process_id'], $c['facility_id'], $c['provider_id'])) {
        flash('error', 'Pick a client, process, facility and provider you have access to.');
        redirect('/admin/coding-upload.php');
    }
    $names = $pdo->prepare("SELECT c.name cn, p.name pn, f.name fn, pr.name prn
        FROM clients c JOIN processes p ON p.id=? JOIN coding_facilities f ON f.id=? JOIN coding_providers pr ON pr.id=?
        WHERE c.id=?");
    $names->execute([$c['process_id'], $c['facility_id'], $c['provider_id'], $c['client_id']]);
    $n = $names->fetch();
    require_once __DIR__ . '/../includes/xlsx.php';
    $headers = ['Client','Process','Facility','Provider','Patient MRN/PRN (optional)','Patient Name','Patient DOB (MM/DD/YYYY)','Record Sign Date (MM/DD/YYYY)'];
    $rows = [];
    for ($i = 0; $i < 100; $i++) $rows[] = [$n['cn'], $n['pn'], $n['fn'], $n['prn'], '', '', '', ''];
    $x = new SimpleXlsx();
    $x->addSheet('Inventory', $headers, $rows);
    $x->download('coding-inventory-template.xlsx');   // exits
}

/* ---------- UPLOAD (POST do=upload) ---------- */
if ($do === 'upload' && $_SERVER['REQUEST_METHOD'] === 'POST') {
    csrf_check_or_die();
    $c = _combo($pdo);
    if (!$c['client_id'] || !$c['process_id'] || !$c['facility_id'] || !$c['provider_id']
        || !coding_user_can_tuple($uid, $c['client_id'], $c['process_id'], $c['facility_id'], $c['provider_id'])) {
        flash('error', 'Pick a client, process, facility and provider you have access to.');
        redirect('/admin/coding-upload.php');
    }
    if (empty($_FILES['file']['tmp_name']) || !is_uploaded_file($_FILES['file']['tmp_name'])) {
        flash('error', 'Choose a filled template file to upload.');
        redirect('/admin/coding-upload.php');
    }
    $orig = $_FILES['file']['name'];
    $ext  = strtolower(pathinfo($orig, PATHINFO_EXTENSION));
    if (!in_array($ext, ['xlsx','csv'], true)) { flash('error', 'Upload the .xlsx template (or a .csv).'); redirect('/admin/coding-upload.php'); }
    if ($_FILES['file']['size'] > UPLOAD_MAX_BYTES) { flash('error', 'File is too large.'); redirect('/admin/coding-upload.php'); }

    // Read rows as numerically-indexed arrays.
    $data = [];
    try {
        if ($ext === 'xlsx') {
            require_once __DIR__ . '/../includes/xlsx-reader.php';
            $r = new XlsxReader($_FILES['file']['tmp_name']);
            foreach ($r->rows(0) as $row) $data[] = $row;
            $r->close();
        } else {
            $fh = fopen($_FILES['file']['tmp_name'], 'r');
            while (($row = fgetcsv($fh)) !== false) $data[] = $row;
            fclose($fh);
        }
    } catch (Throwable $e) {
        flash('error', 'Could not read the file: ' . $e->getMessage());
        redirect('/admin/coding-upload.php');
    }
    if (count($data) < 2) { flash('error', 'No data rows found.'); redirect('/admin/coding-upload.php'); }

    // Map patient columns by header keyword, falling back to fixed positions 4..7.
    $idx = function (array $headers, array $needles, int $fb): int {
        foreach ($headers as $i => $h) { $hl = strtolower(trim((string) $h)); foreach ($needles as $nd) if ($hl !== '' && strpos($hl, $nd) !== false) return $i; }
        return $fb;
    };
    $head = array_shift($data);
    $iMrn  = $idx($head, ['mrn','prn'], 4);
    $iName = $idx($head, ['patient name','name'], 5);
    $iDob  = $idx($head, ['dob','birth'], 6);
    $iSign = $idx($head, ['sign','record'], 7);

    $batch = $pdo->prepare("INSERT INTO coding_upload_batches (uploaded_by,client_id,process_id,facility_id,provider_id,file_name,row_count,created_at)
                            VALUES (?,?,?,?,?,?,0,NOW())");
    $batch->execute([$uid, $c['client_id'], $c['process_id'], $c['facility_id'], $c['provider_id'], mb_substr($orig, 0, 255)]);
    $batchId = (int) $pdo->lastInsertId();

    $ins = $pdo->prepare("INSERT INTO coding_inventory
        (batch_id,client_id,process_id,facility_id,provider_id,patient_mrn,patient_name,patient_dob,record_sign_date,
         assigned_to,uploaded_by,uploaded_at,status,created_at,updated_at)
        VALUES (?,?,?,?,?,?,?,?,?,?,?,NOW(),'pending',NOW(),NOW())");

    $n = 0;
    $pdo->beginTransaction();
    foreach ($data as $row) {
        $name = trim((string) ($row[$iName] ?? ''));
        if ($name === '') continue;
        $mrn  = trim((string) ($row[$iMrn] ?? '')) ?: null;
        $dob  = coding_parse_date($row[$iDob] ?? '');
        $sign = coding_parse_date($row[$iSign] ?? '');
        $ins->execute([$batchId, $c['client_id'], $c['process_id'], $c['facility_id'], $c['provider_id'],
                       $mrn, mb_substr($name, 0, 200), $dob, $sign, $uid, $uid]);
        $n++;
    }
    $pdo->prepare("UPDATE coding_upload_batches SET row_count=? WHERE id=?")->execute([$n, $batchId]);
    $pdo->commit();

    audit_log('coding.inventory.upload', 'coding_upload_batches', $batchId, null, ['rows'=>$n] + $c);
    flash('success', "Uploaded $n charts — allocated to you and added to your open queue.");
    redirect('/admin/coding-inventory.php');
}

$pageTitle = 'Upload inventory';
require __DIR__ . '/../includes/header.php';

$tree = coding_accessible_tree($uid);
$recent = $pdo->prepare("SELECT b.*, c.name cn, p.name pn, f.name fn, pr.name prn
    FROM coding_upload_batches b JOIN clients c ON c.id=b.client_id JOIN processes p ON p.id=b.process_id
    JOIN coding_facilities f ON f.id=b.facility_id JOIN coding_providers pr ON pr.id=b.provider_id
    WHERE b.uploaded_by=? ORDER BY b.created_at DESC LIMIT 8");
$recent->execute([$uid]);
$recent = $recent->fetchAll();
?>
<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-upload me-2 text-primary"></i>Upload inventory</h2>
        <div class="text-secondary small">Pick your queue, download the template, fill the patient columns, then upload.</div>
    </div>
</div></div></div>
<div class="page-body"><div class="container-xl">
<?php if (!$tree): ?>
    <div class="alert alert-warning"><i class="ti ti-alert-triangle me-2"></i>You have no client/process/facility/provider access yet. Ask your supervisor to grant you scope (Coder access).</div>
<?php else: ?>
    <div class="card mb-3">
        <div class="card-header"><h3 class="card-title">1 — Choose your queue</h3></div>
        <div class="card-body">
            <div class="row g-2">
                <div class="col-md-3"><label class="form-label required">Client</label><select id="sel_client" class="form-select"><option value="">— client —</option></select></div>
                <div class="col-md-3"><label class="form-label required">Process</label><select id="sel_process" class="form-select"><option value="">—</option></select></div>
                <div class="col-md-3"><label class="form-label required">Facility</label><select id="sel_facility" class="form-select"><option value="">—</option></select></div>
                <div class="col-md-3"><label class="form-label required">Provider</label><select id="sel_provider" class="form-select"><option value="">—</option></select></div>
            </div>
            <div class="d-flex flex-wrap gap-2 mt-3">
                <form method="POST" id="form_tpl" class="d-inline"><?= csrf_field() ?>
                    <input type="hidden" name="do" value="template">
                    <input type="hidden" name="client_id" class="h_client"><input type="hidden" name="process_id" class="h_process">
                    <input type="hidden" name="facility_id" class="h_facility"><input type="hidden" name="provider_id" class="h_provider">
                    <button class="btn btn-outline-primary" type="submit"><i class="ti ti-download me-1"></i>Download template</button>
                </form>
            </div>
        </div>
    </div>

    <div class="card mb-3">
        <div class="card-header"><h3 class="card-title">2 — Upload the filled template</h3></div>
        <div class="card-body">
            <form method="POST" enctype="multipart/form-data" id="form_up"><?= csrf_field() ?>
                <input type="hidden" name="do" value="upload">
                <input type="hidden" name="client_id" class="h_client"><input type="hidden" name="process_id" class="h_process">
                <input type="hidden" name="facility_id" class="h_facility"><input type="hidden" name="provider_id" class="h_provider">
                <div class="row g-2 align-items-end">
                    <div class="col-md-8"><label class="form-label required">File (.xlsx or .csv)</label><input type="file" name="file" class="form-control" accept=".xlsx,.csv" required></div>
                    <div class="col-md-4"><button class="btn btn-primary w-100" type="submit"><i class="ti ti-upload me-1"></i>Upload &amp; allocate to me</button></div>
                </div>
                <div class="form-hint mt-2">Only rows with a Patient Name are imported. The uploaded date is set automatically.</div>
            </form>
        </div>
    </div>

    <?php if ($recent): ?>
    <div class="card">
        <div class="card-header"><h3 class="card-title">Recent uploads</h3></div>
        <div class="table-responsive"><table class="table table-vcenter card-table">
            <thead><tr><th>When</th><th>Client</th><th>Facility</th><th>Provider</th><th class="text-end">Charts</th></tr></thead>
            <tbody>
            <?php foreach ($recent as $b): ?>
                <tr><td class="small text-secondary text-nowrap"><?= e(fmt_dt($b['created_at'])) ?></td>
                    <td class="small"><?= e($b['cn']) ?></td><td class="small"><?= e($b['fn']) ?></td>
                    <td class="small"><?= e($b['prn']) ?></td><td class="text-end"><?= (int)$b['row_count'] ?></td></tr>
            <?php endforeach; ?>
            </tbody>
        </table></div>
    </div>
    <?php endif; ?>

    <script>
    (function(){
        var TREE = <?= json_encode($tree, JSON_HEX_TAG|JSON_HEX_AMP|JSON_HEX_QUOT|JSON_HEX_APOS) ?>;
        var elC=document.getElementById('sel_client'), elP=document.getElementById('sel_process'),
            elF=document.getElementById('sel_facility'), elPr=document.getElementById('sel_provider');
        function opt(v,t){var o=document.createElement('option');o.value=v;o.textContent=t;return o;}
        function fill(el,map){el.innerHTML='<option value="">—</option>';
            Object.keys(map||{}).sort(function(a,b){return (map[a].name||map[a]).localeCompare(map[b].name||map[b]);})
                .forEach(function(k){el.appendChild(opt(k,map[k].name||map[k]));});}
        elC.innerHTML='<option value="">— client —</option>';
        Object.keys(TREE).sort(function(a,b){return TREE[a].name.localeCompare(TREE[b].name);}).forEach(function(k){elC.appendChild(opt(k,TREE[k].name));});
        function sync(){
            document.querySelectorAll('.h_client').forEach(function(x){x.value=elC.value;});
            document.querySelectorAll('.h_process').forEach(function(x){x.value=elP.value;});
            document.querySelectorAll('.h_facility').forEach(function(x){x.value=elF.value;});
            document.querySelectorAll('.h_provider').forEach(function(x){x.value=elPr.value;});
        }
        elC.onchange=function(){var c=TREE[elC.value];elP.innerHTML='<option value="">—</option>';elF.innerHTML='<option value="">—</option>';elPr.innerHTML='<option value="">—</option>';if(c)fill(elP,c.processes);sync();};
        elP.onchange=function(){var c=TREE[elC.value];elF.innerHTML='<option value="">—</option>';elPr.innerHTML='<option value="">—</option>';if(c&&c.processes[elP.value])fill(elF,c.processes[elP.value].facilities);sync();};
        elF.onchange=function(){var c=TREE[elC.value];elPr.innerHTML='<option value="">—</option>';if(c&&c.processes[elP.value]&&c.processes[elP.value].facilities[elF.value])fill(elPr,c.processes[elP.value].facilities[elF.value].providers);sync();};
        elPr.onchange=sync;
        function guard(f){f.addEventListener('submit',function(e){sync();if(!elC.value||!elP.value||!elF.value||!elPr.value){e.preventDefault();alert('Choose client, process, facility and provider first.');}});}
        guard(document.getElementById('form_tpl')); guard(document.getElementById('form_up'));
    })();
    </script>
<?php endif; ?>
</div></div>
<?php require __DIR__ . '/../includes/footer.php'; ?>
