<?php
/**
 * Rebuttals (coding.work). A coder opens an audited chart, sees the auditor's
 * per-code verdict (which codes were correct / incorrect, with category +
 * suggested correction), and raises a rebuttal — disputing specific flagged
 * codes. Disputes route to the auditor (coding-audit.php → Rebuttals), who can
 * accept (flips that code to correct, DPO accuracy recovers) or reject.
 */
require_once __DIR__ . '/../includes/config.php';
$user = require_login('internal');
$pdo  = db();
$uid  = (int) $user['id'];

/* ----------------------------------------------------------- POST: raise */
if ($_SERVER['REQUEST_METHOD'] === 'POST' && ($_POST['action'] ?? '') === 'raise') {
    csrf_check_or_die();
    $id = (int) input('id');
    $comment = trim((string) input('comment'));
    $disputed = array_map('intval', (array) ($_POST['disputed'] ?? []));
    $reasons  = (array) ($_POST['reason'] ?? []);

    $ch = $pdo->prepare("SELECT * FROM coding_inventory WHERE id=? AND coder_id=? AND audit_result='error' AND rebuttal_status='none'");
    $ch->execute([$id, $uid]); $ch = $ch->fetch();
    if (!$ch) { flash('error', 'That chart is not open for rebuttal.'); redirect('/admin/coding-rebuttals.php'); }
    if ($comment === '')   { flash('error', 'Add a comment explaining your rebuttal.'); redirect('/admin/coding-rebuttals.php?id=' . $id); }
    if (!$disputed)        { flash('error', 'Tick at least one flagged code you disagree with.'); redirect('/admin/coding-rebuttals.php?id=' . $id); }

    $pdo->beginTransaction();
    $pdo->prepare("UPDATE coding_inventory SET rebuttal_status='raised', rebuttal_comment=?, rebuttal_at=NOW(), updated_at=NOW() WHERE id=?")
        ->execute([$comment, $id]);
    // Fresh round: clear any prior dispute markers (from an earlier partial resolution that re-opened this chart) so
    // the auditor only sees THIS round's disputes. Already-accepted codes are result='correct' and stay settled.
    $pdo->prepare("UPDATE coding_audit_codes SET disputed=0, dispute_reason=NULL, rebuttal_result=NULL WHERE inventory_id=?")->execute([$id]);
    // Mark only the disputed findings (that belong to this chart and are actually flagged).
    $mark = $pdo->prepare("UPDATE coding_audit_codes SET disputed=1, dispute_reason=?, rebuttal_result='pending' WHERE id=? AND inventory_id=? AND result<>'correct'");
    foreach ($disputed as $fid) $mark->execute([mb_substr(trim((string) ($reasons[$fid] ?? '')), 0, 255) ?: null, $fid, $id]);
    coding_log_event($pdo, $id, 'rebuttal_raise', $uid, $comment, 'error', 'raised');
    $pdo->commit();
    audit_log('coding.rebuttal.raise', 'coding_inventory', $id, null, ['disputed'=>$disputed]);
    flash('success', 'Rebuttal raised on ' . count($disputed) . ' code(s) — sent to the auditor.');
    redirect('/admin/coding-rebuttals.php?q=disputed');
}

/* ----------------------------------------------------------- POST: agree (acknowledge & accept) */
if ($_SERVER['REQUEST_METHOD'] === 'POST' && ($_POST['action'] ?? '') === 'agree') {
    csrf_check_or_die();
    $id = (int) input('id');
    $ch = $pdo->prepare("SELECT id FROM coding_inventory WHERE id=? AND coder_id=? AND audit_result='error' AND rebuttal_status='none'");
    $ch->execute([$id, $uid]);
    if (!$ch->fetch()) { flash('error', 'That chart is not open for acknowledgement.'); redirect('/admin/coding-rebuttals.php'); }
    $pdo->prepare("UPDATE coding_inventory SET rebuttal_status='agreed', ack_at=NOW(), ack_by=?, updated_at=NOW() WHERE id=?")->execute([$uid, $id]);
    coding_log_event($pdo, $id, 'rebuttal_agree', $uid, null, 'error', 'agreed');
    audit_log('coding.rebuttal.agree', 'coding_inventory', $id);
    flash('success', 'Acknowledged — you agreed with the audit findings.');
    redirect('/admin/coding-rebuttals.php?q=agreed');
}

$typeColor = ['cpt'=>'blue','icd'=>'cyan','modifier'=>'secondary'];
$rbColor   = ['none'=>'secondary','agreed'=>'success','raised'=>'yellow','accepted'=>'success','rejected'=>'danger'];

/* ============================ DETAIL VIEW (?id=X) ============================ */
$id = (int) ($_GET['id'] ?? 0);
if ($id) {
    $chart = $pdo->prepare("SELECT ci.*, f.name fn, pr.name prn, au.name auditor
        FROM coding_inventory ci JOIN coding_facilities f ON f.id=ci.facility_id JOIN coding_providers pr ON pr.id=ci.provider_id
        LEFT JOIN users au ON au.id=ci.auditor_id WHERE ci.id=? AND ci.coder_id=?");
    $chart->execute([$id, $uid]); $chart = $chart->fetch();
    if (!$chart) { flash('error', 'Chart not found.'); redirect('/admin/coding-rebuttals.php'); }
    $codes = coding_audit_codes($pdo, $id);
    $canRaise = ($chart['audit_result'] === 'error' && $chart['rebuttal_status'] === 'none');

    $opp = count($codes); $def = 0; foreach ($codes as $c) if ($c['result'] !== 'correct') $def++;
    $acc = $opp ? round(100 * ($opp - $def) / $opp, 1) : null;

    $pageTitle = 'Rebuttal';
    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-message-report me-2 text-primary"></i>Audit result — <?= e($chart['patient_name']) ?></h2>
            <div class="text-secondary small"><?= e($chart['fn']) ?> · <?= e($chart['prn']) ?> · audited by <strong><?= e($chart['auditor'] ?? '—') ?></strong> <?= e(fmt_dt($chart['audited_at'])) ?>
                <?php if ($acc!==null): ?><span class="badge bg-<?= $acc>=95?'success':($acc>=90?'warning':'danger') ?>-lt ms-1"><?= $acc ?>% accuracy · <?= $def ?>/<?= $opp ?> defects</span><?php endif; ?>
            </div>
        </div>
        <div class="col-auto"><a href="<?= e(url('/admin/coding-rebuttals.php')) ?>" class="btn btn-outline-secondary"><i class="ti ti-arrow-left me-1"></i>Back</a></div>
    </div></div></div>

    <form method="POST" action="<?= e(url('/admin/coding-rebuttals.php')) ?>">
    <?= csrf_field() ?><input type="hidden" name="id" value="<?= $id ?>">
    <div class="page-body"><div class="container-xl">
        <?php if ($chart['audit_comment']): ?><div class="alert alert-secondary py-2"><strong>Auditor comment:</strong> <?= nl2br(e($chart['audit_comment'])) ?></div><?php endif; ?>

        <div class="card mb-3">
            <div class="card-header py-2"><h3 class="card-title small"><i class="ti ti-list-check me-1"></i>Code-by-code result</h3>
                <?php if ($canRaise): ?><div class="card-actions text-secondary small">Tick the flagged codes you disagree with, then raise below.</div><?php endif; ?>
            </div>
            <div class="table-responsive"><table class="table table-vcenter card-table">
                <thead><tr><th>Code</th><th>Result</th><th>Error category</th><th>Auditor's correction</th><th>Note</th>
                    <?php if ($canRaise): ?><th class="w-1 text-center">Dispute?</th><th>Your reason</th><?php endif; ?>
                    <?php if (!$canRaise): ?><th>Dispute</th><?php endif; ?></tr></thead>
                <tbody>
                <?php foreach ($codes as $c): $bad = $c['result'] !== 'correct'; ?>
                    <tr class="<?= $bad?'':'' ?>">
                        <td><span class="badge bg-<?= $typeColor[$c['code_type']] ?>-lt text-uppercase me-1"><?= e($c['code_type']) ?></span><code class="fw-bold"><?= e($c['code_value']) ?></code></td>
                        <td><?php if($bad): ?><span class="badge bg-danger-lt"><i class="ti ti-x"></i> <?= e($c['result']) ?></span><?php else: ?><span class="badge bg-success-lt"><i class="ti ti-check"></i> correct</span><?php endif; ?></td>
                        <td class="small"><?= e($c['error_category'] ?? '') ?: ($bad?'':'<span class="text-secondary">—</span>') ?></td>
                        <td class="small"><?= $c['correct_value'] ? '<code class="text-success">'.e($c['correct_value']).'</code>' : '<span class="text-secondary">—</span>' ?></td>
                        <td class="small"><?= e($c['note'] ?? '') ?: '<span class="text-secondary">—</span>' ?></td>
                        <?php if ($canRaise): ?>
                            <td class="text-center"><?php if($bad): ?><input type="checkbox" class="form-check-input m-0" name="disputed[]" value="<?= (int)$c['id'] ?>"><?php endif; ?></td>
                            <td><?php if($bad): ?><input name="reason[<?= (int)$c['id'] ?>]" class="form-control form-control-sm" placeholder="Why is this correct?"><?php endif; ?></td>
                        <?php else: ?>
                            <td><?php if($c['disputed']): ?><span class="badge bg-<?= ['pending'=>'yellow','accepted'=>'success','rejected'=>'danger'][$c['rebuttal_result']??'pending'] ?>-lt"><?= e($c['rebuttal_result'] ?: 'raised') ?></span> <span class="small text-secondary"><?= e($c['dispute_reason']) ?></span><?php elseif($bad): ?><span class="text-secondary small">—</span><?php endif; ?></td>
                        <?php endif; ?>
                    </tr>
                <?php endforeach; ?>
                <?php if (!$codes): ?><tr><td colspan="<?= $canRaise?7:6 ?>" class="text-center text-secondary py-3">No code-level findings recorded.</td></tr><?php endif; ?>
                </tbody>
            </table></div>
        </div>

        <?php if ($canRaise): ?>
        <div class="card">
            <div class="card-header py-2"><h3 class="card-title small"><i class="ti ti-gavel me-1"></i>Your acknowledgement</h3>
                <div class="card-actions text-secondary small">Review the findings above, then agree or dispute.</div></div>
            <div class="card-body"><div class="row g-3">
                <div class="col-md-5"><div class="border rounded p-3 h-100 d-flex flex-column">
                    <div class="fw-bold mb-1 text-success"><i class="ti ti-thumb-up me-1"></i>I agree with the audit</div>
                    <div class="text-secondary small mb-3 flex-grow-1">Accept the auditor's findings. The chart moves to your <strong>Agreed</strong> queue — no dispute is raised.</div>
                    <button type="submit" name="action" value="agree" formnovalidate class="btn btn-success"
                        onclick="return confirm('Acknowledge and agree with all audit findings on this chart?');"><i class="ti ti-check me-1"></i>Agree &amp; acknowledge</button>
                </div></div>
                <div class="col-md-7"><div class="border rounded p-3 h-100">
                    <div class="fw-bold mb-1 text-warning"><i class="ti ti-thumb-down me-1"></i>I disagree — raise a dispute</div>
                    <div class="text-secondary small mb-2">Tick the flagged code(s) above you disagree with, explain why, and send it to the auditor.</div>
                    <label class="form-label required mb-1">Comment</label>
                    <textarea name="comment" class="form-control mb-2" rows="2" placeholder="Explain why the ticked codes are correct"></textarea>
                    <button type="submit" name="action" value="raise" class="btn btn-warning"><i class="ti ti-send me-1"></i>Raise dispute</button>
                </div></div>
            </div></div>
        </div>
        <?php elseif ($chart['rebuttal_status'] !== 'none'): ?>
        <div class="alert alert-<?= $rbColor[$chart['rebuttal_status']] ?? 'secondary' ?>">
            <i class="ti ti-info-circle me-1"></i>
            <?php if ($chart['rebuttal_status']==='agreed'): ?>You <strong>agreed</strong> with the audit findings<?= !empty($chart['ack_at']) ? ' on ' . e(fmt_dt($chart['ack_at'])) : '' ?>.
            <?php else: ?>Rebuttal <strong><?= e($chart['rebuttal_status']) ?></strong><?= $chart['rebuttal_comment'] ? ' — ' . e($chart['rebuttal_comment']) : '' ?><?php endif; ?>
        </div>
        <?php endif; ?>
    </div></div>
    </form>
    <?php require __DIR__ . '/../includes/footer.php'; exit;
}

/* ============================ LIST (queue tabs) ============================ */
$whereByQ = ['toack'=>"ci.rebuttal_status='none'", 'agreed'=>"ci.rebuttal_status='agreed'", 'disputed'=>"ci.rebuttal_status IN ('raised','accepted','rejected')"];
$q = isset($_GET['q'], $whereByQ[$_GET['q']]) ? $_GET['q'] : 'toack';

/* Filters — narrow the displayed list; the tab counts stay total (per the coder's audit errors). */
$fClient   = (int) ($_GET['client_id'] ?? 0);
$fFacility = (int) ($_GET['facility_id'] ?? 0);
$fProvider = (int) ($_GET['provider_id'] ?? 0);   // billing provider (matches the displayed column)
$fAuditor  = (int) ($_GET['auditor_id'] ?? 0);
$from = preg_match('/^\d{4}-\d{2}-\d{2}$/', (string)($_GET['from'] ?? '')) ? $_GET['from'] : '';
$to   = preg_match('/^\d{4}-\d{2}-\d{2}$/', (string)($_GET['to'] ?? '')) ? $_GET['to'] : '';
$fw = []; $fp = [];
if ($fClient)   { $fw[] = 'ci.client_id = ?';           $fp[] = $fClient; }
if ($fFacility) { $fw[] = 'ci.facility_id = ?';         $fp[] = $fFacility; }
if ($fProvider) { $fw[] = 'ci.billing_provider_id = ?'; $fp[] = $fProvider; }
if ($fAuditor)  { $fw[] = 'ci.auditor_id = ?';          $fp[] = $fAuditor; }
if ($from)      { $fw[] = 'DATE(ci.audited_at) >= ?';   $fp[] = $from; }
if ($to)        { $fw[] = 'DATE(ci.audited_at) <= ?';   $fp[] = $to; }
$fwSql = $fw ? (' AND ' . implode(' AND ', $fw)) : '';
/* filter option sources — the coder's own audit-error charts ($uid is an int) */
$fScope   = "ci.coder_id=" . $uid . " AND ci.audit_result='error'";
$fClients = $pdo->query("SELECT DISTINCT c.id,c.name FROM coding_inventory ci JOIN clients c ON c.id=ci.client_id WHERE $fScope ORDER BY c.name")->fetchAll();
$fFacils  = $pdo->query("SELECT DISTINCT f.id,f.name FROM coding_inventory ci JOIN coding_facilities f ON f.id=ci.facility_id WHERE $fScope ORDER BY f.name")->fetchAll();
$fProvs   = $pdo->query("SELECT DISTINCT bp.id,bp.name FROM coding_inventory ci JOIN coding_providers bp ON bp.id=ci.billing_provider_id WHERE $fScope ORDER BY bp.name")->fetchAll();
$fAuds    = $pdo->query("SELECT DISTINCT au.id,au.name FROM coding_inventory ci JOIN users au ON au.id=ci.auditor_id WHERE $fScope ORDER BY au.name")->fetchAll();
/* tab links preserve the active filters */
$tabUrl = fn($k) => url('/admin/coding-rebuttals.php?' . http_build_query(array_filter(
    ['q'=>$k, 'client_id'=>$fClient, 'facility_id'=>$fFacility, 'provider_id'=>$fProvider, 'auditor_id'=>$fAuditor, 'from'=>$from, 'to'=>$to],
    fn($v)=>$v!=='' && $v!==0)));

$cnt = $pdo->prepare("SELECT COALESCE(SUM(rebuttal_status='none'),0) toack, COALESCE(SUM(rebuttal_status='agreed'),0) agreed,
        COALESCE(SUM(rebuttal_status IN ('raised','accepted','rejected')),0) disputed
    FROM coding_inventory WHERE coder_id=? AND audit_result='error'");
$cnt->execute([$uid]); $counts = $cnt->fetch();

$rows = $pdo->prepare("SELECT ci.*, f.name fn, c.name cn, bp.name billing_prov, au.name auditor
    FROM coding_inventory ci JOIN coding_facilities f ON f.id=ci.facility_id
    JOIN clients c ON c.id=ci.client_id
    LEFT JOIN coding_providers bp ON bp.id=ci.billing_provider_id
    LEFT JOIN users au ON au.id=ci.auditor_id
    WHERE ci.coder_id=? AND ci.audit_result='error' AND {$whereByQ[$q]}$fwSql ORDER BY ci.audited_at DESC LIMIT 300");
$rows->execute(array_merge([$uid], $fp));
$rows = $rows->fetchAll();
$rbLines = coding_effective_lines_bulk($pdo, array_column($rows, 'id'));

$qMeta = [
    'toack'    => ['To acknowledge', 'yellow', 'No audit errors waiting for your acknowledgement. 🎉'],
    'agreed'   => ['Agreed',         'green',  'No charts agreed yet.'],
    'disputed' => ['Disputed',       'blue',   'You have not raised any disputes.'],
];
$pageTitle = 'My audit errors';
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-message-report me-2 text-primary"></i>My audit errors &amp; rebuttals</h2>
        <div class="text-secondary small">Open a flagged chart, review the auditor's findings, then <strong>agree</strong> (acknowledge) or <strong>dispute</strong>.</div>
    </div>
</div></div></div>
<div class="page-body"><div class="container-xl">
    <ul class="nav nav-tabs mb-3">
        <?php foreach ($qMeta as $k=>$m): ?>
        <li class="nav-item"><a class="nav-link <?= $q===$k?'active':'' ?>" href="<?= e($tabUrl($k)) ?>">
            <?= e($m[0]) ?> <span class="badge bg-<?= $m[1] ?>-lt ms-1"><?= (int)$counts[$k] ?></span></a></li>
        <?php endforeach; ?>
    </ul>
    <div class="card mb-3"><div class="card-body py-2"><form method="GET" class="row g-2 align-items-end">
        <input type="hidden" name="q" value="<?= e($q) ?>">
        <?php $rbSel = function($name,$opts,$cur,$all){ $h='<select name="'.e($name).'" class="form-select form-select-sm"><option value="">'.e($all).'</option>';
            foreach($opts as $o) $h.='<option value="'.(int)$o['id'].'"'.($cur===(int)$o['id']?' selected':'').'>'.e($o['name']).'</option>'; return $h.'</select>'; }; ?>
        <div class="col-6 col-md-2"><label class="form-label small mb-1">Client</label><?= $rbSel('client_id',$fClients,$fClient,'All clients') ?></div>
        <div class="col-6 col-md-2"><label class="form-label small mb-1">Facility</label><?= $rbSel('facility_id',$fFacils,$fFacility,'All facilities') ?></div>
        <div class="col-6 col-md-2"><label class="form-label small mb-1">Billing prov</label><?= $rbSel('provider_id',$fProvs,$fProvider,'All providers') ?></div>
        <div class="col-6 col-md-2"><label class="form-label small mb-1">Auditor</label><?= $rbSel('auditor_id',$fAuds,$fAuditor,'All auditors') ?></div>
        <div class="col-6 col-md-2"><label class="form-label small mb-1">Audited from</label><input type="date" name="from" value="<?= e($from) ?>" class="form-control form-control-sm"></div>
        <div class="col-6 col-md-2"><label class="form-label small mb-1">to</label><input type="date" name="to" value="<?= e($to) ?>" class="form-control form-control-sm"></div>
        <div class="col-auto"><button class="btn btn-sm btn-primary"><i class="ti ti-filter me-1"></i>Filter</button> <a href="<?= e(url('/admin/coding-rebuttals.php?q='.$q)) ?>" class="btn btn-sm btn-ghost-secondary">Clear</a></div>
    </form></div></div>
    <div class="card"><div class="table-responsive"><table class="table table-vcenter card-table table-sm" style="font-size:.8rem">
        <thead><tr><th>Patient</th><th>MRN/PRN</th><th>DOB</th><th>Gender</th><th>Record sign</th><th>Client</th><th>Facility</th><th>Billing prov</th><th>DOS</th><th>CPT</th><th class="text-center">Units</th><th>Modifier(s)</th><th>ICD(s)</th><th>Auditor</th><th>Audited</th><th class="text-end">Defects</th><th>Acknowledgement</th><th class="w-1"></th></tr></thead>
        <tbody>
        <?php foreach ($rows as $r): $rl = $rbLines[(int)$r['id']] ?? []; $hasOpp = (int)$r['audit_opportunities'] > 0; $rs=$r['rebuttal_status']; ?>
            <tr style="cursor:pointer" onclick="location.href='<?= e(url('/admin/coding-rebuttals.php?id='.(int)$r['id'])) ?>'">
                <td><strong><?= e($r['patient_name']) ?></strong></td>
                <td class="small"><?= e($r['patient_mrn']) ?></td>
                <td class="small text-nowrap"><?= e(fmt_date($r['patient_dob'])) ?></td>
                <td class="small"><?= e(ucfirst($r['gender'] ?: '—')) ?></td>
                <td class="small text-nowrap"><?= e(fmt_date($r['record_sign_date'])) ?></td>
                <td class="small"><?= e($r['cn']) ?></td>
                <td class="small"><?= e($r['fn']) ?></td>
                <td class="small"><?= e($r['billing_prov'] ?: '—') ?></td>
                <td class="small"><?= coding_lines_cell($rl, 'dos') ?></td>
                <td class="small"><?= coding_lines_cell($rl, 'cpt') ?></td>
                <td class="small text-center"><?= coding_lines_cell($rl, 'units') ?></td>
                <td class="small"><?= coding_lines_cell($rl, 'mods') ?></td>
                <td class="small"><?= coding_lines_cell($rl, 'icds') ?></td>
                <td class="small"><?= e($r['auditor'] ?? '—') ?></td>
                <td class="small text-secondary text-nowrap"><?= e(fmt_dt($r['audited_at'])) ?></td>
                <td class="text-end text-danger"><?= (int)$r['audit_defects'] ?: '—' ?><?= $hasOpp?' / '.(int)$r['audit_opportunities']:'' ?></td>
                <td>
                    <?php if ($rs==='none'): ?><span class="badge bg-yellow-lt"><i class="ti ti-clock me-1"></i>awaiting you</span>
                    <?php elseif ($rs==='agreed'): ?><span class="badge bg-success-lt"><i class="ti ti-thumb-up me-1"></i>agreed</span>
                    <?php else: ?><span class="badge bg-<?= $rbColor[$rs] ?? 'secondary' ?>-lt">dispute <?= e($rs) ?></span><?php endif; ?>
                </td>
                <td><a href="<?= e(url('/admin/coding-rebuttals.php?id='.(int)$r['id'])) ?>" class="btn btn-sm"><?= $rs==='none'?'Review':'View' ?> <i class="ti ti-chevron-right"></i></a></td>
            </tr>
        <?php endforeach; ?>
        <?php if (!$rows): ?><tr><td colspan="18" class="text-center text-secondary py-4"><?= e($qMeta[$q][2]) ?></td></tr><?php endif; ?>
        </tbody>
    </table></div></div>
</div></div>
<?php require __DIR__ . '/../includes/footer.php'; ?>
