<?php
declare(strict_types=1);

require_once __DIR__ . '/../includes/config.php';
require_once __DIR__ . '/../includes/db.php';
require_once __DIR__ . '/../includes/functions.php';
require_once __DIR__ . '/../includes/admin-auth.php';

$pdo = db();
requireAdmin();

if (isPost()) { requireCsrf(); }

$success = '';
$error = '';

if (isset($_GET['generate']) && is_numeric($_GET['generate'])) {

    $examId = (int)$_GET['generate'];
    $newCode = 'SMI-ExamsUnit-' . random_int(10000, 99999);

    try {
        $stmt = $pdo->prepare("
            UPDATE core_exams
            SET exam_code = ?
            WHERE id = ?
        ");

        $stmt->execute([
            $newCode,
            $examId
        ]);

        $success = 'New exam code generated successfully.';

    } catch (Throwable $e) {
        if (APP_DEBUG) {
            die($e->getMessage());
        }

        $error = 'Failed to generate exam code.';
    }
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {

    $examId = (int)($_POST['exam_id'] ?? 0);
    $examCode = strtoupper(trim($_POST['exam_code'] ?? ''));

    if ($examId <= 0 || $examCode === '') {
        $error = 'Please select exam and enter code.';
    } else {
        try {
            $stmt = $pdo->prepare("
                UPDATE core_exams
                SET exam_code = ?
                WHERE id = ?
            ");

            $stmt->execute([
                $examCode,
                $examId
            ]);

            $success = 'Exam code updated successfully.';

        } catch (Throwable $e) {
            if (APP_DEBUG) {
                die($e->getMessage());
            }

            $error = 'Failed to update exam code.';
        }
    }
}

$exams = [];

if (tableExists($pdo, 'core_exams')) {
    $exams = $pdo->query("
        SELECT e.*, c.title AS course_title
        FROM core_exams e
        LEFT JOIN core_courses c ON c.id = e.course_id
        ORDER BY e.id DESC
    ")->fetchAll();
}

?>

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">

<title>Exam Codes</title>

<link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700;800;900&display=swap" rel="stylesheet">

<style>
*{margin:0;padding:0;box-sizing:border-box}
body{font-family:'Inter',sans-serif;background:#f1f5f9;color:#0f172a}
.page{padding:34px}
.topbar{display:flex;justify-content:space-between;align-items:center;margin-bottom:30px}
.page-title{font-size:42px;font-weight:900}
.back-btn{background:#dbeafe;color:#1d4ed8;text-decoration:none;padding:14px 20px;border-radius:18px;font-weight:900}
.card{background:#fff;border-radius:34px;padding:30px;border:1px solid #e2e8f0;box-shadow:0 18px 45px rgba(15,23,42,.05);margin-bottom:26px}
.card h2{font-size:30px;margin-bottom:22px;font-weight:900}
.grid{display:grid;grid-template-columns:1fr 1fr 220px;gap:18px;align-items:end}
.form-group label{display:block;margin-bottom:10px;font-weight:800}
.form-control{width:100%;padding:16px;border-radius:18px;border:1px solid #cbd5e1}
.submit-btn{border:none;background:linear-gradient(135deg,#7c3aed,#2563eb);color:#fff;padding:16px 24px;border-radius:18px;font-weight:900;cursor:pointer;width:100%}
.table-wrap{overflow:auto}
table{width:100%;border-collapse:collapse}
th{background:#f8fafc;padding:18px;text-align:left;font-size:13px;text-transform:uppercase;color:#64748b}
td{padding:18px;border-top:1px solid #e2e8f0;font-size:14px}
.code{display:inline-block;background:#ede9fe;color:#6d28d9;padding:10px 14px;border-radius:999px;font-weight:900}
.action-btn{display:inline-block;text-decoration:none;background:#dbeafe;color:#1d4ed8;padding:10px 14px;border-radius:14px;font-size:12px;font-weight:900}
.alert{padding:18px;border-radius:18px;margin-bottom:24px;font-weight:800}
.alert-success{background:#dcfce7;color:#166534}
.alert-danger{background:#fee2e2;color:#991b1b}
@media(max-width:900px){.grid{grid-template-columns:1fr}}
</style>
</head>

<body>

<div class="page">

    <div class="topbar">
        <h1 class="page-title">Exam Codes</h1>
        <a href="dashboard.php" class="back-btn">← Dashboard</a>
    </div>

    <?php if($success): ?>
        <div class="alert alert-success"><?php echo e($success); ?></div>
    <?php endif; ?>

    <?php if($error): ?>
        <div class="alert alert-danger"><?php echo e($error); ?></div>
    <?php endif; ?>

    <div class="card">

        <h2>Update Exam Code</h2>

        <form method="POST">
<?php echo csrfField(); ?>

            <div class="grid">

                <div class="form-group">
                    <label>Exam</label>
                    <select name="exam_id" class="form-control" required>
                        <option value="">Select Exam</option>

                        <?php foreach($exams as $exam): ?>
                            <option value="<?php echo e((string)$exam['id']); ?>">
                                <?php echo e($exam['title']); ?> —
                                <?php echo e($exam['course_title'] ?? 'N/A'); ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                </div>

                <div class="form-group">
                    <label>Exam Code</label>
                    <input
                    type="text"
                    name="exam_code"
                    class="form-control"
                    placeholder="SMI-ExamsUnit-12345"
                    required>
                </div>

                <button type="submit" class="submit-btn">
                    Save Code
                </button>

            </div>

        </form>

    </div>

    <div class="card">

        <h2>Exam Codes List</h2>

        <div class="table-wrap">

            <table>
                <thead>
                    <tr>
                        <th>Exam</th>
                        <th>Course</th>
                        <th>Code</th>
                        <th>Status</th>
                        <th>Generate</th>
                    </tr>
                </thead>

                <tbody>
                <?php if($exams): ?>
                    <?php foreach($exams as $exam): ?>
                        <tr>
                            <td><?php echo e($exam['title']); ?></td>

                            <td><?php echo e($exam['course_title'] ?? 'N/A'); ?></td>

                            <td>
                                <span class="code">
                                    <?php echo e($exam['exam_code'] ?? 'No Code'); ?>
                                </span>
                            </td>

                            <td><?php echo e(ucfirst($exam['status'] ?? 'scheduled')); ?></td>

                            <td>
                                <a
                                href="?generate=<?php echo e((string)$exam['id']); ?>"
                                class="action-btn"
                                onclick="return confirm('Generate new code for this exam?')">
                                    Generate New
                                </a>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                <?php else: ?>
                    <tr>
                        <td colspan="5">No exams found.</td>
                    </tr>
                <?php endif; ?>
                </tbody>
            </table>

        </div>

    </div>

</div>

</body>
</html>