<?php
session_start();
if (!isset($_SESSION['admin_logged_in']) || $_SESSION['admin_logged_in'] !== true) {
    header('Location: admin_login.php');
    exit;
}

// Database connection
require_once 'connectiondb.php';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $exam_name = $_POST['exam_name'] ?? '';
    $exam_code = $_POST['exam_code'] ?? '';
    $duration = $_POST['duration'] ?? null;
    $exam_month = $_POST['exam_month'] ?? null;
    $allowed_attempts = $_POST['allowed_attempts'] ?? null;

    if (empty($exam_name) || empty($exam_code) || empty($exam_month) || empty($allowed_attempts)) {
        $error = "Please fill all required fields including exam month and allowed attempts.";
    } else {
        try {
            // Check if exam_code already exists
            $stmt = $pdo->prepare("SELECT id FROM exams WHERE exam_code = ?");
            $stmt->execute([$exam_code]);
            if ($stmt->fetch()) {
                $error = "Exam code already exists. Please choose a different exam code.";
            } else {
                // Insert exam
                $stmt = $pdo->prepare("INSERT INTO exams (exam_name, exam_code, duration, exam_month, allowed_attempts) VALUES (?, ?, ?, ?, ?)");
                $stmt->execute([$exam_name, $exam_code, $duration, $exam_month, $allowed_attempts]);
                $exam_id = $pdo->lastInsertId();

                // Process CSV file if uploaded
                if (isset($_FILES['csv_file']) && $_FILES['csv_file']['error'] === UPLOAD_ERR_OK) {
                    $fileTmpPath = $_FILES['csv_file']['tmp_name'];
                    if (($handle = fopen($fileTmpPath, "r")) !== false) {
                        $rowIndex = 0;
                        while (($data = fgetcsv($handle, 1000, ",")) !== false) {
                            if ($rowIndex === 0) {
                                // Skip header row
                                $rowIndex++;
                                continue;
                            }

                            // Extract data from CSV row
                            $question_text = trim($data[0] ?? '');
                            $options = array_slice($data, 1, 4);
                            $correct_option_raw = $data[5] ?? '';

                            // Validate data
                            if (empty($question_text) || count($options) < 4 || $correct_option_raw === '') {
                                $rowIndex++;
                                continue;
                            }

                            // Convert correct option to zero-based index
                            $correct_option = intval($correct_option_raw) - 1;

                            // Validate correct_option index range
                            if ($correct_option < 0 || $correct_option >= count($options)) {
                                $rowIndex++;
                                continue;
                            }

                            // Insert question
                            $stmt = $pdo->prepare("INSERT INTO questions (exam_id, question_text) VALUES (?, ?)");
                            $stmt->execute([$exam_id, $question_text]);
                            $question_id = $pdo->lastInsertId();

                            // Insert options
                            $stmt = $pdo->prepare("INSERT INTO options (question_id, option_text, is_correct) VALUES (?, ?, ?)");
                            foreach ($options as $key => $option_text) {
                                $is_correct = ($key === $correct_option) ? 1 : 0;
                                $stmt->execute([$question_id, $option_text, $is_correct]);
                            }

                            $rowIndex++;
                        }
                        fclose($handle);
                        $success = "Exam and questions uploaded successfully.";
                    } else {
                        $error = "Failed to open uploaded CSV file.";
                    }
                } else {
                    $success = "Exam created successfully without CSV upload.";
                }
            }
        } catch (PDOException $e) {
            $error = "Database error: " . $e->getMessage();
            error_log($error);
        }
    }
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <title>Create Exam - Admin Panel</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet" 
        integrity="sha384-ENjdO4Dr2bkBIFxQpeoYz1HIcje39Wm4jDKdf19U8gI4ddQ3GYNS7NTKfAdVQSZe" crossorigin="anonymous">
    <style>
        body {
            background: linear-gradient(135deg,rgb(16, 99, 253) 0%,rgb(255, 255, 255) 100%);
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            color: #333;
        }
        .content-area {
            margin-top: 80px;
            padding: 30px 40px;
            min-height: calc(100vh - 80px);
            background: #ffffffcc;
            border-radius: 12px;
            max-width: 650px;
            margin-left: auto;
            margin-right: auto;
            box-shadow: 0 8px 24px rgba(0,0,0,0.15);
            backdrop-filter: blur(10px);
        }
        h2 {
            text-align: center;
            margin-bottom: 30px;
            color: #1a237e;
            font-weight: 800;
            font-size: 2.5rem;
            letter-spacing: 2px;
            text-shadow: 1px 1px 3px rgba(0,0,0,0.2);
        }
        label {
            font-weight: 700;
            color: #1a237e;
            font-size: 1.1rem;
        }
        input.form-control, select.form-select {
            border: 2px solid #1a237e;
            border-radius: 8px;
            padding: 10px 12px;
            font-size: 1rem;
            transition: all 0.4s ease;
        }
        input.form-control:focus, select.form-select:focus {
            border-color: #ff6f00;
            box-shadow: 0 0 12px #ff6f00aa;
            outline: none;
            background-color: #fff8e1;
        }
        button.btn-success, button.btn-primary {
            width: 100%;
            padding: 14px;
            font-size: 1.2rem;
            font-weight: 700;
            border-radius: 10px;
            border: none;
            cursor: pointer;
            transition: all 0.4s ease;
            box-shadow: 0 4px 12px rgba(0,0,0,0.1);
        }
        button.btn-success {
            background-color: #43a047;
            color: white;
        }
        button.btn-success:hover {
            background-color: #2e7d32;
            box-shadow: 0 6px 16px rgba(46,125,50,0.6);
        }
        button.btn-primary {
            background-color: #1a237e;
            color: white;
            margin-top: 10px;
        }
        button.btn-primary:hover {
            background-color: #0d1451;
            box-shadow: 0 6px 16px rgba(13,20,81,0.6);
        }
        a.text-danger {
            display: block;
            text-align: center;
            font-weight: 700;
            margin-top: 25px;
            font-size: 1.1rem;
            color: #b71c1c;
            transition: color 0.3s ease;
        }
        a.text-danger:hover {
            color: #7f0000;
            text-decoration: none;
        }
        p.text-danger, p.text-success {
            text-align: center;
            font-size: 1.2rem;
            margin-bottom: 25px;
            font-weight: 700;
            text-shadow: 1px 1px 2px rgba(0,0,0,0.1);
        }
    </style>
</head>
<body>

    <style>
        .navbar-container {
            padding: 0;
            width: 100%;
            z-index: 1050;
            box-shadow: 0 2px 8px rgba(0,0,0,0.15);
            overflow-x: auto !important;
            white-space: nowrap !important;
        }
        .navbar-inner {
            max-width: 1200px;
            margin: 0 auto;
            padding: 0 20px;
            display: flex !important;
            flex-wrap: nowrap !important;
            overflow-x: auto !important;
            white-space: nowrap !important;
        }
        /* Navbar text styling */
        .navbar-container .navbar, 
        .navbar-container .navbar-nav .nav-link,
        .navbar-container .navbar-brand {
            color: #ffffff !important;
            font-weight: 600;
            font-size: 1.1rem;
            text-shadow: 0 1px 2px rgba(0,0,0,0.3);
        }
        .navbar-container .navbar-nav .nav-link:hover {
            color: #ffca28 !important;
            text-decoration: underline;
        }
        /* Remove bullets from navbar ul */
        .navbar-container .navbar-nav {
            list-style-type: none !important;
            padding-left: 0 !important;
            margin-bottom: 0 !important;
            display: flex !important;
            flex-direction: row !important;
            align-items: center !important;
            gap: 1rem;
        }
        .navbar-container .navbar {
            display: flex !important;
            flex-wrap: nowrap !important;
            align-items: center !important;
            justify-content: space-between !important;
            overflow-x: auto !important;
            white-space: nowrap !important;
        }
        .navbar-container .navbar-nav .nav-item {
            white-space: nowrap !important;
        }
        .content-area {
            margin-top: 70px;
            padding: 30px 40px;
            min-height: calc(100vh - 70px);
            background: #ffffffcc;
            border-radius: 12px;
            max-width: 650px;
            margin-left: auto;
            margin-right: auto;
            box-shadow: 0 8px 24px rgba(0,0,0,0.15);
            backdrop-filter: blur(10px);
        }
    </style>
    <div>
        <div class="navbar-container bg-primary fixed-top">
        <div class="navbar-inner d-flex align-items-center">
            <?php include 'navbar.php'; ?>
        </div>
        </div>
        <div class="content-area">
            <h2>Create Exam</h2>
            <?php if (!empty($error)) { echo "<p class='text-danger fw-semibold'>$error</p>"; } ?>
            <?php if (!empty($success)) { echo "<p class='text-success fw-semibold'>$success</p>"; } ?>
            <form method="POST" action="create_exam.php" enctype="multipart/form-data">
                <div class="mb-3">
                    <label for="exam_name" class="form-label">Exam Name:</label>
                    <input type="text" id="exam_name" name="exam_name" class="form-control" required>
                </div>
                <div class="mb-3">
                    <label for="exam_code" class="form-label">Exam Code:</label>
                    <input type="text" id="exam_code" name="exam_code" class="form-control" required>
                </div>
                <div class="mb-3">
                    <label for="exam_month" class="form-label">Exam Month:</label>
                    <select id="exam_month" name="exam_month" class="form-select" required>
                        <option value="" disabled selected>Select month</option>
                        <option value="January">January</option>
                        <option value="February">February</option>
                        <option value="March">March</option>
                        <option value="April">April</option>
                        <option value="May">May</option>
                        <option value="June">June</option>
                        <option value="July">July</option>
                        <option value="August">August</option>
                        <option value="September">September</option>
                        <option value="October">October</option>
                        <option value="November">November</option>
                        <option value="December">December</option>
                    </select>
                </div>
                <div class="mb-3">
                    <label for="allowed_attempts" class="form-label">Allowed Attempts:</label>
                    <input type="number" id="allowed_attempts" name="allowed_attempts" min="1" max="10" placeholder="Enter allowed attempts" class="form-control" required>
                </div>
                <div class="mb-3">
                    <label for="duration" class="form-label">Duration (minutes):</label>
                    <input type="number" id="duration" name="duration" min="1" max="600" placeholder="Enter duration in minutes" class="form-control">
                </div>
                <div class="mb-3">
                    <label for="csv_file" class="form-label">Upload CSV File:</label>
                    <input type="file" id="csv_file" name="csv_file" accept=".csv" class="form-control">
                    <a href="templates/exam_template.csv" download class="d-block mt-2">Download CSV Template</a>
                </div>
                <button type="submit" class="btn btn-primary">Create Exam</button>
            </form>
            <br>
            <a href="admin_logout.php" class="text-danger text-decoration-underline">Logout</a>
        </div>
    </div>
</body>
</html>
