<?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 exam assignments for a specific exam or all assignments
            $examId = $_GET['exam_id'] ?? null;

            if ($examId) {
                // Get students assigned to a specific exam
                $stmt = $db->prepare("
                    SELECT ea.*, u.username, u.email, up.first_name, up.last_name,
                           CASE WHEN ea.id IS NOT NULL THEN 1 ELSE 0 END as is_assigned
                    FROM users u
                    LEFT JOIN user_profiles up ON u.id = up.user_id
                    LEFT JOIN exam_access ea ON u.id = ea.student_id AND ea.exam_id = ?
                    WHERE u.role = 'student'
                    ORDER BY COALESCE(up.last_name, u.username), COALESCE(up.first_name, '')
                ");
                $stmt->execute([$examId]);
                $assignments = $stmt->fetchAll(PDO::FETCH_ASSOC);

                echo json_encode([
                    'success' => true,
                    'data' => $assignments
                ]);
            } else {
                // Get all exam assignments for instructor's exams
                $stmt = $db->prepare("
                    SELECT ea.*, e.title as exam_title, u.username, u.email, up.first_name, up.last_name
                    FROM exam_access ea
                    JOIN exams e ON ea.exam_id = e.id
                    JOIN users u ON ea.student_id = u.id
                    LEFT JOIN user_profiles up ON u.id = up.user_id
                    WHERE e.instructor_id = ?
                    ORDER BY ea.created_at DESC
                ");
                $stmt->execute([$userId]);
                $assignments = $stmt->fetchAll(PDO::FETCH_ASSOC);

                echo json_encode([
                    'success' => true,
                    'data' => $assignments
                ]);
            }
            break;

        case 'POST':
            // Assign or unassign exam to/from student
            $data = json_decode(file_get_contents('php://input'), true);

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

            $examId = $data['exam_id'] ?? null;
            $studentId = $data['student_id'] ?? null;
            $action = $data['action'] ?? null; // 'assign' or 'unassign'

            if (!$examId || !$studentId || !$action) {
                throw new Exception('Exam ID, student ID, and action are required');
            }

            // Verify the exam belongs to this instructor
            $stmt = $db->prepare("SELECT id FROM exams WHERE id = ? AND instructor_id = ?");
            $stmt->execute([$examId, $userId]);
            if (!$stmt->fetch()) {
                throw new Exception('Exam not found or access denied');
            }

            // Verify the student exists
            $stmt = $db->prepare("SELECT id FROM users WHERE id = ? AND role = 'student'");
            $stmt->execute([$studentId]);
            if (!$stmt->fetch()) {
                throw new Exception('Student not found');
            }

            if ($action === 'assign') {
                // Check if already assigned
                $stmt = $db->prepare("SELECT id FROM exam_access WHERE exam_id = ? AND student_id = ?");
                $stmt->execute([$examId, $studentId]);
                if ($stmt->fetch()) {
                    throw new Exception('Student is already assigned to this exam');
                }

                // Assign exam to student
                $stmt = $db->prepare("
                    INSERT INTO exam_access (exam_id, student_id, payment_status, access_granted_at)
                    VALUES (?, ?, 'free', NOW())
                ");
                $stmt->execute([$examId, $studentId]);

                echo json_encode([
                    'success' => true,
                    'message' => 'Exam assigned successfully'
                ]);

            } elseif ($action === 'unassign') {
                // Check if assigned
                $stmt = $db->prepare("SELECT id FROM exam_access WHERE exam_id = ? AND student_id = ?");
                $stmt->execute([$examId, $studentId]);
                if (!$stmt->fetch()) {
                    throw new Exception('Student is not assigned to this exam');
                }

                // Unassign exam from student
                $stmt = $db->prepare("DELETE FROM exam_access WHERE exam_id = ? AND student_id = ?");
                $stmt->execute([$examId, $studentId]);

                echo json_encode([
                    'success' => true,
                    'message' => 'Exam unassigned successfully'
                ]);

            } else {
                throw new Exception('Invalid action. Must be "assign" or "unassign"');
            }
            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()]);
}
?>