<?php
/**
 * AJAX endpoint to get exam status - CORRECTED for your database structure
 * Accepts POST parameters: exam_id, school_id, teacher_id
 * Returns JSON with exam status, name, and published date
 */

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'] ?? '';

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;
    
    // Query the exam status with teacher verification using your actual database structure
    $query = "
        SELECT 
            e.exam_id,
            e.exam_name,
            e.status,
            e.updated_at,
            e.school_id
        FROM exams e
        WHERE e.exam_id = ? 
          AND e.school_id = ?
          AND EXISTS (
              SELECT 1 FROM class_subject_teachers cst 
              WHERE cst.teacher_user_id = ? 
                AND cst.school_id = e.school_id
          )
    ";
    
    $stmt = $conn->prepare($query);
    $stmt->bind_param("iii", $exam_id, $school_id, $teacher_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']
        ]);
    } else {
        echo json_encode([
            'success' => false,
            'message' => 'Exam not found or teacher not authorized'
        ]);
    }
    
    $stmt->close();
    
} catch (Exception $e) {
    error_log('Error in ajax_get_exam_status.php: ' . $e->getMessage());
    echo json_encode([
        'success' => false,
        'message' => 'An error occurred while checking exam status'
    ]);
}
?>