<?php
require_once '../../config/database.php';
require_once '../../config/auth.php';
require_once '../../config/rbac.php';
require_once '../../includes/functions.php';
require_once '../../includes/middleware.php';

// Check if user is instructor or admin
anyRoleMiddleware(['instructor', 'admin']);

$user = getUserContext();
$db = getDB();
$userId = $_SESSION['user_id'];

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    header('Location: index.php');
    exit;
}

try {
    $db->beginTransaction();

    // Get form data
    $title = trim($_POST['title'] ?? '');
    $examType = $_POST['exam_type'] ?? 'quiz';
    $description = trim($_POST['description'] ?? '');
    $instructions = trim($_POST['instructions'] ?? '');
    $courseId = !empty($_POST['course_id']) ? intval($_POST['course_id']) : null;
    $timeLimit = !empty($_POST['time_limit']) ? intval($_POST['time_limit']) : null;
    $passingScore = floatval($_POST['passing_score'] ?? 50);
    $maxAttempts = intval($_POST['max_attempts'] ?? 1);
    $shuffleQuestions = isset($_POST['shuffle_questions']) ? 1 : 0;
    $shuffleOptions = isset($_POST['shuffle_options']) ? 1 : 0;
    $showResults = isset($_POST['show_results']) ? 1 : 0;
    $showAnswers = isset($_POST['show_answers']) ? 1 : 0;
    $allowReview = isset($_POST['allow_review']) ? 1 : 0;
    $isProctored = isset($_POST['is_proctored']) ? 1 : 0;
    $startDate = !empty($_POST['start_date']) ? $_POST['start_date'] : null;
    $endDate = !empty($_POST['end_date']) ? $_POST['end_date'] : null;
    $action = $_POST['action'] ?? 'save_draft';

    // Get selected questions
    $questionIds = $_POST['question_ids'] ?? [];
    $questionOrders = $_POST['question_orders'] ?? [];
    $questionPoints = $_POST['question_points'] ?? [];

    // Validate required fields
    if (empty($title)) {
        throw new Exception('Exam title is required');
    }

    if (empty($questionIds) && $action === 'publish') {
        throw new Exception('At least one question must be selected to publish the exam');
    }

    // Calculate total points
    $totalPoints = 0;
    if (!empty($questionIds)) {
        foreach ($questionIds as $index => $questionId) {
            $totalPoints += floatval($questionPoints[$index] ?? 1);
        }
    }

    // Generate slug
    $slug = strtolower(str_replace(' ', '-', preg_replace('/[^A-Za-z0-9\s]/', '', $title)));
    $originalSlug = $slug;
    $counter = 1;

    // Ensure unique slug
    while (true) {
        $stmt = $db->prepare("SELECT id FROM exams WHERE slug = ? AND instructor_id = ?");
        $stmt->execute([$slug, $userId]);
        if (!$stmt->fetch()) break;

        $slug = $originalSlug . '-' . $counter;
        $counter++;
    }

    // Determine status
    $status = 'draft';
    if ($action === 'publish') {
        $status = 'published';
    }

    // Prepare security and proctoring settings
    $securitySettings = [];
    $proctoringSettings = [];

    if ($isProctored) {
        $proctoringSettings = [
            'camera_required' => true,
            'screen_monitoring' => true,
            'browser_lockdown' => true,
            'tab_switch_detection' => true,
            'copy_paste_prevention' => true
        ];
    }

    $securitySettingsJson = json_encode($securitySettings);
    $proctoringSettingsJson = json_encode($proctoringSettings);

    // Insert exam
    $stmt = $db->prepare("
        INSERT INTO exams (
            title, slug, description, course_id, instructor_id, exam_type,
            total_points, passing_score, time_limit, max_attempts,
            shuffle_questions, shuffle_options, show_results, show_answers,
            allow_review, start_date, end_date, is_proctored,
            proctoring_settings, security_settings, instructions,
            status, created_at, updated_at
        ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NOW(), NOW())
    ");

    $stmt->execute([
        $title, $slug, $description, $courseId, $userId, $examType,
        $totalPoints, $passingScore, $timeLimit, $maxAttempts,
        $shuffleQuestions, $shuffleOptions, $showResults, $showAnswers,
        $allowReview, $startDate, $endDate, $isProctored,
        $proctoringSettingsJson, $securitySettingsJson, $instructions,
        $status
    ]);

    $examId = $db->lastInsertId();

    // Insert exam questions (only if questions are selected)
    if (!empty($questionIds)) {
        foreach ($questionIds as $index => $questionId) {
            $order = intval($questionOrders[$index] ?? ($index + 1));
            $points = floatval($questionPoints[$index] ?? 1);

            $stmt = $db->prepare("
                INSERT INTO exam_questions (exam_id, question_id, sort_order, points)
                VALUES (?, ?, ?, ?)
            ");
            $stmt->execute([$examId, $questionId, $order, $points]);
        }
    }

    $db->commit();

    // Set success message
    $_SESSION['success_message'] = 'Exam saved successfully!';

    // Redirect based on action
    if ($action === 'publish') {
        header('Location: index.php?status=published');
    } else {
        header('Location: edit.php?id=' . $examId);
    }
    exit;

} catch (Exception $e) {
    $db->rollBack();
    $_SESSION['error_message'] = 'Error saving exam: ' . $e->getMessage();
    header('Location: new.php');
    exit;
}
?>