<?php
session_start();

// Suppress all error output to ensure clean JSON response
error_reporting(E_ALL);
ini_set('display_errors', 0);
ini_set('log_errors', 1);

require_once 'config.php';

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

// Function to safely output JSON and exit
function safe_json_exit($data) {
    echo json_encode($data);
    exit;
}

// Check if user is logged in
if (!isset($_SESSION["loggedin"]) || $_SESSION["loggedin"] !== true) {
    safe_json_exit(['success' => false, 'message' => 'Unauthorized access']);
}

// Check if required POST data exists
if (!isset($_POST['exam_id']) || !isset($_POST['subject_id']) || !isset($_POST['school_id'])) {
    safe_json_exit(['success' => false, 'message' => 'Missing required data']);
}

$exam_id = intval($_POST['exam_id']);
$subject_id = intval($_POST['subject_id']);
$school_id = intval($_POST['school_id']);
$teacher_user_id = $_SESSION["id"] ?? $_SESSION["user_id"] ?? 0;
$user_role = $_SESSION["role"] ?? 0;

try {
    // Check current status
    $sql_check_status = "SELECT status FROM exam_subjects 
                        WHERE exam_id = ? AND subject_id = ?";
    if ($stmt_check = @$conn->prepare($sql_check_status)) {
        $stmt_check->bind_param("ii", $exam_id, $subject_id);
        if ($stmt_check->execute()) {
            $result_check = $stmt_check->get_result();
            $status_data = $result_check->fetch_assoc();
            $current_status = $status_data['status'] ?? '';
            $stmt_check->close();
        } else {
            // Execution failed, treat as missing record
            $current_status = '';
        }
    } else {
        // Failed to prepare statement, treat as missing record  
        $current_status = '';
    }
    
    // DEBUG: Log the current status and IDs
    error_log("DEBUG: Publish attempt - exam_id: $exam_id, subject_id: $subject_id, current_status: '$current_status', user_role: $user_role");
    
    // If record doesn't exist, create it with 'Captured' status (marks have been saved)
    if ($current_status === '') {
        error_log("DEBUG: Creating missing exam_subjects record with Captured status");
        $insert_sql = "INSERT INTO exam_subjects (exam_id, subject_id, status) 
                      VALUES (?, ?, 'Captured')";
        if ($stmt_insert = @$conn->prepare($insert_sql)) {
            $stmt_insert->bind_param("ii", $exam_id, $subject_id);
            if ($stmt_insert->execute()) {
                $stmt_insert->close();
                $current_status = 'Captured';
                error_log("DEBUG: Successfully created exam_subjects record, status set to: '$current_status'");
            } else {
                error_log("DEBUG: Failed to create exam_subjects record: " . $conn->error);
            }
        }
    }
            
    // Only teachers can publish their own subjects, admins can publish any
    if ($user_role == 2) { // Teacher
        // Verify teacher owns this subject
        $sql_verify = "SELECT COUNT(*) as count FROM class_subject_teachers cst 
                     WHERE cst.teacher_user_id = ? AND cst.subject_id = ? AND cst.school_id = ?";
        if ($stmt_verify = @$conn->prepare($sql_verify)) {
            $stmt_verify->bind_param("iii", $teacher_user_id, $subject_id, $school_id);
            if ($stmt_verify->execute()) {
                $result_verify = $stmt_verify->get_result();
                $verify_data = $result_verify->fetch_assoc();
                if ($verify_data['count'] == 0) {
                    $stmt_verify->close();
                    throw new Exception('You are not authorized to publish this subject');
                }
            }
            $stmt_verify->close();
        }
    }
    // Admin (role 0 or 1) can publish any subject without verification
            
    // Check if already published
    if ($current_status === 'Published') {
        throw new Exception('This subject is already published');
    }
            
    // DEBUG: Log final status before publish check
    error_log("DEBUG: Final status check - current_status: '$current_status', user_role: $user_role");
            
    // Can only publish if status is 'Captured' or if admin overrides
    if ($current_status !== 'Captured' && $user_role != 1 && $user_role != 0) {
        error_log("DEBUG: Publish failed - status check failed. current_status: '$current_status', user_role: $user_role");
        throw new Exception('Marks must be captured before publishing');
    }
            
    // Update status to 'Published'
    $sql_publish = "UPDATE exam_subjects 
                  SET status = 'Published' 
                  WHERE exam_id = ? AND subject_id = ?";
    if ($stmt_publish = @$conn->prepare($sql_publish)) {
        $stmt_publish->bind_param("ii", $exam_id, $subject_id);
        if ($stmt_publish->execute()) {
            $stmt_publish->close();
                    
            safe_json_exit([
                'success' => true, 
                'message' => 'Marks published successfully. Further editing is now blocked.',
                'new_status' => 'Published'
            ]);
        } else {
            throw new Exception('Failed to publish marks');
        }
    } else {
        throw new Exception('Database error in publish operation');
    }
    
} catch (Exception $e) {
    error_log("Error publishing marks: " . $e->getMessage());
    safe_json_exit([
        'success' => false, 
        'message' => 'Error publishing marks: ' . $e->getMessage()
    ]);
}
?>