<?php
/**
 * AR / Collections — my audit results & REBUTTALS (ar.work). The AR user reviews each audited visit that
 * has errors and either AGREES or DISPUTES specific failed parameters (rebuttal → auditor). TAT: a flagged
 * visit must be acted on within AR_REBUTTAL_TAT_DAYS days of the audit (shown as a due date / overdue).
 */
require_once __DIR__ . '/../includes/config.php';
$user = require_login('internal');
$pdo  = db();
$uid  = (int) $user['id'];

/* ── POST: raise / agree ── */
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    csrf_check_or_die();
    $act = (string) ($_POST['action'] ?? '');
    $aid = (int) input('audit_id');
    $a = $pdo->prepare("SELECT * FROM ar_visit_audit WHERE id=? AND worker_id=? AND result='error' AND rebuttal_status='none'");
    $a->execute([$aid, $uid]); $a = $a->fetch();
    if (!$a) { flash('error', 'That audit is not open for a rebuttal.'); redirect('/admin/ar-rebuttals.php'); }

    if ($act === 'agree') {
        $pdo->prepare("UPDATE ar_visit_audit SET rebuttal_status='agreed', rebuttal_resolved_at=NOW() WHERE id=?")->execute([$aid]);
        flash('success', 'Acknowledged — you agreed with the audit.');
        redirect('/admin/ar-rebuttals.php?q=agreed');
    }
    if ($act === 'raise') {
        $disputed = array_values(array_filter(array_map('strval', (array) ($_POST['disputed'] ?? []))));
        $reasons  = (array) ($_POST['reason'] ?? []);
        $comment  = trim((string) input('comment'));
        if ($comment === '') { flash('error', 'Add a comment explaining your rebuttal.'); redirect('/admin/ar-rebuttals.php?audit=' . $aid); }
        if (!$disputed)      { flash('error', 'Tick at least one failed parameter you disagree with.'); redirect('/admin/ar-rebuttals.php?audit=' . $aid); }
        $pdo->beginTransaction();
        // fresh round: clear any prior dispute markers, then mark the chosen FAILED params
        $pdo->prepare("UPDATE ar_audit_param SET disputed=0, dispute_reason=NULL, rebuttal_result=NULL WHERE audit_id=?")->execute([$aid]);
        $mark = $pdo->prepare("UPDATE ar_audit_param SET disputed=1, dispute_reason=?, rebuttal_result='pending' WHERE audit_id=? AND param_key=? AND result='fail'");
        $marked = 0;
        foreach ($disputed as $pk) { $mark->execute([mb_substr(trim((string) ($reasons[$pk] ?? '')), 0, 255) ?: null, $aid, $pk]); $marked += $mark->rowCount(); }
        if ($marked === 0) {   // forged/passed-param keys only — nothing actually disputable
            $pdo->rollBack();
            flash('error', 'You can only dispute parameters the auditor marked as FAILED.');
            redirect('/admin/ar-rebuttals.php?audit=' . $aid);
        }
        $pdo->prepare("UPDATE ar_visit_audit SET rebuttal_status='raised', rebuttal_comment=?, rebuttal_at=NOW() WHERE id=?")->execute([$comment, $aid]);
        $pdo->commit();
        flash('success', 'Rebuttal raised — sent to the auditor.');
        redirect('/admin/ar-rebuttals.php?q=disputed');
    }
    redirect('/admin/ar-rebuttals.php');
}

/* ── DETAIL ── */
$auditId = (int) ($_GET['audit'] ?? 0);
if ($auditId) {
    $a = $pdo->prepare("SELECT a.*, v.carrier_name, au.name auditor_name FROM ar_visit_audit a
        LEFT JOIN ar_visit_work v ON v.id=a.visit_work_id LEFT JOIN users au ON au.id=a.auditor_id
        WHERE a.id=? AND a.worker_id=?"); $a->execute([$auditId, $uid]); $a = $a->fetch();
    if (!$a) { flash('error', 'Audit not found.'); redirect('/admin/ar-rebuttals.php'); }
    $params = $pdo->prepare("SELECT * FROM ar_audit_param WHERE audit_id=? ORDER BY FIELD(param_key,'pre_call','documentation','end_action','code_selection','appeal_compliance')");
    $params->execute([$auditId]); $params = $params->fetchAll();
    $canRaise = $a['result'] === 'error' && $a['rebuttal_status'] === 'none';
    $overdue  = $canRaise && $a['rebuttal_due'] && $a['rebuttal_due'] < date('Y-m-d');

    $pageTitle = 'AR audit result';
    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</h2>
            <div class="text-secondary small">Account <span class="font-mono"><?= e($a['chart_number']) ?></span> · Visit <span class="font-mono"><?= e($a['visit_id']) ?></span> · audited by <?= e($a['auditor_name'] ?? '—') ?>
                <span class="badge bg-<?= $a['result']==='pass'?'green':'red' ?>-lt ms-1"><?= (int)$a['opportunities']-(int)$a['defects'] ?>/<?= (int)$a['opportunities'] ?> · <?= $a['result'] ?></span>
                <?php if ($canRaise && $a['rebuttal_due']): ?> <span class="badge bg-<?= $overdue?'red':'yellow' ?>-lt"><i class="ti ti-clock me-1"></i><?= $overdue?'OVERDUE':'due' ?> <?= e(fmt_date($a['rebuttal_due'])) ?></span><?php endif; ?></div></div>
        <div class="col-auto"><a href="<?= e(url('/admin/ar-rebuttals.php')) ?>" class="btn btn-outline-secondary"><i class="ti ti-arrow-left me-1"></i>Back</a></div>
    </div></div></div>
    <div class="page-body"><div class="container-xl">
    <?php if ($a['rebuttal_status'] !== 'none'): ?>
        <div class="alert alert-<?= ['agreed'=>'success','raised'=>'yellow','accepted'=>'success','rejected'=>'danger'][$a['rebuttal_status']] ?? 'secondary' ?>">
            <?php if ($a['rebuttal_status']==='agreed'): ?>You <strong>agreed</strong> with this audit.
            <?php elseif ($a['rebuttal_status']==='raised'): ?>Rebuttal <strong>raised</strong> — awaiting the auditor.
            <?php else: ?>Rebuttal <strong><?= e($a['rebuttal_status']) ?></strong>.<?php endif; ?>
        </div>
    <?php endif; ?>
        <form method="POST" action="<?= e(url('/admin/ar-rebuttals.php')) ?>">
            <?= csrf_field() ?><input type="hidden" name="audit_id" value="<?= (int)$a['id'] ?>">
            <div class="card mb-3"><div class="card-header py-2"><h3 class="card-title small">Parameter results</h3></div>
                <div class="table-responsive"><table class="table table-vcenter card-table table-sm">
                    <thead><tr><?php if ($canRaise): ?><th class="w-1">Dispute</th><?php endif; ?><th>Parameter</th><th>Result</th><th>Auditor note</th><th>Status</th><?php if ($canRaise): ?><th>Reason (if disputing)</th><?php endif; ?></tr></thead>
                    <tbody>
                    <?php foreach ($params as $p): $fail = $p['result']==='fail'; ?>
                        <tr>
                            <?php if ($canRaise): ?><td><?php if ($fail): ?><input type="checkbox" class="form-check-input m-0" name="disputed[]" value="<?= e($p['param_key']) ?>"><?php endif; ?></td><?php endif; ?>
                            <td><strong><?= e(AR_AUDIT_PARAMS[$p['param_key']] ?? $p['param_key']) ?></strong></td>
                            <td><span class="badge bg-<?= $fail?'red':'green' ?>-lt"><?= $fail?'fail':'pass' ?></span></td>
                            <td class="small text-secondary"><?= e($p['note'] ?? '') ?></td>
                            <td class="small"><?php if ($p['disputed']): ?><span class="badge bg-<?= ['pending'=>'yellow','accepted'=>'green','rejected'=>'red'][$p['rebuttal_result']??'pending'] ?>-lt"><?= e($p['rebuttal_result'] ?: 'raised') ?></span> <span class="text-secondary"><?= e($p['dispute_reason']) ?></span><?php endif; ?></td>
                            <?php if ($canRaise): ?><td><?php if ($fail): ?><input type="text" name="reason[<?= e($p['param_key']) ?>]" class="form-control form-control-sm" placeholder="why you disagree"><?php endif; ?></td><?php endif; ?>
                        </tr>
                    <?php endforeach; ?>
                    </tbody>
                </table></div>
            </div>
            <?php if ($canRaise): ?>
            <div class="card"><div class="card-body">
                <label class="form-label">Comment <span class="text-secondary small">(required to dispute)</span></label>
                <textarea name="comment" class="form-control mb-2" rows="2" placeholder="Explain your rebuttal"></textarea>
                <button class="btn btn-primary" name="action" value="raise"><i class="ti ti-message-report me-1"></i>Raise rebuttal</button>
                <button class="btn btn-outline-success" name="action" value="agree" onclick="return confirm('Agree with the audit? This closes it.');"><i class="ti ti-thumb-up me-1"></i>Agree</button>
                <span class="text-secondary small ms-2">You have <?= AR_REBUTTAL_TAT_DAYS ?> days from the audit to act.</span>
            </div></div>
            <?php endif; ?>
        </form>
    </div></div>
    <?php require __DIR__ . '/../includes/footer.php'; exit;
}

/* ── LIST ── */
$q = in_array($_GET['q'] ?? '', ['toreview', 'agreed', 'disputed'], true) ? $_GET['q'] : 'toreview';
$whereByQ = ['toreview' => "a.rebuttal_status='none'", 'agreed' => "a.rebuttal_status='agreed'", 'disputed' => "a.rebuttal_status IN ('raised','accepted','rejected')"];
$cnt = $pdo->prepare("SELECT COALESCE(SUM(rebuttal_status='none'),0) toreview, COALESCE(SUM(rebuttal_status='agreed'),0) agreed,
        COALESCE(SUM(rebuttal_status IN ('raised','accepted','rejected')),0) disputed
    FROM ar_visit_audit WHERE worker_id=? AND result='error'");
$cnt->execute([$uid]); $cnt = $cnt->fetch();
$rows = $pdo->prepare("SELECT a.id, a.chart_number, a.visit_id, a.opportunities, a.defects, a.result, a.rebuttal_status, a.rebuttal_due, a.audited_at, au.name auditor_name
    FROM ar_visit_audit a LEFT JOIN users au ON au.id=a.auditor_id
    WHERE a.worker_id=? AND a.result='error' AND {$whereByQ[$q]} ORDER BY a.audited_at DESC LIMIT 500");
$rows->execute([$uid]); $rows = $rows->fetchAll();

$pageTitle = 'My AR audit rebuttals';
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">Visits where the auditor flagged a parameter. Review within <strong><?= AR_REBUTTAL_TAT_DAYS ?> days</strong> — Agree, or Dispute the parameters you disagree with.</div></div>
</div></div></div>
<div class="page-body"><div class="container-xl">
    <ul class="nav nav-tabs mb-3">
        <?php foreach (['toreview'=>'To review', 'agreed'=>'Agreed', 'disputed'=>'Disputed'] as $k => $lbl): ?>
            <li class="nav-item"><a class="nav-link <?= $q===$k?'active':'' ?>" href="<?= e(url('/admin/ar-rebuttals.php?q=' . $k)) ?>"><?= e($lbl) ?>
                <?php if ((int)$cnt[$k]): ?><span class="badge bg-<?= $k==='toreview'?'yellow':'secondary' ?> ms-1"><?= (int)$cnt[$k] ?></span><?php endif; ?></a></li>
        <?php endforeach; ?>
    </ul>
    <div class="card"><div class="table-responsive"><table class="table table-vcenter card-table table-sm">
        <thead><tr><th>Patient Account #</th><th>Visit ID</th><th>Auditor</th><th>Score</th><th>Audited</th><?php if ($q==='toreview'): ?><th>Act by</th><?php endif; ?><th class="w-1"></th></tr></thead>
        <tbody>
        <?php if (!$rows): ?><tr><td colspan="7" class="text-center text-secondary py-4">Nothing here. 🎉</td></tr>
        <?php else: foreach ($rows as $r): $od = $q==='toreview' && $r['rebuttal_due'] && $r['rebuttal_due'] < date('Y-m-d'); ?>
            <tr>
                <td class="font-mono"><?= e($r['chart_number']) ?></td>
                <td class="font-mono small"><?= e($r['visit_id']) ?></td>
                <td class="small"><?= e($r['auditor_name'] ?? '—') ?></td>
                <td><span class="badge bg-red-lt"><?= (int)$r['opportunities']-(int)$r['defects'] ?>/<?= (int)$r['opportunities'] ?></span></td>
                <td class="small text-nowrap"><?= e(fmt_date($r['audited_at'])) ?></td>
                <?php if ($q==='toreview'): ?><td class="small text-nowrap"><span class="badge bg-<?= $od?'red':'yellow' ?>-lt"><?= $od?'OVERDUE':'' ?> <?= e(fmt_date($r['rebuttal_due'])) ?></span></td><?php endif; ?>
                <td class="text-end"><a href="<?= e(url('/admin/ar-rebuttals.php?audit=' . (int)$r['id'])) ?>" class="btn btn-sm btn-<?= $q==='toreview'?'primary':'outline-secondary' ?>"><?= $q==='toreview'?'Review':'View' ?></a></td>
            </tr>
        <?php endforeach; endif; ?>
        </tbody>
    </table></div></div>
</div></div>
<?php require __DIR__ . '/../includes/footer.php'; ?>
