<?php
/**
 * AJAX Handler for Getting Exam Publishing Status
 * Returns current publishing status and controls for the teacher interface
 */

session_start();
require_once 'config.php';

// Check if user is logged in
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 request
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $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 and get publishing status
    $stmt = $conn->prepare("
        SELECT 
            exam_id,
            exam_name,
            status,
            teacher_published,
            submitted_for_review_at,
            reviewed_by_admin,
            admin_reviewed_at,
            admin_notes,
            updated_at
        FROM exams 
        WHERE exam_id = ? AND school_id = ?
    ");
    $stmt->bind_param("ii", $exam_id, $school_id);
    $stmt->execute();
    $result = $stmt->get_result();
    
    if ($result->num_rows === 0) {
        echo json_encode(['success' => false, 'message' => 'Exam not found']);
        $stmt->close();
        exit;
    }
    
    $exam = $result->fetch_assoc();
    $stmt->close();

    // Get admin name if reviewed
    $admin_name = '';
    if ($exam['reviewed_by_admin']) {
        $admin_stmt = $conn->prepare("SELECT username FROM users WHERE id = ?");
        $admin_stmt->bind_param("i", $exam['reviewed_by_admin']);
        $admin_stmt->execute();
        $admin_result = $admin_stmt->get_result();
        if ($admin_row = $admin_result->fetch_assoc()) {
            $admin_name = $admin_row['username'];
        }
        $admin_stmt->close();
    }

    // Determine current status and what actions are available
    $current_status = determineCurrentStatus($exam);
    $available_actions = getAvailableActions($exam);
    
    // Build response
    $response = [
        'success' => true,
        'exam_id' => $exam['exam_id'],
        'exam_name' => $exam['exam_name'],
        'exam_status' => $exam['status'],
        'teacher_published' => (bool)$exam['teacher_published'],
        'submitted_for_review_at' => $exam['submitted_for_review_at'],
        'admin_reviewed_at' => $exam['admin_reviewed_at'],
        'admin_notes' => $exam['admin_notes'],
        'admin_name' => $admin_name,
        'current_status' => $current_status,
        'available_actions' => $available_actions,
        'last_updated' => $exam['updated_at']
    ];

    echo json_encode($response);
} else {
    echo json_encode(['success' => false, 'message' => 'Invalid request method']);
}

function determineCurrentStatus($exam) {
    // Priority: Published > Submitted for Review > Draft
    if ($exam['status'] === 'Published') {
        return 'Published';
    }
    
    if ($exam['teacher_published'] && $exam['submitted_for_review_at']) {
        return 'Under Review';
    }
    
    return 'Draft';
}

function getAvailableActions($exam) {
    $actions = [];
    
    if ($exam['status'] === 'Published') {
        $actions[] = 'view_only'; // No actions available
    } elseif ($exam['teacher_published'] && $exam['submitted_for_review_at']) {
        $actions[] = 'view_status'; // Can view review status
        $actions[] = 'wait_for_review'; // Waiting for admin
    } else {
        $actions[] = 'submit_for_review'; // Can submit for review
        $actions[] = 'continue_editing'; // Can continue editing
    }
    
    return $actions;
}
?>