<?php
/**
 * AJAX endpoint for admin to publish/unpublish individual classes
 * Replaces whole-exam publishing with class-by-class publishing
 */

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 user is admin
if (!isset($_SESSION["loggedin"]) || $_SESSION["loggedin"] !== true) {
    echo json_encode([
        'success' => false,
        'message' => 'Unauthorized access'
    ]);
    exit;
}

if ($_SESSION["role"] !== 1 && $_SESSION["role"] !== 0) { // Admin or Super Admin
    echo json_encode([
        'success' => false,
        'message' => 'Insufficient permissions'
    ]);
    exit;
}

// 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'] ?? '';
$class_id = $_POST['class_id'] ?? '';
$stream_id = $_POST['stream_id'] ?? '';
$action = $_POST['action'] ?? ''; // 'publish', 'unpublish', 'create_table', 'migrate_exam'
$school_id = $_SESSION['school_id'];
$user_id = $_SESSION['id'];

// Special actions that don't require all parameters
if ($action === 'create_table') {
    // Just create the table and return
    try {
        $create_table_sql = "
            CREATE TABLE IF NOT EXISTS exam_class_status (
                exam_class_status_id INT AUTO_INCREMENT PRIMARY KEY,
                exam_id INT NOT NULL,
                class_id INT NOT NULL,
                stream_id INT DEFAULT NULL,
                status ENUM('Draft', 'Published') DEFAULT 'Draft',
                published_by INT NULL,
                published_at TIMESTAMP NULL,
                created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
                updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
                UNIQUE KEY unique_exam_class_stream (exam_id, class_id, stream_id),
                INDEX idx_exam_id (exam_id),
                INDEX idx_class_id (class_id),
                INDEX idx_status (status)
            )
        ";
        
        if ($conn->query($create_table_sql)) {
            echo json_encode([
                'success' => true,
                'message' => 'exam_class_status table created successfully'
            ]);
        } else {
            echo json_encode([
                'success' => false,
                'message' => 'Failed to create table: ' . $conn->error
            ]);
        }
        exit;
    } catch (Exception $e) {
        echo json_encode([
            'success' => false,
            'message' => 'Error creating table: ' . $e->getMessage()
        ]);
        exit;
    }
}

if ($action === 'migrate_exam') {
    // Migrate an existing exam to class-level publishing
    if (empty($exam_id)) {
        echo json_encode([
            'success' => false,
            'message' => 'Missing required parameter: exam_id'
        ]);
        exit;
    }
    
    try {
        $exam_id = (int)$exam_id;
        
        // Check if exam exists
        $check_exam = $conn->prepare("SELECT exam_id, exam_name, status, school_id FROM exams WHERE exam_id = ? AND school_id = ?");
        $check_exam->bind_param("ii", $exam_id, $school_id);
        $check_exam->execute();
        $result = $check_exam->get_result();
        
        if (!$exam = $result->fetch_assoc()) {
            echo json_encode([
                'success' => false,
                'message' => 'Exam not found or access denied'
            ]);
            exit;
        }
        
        $check_exam->close();
        
        // Get all classes that have teacher assignments for this exam
        $classes_sql = "
            SELECT DISTINCT
                c.class_id,
                c.class_name,
                st.stream_id,
                st.stream_name,
                ecs.exam_class_status_id
            FROM classes c
            LEFT JOIN streams st ON st.school_id = c.school_id
            LEFT JOIN class_subject_teachers cst ON cst.class_id = c.class_id 
                AND cst.stream_id = st.stream_id 
                AND cst.school_id = ?
            LEFT JOIN exam_subjects es ON es.subject_id = cst.subject_id 
                AND es.exam_id = ?
            LEFT JOIN exam_class_status ecs ON ecs.exam_id = ?
                AND ecs.class_id = c.class_id 
                AND (ecs.stream_id = st.stream_id OR ecs.stream_id IS NULL)
            WHERE c.school_id = ?
              AND es.subject_id IS NOT NULL
              AND ecs.exam_class_status_id IS NULL
            ORDER BY c.class_name, st.stream_name
        ";
        
        $stmt = $conn->prepare($classes_sql);
        $stmt->bind_param("iiii", $school_id, $exam_id, $exam_id, $school_id);
        $stmt->execute();
        $result = $stmt->get_result();
        
        $migrated_count = 0;
        while ($class = $result->fetch_assoc()) {
            // Insert class record with the exam's current status
            $status = $exam['status'];
            $published_by = ($status === 'Published') ? $user_id : null;
            $published_at = ($status === 'Published') ? date('Y-m-d H:i:s') : null;
            
            $insert_sql = "
                INSERT INTO exam_class_status (exam_id, class_id, stream_id, status, published_by, published_at, created_at)
                VALUES (?, ?, ?, ?, ?, ?, NOW())
            ";
            
            $insert_stmt = $conn->prepare($insert_sql);
            $insert_stmt->bind_param("iiiisi", $exam_id, $class['class_id'], $class['stream_id'], $status, $published_by, $published_at);
            
            if ($insert_stmt->execute()) {
                $migrated_count++;
            }
            
            $insert_stmt->close();
        }
        
        $stmt->close();
        
        echo json_encode([
            'success' => true,
            'message' => "Migrated {$migrated_count} class records for exam '{$exam['exam_name']}'",
            'data' => [
                'exam_id' => $exam_id,
                'exam_name' => $exam['exam_name'],
                'original_status' => $exam['status'],
                'migrated_classes' => $migrated_count
            ]
        ]);
        
    } catch (Exception $e) {
        echo json_encode([
            'success' => false,
            'message' => 'Migration error: ' . $e->getMessage()
        ]);
    }
    exit;
}

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

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

try {
    // Validate inputs
    $exam_id = (int)$exam_id;
    $class_id = (int)$class_id;
    $stream_id = (int)($stream_id ?: 0);
    $new_status = ($action === 'publish') ? 'Published' : 'Draft';
    
    // Check if the exam_class_status table exists, if not create it
    $table_check = $conn->query("SHOW TABLES LIKE 'exam_class_status'");
    if ($table_check->num_rows == 0) {
        // Create the table if it doesn't exist
        $create_table_sql = "
            CREATE TABLE exam_class_status (
                exam_class_status_id INT AUTO_INCREMENT PRIMARY KEY,
                exam_id INT NOT NULL,
                class_id INT NOT NULL,
                stream_id INT DEFAULT NULL,
                status ENUM('Draft', 'Published') DEFAULT 'Draft',
                published_by INT NULL,
                published_at TIMESTAMP NULL,
                created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
                updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
                UNIQUE KEY unique_exam_class_stream (exam_id, class_id, stream_id),
                INDEX idx_exam_id (exam_id),
                INDEX idx_class_id (class_id),
                INDEX idx_status (status)
            )
        ";
        
        $conn->query($create_table_sql);
    }
    
    // Check if exam exists and user has permission
    $check_exam = $conn->prepare("SELECT exam_id, exam_name, school_id FROM exams WHERE exam_id = ? AND school_id = ?");
    $check_exam->bind_param("ii", $exam_id, $school_id);
    $check_exam->execute();
    $result = $check_exam->get_result();
    
    if (!$exam = $result->fetch_assoc()) {
        echo json_encode([
            'success' => false,
            'message' => 'Exam not found or access denied'
        ]);
        exit;
    }
    
    $check_exam->close();
    
    // Check if class exists
    $check_class = $conn->prepare("SELECT class_name FROM classes WHERE class_id = ?");
    $check_class->bind_param("i", $class_id);
    $check_class->execute();
    $result_class = $check_class->get_result();
    
    if (!$class = $result_class->fetch_assoc()) {
        echo json_encode([
            'success' => false,
            'message' => 'Class not found'
        ]);
        exit;
    }
    
    $check_class->close();
    
    // Insert or update exam_class_status record
    $upsert_query = "
        INSERT INTO exam_class_status (exam_id, class_id, stream_id, status, published_by, published_at, created_at)
        VALUES (?, ?, ?, ?, ?, 
            CASE WHEN ? = 'Published' THEN NOW() ELSE NULL END, 
            NOW()
        )
        ON DUPLICATE KEY UPDATE 
            status = VALUES(status),
            published_by = VALUES(published_by),
            published_at = VALUES(published_at),
            updated_at = NOW()
    ";
    
    $stmt = $conn->prepare($upsert_query);
    $published_by = ($action === 'publish') ? $user_id : null;
    
    $stmt->bind_param("iiiisii", $exam_id, $class_id, $stream_id, $new_status, $published_by, $new_status);
    $stmt->execute();
    
    if ($stmt->affected_rows > 0) {
        $action_text = ($action === 'publish') ? 'published' : 'unpublished';
        
        echo json_encode([
            'success' => true,
            'message' => "Class {$action_text} successfully!",
            'data' => [
                'exam_id' => $exam_id,
                'exam_name' => $exam['exam_name'],
                'class_id' => $class_id,
                'class_name' => $class['class_name'],
                'stream_id' => $stream_id ?: null,
                'new_status' => $new_status,
                'action' => $action
            ]
        ]);
        
        // Log the action
        error_log("ADMIN ACTION: Class {$class['class_name']} for exam {$exam['exam_name']} {$action_text} by user {$user_id}");
        
    } else {
        echo json_encode([
            'success' => false,
            'message' => 'Failed to update class status'
        ]);
    }
    
    $stmt->close();
    
} catch (Exception $e) {
    error_log('Error in ajax_manage_exam_class_status.php: ' . $e->getMessage());
    echo json_encode([
        'success' => false,
        'message' => 'An error occurred while managing class status'
    ]);
}
?>