<?php
/**
 * BILLING — audit SAMPLING (billing.supervise). Supervisor/manager sets, per biller, the % of that biller's
 * worked charts that enter the audit sample. A per-user % OVERRIDES the global billing.audit_sample_pct
 * (set on billing-audit.php); billers without an override keep inheriting the global rate. Team-scoped
 * (coding_team_scope / reports_to tree). The % is applied at work-save time (billing_audit_sample_decision);
 * changing it affects future work, not already-decided charts.
 *
 * Filters (search / sample-status / sort) narrow the roster.
 */
require_once __DIR__ . '/../includes/config.php';
$user = require_login('internal');
$pdo  = db();
$uid  = (int) $user['id'];

$team   = coding_team_scope($pdo, $uid);                   // null = all (sysadmin)
$inTeam = fn(int $id) => $team === null || in_array($id, $team, true);

/* Billers in scope (billing.work holders within the team). */
$allUsers = billing_allocatable_billers($pdo, $team);      // null → all; array → restricted to the team

$globalPct = billing_audit_sample_pct($pdo);               // fallback for billers without an override

if ($_SERVER['REQUEST_METHOD'] === 'POST' && ($_POST['action'] ?? '') === 'save_samples') {
    csrf_check_or_die();
    if (!can('billing.supervise')) { http_response_code(403); exit('Forbidden'); }
    $pcts = (array) ($_POST['pct'] ?? []);
    $n = 0;
    foreach ($pcts as $u => $pct) {
        $u = (int) $u;
        if (!$inTeam($u)) continue;                        // never trust a posted id outside the team
        billing_set_user_sample($pdo, $u, (int) $pct, $uid);
        $n++;
    }
    flash('success', "Saved sample % for $n biller(s).");
    audit_log('billing.sampling.save', 'scope', null, null, ['billers' => $n]);
    $keep = array_filter([
        'q'      => (string) ($_POST['f_q'] ?? ''),
        'status' => (string) ($_POST['f_status'] ?? ''),
        'sort'   => (string) ($_POST['f_sort'] ?? ''),
    ], fn($v) => $v !== '');
    redirect('/admin/billing-sampling.php' . ($keep ? '?' . http_build_query($keep) : ''));
}

/* current effective %s + override flags + rolling quality, batched. */
$pct = []; $override = []; $qual = [];
foreach ($allUsers as $u) {
    $id = (int) $u['id'];
    $pct[$id]      = billing_user_sample_pct($pdo, $id);
    $override[$id] = billing_user_has_sample_override($pdo, $id);
    $qual[$id]     = billing_user_quality_pct($pdo, $id, 21);
}

/* ---- filters ---- */
$fQ      = trim((string) ($_GET['q'] ?? ''));
$fStatus = in_array($_GET['status'] ?? '', ['full', 'partial', 'none', 'override', 'inherit'], true) ? $_GET['status'] : 'all';
$fSort   = in_array($_GET['sort'] ?? '', ['quality', 'pct'], true) ? $_GET['sort'] : 'name';

$users = array_values(array_filter($allUsers, function ($u) use ($fQ, $fStatus, $pct, $override) {
    $id = (int) $u['id'];
    if ($fQ !== '' && stripos(($u['name'] ?? '') . ' ' . ($u['email'] ?? ''), $fQ) === false) return false;
    $p = (int) ($pct[$id] ?? 0);
    if ($fStatus === 'full'     && $p !== 100)               return false;
    if ($fStatus === 'partial'  && !($p > 0 && $p < 100))    return false;
    if ($fStatus === 'none'     && $p !== 0)                 return false;
    if ($fStatus === 'override' && empty($override[$id]))    return false;
    if ($fStatus === 'inherit'  && !empty($override[$id]))   return false;
    return true;
}));

if ($fSort === 'quality')   usort($users, fn($a, $b) => (($qual[(int) $a['id']] ?? 101)) <=> (($qual[(int) $b['id']] ?? 101)));   // nulls last, worst first
elseif ($fSort === 'pct')   usort($users, fn($a, $b) => ((int) $pct[(int) $a['id']]) <=> ((int) $pct[(int) $b['id']]));            // lowest sample first
// 'name' keeps billing_allocatable_billers' name order

$pageTitle = 'Billing audit sampling';
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-percentage me-2 text-primary"></i>Billing audit sampling</h2>
        <div class="text-secondary small">Set, per biller, the <strong>% of worked charts</strong> that get audited. A per-biller %
            <strong>overrides</strong> the overall rate (<span class="badge bg-azure-lt"><?= (int) $globalPct ?>%</span>, set on
            <a href="<?= e(url('/admin/billing-audit.php')) ?>">Billing audit</a>); billers left on <em>Inherit</em> use that overall rate.
            Applied when a chart is worked; <strong>100%</strong> audits everything.</div></div>
</div></div></div>

<div class="page-body"><div class="container-xl">

    <!-- filter bar -->
    <form method="GET" class="card mb-3"><div class="card-body py-2">
        <div class="row g-2 align-items-end">
            <div class="col-auto"><label class="form-label small mb-1">Sample %</label>
                <select name="status" class="form-select form-select-sm" onchange="this.form.submit()">
                    <option value="all"      <?= $fStatus==='all'?'selected':'' ?>>Any</option>
                    <option value="full"     <?= $fStatus==='full'?'selected':'' ?>>Full (100%)</option>
                    <option value="partial"  <?= $fStatus==='partial'?'selected':'' ?>>Partial (1–99%)</option>
                    <option value="none"     <?= $fStatus==='none'?'selected':'' ?>>None (0%)</option>
                    <option value="override" <?= $fStatus==='override'?'selected':'' ?>>Has override</option>
                    <option value="inherit"  <?= $fStatus==='inherit'?'selected':'' ?>>Inherits global</option>
                </select></div>
            <div class="col-auto"><label class="form-label small mb-1">Sort by</label>
                <select name="sort" class="form-select form-select-sm" onchange="this.form.submit()">
                    <option value="name"    <?= $fSort==='name'?'selected':'' ?>>Name</option>
                    <option value="quality" <?= $fSort==='quality'?'selected':'' ?>>Quality (low→high)</option>
                    <option value="pct"     <?= $fSort==='pct'?'selected':'' ?>>Sample % (low→high)</option>
                </select></div>
            <div class="col"><label class="form-label small mb-1">Search</label>
                <input type="search" name="q" value="<?= e($fQ) ?>" class="form-control form-control-sm" placeholder="Name or email…"></div>
            <div class="col-auto"><button class="btn btn-sm btn-primary"><i class="ti ti-filter me-1"></i>Apply</button></div>
            <div class="col-auto"><a href="<?= e(url('/admin/billing-sampling.php')) ?>" class="btn btn-sm btn-link text-secondary">Clear</a></div>
        </div>
    </div></form>

    <form method="POST" action="<?= e(url('/admin/billing-sampling.php')) ?>">
        <?= csrf_field() ?><input type="hidden" name="action" value="save_samples">
        <input type="hidden" name="f_q" value="<?= e($fQ) ?>">
        <input type="hidden" name="f_status" value="<?= e($fStatus) ?>"><input type="hidden" name="f_sort" value="<?= e($fSort) ?>">
        <div class="card">
            <div class="card-header"><h3 class="card-title"><i class="ti ti-users me-2"></i>Your billers
                <span class="badge bg-blue-lt ms-2"><?= count($users) ?></span>
                <?php if (count($users) !== count($allUsers)): ?><span class="text-secondary small ms-1">of <?= count($allUsers) ?></span><?php endif; ?></h3>
                <div class="card-actions"><button class="btn btn-sm btn-primary"><i class="ti ti-device-floppy me-1"></i>Save all</button></div></div>
            <div class="table-responsive"><table class="table table-vcenter card-table">
                <thead><tr><th>Biller</th><th class="text-center">Source</th><th class="text-end">3-week quality</th><th class="w-1 text-nowrap">Sample %</th></tr></thead>
                <tbody>
                <?php if (!$allUsers): ?><tr><td colspan="4" class="text-center text-secondary py-4">No billers on your team yet.</td></tr>
                <?php elseif (!$users): ?><tr><td colspan="4" class="text-center text-secondary py-4">No billers match these filters. <a href="<?= e(url('/admin/billing-sampling.php')) ?>">Clear filters</a>.</td></tr>
                <?php else: foreach ($users as $u): $id = (int) $u['id']; $q = $qual[$id]; ?>
                    <tr>
                        <td><div class="fw-medium"><?= e($u['name']) ?></div><div class="text-secondary small"><?= e($u['email']) ?></div></td>
                        <td class="text-center"><?php if (!empty($override[$id])): ?><span class="badge bg-purple-lt" title="Per-biller override">Override</span>
                            <?php else: ?><span class="badge bg-secondary-lt" title="Uses the overall rate">Inherits <?= (int) $globalPct ?>%</span><?php endif; ?></td>
                        <td class="text-end"><?= $q === null ? '<span class="text-secondary">—</span>' : '<span class="badge bg-' . ($q>=95?'green':($q>=85?'yellow':'red')) . '-lt">' . $q . '%</span>' ?></td>
                        <td><div class="input-group input-group-sm" style="width:120px">
                            <input type="number" name="pct[<?= $id ?>]" class="form-control text-end" min="0" max="100" step="1" value="<?= (int)$pct[$id] ?>">
                            <span class="input-group-text">%</span></div></td>
                    </tr>
                <?php endforeach; endif; ?>
                </tbody>
            </table></div>
            <div class="card-footer text-secondary small">Saving a row sets a per-biller override. To return a biller to the overall rate, set their % to match the global (<?= (int) $globalPct ?>%) or clear the override in the database.</div>
        </div>
    </form>
</div></div>
<?php require __DIR__ . '/../includes/footer.php'; ?>
