<?php
require_once '../includes/include_all.inc.php';
require_once '../includes/session_settings.php';

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

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    echo json_encode(['error' => 'Method not allowed']);
    exit;
}

if (!isset($_SESSION['front_user_id'])) {
    http_response_code(401);
    echo json_encode(['error' => 'Unauthorized']);
    exit;
}

$userId = $_SESSION['front_user_id'];
$stmt = $pdo->prepare("SELECT is_super FROM " . WP_PREFIX . "users WHERE ID = ?");
$stmt->execute([$userId]);
$user = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$user || !$user['is_super']) {
    http_response_code(403);
    echo json_encode(['error' => 'Forbidden - Super admin only']);
    exit;
}

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

if (!isset($data['enabled'])) {
    http_response_code(400);
    echo json_encode(['error' => 'Missing enabled parameter']);
    exit;
}

$success = true;
$stmt = $pdo->prepare("INSERT INTO wp_settings (setting_key, setting_value, setting_type) VALUES (?, ?, ?) ON DUPLICATE KEY UPDATE setting_value = VALUES(setting_value), updated_at = CURRENT_TIMESTAMP");
$stmt->execute(['global_session_termination_enabled', $data['enabled'] ? '1' : '0', 'boolean']);

if ($success) {
    echo json_encode(['success' => true, 'enabled' => $data['enabled']]);
} else {
    http_response_code(500);
    echo json_encode(['error' => 'Failed to update setting']);
}
?>