<?php
/**
 * AR / Collections — audit SAMPLING (ar.supervise). Supervisor/manager sets, per AR user, the % of their
 * worked visits that enter the audit sample. Team-scoped (reports_to tree). The % is applied at work-save
 * time (ar_visit_in_sample_decision); changing it affects future work, not already-decided visits.
 *
 * Filters (Role / search / sample-status / sort) narrow the roster. The Role filter DEFAULTS to
 * "Account Receivable" so a supervisor lands straight on their AR workers.
 */
require_once __DIR__ . '/../includes/config.php';
$user = require_login('internal');
$pdo  = db();
$uid  = (int) $user['id'];

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

/* AR workers in scope (ar.work holders within the team). */
$allUsers = ar_allocatable_users($pdo);
if ($team !== null) $allUsers = array_values(array_filter($allUsers, fn($u) => in_array((int) $u['id'], $team, true)));

if ($_SERVER['REQUEST_METHOD'] === 'POST' && ($_POST['action'] ?? '') === 'save_samples') {
    csrf_check_or_die();
    if (!can('ar.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
        ar_set_user_sample($pdo, $u, (int) $pct, $uid);
        $n++;
    }
    flash('success', "Saved sample % for $n user(s).");
    // preserve the active filter view across the save
    $keep = array_filter([
        'role'   => (string) ($_POST['f_role'] ?? ''),
        'q'      => (string) ($_POST['f_q'] ?? ''),
        'status' => (string) ($_POST['f_status'] ?? ''),
        'sort'   => (string) ($_POST['f_sort'] ?? ''),
    ], fn($v) => $v !== '');
    redirect('/admin/ar-sampling.php' . ($keep ? '?' . http_build_query($keep) : ''));
}

/* current %s + rolling quality, batched (for the full roster — status filter/sort read these) */
$pct = []; $qual = [];
foreach ($allUsers as $u) { $id = (int) $u['id']; $pct[$id] = ar_user_sample_pct($pdo, $id); $qual[$id] = ar_quality_pct($pdo, $id, 21); }

/* distinct role tokens across the roster (roles is a ", "-joined GROUP_CONCAT of role names) */
$roleTokens = [];
foreach ($allUsers as $u) foreach (array_filter(array_map('trim', explode(',', (string) ($u['roles'] ?? '')))) as $rt) $roleTokens[$rt] = true;
$roleOptions = array_keys($roleTokens); sort($roleOptions);

/* ---- filters ---- */
$AR_ROLE = 'Account Receivable';
$fRole   = isset($_GET['role']) ? (string) $_GET['role'] : (in_array($AR_ROLE, $roleOptions, true) ? $AR_ROLE : '__all__');
$fQ      = trim((string) ($_GET['q'] ?? ''));
$fStatus = in_array($_GET['status'] ?? '', ['full', 'partial', 'none'], true) ? $_GET['status'] : 'all';
$fSort   = in_array($_GET['sort'] ?? '', ['quality', 'pct'], true) ? $_GET['sort'] : 'name';

$users = array_values(array_filter($allUsers, function ($u) use ($fRole, $fQ, $fStatus, $pct) {
    $id = (int) $u['id'];
    if ($fRole !== '__all__') {
        $tokens = array_map('trim', explode(',', (string) ($u['roles'] ?? '')));
        if (!in_array($fRole, $tokens, true)) return false;
    }
    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;
    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 ar_allocatable_users' name order

$pageTitle = 'AR 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>AR audit sampling</h2>
        <div class="text-secondary small">Set, per AR user, the <strong>% of worked visits</strong> that get audited. Applied when a visit 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">Role</label>
                <select name="role" class="form-select form-select-sm" onchange="this.form.submit()">
                    <option value="__all__" <?= $fRole==='__all__'?'selected':'' ?>>All roles</option>
                    <?php foreach ($roleOptions as $ro): ?>
                        <option value="<?= e($ro) ?>" <?= $fRole===$ro?'selected':'' ?>><?= e($ro) ?></option>
                    <?php endforeach; ?>
                </select></div>
            <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>
                </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/ar-sampling.php?role=__all__')) ?>" class="btn btn-sm btn-link text-secondary">Clear</a></div>
        </div>
    </div></form>

    <form method="POST" action="<?= e(url('/admin/ar-sampling.php')) ?>">
        <?= csrf_field() ?><input type="hidden" name="action" value="save_samples">
        <input type="hidden" name="f_role" value="<?= e($fRole) ?>"><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 AR team
                <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; ?>
                <?php if ($fRole !== '__all__'): ?><span class="badge bg-azure-lt ms-2"><?= e($fRole) ?></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>AR user</th><th>Role</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 AR workers on your team yet.</td></tr>
                <?php elseif (!$users): ?><tr><td colspan="4" class="text-center text-secondary py-4">No users match these filters. <a href="<?= e(url('/admin/ar-sampling.php?role=__all__')) ?>">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="small text-secondary"><?= e($u['roles'] ?? '') ?></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>
    </form>
</div></div>
<?php require __DIR__ . '/../includes/footer.php'; ?>
