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

// 1. SECURITY CHECK (Updated for Sub-Admin)
// Ensure only Admins and Sub-Admins can execute this bulk update
if (!isset($_SESSION['role']) || !in_array($_SESSION['role'], ['admin', 'subadmin'])) {
    error_log("Unauthorized Access Attempt by User ID: " . ($_SESSION['user_id'] ?? 'Unknown'));
    die("Unauthorized access. This action has been logged.");
}

// 2. ACTION HANDLING
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['release_action'])) {
    
    // Sanitize inputs
    $session = htmlspecialchars(strip_tags($_POST['session']));
    $term    = htmlspecialchars(strip_tags($_POST['term']));
    
    // Convert button value to integer (1 for release, 0 for hide)
    $status = ($_POST['release_action'] === 'release') ? 1 : 0;

    try {
        // 3. DATABASE UPDATE
        // Updates visibility status for all results in the selected term
        $stmt = $pdo->prepare("
            UPDATE results 
            SET is_approved = :status 
            WHERE session = :session 
            AND term = :term
        ");
        
        $stmt->execute([
            ':status'  => $status,
            ':session' => $session,
            ':term'    => $term
        ]);

        // 4. REDIRECT WITH SUCCESS MESSAGE
        // msgType helps the dashboard show a specific responsive alert
        $msgType = ($status === 1) ? 'released' : 'hidden';
        header("Location: dashboard.php?success=results_" . $msgType);
        exit();

    } catch (PDOException $e) {
        // Log error and return to dashboard with error info
        error_log("Result Release Error: " . $e->getMessage());
        header("Location: dashboard.php?error=db_fail");
        exit();
    }
} else {
    // Prevent direct URL access
    header("Location: dashboard.php");
    exit();
}