<?php
session_start();
require_once 'config.php';

header('Content-Type: application/json');

if (!isset($_SESSION["loggedin"]) || $_SESSION["loggedin"] !== true) {
    echo json_encode(['success' => false, 'message' => 'Unauthorized']);
    exit;
}

// Check if user is admin
$user_role_code = $_SESSION["role"] ?? 0;
if ($user_role_code != 1) {
    echo json_encode(['success' => false, 'message' => 'Only administrators can unpublish subjects']);
    exit;
}

$exam_id = $_POST['exam_id'] ?? 0;
$subject_id = $_POST['subject_id'] ?? 0;
$school_id = $_POST['school_id'] ?? 0;

if ($exam_id == 0 || $subject_id == 0 || $school_id == 0) {
    echo json_encode(['success' => false, 'message' => 'Invalid parameters']);
    exit;
}

try {
    // Check if subject is published
    $sql_check = "SELECT status FROM exam_subjects WHERE exam_id = ? AND subject_id = ?";
    $stmt_check = $conn->prepare($sql_check);
    $stmt_check->bind_param("ii", $exam_id, $subject_id);
    $stmt_check->execute();
    $result = $stmt_check->get_result();
    $subject_data = $result->fetch_assoc();
    
    if (!$subject_data) {
        echo json_encode(['success' => false, 'message' => 'Subject not found for this exam']);
        exit;
    }
    
    if ($subject_data['status'] !== 'Published') {
        echo json_encode(['success' => false, 'message' => 'Subject is not published']);
        exit;
    }
    
    // Update subject status back to 'Captured'
    $sql_update = "UPDATE exam_subjects SET status = 'Captured' WHERE exam_id = ? AND subject_id = ?";
    $stmt_update = $conn->prepare($sql_update);
    $stmt_update->bind_param("ii", $exam_id, $subject_id);
    
    if ($stmt_update->execute()) {
        echo json_encode(['success' => true, 'message' => 'Subject unpublished successfully. Marks entry is now enabled.']);
    } else {
        echo json_encode(['success' => false, 'message' => 'Failed to unpublish subject']);
    }
    
} catch (Exception $e) {
    echo json_encode(['success' => false, 'message' => 'Error: ' . $e->getMessage()]);
}
?>