<?php
// admin/users/update_access_status.php
session_start();
require_once "../../config/database.php";

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

// --- UPDATED AUTH CHECK ---
// Allow both admin and subadmin to toggle access status
if (!isset($_SESSION['role']) || !in_array($_SESSION['role'], ['admin', 'subadmin'])) {
    echo json_encode(['success' => false, 'error' => 'Unauthorized access.']);
    exit();
}

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $id = $_POST['student_id'] ?? null;
    $status = $_POST['status'] ?? 0;

    if ($id) {
        try {
            $stmt = $pdo->prepare("UPDATE students SET result_access = ? WHERE id = ?");
            $stmt->execute([$status, $id]);
            echo json_encode(['success' => true]);
        } catch (PDOException $e) {
            echo json_encode(['success' => false, 'error' => 'Database error: ' . $e->getMessage()]);
        }
    } else {
        echo json_encode(['success' => false, 'error' => 'Invalid Student ID']);
    }
} else {
    echo json_encode(['success' => false, 'error' => 'Invalid request method']);
}