<?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 and is admin
if (!isset($_SESSION["loggedin"]) || $_SESSION["loggedin"] !== true || ($_SESSION["role"] != 0 && $_SESSION["role"] != 1)) {
    safe_json_exit(['success' => false, 'message' => 'Unauthorized access - Admin access required']);
}

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

$exam_id = intval($_POST['exam_id']);
$subject_id = intval($_POST['subject_id']);

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();
            
            // Allow admin to unpublish (set back to Captured)
            if ($current_status === 'Published') {
                $sql_unpublish = "UPDATE exam_subjects 
                                SET status = 'Captured' 
                                WHERE exam_id = ? AND subject_id = ?";
                if ($stmt_unpublish = @$conn->prepare($sql_unpublish)) {
                    $stmt_unpublish->bind_param("ii", $exam_id, $subject_id);
                    if ($stmt_unpublish->execute()) {
                        $stmt_unpublish->close();
                        
                        safe_json_exit([
                            'success' => true, 
                            'message' => 'Admin override: Marks unpublished. Editing is now allowed.',
                            'new_status' => 'Captured'
                        ]);
                    } else {
                        throw new Exception('Failed to unpublish marks');
                    }
                } else {
                    throw new Exception('Database error in admin unpublish operation');
                }
            } else {
                throw new Exception('Only published marks can be unpublished by admin');
            }
            
        } else {
            throw new Exception('Could not check current status');
        }
    } else {
        throw new Exception('Database error accessing exam_subjects table');
    }
    
} catch (Exception $e) {
    error_log("Error in admin override: " . $e->getMessage());
    safe_json_exit([
        'success' => false, 
        'message' => 'Error in admin override: ' . $e->getMessage()
    ]);
}
?>