<?php
/**
 * AJAX endpoint to get exam class status - CLASS-BY-CLASS LOCKING
 * This endpoint checks if a specific class for an exam is published
 * Replaces the whole-exam locking with individual class locking
 */

session_start();

// Include database configuration
require_once 'config.php';

// Set content type to JSON
header('Content-Type: application/json');

// Disable error display to prevent HTML output
error_reporting(0);
ini_set('display_errors', 0);

// Check if request method is POST
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    echo json_encode([
        'success' => false,
        'message' => 'Method not allowed'
    ]);
    exit;
}

// Get POST parameters
$exam_id = $_POST['exam_id'] ?? '';
$school_id = $_POST['school_id'] ?? '';
$teacher_id = $_POST['teacher_id'] ?? '';
$class_id = $_POST['class_id'] ?? '';
$stream_id = $_POST['stream_id'] ?? '';

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

try {
    // Validate inputs
    $exam_id = (int)$exam_id;
    $school_id = (int)$school_id;
    $teacher_id = (int)$teacher_id;
    $class_id = (int)($class_id ?: 0);
    $stream_id = (int)($stream_id ?: 0);
    
    // Check if the exam_class_status table exists
    $table_check = $conn->query("SHOW TABLES LIKE 'exam_class_status'");
    if ($table_check->num_rows == 0) {
        // Table doesn't exist yet, fallback to whole exam checking
        $query = "
            SELECT 
                exam_id,
                exam_name,
                status,
                updated_at,
                school_id
            FROM exams
            WHERE exam_id = ? 
              AND school_id = ?
        ";
        
        $stmt = $conn->prepare($query);
        $stmt->bind_param("ii", $exam_id, $school_id);
        $stmt->execute();
        $result = $stmt->get_result();
        
        if ($exam = $result->fetch_assoc()) {
            echo json_encode([
                'success' => true,
                'exam_status' => $exam['status'],
                'exam_name' => $exam['exam_name'],
                'published_date' => $exam['updated_at'],
                'locking_type' => 'whole_exam',
                'message' => 'Using whole-exam locking - exam_class_status table not found'
            ]);
        } else {
            echo json_encode([
                'success' => false,
                'message' => 'Exam not found'
            ]);
        }
        
        $stmt->close();
    } else {
        // Table exists, use class-level checking
        
        // First check if there's a specific class-stream combination
        if ($class_id > 0) {
            $query = "
                SELECT 
                    ecs.status,
                    ecs.published_at,
                    c.class_name,
                    st.stream_name,
                    e.exam_name
                FROM exam_class_status ecs
                LEFT JOIN classes c ON ecs.class_id = c.class_id
                LEFT JOIN streams st ON ecs.stream_id = st.stream_id  
                LEFT JOIN exams e ON ecs.exam_id = e.exam_id
                WHERE ecs.exam_id = ?
                  AND ecs.class_id = ?
                  AND (? = 0 OR ecs.stream_id = ?)
            ";
            
            $stmt = $conn->prepare($query);
            $stream_param = $stream_id ?: 0;
            $stmt->bind_param("iiii", $exam_id, $class_id, $stream_param, $stream_param);
            $stmt->execute();
            $result = $stmt->get_result();
            
            if ($class_status = $result->fetch_assoc()) {
                echo json_encode([
                    'success' => true,
                    'exam_status' => $class_status['status'],
                    'exam_name' => $class_status['exam_name'],
                    'published_date' => $class_status['published_at'],
                    'class_name' => $class_status['class_name'],
                    'stream_name' => $class_status['stream_name'],
                    'locking_type' => 'class_level',
                    'message' => 'Individual class locking active'
                ]);
            } else {
                // No specific class record found, check if class is available for this exam
                $availability_query = "
                    SELECT 
                        ecs.status,
                        ecs.published_at,
                        c.class_name,
                        st.stream_name,
                        e.exam_name
                    FROM exam_class_status ecs
                    LEFT JOIN classes c ON ecs.class_id = c.class_id
                    LEFT JOIN streams st ON ecs.stream_id = st.stream_id  
                    LEFT JOIN exams e ON ecs.exam_id = e.exam_id
                    WHERE ecs.exam_id = ?
                      AND (? = 0 OR ecs.stream_id IS NULL)
                      AND (? = 0 OR ecs.class_id = ?)
                ";
                
                $stmt_avail = $conn->prepare($availability_query);
                $stmt_avail->bind_param("iiii", $exam_id, $class_id, $stream_id, $class_id);
                $stmt_avail->execute();
                $result_avail = $stmt_avail->get_result();
                
                if ($class_status_avail = $result_avail->fetch_assoc()) {
                    echo json_encode([
                        'success' => true,
                        'exam_status' => $class_status_avail['status'],
                        'exam_name' => $class_status_avail['exam_name'],
                        'published_date' => $class_status_avail['published_at'],
                        'class_name' => $class_status_avail['class_name'],
                        'stream_name' => $class_status_avail['stream_name'],
                        'locking_type' => 'class_level',
                        'message' => 'Individual class locking active'
                    ]);
                } else {
                    // Class not yet tracked in exam_class_status, so it's available (Draft)
                    echo json_encode([
                        'success' => true,
                        'exam_status' => 'Draft',
                        'exam_name' => '',
                        'published_date' => null,
                        'class_name' => '',
                        'stream_name' => '',
                        'locking_type' => 'class_level',
                        'message' => 'Class available for publishing'
                    ]);
                }
                
                $stmt_avail->close();
            }
            
            $stmt->close();
        } else {
            // No specific class provided, check overall exam status
            $query = "
                SELECT 
                    COUNT(CASE WHEN ecs.status = 'Published' THEN 1 END) as published_classes,
                    COUNT(CASE WHEN ecs.status = 'Draft' THEN 1 END) as draft_classes,
                    COUNT(*) as total_classes
                FROM exam_class_status ecs
                WHERE ecs.exam_id = ?
            ";
            
            $stmt = $conn->prepare($query);
            $stmt->bind_param("i", $exam_id);
            $stmt->execute();
            $result = $stmt->get_result();
            
            $class_summary = $result->fetch_assoc();
            
            if ($class_summary['total_classes'] == 0) {
                // No class-level tracking exists, check whole exam
                $exam_query = "
                    SELECT 
                        exam_id,
                        exam_name,
                        status,
                        updated_at,
                        school_id
                    FROM exams
                    WHERE exam_id = ? 
                      AND school_id = ?
                ";
                
                $stmt_exam = $conn->prepare($exam_query);
                $stmt_exam->bind_param("ii", $exam_id, $school_id);
                $stmt_exam->execute();
                $result_exam = $stmt_exam->get_result();
                
                if ($exam = $result_exam->fetch_assoc()) {
                    echo json_encode([
                        'success' => true,
                        'exam_status' => $exam['status'],
                        'exam_name' => $exam['exam_name'],
                        'published_date' => $exam['updated_at'],
                        'locking_type' => 'whole_exam',
                        'class_summary' => $class_summary,
                        'message' => 'Using whole-exam locking - no class tracking found'
                    ]);
                } else {
                    echo json_encode([
                        'success' => false,
                        'message' => 'Exam not found'
                    ]);
                }
                
                $stmt_exam->close();
            } else {
                // Class-level tracking exists
                echo json_encode([
                    'success' => true,
                    'exam_status' => $class_summary['published_classes'] == $class_summary['total_classes'] ? 'Published' : 'Draft',
                    'exam_name' => '',
                    'published_date' => null,
                    'locking_type' => 'class_level',
                    'class_summary' => $class_summary,
                    'message' => 'Class-level tracking active'
                ]);
            }
            
            $stmt->close();
        }
    }
    
} catch (Exception $e) {
    error_log('Error in ajax_get_exam_class_status.php: ' . $e->getMessage());
    echo json_encode([
        'success' => false,
        'message' => 'An error occurred while checking exam class status'
    ]);
}
?>