<?php

declare(strict_types=1);

require_once __DIR__ . '/../../library/auth.php';
require_once __DIR__ . '/../helpers/result-helper.php';
require_once __DIR__ . '/../services/ResultPublishService.php';

allow_roles(['admin']);
requirePostRequest();
verifyCsrfToken();

$school_id = (int) $_SESSION['school_id'];
$session_id = (int) ($_SESSION['session_id'] ?? 0);
$user_id = (int) ($_SESSION['user_id'] ?? 0);

$exam_type_id = validateId($_POST['exam_type_id'] ?? 0);
$class_id = validateId($_POST['class_id'] ?? 0);
$action = $_POST['action'] ?? ''; // 'publish' or 'unpublish'

if ($exam_type_id <= 0 || $class_id <= 0 || $session_id <= 0 || !in_array($action, ['publish', 'unpublish'], true)) {
    jsonResponse(false, 'Invalid request data.');
}

try {
    $service = new ResultPublishService($pdo);
    $isPublishing = ($action === 'publish');

    // Business Logic Check
    $isCurrentlyPublished = $service->isPublished($school_id, $session_id, $exam_type_id, $class_id);
    
    if ($isCurrentlyPublished === $isPublishing) {
        throw new Exception("Results are already " . ($isPublishing ? 'published' : 'unpublished') . ".");
    }

    $pdo->beginTransaction();

    // Perform Update
    $success = $service->updateStatus($school_id, $session_id, $exam_type_id, $class_id, $isPublishing);

    if (!$success) {
        throw new Exception("Failed to update status.");
    }

    // Audit Log
    $stmt = $pdo->prepare("
        INSERT INTO audit_logs (school_id, user_id, module, action, message, ip_address, user_agent) 
        VALUES (?, ?, ?, ?, ?, ?, ?)
    ");
    $stmt->execute([
        $school_id, $user_id, 'Exams', ucfirst($action) . ' Results',
        "Results " . $action . "ed successfully.",
        $_SERVER['REMOTE_ADDR'] ?? '0.0.0.0',
        $_SERVER['HTTP_USER_AGENT'] ?? 'N/A'
    ]);

    $pdo->commit();
    jsonResponse(true, "Results " . $action . "ed successfully.");

} catch (Throwable $e) {
    if ($pdo->inTransaction()) {
        $pdo->rollBack();
    }
    jsonResponse(false, $e->getMessage());
}