<?php
// servers.php - Gerenciador de Load Balance Responsivo
session_start();
require_once 'includes/db.php';
if (!isset($_SESSION['logged_in_fxtream'])) { header('Location: index.php'); exit; }
?>
<!DOCTYPE html>
<html lang="pt-br">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <title>Gerenciar Load Balance</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.6.0/css/bootstrap.min.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/toastr.js/latest/toastr.min.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/hamburgers/1.1.3/hamburgers.min.css">
    <style>
        body { background-color: #121212; color: #e0e0e0; font-family: 'Segoe UI', sans-serif; }
        
        /* Card do Servidor */
        .server-card { background-color: #1e1e1e; border: 1px solid #333; border-radius: 10px; margin-bottom: 20px; transition: transform 0.2s; box-shadow: 0 4px 6px rgba(0,0,0,0.3); }
        .server-card:hover { transform: translateY(-3px); border-color: #555; }
        .server-header { padding: 15px; border-bottom: 1px solid #333; display: flex; justify-content: space-between; align-items: center; }
        .server-body { padding: 15px; }
        .server-footer { padding: 10px 15px; background: #252525; border-top: 1px solid #333; border-radius: 0 0 10px 10px; display: flex; justify-content: space-between; }
        
        .progress { background-color: #333; height: 15px; border-radius: 10px; margin-top: 10px; }
        .badge-status { padding: 5px 10px; border-radius: 15px; font-size: 0.8rem; font-weight: bold; }
        .status-on { background: rgba(40, 167, 69, 0.2); color: #28a745; border: 1px solid #28a745; }
        .status-off { background: rgba(220, 53, 69, 0.2); color: #dc3545; border: 1px solid #dc3545; }

        /* Menu Mobile */
        @media (min-width: 992px) {
            #sidebar { width: 240px; position: fixed; top: 0; left: 0; height: 100vh; z-index: 1000; overflow-y: auto; }
            .container-main { margin-left: 240px; width: calc(100% - 240px); padding: 30px; }
            .hamburger { display: none !important; }
        }
        @media (max-width: 991px) {
            #sidebar { position: fixed; top: 0; left: -260px; width: 250px; height: 100vh; z-index: 9999; transition: all 0.3s ease; }
            #sidebar.active { left: 0; }
            .container-main { margin-left: 0; width: 100%; padding: 15px; }
            .overlay-menu { display: none; position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(0,0,0,0.5); z-index: 9998; }
            .overlay-menu.active { display: block; }
        }

        .modal-content { background-color: #1f1f1f; border: 1px solid #444; color: white; }
        .form-control { background: #2c2c2c; border: 1px solid #444; color: white; }
        .form-control:focus { background: #333; color: white; border-color: #007bff; }
    </style>
</head>
<body>

<?php include 'includes/sidebar.php'; ?>
<div class="overlay-menu" id="overlayMenu"></div>

<div class="container-main">
    
    <div class="d-lg-none d-flex justify-content-between align-items-center mb-3 bg-dark p-3 rounded shadow-sm">
        <button class="hamburger hamburger--slider" type="button" id="btnToggleMenu">
            <span class="hamburger-box"><span class="hamburger-inner"></span></span>
        </button>
        <span class="font-weight-bold text-white">Load Balance</span>
        <button class="btn btn-sm btn-success" onclick="openModal()"><i class="fa fa-plus"></i></button>
    </div>

    <div class="d-none d-lg-flex justify-content-between align-items-center mb-4">
        <h2><i class="fa fa-server text-info"></i> Gerenciar Load Balance</h2>
        <button class="btn btn-success font-weight-bold shadow" onclick="openModal()"><i class="fa fa-plus-circle"></i> Novo Servidor</button>
    </div>

    <div class="row" id="serverGrid">
        <div class="col-12 text-center py-5"><i class="fa fa-spinner fa-spin fa-3x text-muted"></i></div>
    </div>

</div>

<div class="modal fade" id="modalServer" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header border-secondary">
                <h5 class="modal-title" id="modalTitle">Novo Servidor</h5>
                <button type="button" class="close text-white" data-dismiss="modal">×</button>
            </div>
            <div class="modal-body">
                <form id="formServer">
                    <input type="hidden" name="action" value="save">
                    <input type="hidden" name="id" id="editId">
                    
                    <div class="form-group">
                        <label>Nome do Servidor</label>
                        <input type="text" class="form-control" name="name" id="editName" placeholder="Ex: Servidor 02 - EUA" required>
                    </div>
                    
                    <div class="form-group">
                        <label>URL / Domínio (Com http://)</label>
                        <input type="url" class="form-control" name="domain" id="editDomain" placeholder="Ex: http://server2.meuiptv.com" required>
                        <small class="text-muted">A URL onde o painel/script está instalado neste servidor.</small>
                    </div>

                    <div class="row">
                        <div class="col-6">
                            <div class="form-group">
                                <label>Endereço IP</label>
                                <input type="text" class="form-control" name="ip_address" id="editIp" placeholder="192.168..." required>
                            </div>
                        </div>
                        <div class="col-6">
                            <div class="form-group">
                                <label>Limite Conexões</label>
                                <input type="number" class="form-control" name="max_connections" id="editMax" value="1000" required>
                            </div>
                        </div>
                    </div>

                    <button type="submit" class="btn btn-success btn-block py-2 font-weight-bold">SALVAR</button>
                </form>
            </div>
        </div>
    </div>
</div>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.6.0/js/bootstrap.bundle.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/toastr.js/latest/toastr.min.js"></script>

<script>
    // Menu Mobile
    $('#btnToggleMenu, #overlayMenu').click(function() {
        $('#sidebar').toggleClass('active');
        $('#overlayMenu').toggleClass('active');
        $('#btnToggleMenu').toggleClass('is-active');
    });

    // 1. Carregar Servidores
    function loadServers() {
        $.post('api/servers_api.php', {action: 'list'}, function(data){
            let html = '';
            if(data.length > 0) {
                data.forEach(s => {
                    let percent = Math.round((s.active_connections / s.max_connections) * 100);
                    let color = percent > 80 ? 'bg-danger' : (percent > 50 ? 'bg-warning' : 'bg-success');
                    let statusBadge = s.status == 1 
                        ? `<span class="badge-status status-on"><i class="fa fa-check"></i> ATIVO</span>` 
                        : `<span class="badge-status status-off"><i class="fa fa-ban"></i> OFF</span>`;

                    // STRINGIFY seguro para passar no onclick
                    let jsonStr = JSON.stringify(s).replace(/"/g, '&quot;');

                    html += `
                    <div class="col-xl-3 col-lg-4 col-md-6 col-12">
                        <div class="server-card">
                            <div class="server-header">
                                <h6 class="mb-0 font-weight-bold text-white"><i class="fa fa-server mr-2"></i> ${s.name}</h6>
                                ${statusBadge}
                            </div>
                            <div class="server-body">
                                <small class="text-muted d-block mb-1"><i class="fa fa-globe"></i> ${s.domain}</small>
                                <small class="text-muted d-block mb-3"><i class="fa fa-network-wired"></i> ${s.ip_address}</small>
                                
                                <div class="d-flex justify-content-between small text-white">
                                    <span>Uso: ${s.active_connections} / ${s.max_connections}</span>
                                    <span>${percent}%</span>
                                </div>
                                <div class="progress">
                                    <div class="progress-bar ${color}" style="width: ${percent}%"></div>
                                </div>
                            </div>
                            <div class="server-footer">
                                <div>
                                    <button class="btn btn-sm btn-outline-light mr-1" onclick="toggleStatus(${s.id}, ${s.status})" title="Ligar/Desligar"><i class="fa fa-power-off"></i></button>
                                    <button class="btn btn-sm btn-outline-warning" onclick="resetCount(${s.id})" title="Zerar Contador (Correção)"><i class="fa fa-sync"></i></button>
                                </div>
                                <div>
                                    <button class="btn btn-sm btn-info mr-1" onclick="edit(${jsonStr})"><i class="fa fa-pen"></i></button>
                                    <button class="btn btn-sm btn-danger" onclick="del(${s.id})"><i class="fa fa-trash"></i></button>
                                </div>
                            </div>
                        </div>
                    </div>`;
                });
            } else {
                html = '<div class="col-12 text-center text-muted py-5"><h4>Nenhum servidor cadastrado.</h4><p>Clique em "Novo Servidor" para começar o balanceamento.</p></div>';
            }
            $('#serverGrid').html(html);
        }, 'json');
    }

    // 2. Ações
    function openModal() {
        $('#formServer')[0].reset();
        $('#editId').val('');
        $('#modalTitle').text('Novo Servidor');
        $('#modalServer').modal('show');
    }

    function edit(s) {
        $('#editId').val(s.id);
        $('#editName').val(s.name);
        $('#editDomain').val(s.domain);
        $('#editIp').val(s.ip_address);
        $('#editMax').val(s.max_connections);
        $('#modalTitle').text('Editar: ' + s.name);
        $('#modalServer').modal('show');
    }

    function del(id) {
        if(confirm('Tem certeza? Isso vai remover o servidor do balanceamento.')) {
            $.post('api/servers_api.php', {action:'delete', id:id}, function(res){
                if(res.status) { toastr.success(res.msg); loadServers(); }
            }, 'json');
        }
    }

    function toggleStatus(id, current) {
        $.post('api/servers_api.php', {action:'toggle_status', id:id, status:current}, function(res){
            loadServers();
        }, 'json');
    }

    function resetCount(id) {
        if(confirm('Isso vai zerar o contador de conexões deste servidor para 0. Use apenas se o número estiver errado.')) {
            $.post('api/servers_api.php', {action:'reset_count', id:id}, function(res){
                toastr.success(res.msg); loadServers();
            }, 'json');
        }
    }

    $('#formServer').submit(function(e){
        e.preventDefault();
        $.post('api/servers_api.php', $(this).serialize(), function(res){
            if(res.status) {
                toastr.success(res.msg);
                $('#modalServer').modal('hide');
                loadServers();
            } else {
                toastr.error(res.msg);
            }
        }, 'json');
    });

    // Iniciar
    $(document).ready(function(){
        loadServers();
        // Atualiza a cada 5 segundos para ver o load balance funcionando em tempo real
        setInterval(loadServers, 5000);
    });
</script>

</body>
</html>