<?php
require_once __DIR__ . '/header.php';
require_login();

$user       = current_user();
$canManage  = perms_can_manage_candidates($user);
$isSuper    = perms_is_super($user);
$canDelete  = perms_can_delete_candidates($user);
$facilityId = $user['facility_id'] ?? null;

if ($isSuper && isset($_GET['facility_id']) && $_GET['facility_id'] !== '') {
    $facilityFilter = v_int($_GET['facility_id'], 1);
} else {
    $facilityFilter = $facilityId;
}

$msg = '';
$err = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['add_candidate']) && $canManage) {
    csrf_require();

    $name    = v_clean_string($_POST['name'] ?? '', 100);
    $candNo  = v_clean_string($_POST['candidate_number'] ?? '', 50);
    $section = v_clean_string($_POST['section'] ?? '', 50);
    $circuit = v_clean_string($_POST['circuit_type'] ?? '', 50);
    $year    = v_clean_string($_POST['cohort_year'] ?? '', 10);
    $facId   = $facilityFilter ?: v_int($_POST['facility_id'] ?? 0, 1);

    if ($name === '' || $candNo === '' || $facId <= 0) {
        $err = 'Name, candidate number, and facility are required.';
    } else {
        // Look up facility code so barcode = {CODE}-{NUMBER}
        $fs = $pdo->prepare("SELECT code FROM facilities WHERE id = ?");
        $fs->execute([$facId]);
        $facCode = $fs->fetch()['code'] ?? null;

        $barcode = barcode_from_candidate($candNo, $facCode, $facId);

        try {
            // Handle barcode collision by appending -2, -3...
            $tries = 0;
            $finalBarcode = $barcode;
            while ($tries < 20) {
                try {
                    $pdo->prepare('INSERT INTO candidates (facility_id, candidate_number, name, section, circuit_type, cohort_year, barcode) VALUES (?, ?, ?, ?, ?, ?, ?)')
                        ->execute([$facId, $candNo, $name, $section ?: null, $circuit ?: null, $year ?: null, $finalBarcode]);
                    break;
                } catch (PDOException $e) {
                    if (str_contains($e->getMessage(), 'Duplicate') && str_contains($e->getMessage(), 'barcode')) {
                        $tries++;
                        $finalBarcode = $barcode . '-' . ($tries + 1);
                        continue;
                    }
                    throw $e;
                }
            }
            $id = (int)$pdo->lastInsertId();
            audit_log($pdo, 'candidate_create', ['id' => $id, 'candidate_number' => $candNo, 'barcode' => $finalBarcode]);
            $msg = 'Candidate added. Barcode: <strong>' . h($finalBarcode) . '</strong>';
        } catch (Throwable $e) {
            $err = 'Could not add candidate.';
            error_log('candidate_create: ' . $e->getMessage());
        }
    }
}

// Edit candidate
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['update_candidate']) && $canManage) {
    csrf_require();

    $id      = v_int($_POST['candidate_id'] ?? 0, 1);
    $name    = v_clean_string($_POST['name'] ?? '', 100);
    $candNo  = v_clean_string($_POST['candidate_number'] ?? '', 50);
    $section = v_clean_string($_POST['section'] ?? '', 50);
    $circuit = v_clean_string($_POST['circuit_type'] ?? '', 50);
    $year    = v_clean_string($_POST['cohort_year'] ?? '', 10);

    $cs = $pdo->prepare('SELECT facility_id FROM candidates WHERE id = ?');
    $cs->execute([$id]);
    $row = $cs->fetch();
    if (!$row || !perms_owns_facility($user, $row['facility_id'])) {
        $err = 'You can only edit candidates within your facility.';
    } else {
        $pdo->prepare('UPDATE candidates SET candidate_number=?, name=?, section=?, circuit_type=?, cohort_year=? WHERE id=?')
            ->execute([$candNo, $name, $section ?: null, $circuit ?: null, $year ?: null, $id]);
        audit_log($pdo, 'candidate_update', ['id' => $id]);
        $msg = 'Candidate updated.';
    }
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['regen_barcode']) && $canManage) {
    csrf_require();
    $id = v_int($_POST['regen_barcode'], 1);
    $row = $pdo->prepare("SELECT c.id, c.candidate_number, c.facility_id, f.code AS facility_code FROM candidates c JOIN facilities f ON f.id = c.facility_id WHERE c.id = ?");
    $row->execute([$id]);
    $r = $row->fetch();
    if ($r && perms_owns_facility($user, $r['facility_id'])) {
        $new = barcode_from_candidate($r['candidate_number'], $r['facility_code'], (int)$r['facility_id']);
        try {
            $tries = 0; $final = $new;
            while ($tries < 20) {
                try {
                    $pdo->prepare("UPDATE candidates SET barcode = ? WHERE id = ?")->execute([$final, $id]);
                    break;
                } catch (PDOException $e) {
                    if (str_contains($e->getMessage(), 'Duplicate')) {
                        $tries++;
                        $final = $new . '-' . ($tries + 1);
                        continue;
                    }
                    throw $e;
                }
            }
            audit_log($pdo, 'candidate_barcode_regen', ['id' => $id, 'barcode' => $final]);
            $msg = 'Barcode regenerated: <strong>' . h($final) . '</strong>';
        } catch (Throwable $e) {
            $err = 'Could not regenerate barcode.';
            error_log('regen_barcode: ' . $e->getMessage());
        }
    }
}

// Bulk soft-delete selected candidates (super admin only).
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['bulk_delete_candidates']) && $canDelete) {
    csrf_require();
    $ids = array_values(array_filter(
        array_map('intval', (array)($_POST['ids'] ?? [])),
        static fn($n) => $n > 0
    ));
    if ($ids) {
        $in = implode(',', array_fill(0, count($ids), '?'));
        $pdo->prepare("UPDATE candidates SET deleted_at = NOW() WHERE id IN ($in) AND deleted_at IS NULL")
            ->execute($ids);
        audit_log($pdo, 'candidate_bulk_delete', ['ids' => $ids, 'count' => count($ids)]);
        $msg = count($ids) . ' candidate(s) moved to trash. Restore from <a href="export_candidates.php">Export Candidates</a>.';
    } else {
        $err = 'No candidates were selected.';
    }
}

$facilities = $isSuper ? $pdo->query('SELECT * FROM facilities WHERE deleted_at IS NULL ORDER BY name')->fetchAll() : [];

// Build query
$params = [];
$sql = 'SELECT c.*, f.name AS facility_name, f.code AS facility_code FROM candidates c JOIN facilities f ON c.facility_id = f.id WHERE c.deleted_at IS NULL';
if ($facilityFilter) {
    $sql .= ' AND c.facility_id = ?';
    $params[] = $facilityFilter;
}
$sql .= ' ORDER BY c.created_at DESC';
$stmt = $pdo->prepare($sql);
$stmt->execute($params);
$candidates = $stmt->fetchAll();
?>

<h2>Candidates</h2>
<?php if (!$canManage): ?>
    <div class="alert alert-info">Read-only view. Coordinators and super admins can add or edit candidates.</div>
<?php endif; ?>
<?php if ($msg): ?><div class="alert alert-success"><?php echo $msg; ?></div><?php endif; ?>
<?php if ($err): ?><div class="alert alert-danger"><?php echo h($err); ?></div><?php endif; ?>

<?php if ($isSuper): ?>
<form method="get" class="mb-2">
    <label>Facility filter:
        <select name="facility_id" onchange="this.form.submit()">
            <option value="">-- All --</option>
            <?php foreach ($facilities as $f): ?>
                <option value="<?php echo (int)$f['id']; ?>" <?php if ((int)$facilityFilter===(int)$f['id']) echo 'selected'; ?>>
                    <?php echo h($f['name']); ?><?php if ($f['code']) echo ' [' . h($f['code']) . ']'; ?>
                </option>
            <?php endforeach; ?>
        </select>
    </label>
</form>
<?php endif; ?>

<?php if ($canManage): ?>
<h3>Add Candidate</h3>
<form method="post">
    <?php echo csrf_field(); ?>
    <input type="hidden" name="add_candidate" value="1">
    <div class="form-row">
        <?php if ($isSuper && !$facilityFilter): ?>
            <div class="field"><label>Facility *</label>
                <select name="facility_id" required>
                    <option value="">Choose…</option>
                    <?php foreach ($facilities as $f): ?>
                        <option value="<?php echo (int)$f['id']; ?>"><?php echo h($f['name']); ?><?php if ($f['code']) echo ' [' . h($f['code']) . ']'; ?></option>
                    <?php endforeach; ?>
                </select>
            </div>
        <?php endif; ?>
        <div class="field"><label>Candidate # *</label><input type="text" name="candidate_number" required placeholder="2024GMD01"></div>
        <div class="field"><label>Full Name *</label><input type="text" name="name" required></div>
        <div class="field"><label>Cohort / Year</label><input type="text" name="cohort_year" placeholder="2024"></div>
        <div class="field"><label>Section</label><input type="text" name="section" placeholder="A"></div>
        <div class="field"><label>Circuit Type</label><input type="text" name="circuit_type" placeholder="Standard"></div>
    </div>
    <button type="submit" class="btn btn-primary">Add Candidate</button>
    <a href="candidates_import.php" class="btn">Import from CSV</a>
    <a href="barcode_labels.php" class="btn">Print Barcode Labels</a>
</form>
<?php endif; ?>

<h3 class="mt-3">Existing Candidates (<?php echo count($candidates); ?>)</h3>

<?php if ($canDelete): ?>
<form id="bulk-del-cand" method="post" class="mb-1" onsubmit="return bulkConfirmCand();">
    <?php echo csrf_field(); ?>
    <input type="hidden" name="bulk_delete_candidates" value="1">
    <button type="submit" class="btn btn-danger btn-sm">🗑 Delete Selected</button>
    <span class="muted" id="cand-sel-count"></span>
</form>
<?php endif; ?>

<div class="table-wrap">
<table class="data">
    <thead>
    <tr>
        <?php if ($canDelete): ?><th><input type="checkbox" id="cand-check-all" title="Select all"></th><?php endif; ?>
        <th>ID</th>
        <?php if ($isSuper): ?><th>Facility</th><?php endif; ?>
        <th>Candidate #</th><th>Name</th>
        <th>Year</th><th>Section</th><th>Circuit</th>
        <th>Barcode</th>
        <?php if ($canManage): ?><th>Actions</th><?php endif; ?>
    </tr>
    </thead>
    <tbody>
    <?php foreach ($candidates as $c): ?>
        <tr>
            <form method="post">
                <?php if ($canManage): ?>
                    <?php echo csrf_field(); ?>
                    <input type="hidden" name="update_candidate" value="1">
                    <input type="hidden" name="candidate_id" value="<?php echo (int)$c['id']; ?>">
                <?php endif; ?>

                <?php if ($canDelete): ?>
                <td><input type="checkbox" class="cand-check" name="ids[]" value="<?php echo (int)$c['id']; ?>" form="bulk-del-cand"></td>
                <?php endif; ?>
                <td data-label="ID"><?php echo (int)$c['id']; ?></td>
                <?php if ($isSuper): ?>
                    <td data-label="Facility"><?php echo h($c['facility_name']); ?><?php if ($c['facility_code']) echo ' <small class="muted">['.h($c['facility_code']).']</small>'; ?></td>
                <?php endif; ?>
                <td data-label="Candidate #">
                    <?php if ($canManage): ?>
                        <input type="text" name="candidate_number" value="<?php echo h($c['candidate_number']); ?>" style="max-width:140px;">
                    <?php else: ?>
                        <?php echo h($c['candidate_number']); ?>
                    <?php endif; ?>
                </td>
                <td data-label="Name">
                    <?php if ($canManage): ?>
                        <input type="text" name="name" value="<?php echo h($c['name']); ?>">
                    <?php else: ?>
                        <?php echo h($c['name']); ?>
                    <?php endif; ?>
                </td>
                <td data-label="Year">
                    <?php if ($canManage): ?>
                        <input type="text" name="cohort_year" value="<?php echo h($c['cohort_year'] ?? ''); ?>" style="max-width:80px;">
                    <?php else: ?>
                        <?php echo h($c['cohort_year'] ?? ''); ?>
                    <?php endif; ?>
                </td>
                <td data-label="Section">
                    <?php if ($canManage): ?>
                        <input type="text" name="section" value="<?php echo h($c['section'] ?? ''); ?>" style="max-width:80px;">
                    <?php else: ?>
                        <?php echo h($c['section'] ?? ''); ?>
                    <?php endif; ?>
                </td>
                <td data-label="Circuit">
                    <?php if ($canManage): ?>
                        <input type="text" name="circuit_type" value="<?php echo h($c['circuit_type'] ?? ''); ?>" style="max-width:100px;">
                    <?php else: ?>
                        <?php echo h($c['circuit_type'] ?? ''); ?>
                    <?php endif; ?>
                </td>
                <td data-label="Barcode"><code><?php echo h($c['barcode']); ?></code></td>
                <?php if ($canManage): ?>
                <td>
                    <button type="submit" class="btn btn-sm">Save</button>
                    <button type="submit" name="regen_barcode" value="<?php echo (int)$c['id']; ?>" class="btn btn-sm"
                            onclick="return confirm('Regenerate barcode from candidate number?');">↻ Barcode</button>
                </td>
                <?php endif; ?>
            </form>
        </tr>
    <?php endforeach; ?>
    </tbody>
</table>
</div>

<p class="muted mt-2">Soft-deletion / restore is done from <a href="export_candidates.php">Export Candidates</a> (super admin).</p>

<?php if ($canDelete): ?>
<script>
(function () {
    const all   = document.getElementById('cand-check-all');
    const count = document.getElementById('cand-sel-count');
    const boxes = () => document.querySelectorAll('.cand-check');
    function update() {
        const n = document.querySelectorAll('.cand-check:checked').length;
        if (count) count.textContent = n ? (n + ' selected') : '';
    }
    if (all) all.addEventListener('change', () => { boxes().forEach(b => b.checked = all.checked); update(); });
    boxes().forEach(b => b.addEventListener('change', update));
    window.bulkConfirmCand = function () {
        const n = document.querySelectorAll('.cand-check:checked').length;
        if (!n) { alert('Select at least one candidate first.'); return false; }
        return confirm('Move ' + n + ' selected candidate(s) to trash? You can restore them from Export Candidates.');
    };
})();
</script>
<?php endif; ?>

<?php require __DIR__ . '/footer.php'; ?>
