<?php
// api/servers_api.php - API de Gerenciamento de Servidores
session_start();
require_once '../includes/db.php';
header('Content-Type: application/json');

if (!isset($_SESSION['logged_in_fxtream'])) { 
    echo json_encode(['status'=>false, 'msg'=>'Acesso negado']); exit; 
}

$action = $_POST['action'] ?? '';

// 1. LISTAR SERVIDORES
if ($action == 'list') {
    $stmt = $pdo->query("SELECT * FROM servers ORDER BY id DESC");
    $data = $stmt->fetchAll(PDO::FETCH_ASSOC);
    echo json_encode($data);
    exit;
}

// 2. SALVAR (CRIAR OU EDITAR)
if ($action == 'save') {
    $id = (int)$_POST['id'];
    $name = $_POST['name'];
    $domain = rtrim($_POST['domain'], '/'); // Remove barra final se tiver
    $ip = $_POST['ip_address'];
    $max = (int)$_POST['max_connections'];

    if (empty($name) || empty($domain)) {
        echo json_encode(['status'=>false, 'msg'=>'Preencha Nome e Domínio']); exit;
    }

    if ($id > 0) {
        // Editar
        $sql = "UPDATE servers SET name=?, domain=?, ip_address=?, max_connections=? WHERE id=?";
        $pdo->prepare($sql)->execute([$name, $domain, $ip, $max, $id]);
        $msg = "Servidor atualizado!";
    } else {
        // Criar Novo
        $sql = "INSERT INTO servers (name, domain, ip_address, max_connections, status, active_connections) VALUES (?, ?, ?, ?, 1, 0)";
        $pdo->prepare($sql)->execute([$name, $domain, $ip, $max]);
        $msg = "Servidor adicionado!";
    }
    echo json_encode(['status'=>true, 'msg'=>$msg]);
    exit;
}

// 3. EXCLUIR
if ($action == 'delete') {
    $id = (int)$_POST['id'];
    $pdo->prepare("DELETE FROM servers WHERE id=?")->execute([$id]);
    echo json_encode(['status'=>true, 'msg'=>'Servidor removido!']);
    exit;
}

// 4. MUDAR STATUS (ON/OFF)
if ($action == 'toggle_status') {
    $id = (int)$_POST['id'];
    $current = (int)$_POST['status']; // 1 ou 0
    $new = ($current == 1) ? 0 : 1;
    $pdo->prepare("UPDATE servers SET status=? WHERE id=?")->execute([$new, $id]);
    echo json_encode(['status'=>true, 'msg'=>'Status alterado!']);
    exit;
}

// 5. ZERAR CONTADOR (Útil se bugar)
if ($action == 'reset_count') {
    $id = (int)$_POST['id'];
    $pdo->prepare("UPDATE servers SET active_connections=0 WHERE id=?")->execute([$id]);
    echo json_encode(['status'=>true, 'msg'=>'Contador zerado!']);
    exit;
}
?>