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

$user = current_user();
$isSuper = perms_is_super($user);
$msg = ''; $err = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['create_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';
    $facId     = $isSuper ? (($_POST['facility_id'] ?? '') === '' ? null : v_int($_POST['facility_id'], 1))
                          : (int)$user['facility_id'];

    if ($name === '') {
        $err = 'Name is required.';
    } elseif ($dateStr !== '' && !preg_match('/^\d{4}-\d{2}-\d{2}$/', $dateStr)) {
        $err = 'Invalid date.';
    } else {
        $pdo->prepare('INSERT INTO exams (facility_id, name, description, exam_date, status, created_by) VALUES (?, ?, ?, ?, ?, ?)')
            ->execute([$facId, $name, $desc, $dateStr ?: null, $status, $user['id']]);
        $newId = (int)$pdo->lastInsertId();
        audit_log($pdo, 'exam_create', ['id' => $newId, 'name' => $name]);
        header('Location: exam_edit.php?id=' . $newId);
        exit;
    }
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['delete_exam'])) {
    csrf_require();
    $id = v_int($_POST['delete_exam'], 1);
    $check = $pdo->prepare('SELECT facility_id FROM exams WHERE id = ?');
    $check->execute([$id]); $row = $check->fetch();
    if ($row && perms_owns_facility($user, $row['facility_id'])) {
        $pdo->prepare('UPDATE exams SET deleted_at = NOW() WHERE id = ?')->execute([$id]);
        audit_log($pdo, 'exam_soft_delete', ['id' => $id]);
        $msg = 'Exam moved to trash.';
    } else { $err = 'Permission denied.'; }
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['restore_exam'])) {
    csrf_require();
    $id = v_int($_POST['restore_exam'], 1);
    $check = $pdo->prepare('SELECT facility_id FROM exams WHERE id = ?');
    $check->execute([$id]); $row = $check->fetch();
    if ($row && perms_owns_facility($user, $row['facility_id'])) {
        $pdo->prepare('UPDATE exams SET deleted_at = NULL WHERE id = ?')->execute([$id]);
        audit_log($pdo, 'exam_restore', ['id' => $id]);
        $msg = 'Exam restored.';
    }
}

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

$showDeleted = isset($_GET['show_deleted']) && $_GET['show_deleted'] === '1';
$where = [];
$params = [];
if (!$showDeleted) $where[] = 'e.deleted_at IS NULL';
if (!$isSuper && $user['facility_id']) {
    $where[]  = 'e.facility_id = ?';
    $params[] = $user['facility_id'];
}
$whereSql = $where ? 'WHERE ' . implode(' AND ', $where) : '';
$stmt = $pdo->prepare("SELECT e.*, f.name AS facility_name, f.code AS facility_code FROM exams e LEFT JOIN facilities f ON e.facility_id = f.id $whereSql ORDER BY e.exam_date DESC, e.id DESC");
$stmt->execute($params);
$exams = $stmt->fetchAll();
?>
<h2>Exam Days</h2>
<p class="muted">An "Exam" = one OSCE event with multiple stations. Coordinators see only their facility's exams.</p>

<?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>Create New Exam</h3>
<form method="post">
    <?php echo csrf_field(); ?>
    <input type="hidden" name="create_exam" value="1">
    <div class="form-row">
        <div class="field"><label>Name *</label><input type="text" name="name" required></div>
        <div class="field"><label>Exam Date</label><input type="date" name="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 echo ucfirst($s); ?></option>
                <?php endforeach; ?>
            </select>
        </div>
        <?php if ($isSuper): ?>
        <div class="field"><label>Facility</label>
            <select name="facility_id">
                <option value="">Global</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>
    <div class="field mb-2"><label>Description</label><textarea name="description" rows="2"></textarea></div>
    <button type="submit" class="btn btn-primary">Create &amp; Configure</button>
</form>

<h3 class="mt-3">Existing Exams</h3>
<p><a href="exams.php?show_deleted=<?php echo $showDeleted ? '0' : '1'; ?>" class="btn btn-sm"><?php echo $showDeleted ? '◀ Hide deleted' : '🗑 Show deleted'; ?></a></p>
<div class="table-wrap">
<table class="data">
    <thead><tr><th>ID</th><th>Name</th><th>Date</th><th>Facility</th><th>Status</th><th>Stations</th><th>Actions</th></tr></thead>
    <tbody>
    <?php foreach ($exams as $e):
        $cnt = $pdo->prepare('SELECT COUNT(*) AS c FROM exam_stations WHERE exam_id = ?');
        $cnt->execute([$e['id']]);
        $nStations = (int)$cnt->fetch()['c'];
    ?>
        <tr<?php if ($e['deleted_at']) echo ' style="opacity:.55"'; ?>>
            <td data-label="ID"><?php echo (int)$e['id']; ?></td>
            <td data-label="Name"><?php echo h($e['name']); ?></td>
            <td data-label="Date"><?php echo h($e['exam_date'] ?? ''); ?></td>
            <td data-label="Facility"><?php echo $e['facility_name'] ? h($e['facility_name']) : '<em>Global</em>'; ?></td>
            <td data-label="Status"><span class="badge badge-<?php echo h($e['status']); ?>"><?php echo strtoupper(h($e['status'])); ?></span></td>
            <td data-label="Stations" class="num"><?php echo $nStations; ?></td>
            <td>
                <?php if (!$e['deleted_at']): ?>
                    <a href="exam_edit.php?id=<?php echo (int)$e['id']; ?>" class="btn btn-sm">Configure</a>
                    <a href="assignments.php?exam_id=<?php echo (int)$e['id']; ?>" class="btn btn-sm">Assignments</a>
                    <form method="post" style="display:inline" onsubmit="return confirm('Move this exam to trash?');">
                        <?php echo csrf_field(); ?>
                        <button type="submit" name="delete_exam" value="<?php echo (int)$e['id']; ?>" class="btn btn-sm btn-danger">Delete</button>
                    </form>
                <?php else: ?>
                    <form method="post" style="display:inline">
                        <?php echo csrf_field(); ?>
                        <button type="submit" name="restore_exam" value="<?php echo (int)$e['id']; ?>" class="btn btn-sm">Restore</button>
                    </form>
                <?php endif; ?>
            </td>
        </tr>
    <?php endforeach; ?>
    </tbody>
</table>
</div>

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