<?php
/**
 * RTO — Return To Origin (coding.supervise OR coding.audit).
 * RFI / Disregard charts (tagged by coder or auditor) that have come back from the
 * client with clarification are sent back to a coder's OPEN queue at TOP priority.
 */
require_once __DIR__ . '/../includes/config.php';
$user = require_login('internal');
$pdo  = db();
$uid  = (int) $user['id'];

if ($_SERVER['REQUEST_METHOD'] === 'POST' && ($_POST['action'] ?? '') === 'send_back') {
    csrf_check_or_die();
    $id = (int) input('id');
    $to = (int) input('to_coder');
    if (!$to) { flash('error', 'Choose a coder to send it to.'); redirect('/admin/coding-rto.php'); }
    $ch = $pdo->prepare("SELECT * FROM coding_inventory WHERE id=?"); $ch->execute([$id]); $ch = $ch->fetch();
    if (!$ch) { flash('error', 'Chart not found.'); redirect('/admin/coding-rto.php'); }
    /* This UPDATE's WHERE is the posted id and nothing else — it is the one status write in the app with no
     * eligibility guard. That was harmless while every status was a working state, but a chart sitting in the
     * Deletion Requests bucket must not be silently yanked back into a coder's queue: it would re-enter the
     * workable set while an approved deletion request still points at it, and the Manager's stale-approval guard
     * would then (correctly) refuse to delete it — leaving the request stranded and the chart quietly resurrected
     * with nobody told. Reject it here instead, and say why. */
    if (($ch['status'] ?? '') === 'deletion_requested') {
        flash('error', 'That chart is awaiting a deletion decision and cannot be sent back. Reject the deletion '
                     . 'request first (Coding › Deletion requests) — that returns it to the coder\'s queue.');
        redirect('/admin/coding-rto.php');
    }
    // Back to open queue, TOP priority, optionally a different coder. Clear audit state.
    $pdo->prepare("UPDATE coding_inventory SET status='pending', assigned_to=?, is_priority=1, priority_by=?, priority_at=NOW(),
                    started_at=NULL, submitted_at=NULL, in_sample=0, sample_pct=NULL,
                    audit_status=NULL, audit_result=NULL, audit_comment=NULL, audit_secondary_reason=NULL, auditor_id=NULL, audited_at=NULL,
                    client_sent_at=NULL, client_sent_by=NULL,
                    rto_at=NOW(), rto_by=?, updated_at=NOW() WHERE id=?")
        ->execute([$to, $uid, $uid, $id]);
    coding_log_event($pdo, $id, 'rto', $uid, 'sent back to coder #' . $to, ($ch['audit_status'] ?: $ch['status']), 'pending');
    audit_log('coding.rto', 'coding_inventory', $id, null, ['to'=>$to]);
    flash('success', 'Chart returned to the coder’s open queue at TOP priority.');
    redirect('/admin/coding-rto.php');
}

$rows = $pdo->query("SELECT ci.*, c.name cn, f.name fn, pr.name prn, u.name coder,
        COALESCE(ci.audit_secondary_reason, ci.secondary_reason) AS reason,
        CASE WHEN ci.audit_status IN ('rfi','disregard') THEN ci.audit_status ELSE ci.status END AS tag,
        CASE WHEN ci.audit_status IN ('rfi','disregard') THEN 'auditor' ELSE 'coder' END AS tagged_by
    FROM coding_inventory ci JOIN clients c ON c.id=ci.client_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.coder_id
    WHERE ci.audit_status IN ('rfi','disregard') OR ci.status IN ('rfi','disregard')
    ORDER BY ci.updated_at DESC LIMIT 500")->fetchAll();

$coders = $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') ORDER BY u.name")->fetchAll();

$pageTitle = 'RTO — rework';
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-rotate me-2 text-primary"></i>RTO — Return To Origin</h2>
        <div class="text-secondary small">RFI / Disregard charts cleared by the client → send back to a coder’s open queue at TOP priority.</div>
    </div>
</div></div></div>
<div class="page-body"><div class="container-xl">
    <div class="card"><div class="table-responsive"><table class="table table-vcenter card-table">
        <thead><tr><th>Patient</th><th>Client</th><th>Facility</th><th>Provider</th><th>Tag</th><th>Reason</th><th>Origin coder</th><th>Send to</th></tr></thead>
        <tbody>
        <?php foreach ($rows as $r): ?>
            <tr>
                <td><strong><?= e($r['patient_name']) ?></strong></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><span class="badge bg-<?= $r['tag']==='rfi'?'orange':'danger' ?>-lt"><?= e($r['tag']) ?></span> <span class="text-secondary small"><?= e($r['tagged_by']) ?></span></td>
                <td class="small"><?= e($r['reason'] ?? '—') ?></td>
                <td class="small"><?= e($r['coder'] ?? '—') ?></td>
                <td>
                    <form method="POST" class="d-flex gap-1"><?= csrf_field() ?><input type="hidden" name="action" value="send_back"><input type="hidden" name="id" value="<?= (int)$r['id'] ?>">
                        <select name="to_coder" class="form-select form-select-sm w-auto">
                            <?php foreach ($coders as $o): ?><option value="<?= (int)$o['id'] ?>" <?= (int)$r['coder_id']===(int)$o['id']?'selected':'' ?>><?= e($o['name']) ?></option><?php endforeach; ?>
                        </select>
                        <button class="btn btn-sm btn-primary"><i class="ti ti-send"></i></button>
                    </form>
                </td>
            </tr>
        <?php endforeach; ?>
        <?php if (!$rows): ?><tr><td colspan="8" class="text-center text-secondary py-4">No RFI / Disregard charts pending rework.</td></tr><?php endif; ?>
        </tbody>
    </table></div></div>
</div></div>
<?php require __DIR__ . '/../includes/footer.php'; ?>
