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

// Set JSON response header
header('Content-Type: application/json');

// Check authentication
if (!isLoggedIn()) {
    http_response_code(401);
    echo json_encode(['error' => 'Authentication required']);
    exit;
}

// Check if user is instructor or admin
if (!hasAnyRole(['instructor', 'admin'])) {
    http_response_code(403);
    echo json_encode(['error' => 'Access denied']);
    exit;
}

$db = getDB();
$userId = $_SESSION['user_id'];
$method = $_SERVER['REQUEST_METHOD'];

try {
    switch ($method) {
        case 'GET':
            // Get exams with optional filters
            $search = $_GET['search'] ?? '';
            $type = $_GET['type'] ?? '';
            $status = $_GET['status'] ?? '';
            $course = $_GET['course'] ?? '';
            $limit = isset($_GET['limit']) ? intval($_GET['limit']) : 50;
            $offset = isset($_GET['offset']) ? intval($_GET['offset']) : 0;

            $query = "
                SELECT e.*, c.title as course_title,
                       COUNT(eq.id) as question_count,
                       COUNT(DISTINCT ea.student_id) as attempt_count
                FROM exams e
                LEFT JOIN courses c ON e.course_id = c.id
                LEFT JOIN exam_questions eq ON e.id = eq.exam_id
                LEFT JOIN exam_attempts ea ON e.id = ea.exam_id
                WHERE e.instructor_id = ?
            ";

            $params = [$userId];

            if (!empty($search)) {
                $query .= " AND (e.title LIKE ? OR e.description LIKE ?)";
                $params[] = "%$search%";
                $params[] = "%$search%";
            }

            if (!empty($type)) {
                $query .= " AND e.exam_type = ?";
                $params[] = $type;
            }

            if (!empty($status)) {
                $query .= " AND e.status = ?";
                $params[] = $status;
            }

            if (!empty($course)) {
                $query .= " AND e.course_id = ?";
                $params[] = $course;
            }

            $query .= " GROUP BY e.id ORDER BY e.created_at DESC LIMIT ? OFFSET ?";
            $params[] = $limit;
            $params[] = $offset;

            $stmt = $db->prepare($query);
            $stmt->execute($params);
            $exams = $stmt->fetchAll(PDO::FETCH_ASSOC);

            // Process exams to decode JSON fields
            foreach ($exams as &$exam) {
                $exam['proctoring_settings'] = json_decode($exam['proctoring_settings'], true) ?: [];
                $exam['security_settings'] = json_decode($exam['security_settings'], true) ?: [];
            }

            echo json_encode([
                'success' => true,
                'data' => $exams,
                'meta' => [
                    'total' => count($exams),
                    'limit' => $limit,
                    'offset' => $offset
                ]
            ]);
            break;

        case 'POST':
            // Create new exam
            $data = json_decode(file_get_contents('php://input'), true);

            if (!$data) {
                throw new Exception('Invalid JSON data');
            }

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

            if (empty($data['question_ids']) || !is_array($data['question_ids'])) {
                throw new Exception('At least one question must be selected');
            }

            $db->beginTransaction();

            // Calculate total points
            $totalPoints = 0;
            if (isset($data['question_points']) && is_array($data['question_points'])) {
                foreach ($data['question_points'] as $points) {
                    $totalPoints += floatval($points);
                }
            }

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

            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++;
            }

            // 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([
                $data['title'],
                $slug,
                $data['description'] ?? '',
                $data['course_id'] ?? null,
                $userId,
                $data['exam_type'] ?? 'quiz',
                $totalPoints,
                $data['passing_score'] ?? 50,
                $data['time_limit'] ?? null,
                $data['max_attempts'] ?? 1,
                $data['shuffle_questions'] ?? false,
                $data['shuffle_options'] ?? false,
                $data['show_results'] ?? true,
                $data['show_answers'] ?? false,
                $data['allow_review'] ?? true,
                $data['start_date'] ?? null,
                $data['end_date'] ?? null,
                $data['is_proctored'] ?? false,
                json_encode($data['proctoring_settings'] ?? []),
                json_encode($data['security_settings'] ?? []),
                $data['instructions'] ?? '',
                $data['status'] ?? 'draft'
            ]);

            $examId = $db->lastInsertId();

            // Insert exam questions
            if (isset($data['question_ids']) && isset($data['question_points'])) {
                foreach ($data['question_ids'] as $index => $questionId) {
                    $points = floatval($data['question_points'][$index] ?? 1);
                    $order = $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();

            echo json_encode([
                'success' => true,
                'message' => 'Exam created successfully',
                'data' => ['id' => $examId]
            ]);
            break;

        default:
            http_response_code(405);
            echo json_encode(['error' => 'Method not allowed']);
    }

} catch (Exception $e) {
    http_response_code(500);
    echo json_encode(['error' => $e->getMessage()]);
}
?>