<?php
require_once __DIR__ . '/header.php';
perms_require('manage_assignments');
$user = current_user();

$examId = v_int($_GET['exam_id'] ?? 0, 1);
if ($examId <= 0) {
    // pick first active exam
    $r = $pdo->query("SELECT id FROM exams WHERE deleted_at IS NULL ORDER BY exam_date DESC, id DESC LIMIT 1")->fetch();
    if ($r) {
        header('Location: assignments.php?exam_id=' . (int)$r['id']);
        exit;
    }
    echo '<div class="alert alert-info">No exams found. Create one first.</div>';
    require __DIR__ . '/footer.php';
    exit;
}

$stmt = $pdo->prepare('SELECT * FROM exams WHERE id = ? AND deleted_at IS NULL');
$stmt->execute([$examId]);
$exam = $stmt->fetch();
if (!$exam) {
    echo '<div class="alert alert-danger">Exam not found.</div>';
    require __DIR__ . '/footer.php'; exit;
}
if (!perms_owns_facility($user, $exam['facility_id'])) {
    echo '<div class="alert alert-danger">Forbidden.</div>';
    require __DIR__ . '/footer.php'; exit;
}

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

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['assign'])) {
    csrf_require();
    $esId = v_int($_POST['exam_station_id'] ?? 0, 1);
    $eId  = v_int($_POST['examiner_id'] ?? 0, 1);
    if ($esId > 0 && $eId > 0) {
        try {
            $pdo->prepare('INSERT IGNORE INTO examiner_assignments (exam_station_id, examiner_id) VALUES (?, ?)')
                ->execute([$esId, $eId]);
            audit_log($pdo, 'examiner_assign', ['exam_station_id'=>$esId,'examiner_id'=>$eId]);
            $msg = 'Examiner assigned.';
        } catch (Throwable $e) {
            $err = 'Could not assign.';
            error_log('assign: ' . $e->getMessage());
        }
    }
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['unassign'])) {
    csrf_require();
    $rowId = v_int($_POST['unassign'], 1);
    if ($rowId > 0) {
        $pdo->prepare('DELETE FROM examiner_assignments WHERE id = ?')->execute([$rowId]);
        audit_log($pdo, 'examiner_unassign', ['assignment_id'=>$rowId]);
        $msg = 'Examiner removed from station.';
    }
}

$stations = $pdo->prepare("
    SELECT es.id, es.station_label, es.room, f.name AS form_name
    FROM exam_stations es JOIN forms f ON f.id = es.form_id
    WHERE es.exam_id = ?
    ORDER BY es.sort_order, es.id
");
$stations->execute([$examId]);
$stations = $stations->fetchAll();

$examiners = $pdo->query("SELECT id, username, full_name, role, facility_id FROM users WHERE active = 1 ORDER BY full_name")->fetchAll();

$assignments = $pdo->prepare("
    SELECT ea.id, ea.exam_station_id, ea.examiner_id, u.full_name, u.username
    FROM examiner_assignments ea
    JOIN users u ON u.id = ea.examiner_id
    JOIN exam_stations es ON es.id = ea.exam_station_id
    WHERE es.exam_id = ?
");
$assignments->execute([$examId]);
$assignments = $assignments->fetchAll();

$byStation = [];
foreach ($assignments as $a) $byStation[$a['exam_station_id']][] = $a;
?>
<h2>Examiner Assignments – <?php echo h($exam['name']); ?></h2>
<?php if ($msg): ?><div class="alert alert-success"><?php echo h($msg); ?></div><?php endif; ?>
<?php if ($err): ?><div class="alert alert-danger"><?php echo h($err); ?></div><?php endif; ?>

<p><a href="exam_edit.php?id=<?php echo (int)$examId; ?>" class="btn">← Back to Exam</a></p>

<?php if (!$stations): ?>
    <div class="alert alert-warning">No stations defined for this exam yet. <a href="exam_edit.php?id=<?php echo (int)$examId; ?>">Add stations</a> first.</div>
<?php endif; ?>

<?php foreach ($stations as $s): ?>
    <h3 class="mt-2"><?php echo h($s['station_label']); ?>
        <small class="muted">– <?php echo h($s['form_name']); ?><?php if ($s['room']) echo ' · Room ' . h($s['room']); ?></small>
    </h3>
    <div class="flex mb-1">
        <?php foreach ($byStation[$s['id']] ?? [] as $a): ?>
            <span class="badge">
                <?php echo h($a['full_name']); ?>
                <form method="post" style="display:inline">
                    <?php echo csrf_field(); ?>
                    <button type="submit" name="unassign" value="<?php echo (int)$a['id']; ?>"
                            class="btn btn-sm" style="margin-left:6px; padding:0 6px;">×</button>
                </form>
            </span>
        <?php endforeach; ?>
    </div>
    <form method="post" class="flex">
        <?php echo csrf_field(); ?>
        <input type="hidden" name="assign" value="1">
        <input type="hidden" name="exam_station_id" value="<?php echo (int)$s['id']; ?>">
        <select name="examiner_id" required>
            <option value="">Add examiner…</option>
            <?php foreach ($examiners as $e): ?>
                <option value="<?php echo (int)$e['id']; ?>"><?php echo h($e['full_name'] . ' (' . $e['username'] . ')'); ?></option>
            <?php endforeach; ?>
        </select>
        <button type="submit" class="btn btn-sm btn-primary">Assign</button>
    </form>
<?php endforeach; ?>

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