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

$user    = current_user();
$isSuper = perms_is_super($user);
$examId  = v_int($_GET['id'] ?? 0, 1);

if ($examId <= 0) {
    echo '<div class="alert alert-danger">Exam not found.</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 = '';

// ---- Update exam meta ----
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['update_exam'])) {
    csrf_require();
    $name    = v_clean_string($_POST['name'] ?? '', 150);
    $desc    = v_clean_string($_POST['description'] ?? '', 2000);
    $dateStr = v_clean_string($_POST['exam_date'] ?? '', 20);
    $status  = in_array($_POST['status'] ?? 'draft', ['draft','active','completed','archived'], true) ? $_POST['status'] : 'draft';
    if ($name === '') {
        $err = 'Name is required.';
    } else {
        $pdo->prepare('UPDATE exams SET name=?, description=?, exam_date=?, status=? WHERE id=?')
            ->execute([$name, $desc, $dateStr ?: null, $status, $examId]);
        audit_log($pdo, 'exam_update', ['id' => $examId, 'status' => $status]);
        $msg = 'Exam updated.';
        $exam['name']        = $name;
        $exam['description'] = $desc;
        $exam['exam_date']   = $dateStr ?: null;
        $exam['status']      = $status;
    }
}

// ---- Add station ----
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['add_station'])) {
    csrf_require();
    $formId   = v_int($_POST['form_id'] ?? 0, 1);
    $label    = v_clean_string($_POST['station_label'] ?? '', 100);
    $room     = v_clean_string($_POST['room'] ?? '', 50);
    $duration = v_int($_POST['duration_minutes'] ?? 8, 0, 30, 8);

    if ($formId <= 0 || $label === '') {
        $err = 'Form and station label are required.';
    } else {
        $maxStmt = $pdo->prepare('SELECT COALESCE(MAX(sort_order),0)+1 AS n FROM exam_stations WHERE exam_id = ?');
        $maxStmt->execute([$examId]);
        $next = (int)$maxStmt->fetch()['n'];
        $pdo->prepare('INSERT INTO exam_stations (exam_id, form_id, station_label, room, duration_minutes, sort_order) VALUES (?, ?, ?, ?, ?, ?)')
            ->execute([$examId, $formId, $label, $room, $duration, $next]);
        audit_log($pdo, 'exam_station_add', ['exam_id' => $examId, 'form_id' => $formId]);
        $msg = 'Station added.';
    }
}

// ---- Remove station ----
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['remove_station'])) {
    csrf_require();
    $esId = v_int($_POST['remove_station'], 1);
    if ($esId > 0) {
        $pdo->prepare('DELETE FROM exam_stations WHERE id = ? AND exam_id = ?')->execute([$esId, $examId]);
        audit_log($pdo, 'exam_station_remove', ['exam_station_id' => $esId, 'exam_id' => $examId]);
        $msg = 'Station removed.';
    }
}

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

$stations = $pdo->prepare("
    SELECT es.*, 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();
?>
<h2>Configure Exam: <?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; ?>

<h3>Exam Details</h3>
<form method="post">
    <?php echo csrf_field(); ?>
    <input type="hidden" name="update_exam" value="1">
    <div class="form-row">
        <div class="field"><label>Name</label><input type="text" name="name" value="<?php echo h($exam['name']); ?>" required></div>
        <div class="field"><label>Exam Date</label><input type="date" name="exam_date" value="<?php echo h($exam['exam_date'] ?? ''); ?>"></div>
        <div class="field"><label>Status</label>
            <select name="status">
                <?php foreach (['draft','active','completed','archived'] as $s): ?>
                    <option value="<?php echo $s; ?>" <?php if ($exam['status']===$s) echo 'selected'; ?>><?php echo ucfirst($s); ?></option>
                <?php endforeach; ?>
            </select>
        </div>
    </div>
    <div class="field mb-2"><label>Description</label><textarea name="description" rows="2"><?php echo h($exam['description'] ?? ''); ?></textarea></div>
    <button type="submit" class="btn btn-primary">Save Details</button>
    <a href="assignments.php?exam_id=<?php echo (int)$examId; ?>" class="btn">Manage Examiner Assignments</a>
</form>

<h3 class="mt-3">Stations in this Exam</h3>
<div class="table-wrap">
<table class="data">
    <thead><tr><th>#</th><th>Label</th><th>Form</th><th>Room</th><th>Duration</th><th>Remove</th></tr></thead>
    <tbody>
        <?php foreach ($stations as $i => $s): ?>
        <tr>
            <td data-label="#"><?php echo $i + 1; ?></td>
            <td data-label="Label"><?php echo h($s['station_label']); ?></td>
            <td data-label="Form"><?php echo h($s['form_name']); ?></td>
            <td data-label="Room"><?php echo h($s['room']); ?></td>
            <td data-label="Duration"><?php echo (int)$s['duration_minutes']; ?> min</td>
            <td>
                <form method="post" style="display:inline" onsubmit="return confirm('Remove this station?');">
                    <?php echo csrf_field(); ?>
                    <button type="submit" class="btn btn-sm btn-danger" name="remove_station" value="<?php echo (int)$s['id']; ?>">Remove</button>
                </form>
            </td>
        </tr>
        <?php endforeach; ?>
        <?php if (!$stations): ?>
            <tr><td colspan="6" class="muted">No stations yet.</td></tr>
        <?php endif; ?>
    </tbody>
</table>
</div>

<h3 class="mt-3">Add Station</h3>
<form method="post">
    <?php echo csrf_field(); ?>
    <input type="hidden" name="add_station" value="1">
    <div class="form-row">
        <div class="field"><label>Form (checklist)</label>
            <select name="form_id" required>
                <option value="">Choose form...</option>
                <?php foreach ($forms as $f): ?>
                    <option value="<?php echo (int)$f['id']; ?>"><?php echo h($f['name']); ?></option>
                <?php endforeach; ?>
            </select>
        </div>
        <div class="field"><label>Station Label</label><input type="text" name="station_label" placeholder="e.g. Station 1 – CVS" required></div>
        <div class="field"><label>Room</label><input type="text" name="room"></div>
        <div class="field"><label>Duration (minutes)</label><input type="number" name="duration_minutes" min="0" max="30" value="8"></div>
    </div>
    <button type="submit" class="btn btn-primary">Add Station</button>
</form>

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