<?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
    $examId = $_POST['exam_id'] ?? null;
    $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;
    $status = $_POST['status'] ?? 'draft';
    $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;

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

    // Validate required fields
    if (!$examId || empty($title)) {
        throw new Exception('Required fields are missing');
    }

    // Check if user owns the exam
    $stmt = $db->prepare("SELECT id FROM exams WHERE id = ? AND (instructor_id = ? OR ?)");
    $stmt->execute([$examId, $userId, hasRole('admin') ? true : false]);
    if (!$stmt->fetch()) {
        throw new Exception('Exam not found or access denied');
    }

    // Validate publishing requirements
    if ($status === 'published' && empty($questionIds)) {
        throw new Exception('Cannot publish an exam without questions. Please add at least one question before publishing.');
    }

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

    // 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);

    // Update exam
    $stmt = $db->prepare("
        UPDATE exams SET
            title = ?, description = ?, course_id = ?, exam_type = ?, status = ?,
            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 = ?,
            updated_at = NOW()
        WHERE id = ?
    ");

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

    // Delete existing exam questions
    $stmt = $db->prepare("DELETE FROM exam_questions WHERE exam_id = ?");
    $stmt->execute([$examId]);

    // Insert updated exam questions
    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 updated successfully!';

    // Redirect back to edit page
    header('Location: edit.php?id=' . $examId);
    exit;

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