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

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

// ---- SOFT DELETE / RESTORE ----
if ($_SERVER['REQUEST_METHOD'] === 'POST' && $isSuper && isset($_POST['delete_id'])) {
    csrf_require();
    $delId = v_int($_POST['delete_id'], 1);
    if ($delId > 0) {
        $pdo->prepare("UPDATE attempts SET deleted_at = NOW() WHERE id = ?")->execute([$delId]);
        audit_log($pdo, 'attempt_soft_delete', ['id' => $delId]);
        header('Location: export_grades.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 attempts SET deleted_at = NULL WHERE id = ?")->execute([$rId]);
        audit_log($pdo, 'attempt_restore', ['id' => $rId]);
        header('Location: export_grades.php?msg=restored');
        exit;
    }
}
// Bulk soft-delete selected attempts (super admin only).
if ($_SERVER['REQUEST_METHOD'] === 'POST' && $isSuper && isset($_POST['bulk_delete_attempts'])) {
    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 attempts SET deleted_at = NOW() WHERE id IN ($in) AND deleted_at IS NULL")
            ->execute($ids);
        audit_log($pdo, 'attempt_bulk_delete', ['ids' => $ids, 'count' => count($ids)]);
    }
    header('Location: export_grades.php?msg=bulk_deleted');
    exit;
}

// filters
$candNo   = v_clean_string($_GET['candidate_number'] ?? '', 50);
$candName = v_clean_string($_GET['candidate_name']   ?? '', 100);
$formIdF  = v_int($_GET['form_id'] ?? 0, 0);
$stationF = v_clean_string($_GET['station'] ?? '', 100);
$dateFrom = v_clean_string($_GET['date_from'] ?? '', 20);
$dateTo   = v_clean_string($_GET['date_to']   ?? '', 20);
$showDeleted = isset($_GET['show_deleted']) && $_GET['show_deleted'] === '1';

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

$baseSql = "
    SELECT a.id, a.examiner_id, a.deleted_at,
           c.candidate_number, c.name AS candidate_name, c.barcode,
           fac.name AS facility_name,
           f.name AS form_name,
           a.station_name, a.total_score, a.max_score, a.percentage, a.final_grade, a.global_comment,
           u.full_name AS examiner_name,
           a.created_at
    FROM attempts a
    JOIN candidates c ON a.candidate_id = c.id
    JOIN facilities fac ON c.facility_id = fac.id
    JOIN forms f ON a.form_id = f.id
    JOIN users u ON a.examiner_id = u.id
";
$where = [];
$params = [];
if (!$showDeleted) $where[] = 'a.deleted_at IS NULL';
if (!$canManage) {
    // Examiners only see their own attempts
    $where[]  = 'a.examiner_id = ?';
    $params[] = (int)$user['id'];
} elseif (!$isSuper && $facilityId) {
    // Coordinators see their facility
    $where[]  = 'c.facility_id = ?';
    $params[] = $facilityId;
}
if ($candNo   !== '') { $where[] = 'c.candidate_number LIKE ?'; $params[] = "%$candNo%"; }
if ($candName !== '') { $where[] = 'c.name LIKE ?';             $params[] = "%$candName%"; }
if ($formIdF > 0)     { $where[] = 'a.form_id = ?';             $params[] = $formIdF; }
if ($stationF !== '') { $where[] = 'a.station_name LIKE ?';     $params[] = "%$stationF%"; }
if ($dateFrom !== '' && preg_match('/^\d{4}-\d{2}-\d{2}$/', $dateFrom)) { $where[] = 'DATE(a.created_at) >= ?'; $params[] = $dateFrom; }
if ($dateTo   !== '' && preg_match('/^\d{4}-\d{2}-\d{2}$/', $dateTo))   { $where[] = 'DATE(a.created_at) <= ?'; $params[] = $dateTo; }

$sql = $baseSql . ($where ? ' WHERE ' . implode(' AND ', $where) : '') . ' ORDER BY a.created_at DESC';

if (isset($_GET['download']) && $_GET['download'] === 'csv') {
    header('Content-Type: text/csv; charset=utf-8');
    header('Content-Disposition: attachment; filename=osce_grades_' . date('Ymd_His') . '.csv');
    $out = fopen('php://output', 'w');
    fputcsv($out, ['OSCE Nexus™ Grades Export', 'Copyright © ' . date('Y') . ' Khalaf Almazrouei']);
    fputcsv($out, []);
    fputcsv($out, ['Attempt ID','Candidate Number','Candidate Name','Barcode','Facility','Form','Station','Total','Max','Percent','Final Grade','Global Comment','Examiner','DateTime']);
    $stmt = $pdo->prepare($sql);
    $stmt->execute($params);
    while ($r = $stmt->fetch()) {
        fputcsv($out, [
            $r['id'], $r['candidate_number'], $r['candidate_name'], $r['barcode'], $r['facility_name'],
            $r['form_name'], $r['station_name'], $r['total_score'], $r['max_score'], $r['percentage'],
            $r['final_grade'], $r['global_comment'], $r['examiner_name'], $r['created_at'],
        ]);
    }
    fclose($out);
    audit_log($pdo, 'grades_export', []);
    exit;
}

require_once __DIR__ . '/header.php';

$stmt = $pdo->prepare($sql);
$stmt->execute($params);
$rows = $stmt->fetchAll();

$csvUrl = 'export_grades.php?' . http_build_query(array_merge($_GET, ['download' => 'csv']));
?>
<h2>Grades / Attempts</h2>

<?php
$flash = $_GET['msg'] ?? '';
if ($flash === 'deleted')      echo '<div class="alert alert-success">Attempt moved to trash.</div>';
if ($flash === 'restored')     echo '<div class="alert alert-success">Attempt restored.</div>';
if ($flash === 'bulk_deleted') echo '<div class="alert alert-success">Selected attempts moved to trash.</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>Candidate Name</label><input type="text" name="candidate_name" value="<?php echo h($candName); ?>"></div>
        <div class="field"><label>Form</label>
            <select name="form_id">
                <option value="0">All</option>
                <?php foreach ($allForms as $f): ?>
                    <option value="<?php echo (int)$f['id']; ?>" <?php if ($formIdF==(int)$f['id']) echo 'selected'; ?>><?php echo h($f['name']); ?></option>
                <?php endforeach; ?>
            </select>
        </div>
        <div class="field"><label>Station</label><input type="text" name="station" value="<?php echo h($stationF); ?>"></div>
        <div class="field"><label>Date from</label><input type="date" name="date_from" value="<?php echo h($dateFrom); ?>"></div>
        <div class="field"><label>Date to</label><input type="date" name="date_to" value="<?php echo h($dateTo); ?>"></div>
        <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_grades.php" class="btn">Clear</a>
    <a href="<?php echo h($csvUrl); ?>" class="btn btn-primary">Download CSV</a>
</form>

<?php if (!$rows): ?>
    <p>No attempts recorded for this filter.</p>
<?php else: ?>

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

<div class="table-wrap">
<table class="data">
    <thead><tr>
        <?php if ($isSuper): ?><th><input type="checkbox" id="grade-check-all" title="Select all"></th><?php endif; ?>
        <th>ID</th><th>Candidate #</th><th>Name</th><th>Barcode</th><th>Facility</th>
        <th>Form</th><th>Station</th><th>Total/Max</th><th>%</th><th>Grade</th>
        <th>Examiner</th><th>When</th><th>Actions</th>
    </tr></thead>
    <tbody>
    <?php foreach ($rows as $r): $canEdit = $isSuper || ((int)$user['id'] === (int)$r['examiner_id']); ?>
        <tr<?php if ($r['deleted_at']) echo ' style="opacity:.55"'; ?>>
            <?php if ($isSuper): ?>
            <td><?php if (!$r['deleted_at']): ?><input type="checkbox" class="grade-check" name="ids[]" value="<?php echo (int)$r['id']; ?>" form="bulk-del-grades"><?php endif; ?></td>
            <?php endif; ?>
            <td data-label="ID"><?php echo (int)$r['id']; ?></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="Barcode"><code><?php echo h($r['barcode']); ?></code></td>
            <td data-label="Facility"><?php echo h($r['facility_name']); ?></td>
            <td data-label="Form"><?php echo h($r['form_name']); ?></td>
            <td data-label="Station"><?php echo h($r['station_name']); ?></td>
            <td data-label="Total/Max" class="num"><?php echo (int)$r['total_score'] . ' / ' . (int)$r['max_score']; ?></td>
            <td data-label="%" class="num"><?php echo h($r['percentage']); ?></td>
            <td data-label="Grade"><?php echo h($r['final_grade']); ?></td>
            <td data-label="Examiner"><?php echo h($r['examiner_name']); ?></td>
            <td data-label="When"><?php echo h($r['created_at']); ?></td>
            <td>
                <?php if ($canEdit && !$r['deleted_at']): ?>
                    <a href="edit_attempt.php?id=<?php echo (int)$r['id']; ?>" class="btn btn-sm">Edit</a>
                <?php endif; ?>
                <?php if ($isSuper): ?>
                    <?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 attempt 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; ?>
                <?php endif; ?>
            </td>
        </tr>
    <?php endforeach; ?>
    </tbody>
</table>
</div>

<?php if ($isSuper): ?>
<script>
(function () {
    const all   = document.getElementById('grade-check-all');
    const count = document.getElementById('grade-sel-count');
    const boxes = () => document.querySelectorAll('.grade-check');
    function update() {
        const n = document.querySelectorAll('.grade-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.bulkConfirmGrades = function () {
        const n = document.querySelectorAll('.grade-check:checked').length;
        if (!n) { alert('Select at least one attempt first.'); return false; }
        return confirm('Move ' + n + ' selected attempt(s) to trash? You can restore them with "Show deleted".');
    };
})();
</script>
<?php endif; ?>
<?php endif; ?>

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