<?php
//Developer: core tech web design
error_reporting(0);
ob_start();

if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

$config_path = dirname(__DIR__, 2) . '/include/config.php';
if (file_exists($config_path)) {
    include($config_path);
} else {
    ob_clean();
    echo json_encode(['status' => '0', 'msg' => 'Configuration file not found']);
    exit();
}

ob_clean();
header('Content-Type: application/json; charset=utf-8');

// Must be logged-in admin
if (!isset($_SESSION['logged_in']) || $_SESSION['logged_in'] !== true) {
    echo json_encode(['status' => '0', 'msg' => 'Unauthorized']); exit();
}
try {
    $stmt = $pdo->prepare("SELECT is_admin FROM users WHERE id = :uid");
    $stmt->execute([':uid' => (int)$_SESSION['user_id']]);
    $adm = $stmt->fetch(PDO::FETCH_ASSOC);
    if (!$adm || $adm['is_admin'] != 1) {
        echo json_encode(['status' => '0', 'msg' => 'Unauthorized']); exit();
    }
} catch (PDOException $e) {
    echo json_encode(['status' => '0', 'msg' => 'Auth error']); exit();
}

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    echo json_encode(['status' => '0', 'msg' => 'Invalid method']); exit();
}

$server  = trim($_POST['server']  ?? '');
$enabled = isset($_POST['enabled']) ? (int)$_POST['enabled'] : 0;

$allowed = ['smspva', 'smscodes', 'fivesim', 'smsbus'];
if (!in_array($server, $allowed, true)) {
    echo json_encode(['status' => '0', 'msg' => 'Invalid server identifier']); exit();
}

$enabled = $enabled ? 1 : 0;
$col     = $server . '_enabled';

// Ensure column exists
try {
    $pdo->exec("ALTER TABLE settings ADD COLUMN IF NOT EXISTS {$col} TINYINT(1) NOT NULL DEFAULT 1");
} catch (PDOException $e) {}

try {
    $pdo->prepare("UPDATE settings SET {$col} = :val WHERE id = 1")
        ->execute([':val' => $enabled]);

    $labels = [
        'smspva'   => 'Server1 (smspva)',
        'smscodes' => 'Server2 (smscodes)',
        'fivesim'  => 'Server3 (5SIM)',
        'smsbus'   => 'Server4 (SMS-Bus)',
    ];
    $label = $labels[$server] ?? $server;
    $state = $enabled ? 'enabled' : 'disabled';

    echo json_encode([
        'status'  => '1',
        'msg'     => "{$label} has been {$state} successfully.",
        'enabled' => $enabled,
    ]);
} catch (PDOException $e) {
    echo json_encode(['status' => '0', 'msg' => 'DB error: ' . $e->getMessage()]);
}
