<?php
declare(strict_types=1);

/*
|--------------------------------------------------------------------------
| Exam Control Panel
|--------------------------------------------------------------------------
*/

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

$pdo = db();

requireTeacher();

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

$teacher = currentTeacher($pdo);

if (!$teacher) {

    teacherLogout();

    redirectTo('teacher/login.php');
}

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

$examId =
    (int)($_GET['exam_id'] ?? $_POST['exam_id'] ?? 0);

if (!$examId) {

    redirectTo('teacher/exams.php');
}

/*
|--------------------------------------------------------------------------
| Get Exam
|--------------------------------------------------------------------------
*/

$stmt = $pdo->prepare("

    SELECT
    e.*,
    c.title AS course_title

    FROM core_exams e

    INNER JOIN core_courses c
    ON c.id = e.course_id

    WHERE e.id = ?
    AND e.teacher_id = ?

    LIMIT 1

");

$stmt->execute([

    $examId,
    $teacher['id']

]);

$exam = $stmt->fetch();

if (!$exam) {

    redirectTo('teacher/exams.php');
}

/*
|--------------------------------------------------------------------------
| Actions
|--------------------------------------------------------------------------
*/

if (isPost()) {

    $action =
        trim($_POST['action'] ?? '');

    try {

        /*
        |--------------------------------------------------------------------------
        | Open Exam
        |--------------------------------------------------------------------------
        */

        if ($action === 'open_exam') {

            $updateStmt = $pdo->prepare("

                UPDATE core_exams

                SET status = 'open'

                WHERE id = ?

            ");

            $updateStmt->execute([

                $examId

            ]);

            $success =
                'Exam opened successfully.';
        }

        /*
        |--------------------------------------------------------------------------
        | Close Exam
        |--------------------------------------------------------------------------
        */

        elseif ($action === 'close_exam') {

            $updateStmt = $pdo->prepare("

                UPDATE core_exams

                SET status = 'closed'

                WHERE id = ?

            ");

            $updateStmt->execute([

                $examId

            ]);

            $success =
                'Exam closed successfully.';
        }

        /*
        |--------------------------------------------------------------------------
        | Reset Exam
        |--------------------------------------------------------------------------
        */

        elseif ($action === 'reset_exam') {

            $deleteStmt = $pdo->prepare("

                DELETE FROM core_exam_answers

                WHERE exam_id = ?

            ");

            $deleteStmt->execute([

                $examId

            ]);

            $success =
                'Exam answers reset successfully.';
        }

        /*
        |--------------------------------------------------------------------------
        | Extend Exam Time
        |--------------------------------------------------------------------------
        */

        elseif ($action === 'extend_time') {

            $extraMinutes =
                (int)($_POST['extra_minutes'] ?? 0);

            if ($extraMinutes > 0) {

                $newDuration =
                    (
                        (int)$exam['duration_minutes']
                        +
                        $extraMinutes
                    );

                $durationStmt = $pdo->prepare("

                    UPDATE core_exams

                    SET duration_minutes = ?

                    WHERE id = ?

                ");

                $durationStmt->execute([

                    $newDuration,
                    $examId

                ]);

                $success =
                    'Exam time extended successfully.';
            }
        }

        /*
        |--------------------------------------------------------------------------
        | Refresh Exam
        |--------------------------------------------------------------------------
        */

        $stmt->execute([

            $examId,
            $teacher['id']

        ]);

        $exam =
            $stmt->fetch();

        logActivity(

            $pdo,

            'teacher',

            (int)$teacher['id'],

            'Exam Control Action',

            'Updated exam control for exam ID: ' .
            $examId

        );

    } catch(Throwable $e) {

        if (APP_DEBUG) {

            die($e->getMessage());
        }

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

/*
|--------------------------------------------------------------------------
| Students Submitted
|--------------------------------------------------------------------------
*/

$submittedStudents = [];

if (
    tableExists(
        $pdo,
        'core_exam_answers'
    )
) {

    $answerStmt = $pdo->prepare("

        SELECT
        s.full_name,
        s.student_code,
        ea.created_at AS submitted_at

        FROM core_exam_answers ea

        INNER JOIN students s
        ON s.id = ea.student_id

        WHERE ea.exam_id = ?

        GROUP BY ea.student_id

        ORDER BY ea.created_at AS submitted_at DESC

    ");

    $answerStmt->execute([

        $examId

    ]);

    $submittedStudents =
        $answerStmt->fetchAll();
}

?>

<!DOCTYPE html>
<html lang="en">

<head>

<meta charset="UTF-8">

<meta
name="viewport"
content="width=device-width, initial-scale=1.0">

<title>
Exam Control
</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:#f3f6fb;

    color:#0f172a;
}

.page{

    padding:35px;
}

.topbar{

    display:flex;

    justify-content:space-between;

    align-items:center;

    margin-bottom:30px;
}

.title{

    font-size:42px;

    font-weight:900;
}

.back-btn{

    text-decoration:none;

    background:#eff6ff;

    color:#2563eb;

    padding:14px 22px;

    border-radius:18px;

    font-weight:900;
}

/*
|--------------------------------------------------------------------------
| Alerts
|--------------------------------------------------------------------------
*/

.alert{

    padding:18px 22px;

    border-radius:18px;

    margin-bottom:24px;

    font-weight:800;
}

.alert.error{

    background:#fef2f2;

    color:#dc2626;
}

.alert.success{

    background:#dcfce7;

    color:#16a34a;
}

/*
|--------------------------------------------------------------------------
| Hero
|--------------------------------------------------------------------------
*/

.hero{

    background:
    linear-gradient(
        135deg,
        #7c3aed,
        #4f46e5
    );

    color:#fff;

    border-radius:34px;

    padding:40px;

    margin-bottom:30px;
}

.hero h1{

    font-size:42px;

    margin-bottom:14px;

    font-weight:900;
}

.hero p{

    color:#ede9fe;

    line-height:2;
}

/*
|--------------------------------------------------------------------------
| Grid
|--------------------------------------------------------------------------
*/

.grid{

    display:grid;

    grid-template-columns:
    380px 1fr;

    gap:24px;
}

.card{

    background:#fff;

    border-radius:32px;

    padding:30px;

    border:1px solid #e2e8f0;

    box-shadow:
    0 18px 50px rgba(15,23,42,0.06);
}

.card h2{

    font-size:28px;

    margin-bottom:24px;

    font-weight:900;
}

/*
|--------------------------------------------------------------------------
| Status
|--------------------------------------------------------------------------
*/

.status{

    display:inline-block;

    padding:12px 18px;

    border-radius:999px;

    font-size:13px;

    font-weight:900;

    margin-top:10px;
}

.open{

    background:#dcfce7;

    color:#16a34a;
}

.closed{

    background:#fef2f2;

    color:#dc2626;
}

.scheduled{

    background:#ede9fe;

    color:#7c3aed;
}

/*
|--------------------------------------------------------------------------
| Buttons
|--------------------------------------------------------------------------
*/

.action-form{

    margin-bottom:16px;
}

.action-btn{

    width:100%;

    border:none;

    padding:18px;

    border-radius:20px;

    font-size:15px;

    font-weight:900;

    cursor:pointer;
}

.open-btn{

    background:#16a34a;

    color:#fff;
}

.close-btn{

    background:#dc2626;

    color:#fff;
}

.reset-btn{

    background:#0f172a;

    color:#fff;
}

.extend-btn{

    background:#7c3aed;

    color:#fff;
}

input[type="number"]{

    width:100%;

    padding:16px;

    border-radius:18px;

    border:1px solid #ddd6fe;

    margin-bottom:14px;

    font-size:15px;
}

/*
|--------------------------------------------------------------------------
| Students
|--------------------------------------------------------------------------
*/

.student{

    background:#f8fafc;

    border:1px solid #e2e8f0;

    border-radius:24px;

    padding:22px;

    margin-bottom:18px;
}

.student h3{

    font-size:22px;

    margin-bottom:10px;

    font-weight:900;
}

.student p{

    color:#64748b;

    line-height:1.8;
}

.empty{

    text-align:center;

    padding:60px;

    color:#64748b;
}

@media(max-width:1100px){

    .grid{

        grid-template-columns:1fr;
    }
}

@media(max-width:700px){

    .page{

        padding:20px;
    }

    .topbar{

        flex-direction:column;

        align-items:flex-start;

        gap:16px;
    }

    .title{

        font-size:34px;
    }

    .hero h1{

        font-size:34px;
    }
}

</style>

</head>

<body>

<div class="page">

    <div class="topbar">

        <h1 class="title">

            Exam Control

        </h1>

        <a
        href="exams.php"
        class="back-btn">

            ← Back

        </a>

    </div>

    <?php if($error): ?>

        <div class="alert error">

            <?php
            echo e($error);
            ?>

        </div>

    <?php endif; ?>

    <?php if($success): ?>

        <div class="alert success">

            <?php
            echo e($success);
            ?>

        </div>

    <?php endif; ?>

    <div class="hero">

        <h1>

            <?php
            echo e(
                $exam['title']
            );
            ?>

        </h1>

        <p>

            Course:
            <?php
            echo e(
                $exam['course_title']
            );
            ?>

            <br>

            Exam Code:
            <?php
            echo e(
                $exam['exam_code']
            );
            ?>

            <br>

            Duration:
            <?php
            echo e(
                (string)$exam['duration_minutes']
            );
            ?>

            Minutes

            <br>

            <span class="status <?php
            echo e(
                $exam['status']
            );
            ?>">

                <?php
                echo ucfirst(
                    $exam['status']
                );
                ?>

            </span>

        </p>

    </div>

    <div class="grid">

        <div class="card">

            <h2>

                Control Actions

            </h2>

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

                <input
                type="hidden"
                name="exam_id"
                value="<?php
                echo e(
                    (string)$examId
                );
                ?>">

                <input
                type="hidden"
                name="action"
                value="open_exam">

                <button
                type="submit"
                class="action-btn open-btn">

                    Open Exam

                </button>

            </form>

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

                <input
                type="hidden"
                name="exam_id"
                value="<?php
                echo e(
                    (string)$examId
                );
                ?>">

                <input
                type="hidden"
                name="action"
                value="close_exam">

                <button
                type="submit"
                class="action-btn close-btn">

                    Close Exam

                </button>

            </form>

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

                <input
                type="hidden"
                name="exam_id"
                value="<?php
                echo e(
                    (string)$examId
                );
                ?>">

                <input
                type="hidden"
                name="action"
                value="reset_exam">

                <button
                type="submit"
                class="action-btn reset-btn">

                    Reset Answers

                </button>

            </form>

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

                <input
                type="hidden"
                name="exam_id"
                value="<?php
                echo e(
                    (string)$examId
                );
                ?>">

                <input
                type="hidden"
                name="action"
                value="extend_time">

                <input
                type="number"
                name="extra_minutes"
                placeholder="Extra Minutes">

                <button
                type="submit"
                class="action-btn extend-btn">

                    Extend Time

                </button>

            </form>

        </div>

        <div class="card">

            <h2>

                Submitted Students

            </h2>

            <?php if($submittedStudents): ?>

                <?php foreach($submittedStudents as $student): ?>

                    <div class="student">

                        <h3>

                            <?php
                            echo e(
                                $student['full_name']
                            );
                            ?>

                        </h3>

                        <p>

                            Student Code:
                            <?php
                            echo e(
                                $student['student_code']
                            );
                            ?>

                        </p>

                        <p>

                            Submitted At:
                            <?php
                            echo formatDateTime(
                                $student['submitted_at']
                            );
                            ?>

                        </p>

                    </div>

                <?php endforeach; ?>

            <?php else: ?>

                <div class="empty">

                    No students submitted
                    the exam yet.

                </div>

            <?php endif; ?>

        </div>

    </div>

</div>

</body>
</html>