<?php
/**
 * AJAX Handler for Teacher Exam Publishing Workflow
 * Handles submitting exams for admin review and managing publishing status
 */

session_start();
require_once 'config.php';

// Check if user is logged in and is a teacher
if (!isset($_SESSION['user_id']) || !isset($_SESSION['role']) || $_SESSION['role'] != ROLE_TEACHER) {
    http_response_code(401);
    echo json_encode(['success' => false, 'message' => 'Unauthorized access']);
    exit;
}

$user_id = $_SESSION['user_id'];
$school_id = $_SESSION['school_id'];

// Handle different actions
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? '';
    $exam_id = intval($_POST['exam_id'] ?? 0);
    $school_id = intval($_POST['school_id'] ?? 0);

    if (!$exam_id || !$school_id) {
        echo json_encode(['success' => false, 'message' => 'Missing required parameters']);
        exit;
    }

    // Verify the exam belongs to the teacher's school
    $stmt = $conn->prepare("SELECT * FROM exams WHERE exam_id = ? AND school_id = ?");
    $stmt->bind_param("ii", $exam_id, $school_id);
    $stmt->execute();
    $result = $stmt->get_result();
    $exam = $result->fetch_assoc();
    $stmt->close();

    if (!$exam) {
        echo json_encode(['success' => false, 'message' => 'Exam not found']);
        exit;
    }

    switch ($action) {
        case 'submit_for_review':
            handleSubmitForReview($exam_id, $user_id, $school_id, $conn);
            break;
            
        case 'request_changes':
            handleRequestChanges($exam_id, $user_id, $conn);
            break;
            
        default:
            echo json_encode(['success' => false, 'message' => 'Invalid action']);
            break;
    }
} else {
    echo json_encode(['success' => false, 'message' => 'Invalid request method']);
}

function handleSubmitForReview($exam_id, $user_id, $school_id, $conn) {
    try {
        // Check if exam is already submitted
        $check_stmt = $conn->prepare("SELECT teacher_published, submitted_for_review_at FROM exams WHERE exam_id = ?");
        $check_stmt->bind_param("i", $exam_id);
        $check_stmt->execute();
        $result = $check_stmt->get_result();
        $exam = $result->fetch_assoc();
        $check_stmt->close();

        if ($exam['teacher_published'] && $exam['submitted_for_review_at']) {
            echo json_encode(['success' => false, 'message' => 'Exam is already submitted for review']);
            return;
        }

        if ($exam['status'] === 'Published') {
            echo json_encode(['success' => false, 'message' => 'Exam is already published by admin']);
            return;
        }

        // Update exam to mark as submitted for review
        $update_stmt = $conn->prepare("
            UPDATE exams 
            SET teacher_published = TRUE, 
                submitted_for_review_at = NOW(),
                updated_at = NOW()
            WHERE exam_id = ?
        ");
        $update_stmt->bind_param("i", $exam_id);
        
        if ($update_stmt->execute()) {
            // Log the action
            $log_stmt = $conn->prepare("
                INSERT INTO exam_admin_approvals (exam_id, admin_user_id, action, notes) 
                VALUES (?, ?, 'submitted', 'Teacher submitted exam for admin review')
            ");
            $log_stmt->bind_param("ii", $exam_id, $user_id);
            $log_stmt->execute();
            $log_stmt->close();

            echo json_encode([
                'success' => true, 
                'message' => 'Exam submitted for admin review successfully! You will be notified once the admin approves or requests changes.'
            ]);
        } else {
            echo json_encode(['success' => false, 'message' => 'Failed to submit exam for review']);
        }
        
        $update_stmt->close();
    } catch (Exception $e) {
        error_log("Error in handleSubmitForReview: " . $e->getMessage());
        echo json_encode(['success' => false, 'message' => 'An error occurred while submitting the exam']);
    }
}

function handleRequestChanges($exam_id, $user_id, $conn) {
    try {
        // This would be used by admins to request changes
        // For now, just return success (admin functionality would be in admin interface)
        echo json_encode(['success' => true, 'message' => 'Change request processed successfully']);
    } catch (Exception $e) {
        error_log("Error in handleRequestChanges: " . $e->getMessage());
        echo json_encode(['success' => false, 'message' => 'An error occurred while processing the request']);
    }
}
?>