<?php

require_once __DIR__ . '/../../core/api_bootstrap.php';
require_once __DIR__ . '/../../core/permissions.php';

/* METHOD */
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    json_response(false, 'Invalid request method.', [], 405);
}

/* AUTH */
$user = authenticate($pdo);

/* ROOT CONTROL */
if ($user['role'] !== 'super_admin') {
    json_response(false, 'Access denied.', [], 403);
}

/* RBAC */
require_permission($user, 'rsps', 'edit', $pdo);

/* INPUT */
$input = json_decode(file_get_contents('php://input'), true);

if (!$input || empty($input['rsp_id'])) {
    json_response(false, 'RSP ID required.', [], 400);
}

$rsp_id = (int)$input['rsp_id'];

/* FETCH RSP */
$stmt = $pdo->prepare("
    SELECT id, name, status
    FROM rsps
    WHERE id = ?
    LIMIT 1
");
$stmt->execute([$rsp_id]);
$rsp = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$rsp) {
    json_response(false, 'RSP not found.', [], 404);
}

/* DETERMINE NEW STATUS */
$new_status = ($rsp['status'] === 'active') ? 'inactive' : 'active';

/* PROTECT AGAINST DISABLING LAST ACTIVE RSP */
if ($new_status === 'inactive') {

    $stmt = $pdo->query("
        SELECT COUNT(*) 
        FROM rsps 
        WHERE status = 'active'
    ");

    $active_count = (int)$stmt->fetchColumn();

    if ($active_count <= 1) {
        json_response(false, 'Cannot disable the last active RSP.', [], 409);
    }
}

$pdo->beginTransaction();

try {

    $stmt = $pdo->prepare("
        UPDATE rsps
        SET status = ?
        WHERE id = ?
    ");

    $stmt->execute([$new_status, $rsp_id]);

    /* AUDIT */
    log_admin_action(
        $pdo,
        (int)$user['id'],
        'rsps',
        'status_toggle',
        $rsp_id
    );

    $pdo->commit();

} catch (Throwable $e) {

    $pdo->rollBack();
    json_response(false, 'Failed to update RSP status.', [], 500);
}

/* RESPONSE */
json_response(true, 'RSP status updated.', [
    'rsp_id' => $rsp_id,
    'new_status' => $new_status
]);