<?php
require_once __DIR__ . '/auth.php';
require_login();
if (!perms_can_export_candidates(current_user())) { http_response_code(403); echo 'Forbidden'; exit; }

$user       = current_user();
$isSuper    = perms_is_super($user);
$facilityId = $user['facility_id'];

if ($_SERVER['REQUEST_METHOD'] === 'POST' && $isSuper && isset($_POST['delete_id'])) {
    csrf_require();
    $delId = v_int($_POST['delete_id'], 1);
    if ($delId > 0) {
        $check = $pdo->prepare("SELECT COUNT(*) c FROM attempts WHERE candidate_id = ? AND deleted_at IS NULL");
        $check->execute([$delId]);
        if ((int)$check->fetch()['c'] > 0) {
            header('Location: export_candidates.php?msg=has_attempts'); exit;
        }
        $pdo->prepare("UPDATE candidates SET deleted_at = NOW() WHERE id = ?")->execute([$delId]);
        audit_log($pdo, 'candidate_soft_delete', ['id' => $delId]);
        header('Location: export_candidates.php?msg=deleted'); exit;
    }
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && $isSuper && isset($_POST['restore_id'])) {
    csrf_require();
    $rId = v_int($_POST['restore_id'], 1);
    if ($rId > 0) {
        $pdo->prepare("UPDATE candidates SET deleted_at = NULL WHERE id = ?")->execute([$rId]);
        audit_log($pdo, 'candidate_restore', ['id' => $rId]);
        header('Location: export_candidates.php?msg=restored'); exit;
    }
}

$candNo   = v_clean_string($_GET['candidate_number'] ?? '', 50);
$candName = v_clean_string($_GET['candidate_name']   ?? '', 100);
$facF     = v_int($_GET['facility_id'] ?? 0, 0);
$showDeleted = isset($_GET['show_deleted']) && $_GET['show_deleted'] === '1';

$facilities = $pdo->query('SELECT id, name, code FROM facilities WHERE deleted_at IS NULL ORDER BY name')->fetchAll();

$baseSql = "
    SELECT c.id, c.candidate_number, c.name AS candidate_name, c.barcode, c.created_at, c.deleted_at,
           c.section, c.circuit_type, c.cohort_year,
           f.name AS facility_name, f.code AS facility_code, c.facility_id
    FROM candidates c JOIN facilities f ON c.facility_id = f.id
";
$where = []; $params = [];
if (!$showDeleted) $where[] = 'c.deleted_at IS NULL';
if (!$isSuper && $facilityId) { $where[] = 'c.facility_id = ?'; $params[] = $facilityId; }
if ($candNo !== '')           { $where[] = 'c.candidate_number LIKE ?'; $params[] = "%$candNo%"; }
if ($candName !== '')         { $where[] = 'c.name LIKE ?';             $params[] = "%$candName%"; }
if ($isSuper && $facF > 0)    { $where[] = 'c.facility_id = ?';         $params[] = $facF; }

$sql = $baseSql . ($where ? ' WHERE ' . implode(' AND ', $where) : '') . ' ORDER BY f.name, c.candidate_number';

if (isset($_GET['download']) && $_GET['download'] === 'csv') {
    header('Content-Type: text/csv; charset=utf-8');
    header('Content-Disposition: attachment; filename=osce_candidates_' . date('Ymd_His') . '.csv');
    $out = fopen('php://output', 'w');
    fputcsv($out, ['OSCE Nexus™ Candidates Export', 'Copyright © ' . date('Y') . ' Khalaf Almazrouei']);
    fputcsv($out, []);
    fputcsv($out, ['Facility', 'Candidate Number', 'Name', 'Cohort Year', 'Section', 'Circuit Type', 'Barcode']);
    $stmt = $pdo->prepare($sql);
    $stmt->execute($params);
    while ($r = $stmt->fetch()) {
        fputcsv($out, [
            $r['facility_code'] ?: $r['facility_name'],
            $r['candidate_number'],
            $r['candidate_name'],
            $r['cohort_year'],
            $r['section'],
            $r['circuit_type'],
            $r['barcode'],
        ]);
    }
    fclose($out);
    audit_log($pdo, 'candidates_export', []);
    exit;
}

require_once __DIR__ . '/header.php';

$stmt = $pdo->prepare($sql);
$stmt->execute($params);
$rows = $stmt->fetchAll();
$csvUrl = 'export_candidates.php?' . http_build_query(array_merge($_GET, ['download' => 'csv']));
?>
<h2>Export &amp; Manage Candidates</h2>
<?php
$f = $_GET['msg'] ?? '';
if ($f === 'deleted')      echo '<div class="alert alert-success">Candidate moved to trash.</div>';
elseif ($f === 'restored') echo '<div class="alert alert-success">Candidate restored.</div>';
elseif ($f === 'has_attempts') echo '<div class="alert alert-danger">Cannot delete: candidate has recorded attempts.</div>';
?>

<form method="get" class="mb-2">
    <div class="form-row">
        <div class="field"><label>Candidate #</label><input type="text" name="candidate_number" value="<?php echo h($candNo); ?>"></div>
        <div class="field"><label>Name</label><input type="text" name="candidate_name" value="<?php echo h($candName); ?>"></div>
        <?php if ($isSuper): ?>
        <div class="field"><label>Facility</label>
            <select name="facility_id">
                <option value="0">All</option>
                <?php foreach ($facilities as $f): ?>
                    <option value="<?php echo (int)$f['id']; ?>" <?php if ($facF==(int)$f['id']) echo 'selected'; ?>>
                        <?php echo h($f['name']); ?><?php if ($f['code']) echo ' [' . h($f['code']) . ']'; ?>
                    </option>
                <?php endforeach; ?>
            </select>
        </div>
        <?php endif; ?>
        <div class="field field-inline"><label><input type="checkbox" name="show_deleted" value="1" <?php if ($showDeleted) echo 'checked'; ?>> Show deleted</label></div>
    </div>
    <button type="submit" class="btn">Apply Filters</button>
    <a href="export_candidates.php" class="btn">Clear</a>
    <a href="<?php echo h($csvUrl); ?>" class="btn btn-primary">Download CSV</a>
</form>

<?php if (!$rows): ?>
    <p>No candidates match this filter.</p>
<?php else: ?>
<div class="table-wrap">
<table class="data">
    <thead><tr>
        <th>ID</th><th>Facility</th><th>Candidate #</th><th>Name</th><th>Year</th><th>Sec</th><th>Circuit</th>
        <th>Barcode</th><th>Created</th><th>Status</th>
        <?php if ($isSuper): ?><th>Actions</th><?php endif; ?>
    </tr></thead>
    <tbody>
    <?php foreach ($rows as $r): ?>
        <tr<?php if ($r['deleted_at']) echo ' style="opacity:.55"'; ?>>
            <td data-label="ID"><?php echo (int)$r['id']; ?></td>
            <td data-label="Facility"><?php echo h($r['facility_name']); ?><?php if ($r['facility_code']) echo ' <small class="muted">['.h($r['facility_code']).']</small>'; ?></td>
            <td data-label="Candidate #"><?php echo h($r['candidate_number']); ?></td>
            <td data-label="Name"><?php echo h($r['candidate_name']); ?></td>
            <td data-label="Year"><?php echo h($r['cohort_year'] ?? ''); ?></td>
            <td data-label="Sec"><?php echo h($r['section'] ?? ''); ?></td>
            <td data-label="Circuit"><?php echo h($r['circuit_type'] ?? ''); ?></td>
            <td data-label="Barcode"><code><?php echo h($r['barcode']); ?></code></td>
            <td data-label="Created"><?php echo h($r['created_at']); ?></td>
            <td data-label="Status"><?php echo $r['deleted_at'] ? '<span class="badge badge-timeout">deleted</span>' : '<span class="badge badge-submitted">active</span>'; ?></td>
            <?php if ($isSuper): ?>
            <td>
                <?php if ($r['deleted_at']): ?>
                    <form method="post" style="display:inline">
                        <?php echo csrf_field(); ?>
                        <input type="hidden" name="restore_id" value="<?php echo (int)$r['id']; ?>">
                        <button type="submit" class="btn btn-sm">Restore</button>
                    </form>
                <?php else: ?>
                    <form method="post" style="display:inline" onsubmit="return confirm('Move this candidate to trash?');">
                        <?php echo csrf_field(); ?>
                        <input type="hidden" name="delete_id" value="<?php echo (int)$r['id']; ?>">
                        <button type="submit" class="btn btn-sm btn-danger">Delete</button>
                    </form>
                <?php endif; ?>
            </td>
            <?php endif; ?>
        </tr>
    <?php endforeach; ?>
    </tbody>
</table>
</div>
<?php endif; ?>

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