<?php
/**
 * Reassign inventory & set priority (coding.supervise).
 *  - Move pending / in-progress charts from one coder to another (e.g. absence).
 *  - Flag charts as TOP priority so the assigned coder gets them first.
 * (RTO of RFI/Disregard charts is handled on coding-rto.php in Phase 5.)
 */
require_once __DIR__ . '/../includes/config.php';
$user = require_login('internal');
$pdo  = db();
$uid  = (int) $user['id'];

/* Hierarchy scope: supervisor/manager may only touch their reporting team; sysadmin = everyone. */
$team   = coding_team_scope($pdo, $uid);                       // null = unrestricted
$teamCi = coding_team_in_sql($team, 'ci.assigned_to');        // ' AND ci.assigned_to IN (...)' / '' / ' AND 1=0'
$teamU  = coding_team_in_sql($team, 'u.id');

/* ----------------------------------------------------------- POST handlers */
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    csrf_check_or_die();
    $act = $_POST['action'] ?? '';
    $ids = array_values(array_filter(array_map('intval', (array) ($_POST['chart_ids'] ?? []))));
    if (!$ids) { flash('error', 'Select at least one chart.'); redirect('/admin/coding-reassign.php'); }
    $in = implode(',', array_fill(0, count($ids), '?'));

    $teamUp = coding_team_in_sql($team, 'assigned_to');         // restrict the affected rows to the actor's team
    if ($act === 'reassign') {
        $to = (int) input('to_coder');
        if (!$to) { flash('error', 'Choose a coder to reassign to.'); redirect('/admin/coding-reassign.php'); }
        if ($team !== null && !in_array($to, $team, true)) { flash('error', 'You can only reassign to a member of your team.'); redirect('/admin/coding-reassign.php'); }
        // Only pending / in-progress charts can be reassigned (and only ones within your team).
        $st = $pdo->prepare("UPDATE coding_inventory SET assigned_to=?, status='pending', started_at=NULL, updated_at=NOW()
                             WHERE id IN ($in) AND status IN ('pending','in_progress','hold')$teamUp");
        $st->execute(array_merge([$to], $ids));
        audit_log('coding.inventory.reassign', 'coding_inventory', null, null, ['to'=>$to,'ids'=>$ids]);
        if ($st->rowCount() && $to !== (int) $user['id'])   // tell the new coder (one summary, not per-chart)
            notify($to, 'coding', 'Charts assigned to you', $st->rowCount() . ' chart(s) were assigned to your coding queue by your supervisor.', '/admin/coding-inventory.php');
        flash('success', $st->rowCount() . ' chart(s) reassigned.');
    } elseif ($act === 'set_priority' || $act === 'clear_priority') {
        $val = $act === 'set_priority' ? 1 : 0;
        $st = $pdo->prepare("UPDATE coding_inventory SET is_priority=?, priority_by=?, priority_at=" . ($val ? 'NOW()' : 'NULL') . ", updated_at=NOW()
                             WHERE id IN ($in) AND status IN ('pending','in_progress','hold')$teamUp");
        $st->execute(array_merge([$val, (int) $user['id']], $ids));
        audit_log('coding.inventory.priority', 'coding_inventory', null, null, ['priority'=>$val,'ids'=>$ids]);
        flash('success', ($val ? 'Set TOP priority on ' : 'Cleared priority on ') . $st->rowCount() . ' chart(s).');
    }
    // preserve filters on return
    redirect('/admin/coding-reassign.php?' . http_build_query(array_intersect_key($_POST, array_flip(['client_id','process_id','provider_id','coder_id','status']))));
}

$fClient   = (int) ($_GET['client_id'] ?? 0);
$fProcess  = (int) ($_GET['process_id'] ?? 0);
$fProvider = (int) ($_GET['provider_id'] ?? 0);
$fCoder    = (int) ($_GET['coder_id'] ?? 0);
$fStatus   = (string) ($_GET['status'] ?? 'open');

$where = ["ci.status IN ('pending','in_progress','hold')"]; $params = [];
if (in_array($fStatus, ['pending','in_progress','hold'], true)) { $where = ['ci.status = ?']; $params[] = $fStatus; }
if ($fClient)   { $where[] = 'ci.client_id = ?';   $params[] = $fClient; }
if ($fProcess)  { $where[] = 'ci.process_id = ?';  $params[] = $fProcess; }
if ($fProvider) { $where[] = 'ci.provider_id = ?'; $params[] = $fProvider; }
if ($fCoder)    { $where[] = 'ci.assigned_to = ?'; $params[] = $fCoder; }
$wsql = 'WHERE ' . implode(' AND ', $where) . $teamCi;        // restrict to the actor's reporting team

/* option-source WHERE limited to the same team scope (sysadmin sees all) */
$optWhere = ($team === null) ? '' : ('WHERE ci.assigned_to IN (' . implode(',', $team ?: [0]) . ')');

$rows = $pdo->prepare("SELECT ci.*, c.name cn, p.name pn, f.name fn, pr.name prn, u.name coder
    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 users u ON u.id=ci.assigned_to
    $wsql ORDER BY ci.is_priority DESC, ci.uploaded_at ASC LIMIT 500");
$rows->execute($params);
$rows = $rows->fetchAll();

$clients = $pdo->query("SELECT DISTINCT c.id,c.name FROM coding_inventory ci JOIN clients c ON c.id=ci.client_id $optWhere ORDER BY c.name")->fetchAll();
$procs   = $pdo->query("SELECT DISTINCT p.id,p.name FROM coding_inventory ci JOIN processes p ON p.id=ci.process_id $optWhere ORDER BY p.name")->fetchAll();
$provs   = $pdo->query("SELECT DISTINCT pr.id,pr.name FROM coding_inventory ci JOIN coding_providers pr ON pr.id=ci.provider_id $optWhere ORDER BY pr.name")->fetchAll();
$allCoders = $pdo->query("SELECT DISTINCT u.id,u.name FROM users u JOIN user_roles ur ON ur.user_id=u.id JOIN roles r ON r.id=ur.role_id
    WHERE u.status='active' AND r.code IN ('coder','coding_supervisor','coding_manager')$teamU ORDER BY u.name")->fetchAll();

$pageTitle = 'Reassign / priority';
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-arrows-exchange me-2 text-primary"></i>Reassign &amp; priority</h2>
        <div class="text-secondary small">Move open charts between coders or flag them TOP priority.</div>
    </div>
</div></div></div>
<div class="page-body"><div class="container-xl">
    <div class="card mb-3"><div class="card-body">
        <form method="GET" class="row g-2">
            <div class="col"><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']?>" <?=$fClient===(int)$o['id']?'selected':''?>><?=e($o['name'])?></option><?php endforeach;?></select></div>
            <div class="col"><select name="process_id" class="form-select form-select-sm"><option value="">All processes</option><?php foreach($procs as $o):?><option value="<?=(int)$o['id']?>" <?=$fProcess===(int)$o['id']?'selected':''?>><?=e($o['name'])?></option><?php endforeach;?></select></div>
            <div class="col"><select name="provider_id" class="form-select form-select-sm"><option value="">All providers</option><?php foreach($provs as $o):?><option value="<?=(int)$o['id']?>" <?=$fProvider===(int)$o['id']?'selected':''?>><?=e($o['name'])?></option><?php endforeach;?></select></div>
            <div class="col"><select name="coder_id" class="form-select form-select-sm"><option value="">All coders</option><?php foreach($allCoders as $o):?><option value="<?=(int)$o['id']?>" <?=$fCoder===(int)$o['id']?'selected':''?>><?=e($o['name'])?></option><?php endforeach;?></select></div>
            <div class="col"><select name="status" class="form-select form-select-sm"><option value="open" <?=$fStatus==='open'?'selected':''?>>Open (all)</option><option value="pending" <?=$fStatus==='pending'?'selected':''?>>pending</option><option value="in_progress" <?=$fStatus==='in_progress'?'selected':''?>>in progress</option><option value="hold" <?=$fStatus==='hold'?'selected':''?>>on hold</option></select></div>
            <div class="col-auto"><button class="btn btn-sm btn-primary"><i class="ti ti-filter"></i></button> <a href="<?= e(url('/admin/coding-reassign.php')) ?>" class="btn btn-sm btn-ghost-secondary">Clear</a></div>
        </form>
    </div></div>

    <form method="POST" id="bulk">
        <?= csrf_field() ?>
        <input type="hidden" name="client_id" value="<?= $fClient ?>"><input type="hidden" name="process_id" value="<?= $fProcess ?>">
        <input type="hidden" name="provider_id" value="<?= $fProvider ?>"><input type="hidden" name="coder_id" value="<?= $fCoder ?>"><input type="hidden" name="status" value="<?= e($fStatus) ?>">
        <div class="card">
            <div class="card-header d-flex flex-wrap gap-2 align-items-center">
                <h3 class="card-title mb-0"><?= count($rows) ?> open chart(s)</h3>
                <div class="ms-auto d-flex flex-wrap gap-2 align-items-center">
                    <select name="to_coder" class="form-select form-select-sm w-auto"><option value="">reassign to…</option>
                        <?php foreach ($allCoders as $o): ?><option value="<?= (int)$o['id'] ?>"><?= e($o['name']) ?></option><?php endforeach; ?></select>
                    <button class="btn btn-sm btn-primary" name="action" value="reassign"><i class="ti ti-user-share me-1"></i>Reassign</button>
                    <button class="btn btn-sm btn-outline-danger" name="action" value="set_priority"><i class="ti ti-arrow-up me-1"></i>TOP priority</button>
                    <button class="btn btn-sm btn-outline-secondary" name="action" value="clear_priority">Clear priority</button>
                </div>
            </div>
            <div class="table-responsive"><table class="table table-vcenter card-table">
                <thead><tr>
                    <th class="w-1"><input type="checkbox" id="chkall" class="form-check-input m-0"></th>
                    <th></th><th>Patient</th><th>Client</th><th>Facility</th><th>Provider</th><th>Coder</th><th>Uploaded</th><th>Status</th>
                </tr></thead>
                <tbody>
                <?php if (!$rows): ?><tr><td colspan="9" class="text-center text-secondary py-4">No open charts match.</td></tr>
                <?php else: foreach ($rows as $r): ?>
                    <tr>
                        <td><input type="checkbox" name="chart_ids[]" value="<?= (int)$r['id'] ?>" class="form-check-input m-0 chk"></td>
                        <td><?= (int)$r['is_priority'] ? '<span class="badge bg-red"><i class="ti ti-arrow-up"></i></span>' : '' ?></td>
                        <td><strong><?= e($r['patient_name']) ?></strong><div class="small text-secondary"><?= e($r['patient_mrn'] ?? '') ?></div></td>
                        <td class="small text-secondary"><?= e($r['cn']) ?></td>
                        <td class="small"><?= e($r['fn']) ?></td>
                        <td class="small"><?= e($r['prn']) ?></td>
                        <td class="small"><?= e($r['coder'] ?? '—') ?></td>
                        <td class="small text-secondary text-nowrap"><?= e(fmt_dt($r['uploaded_at'])) ?></td>
                        <td><span class="badge bg-<?= $r['status']==='pending'?'secondary':'info' ?>-lt"><?= e(str_replace('_',' ',$r['status'])) ?></span></td>
                    </tr>
                <?php endforeach; endif; ?>
                </tbody>
            </table></div>
        </div>
    </form>
    <script>
    document.getElementById('chkall').addEventListener('change',function(){document.querySelectorAll('.chk').forEach(function(c){c.checked=document.getElementById('chkall').checked;});});
    </script>
</div></div>
<?php require __DIR__ . '/../includes/footer.php'; ?>
