<?php
// admin/release_results_action.php
session_start();
$projectRoot = dirname(__DIR__);
require_once $projectRoot . '/config/database.php';
require_once $projectRoot . '/config/config.php';

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action'])) {
    
    // --- UPDATED AUTH CHECK ---
    // Allow both admin and subadmin to process the release
    if (!isset($_SESSION['role']) || !in_array($_SESSION['role'], ['admin', 'subadmin'])) {
        error_log("Unauthorized result release attempt by: " . ($_SESSION['email'] ?? 'Unknown'));
        die("Unauthorized access.");
    }

    // Sanitize inputs for safety
    $session = htmlspecialchars(strip_tags($_POST['session']));
    $term    = htmlspecialchars(strip_tags($_POST['term']));
    $status  = ($_POST['action'] === 'release') ? 1 : 0;

    try {
        // Toggle the is_approved status for the specific term/session
        $stmt = $pdo->prepare("
            UPDATE results 
            SET is_approved = :status 
            WHERE session = :session 
            AND term = :term
        ");
        
        $stmt->execute([
            ':status'  => $status,
            ':session' => $session,
            ':term'    => $term
        ]);

        $resultType = ($status === 1) ? 'released' : 'hidden';
        
        // Redirecting with specific parameters to trigger responsive alerts on the dashboard
        header("Location: dashboard.php?msg=success&type=" . $resultType);
        exit();

    } catch (PDOException $e) {
        error_log("Database Error in Release Action: " . $e->getMessage());
        header("Location: dashboard.php?msg=error&detail=db_fail");
        exit();
    }
} else {
    header("Location: manage_release.php");
    exit();
}