<?php
ini_set('pcre.jit', '0');
session_start();

// Apenas o Administrador tem acesso
if (!isset($_SESSION['logado']) || $_SESSION['nivel'] !== 'admin') { 
    header("Location: index.php"); 
    exit; 
}

require_once 'conexao.php'; 

$isAdmin = true;
$usuarioLogado = $_SESSION['usuario'] ?? '';
$msg = "";
$msg_tipo = "";

// --- CORREÇÃO DO ERRO DO MENU LATERAL ---
$total_msg_nao_lidas = 0; 
// ----------------------------------------

// --- 1. CONFIGURAÇÕES VISUAIS ---
$nomePainel = "IPTV PANEL"; 
$corPrimaria = "#7367f0"; 
try {
    $conf = $connGeral->query("SELECT NomePainel, TemaPainel FROM site_config LIMIT 1")->fetch(PDO::FETCH_ASSOC);
    if ($conf) {
        if (!empty($conf['NomePainel'])) $nomePainel = $conf['NomePainel'];
        if (!empty($conf['TemaPainel'])) $corPrimaria = $conf['TemaPainel'];
    }
} catch (Exception $e) { }

// --- 2. PROCURAR O SERVIDOR CSP NA BASE DE DADOS ---
$stmt = $connGeral->query("SELECT url, porta, usuario, senha, protocolo FROM painel WHERE block != 'sim' OR block IS NULL LIMIT 1");
$srv = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$srv) {
    die("ERRO: Nenhum servidor CSP configurado ou ativo na tabela 'painel'.");
}

$ip = str_replace(['http://', 'https://', '/'], '', $srv['url']);
$porta = trim($srv['porta']); 
$user_csp = trim($srv['usuario']);
$pass_csp = trim($srv['senha']);
$protocolo = !empty($srv['protocolo']) ? $srv['protocolo'] : 'http';

$csp_base_url = "{$protocolo}://{$ip}:{$porta}";
$csp_auth = "{$user_csp}:{$pass_csp}";

// --- FUNÇÃO PARA CRIAR SESSÃO NA CSP (LOGIN REAL) ---
function getCspSession($url, $user, $pass, $auth) {
    $ch = curl_init();
    $login_xml = "<cws-status-req ver=\"1.0\">\n<cws-login>\n<user name=\"{$user}\" password=\"{$pass}\"/>\n</cws-login>\n</cws-status-req>";

    curl_setopt($ch, CURLOPT_URL, $url . "/xmlHandler");
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $login_xml);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_TIMEOUT, 10);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_USERPWD, $auth);
    curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
    curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: text/xml']);

    $res = curl_exec($ch);
    curl_close($ch);

    if ($res && preg_match('/state="loggedIn"/i', $res) && preg_match('/session-id="([^"]+)"/i', $res, $matches)) {
        return $matches[1]; 
    }
    return false;
}

// --- FUNÇÃO PARA LER O FICHEIRO XML DE CONFIGURAÇÃO ---
function getCspXml($url, $user, $pass, $auth) {
    $session_id = getCspSession($url, $user, $pass, $auth);
    if (!$session_id) return "ERRO_HTTP|Falha no Login da CSP. Verifique as credenciais.";

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url . "/xmlHandler?command=fetch-cfg");
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_TIMEOUT, 15);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_USERPWD, $auth);
    curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
    curl_setopt($ch, CURLOPT_HTTPHEADER, ["Cookie: sessionId={$session_id}"]);
    
    $xml_raw = curl_exec($ch);
    $httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);
    
    if ($httpcode == 200 && !empty($xml_raw)) {
        if (strpos($xml_raw, 'Super-user required') !== false) return "ERRO_HTTP|Acesso negado: Super User requerido.";
        return trim($xml_raw);
    }
    return "ERRO_HTTP|Código HTTP retornado ao tentar ler: $httpcode.";
}

// --- FUNÇÃO DEFINITIVA PARA LER O STATUS (ONLINE/OFFLINE) ---
function getCspStatus($url, $user, $pass, $auth, &$debug_out) {
    $session_id = getCspSession($url, $user, $pass, $auth);
    if (!$session_id) {
        $debug_out = "ERRO: O Login falhou. Não foi gerado nenhum session-id para o status.";
        return [];
    }

    $ch = curl_init();
    
    $status_xml = "<cws-status-req ver=\"1.0\">\n" .
                  "<session session-id=\"{$session_id}\"/>\n" .
                  "<proxy-status include=\"true\"/>\n" .
                  "<cws-connectors include=\"true\"/>\n" .
                  "</cws-status-req>";

    curl_setopt($ch, CURLOPT_URL, $url . "/xmlHandler");
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $status_xml);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_TIMEOUT, 10);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_USERPWD, $auth);
    curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
    curl_setopt($ch, CURLOPT_HTTPHEADER, [
        'Content-Type: text/xml',
        "Cookie: sessionId={$session_id}"
    ]);
    
    $xml_raw = curl_exec($ch);
    $httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    $curl_error = curl_error($ch);
    curl_close($ch);
    
    $debug_out = "HTTP CODE: {$httpcode}\nCURL ERROR: {$curl_error}\nSESSION: {$session_id}\nXML ENVIADO:\n{$status_xml}\n\nRESPOSTA RAW DO SERVIDOR:\n" . substr($xml_raw, 0, 1500) . "\n...";

    $status_map = [];
    if ($httpcode == 200 && !empty($xml_raw)) {
        if (preg_match_all('/<[^>]*connector\s+([^>]+)>/i', $xml_raw, $matches)) {
            foreach ($matches[1] as $attrs) {
                $name = '';
                $estado = '';
                if (preg_match('/name=["\']([^"\']+)["\']/i', $attrs, $mName)) $name = trim($mName[1]);
                if (preg_match('/state=["\']([^"\']+)["\']/i', $attrs, $mState)) $estado = trim(strtolower($mState[1]));
                if (empty($estado) && preg_match('/status=["\']([^"\']+)["\']/i', $attrs, $mStatus)) {
                    $estado = trim(strtolower($mStatus[1]));
                }
                if (!empty($name) && !empty($estado)) {
                    $status_map[$name] = $estado;
                }
            }
        }
    }
    return $status_map;
}

// --- FUNÇÃO PARA GUARDAR O FICHEIRO XML ---
function saveCspXml($url, $user, $pass, $auth, $xml_content) {
    $session_id = getCspSession($url, $user, $pass, $auth);
    if (!$session_id) return false;

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url . "/cfgHandler");
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $xml_content);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_TIMEOUT, 15);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_USERPWD, $auth);
    curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
    curl_setopt($ch, CURLOPT_HTTPHEADER, [
        'Content-Type: text/xml',
        'Expect:',
        "Cookie: sessionId={$session_id}"
    ]);
    
    $httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_exec($ch);
    curl_close($ch);
    
    return true; 
}

// --- FUNÇÃO: REINICIAR (SHUTDOWN) SERVIDOR CSP ---
function restartCsp($url, $user, $pass, $auth, &$debug_out) {
    $session_id = getCspSession($url, $user, $pass, $auth);
    if (!$session_id) {
        $debug_out = "Falha ao obter session-id para reinício.";
        return false;
    }

    $ch = curl_init();
    
    $restart_xml = "<cws-command-req ver=\"1.0\">\n" .
                   "<session session-id=\"{$session_id}\"/>\n" .
                   "<command command=\"shutdown\"/>\n" .
                   "</cws-command-req>";

    curl_setopt($ch, CURLOPT_URL, $url . "/xmlHandler");
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $restart_xml);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_TIMEOUT, 5); 
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_USERPWD, $auth);
    curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
    curl_setopt($ch, CURLOPT_HTTPHEADER, [
        'Content-Type: text/xml',
        "Cookie: sessionId={$session_id}"
    ]);
    
    $result = curl_exec($ch);
    $httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    $curl_error = curl_error($ch);
    curl_close($ch);
    
    $debug_out = "HTTP: {$httpcode}\nCURL ERR: {$curl_error}\nXML ENVIADO:\n{$restart_xml}\n\nRESPOSTA CSP:\n" . substr($result, 0, 800);

    if ($httpcode == 0 || $result === false) return true;
    if ($httpcode == 200 && strpos($result, 'IllegalArgumentException') === false) return true;

    return false;
}

// --- 3. PROCESSAR FORMULÁRIOS ---
$xml_string = getCspXml($csp_base_url, $user_csp, $pass_csp, $csp_auth);

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['acao']) && strpos($xml_string, 'ERRO_') !== 0) {
    $acao = $_POST['acao'];

    // REINICIAR CSP
    if ($acao === 'reiniciar_csp') {
        $restart_debug = "";
        if (restartCsp($csp_base_url, $user_csp, $pass_csp, $csp_auth, $restart_debug)) {
            $msg = "<i class='fas fa-sync fa-spin me-2'></i> <b>Servidor Desligado/Reiniciado!</b> A ligação com a CSP foi cortada. Se tiver o Auto-Restart (Cão de Guarda) ativado, ela voltará a ligar em menos de 1 minuto."; 
            $msg_tipo = "success";
            sleep(2); 
        } else {
            $msg = "<b>Falha ao reiniciar CSP.</b> Veja a resposta do servidor abaixo:<br><br>
                    <textarea class='form-control bg-dark text-warning font-monospace mt-2' rows='6' readonly>" . htmlspecialchars($restart_debug) . "</textarea>"; 
            $msg_tipo = "danger";
        }
    }
    
    // Processamento de edição do XML
    if ($xml_string && $acao !== 'reiniciar_csp') {
        $dom = new DOMDocument();
        $dom->preserveWhiteSpace = false;
        $dom->formatOutput = true;
        @$dom->loadXML($xml_string);
        
        $xpath = new DOMXPath($dom);
        $connectorsNode = $xpath->query('//cws-connectors')->item(0);

        if ($connectorsNode) {
            // SUBSTITUIÇÃO EM MASSA
            if ($acao === 'substituir_massa') {
                $campo = $_POST['campo']; 
                $valor_antigo = trim($_POST['valor_antigo']);
                $valor_novo = trim($_POST['valor_novo']);
                $linhas_afetadas = 0;

                $connectorsList = $xpath->query('//newcamd-connector');
                foreach ($connectorsList as $conn) {
                    $targetNode = $conn->getElementsByTagName($campo)->item(0);
                    if ($targetNode && $targetNode->nodeValue === $valor_antigo) {
                        $targetNode->nodeValue = $valor_novo;
                        $linhas_afetadas++;
                    }
                }

                if ($linhas_afetadas > 0) {
                    $novo_xml = $dom->saveXML();
                    if (saveCspXml($csp_base_url, $user_csp, $pass_csp, $csp_auth, $novo_xml)) {
                        $msg = "<b>{$linhas_afetadas} linha(s)</b> atualizada(s) com sucesso!"; $msg_tipo = "success";
                        $xml_string = $novo_xml;
                    } else {
                        $msg = "Erro ao guardar as alterações na CSP."; $msg_tipo = "danger";
                    }
                } else {
                    $msg = "Nenhuma linha encontrada com o valor antigo '<b>{$valor_antigo}</b>' no campo '<b>{$campo}</b>'."; 
                    $msg_tipo = "warning";
                }
            }

            // EXCLUIR
            if ($acao === 'excluir' && isset($_POST['connector_name'])) {
                $name_to_delete = $_POST['connector_name'];
                $node_to_delete = $xpath->query("//newcamd-connector[@name='$name_to_delete']")->item(0);
                if ($node_to_delete) {
                    $node_to_delete->parentNode->removeChild($node_to_delete);
                    $novo_xml = $dom->saveXML();
                    if (saveCspXml($csp_base_url, $user_csp, $pass_csp, $csp_auth, $novo_xml)) {
                        $msg = "Conector <b>{$name_to_delete}</b> removido com sucesso!"; $msg_tipo = "success";
                        $xml_string = $novo_xml; 
                    } else {
                        $msg = "Erro ao guardar na CSP."; $msg_tipo = "danger";
                    }
                }
            }
            
            // ADICIONAR
            if ($acao === 'adicionar') {
                $profile = $_POST['profile'];
                $name = $_POST['name'];
                $host = $_POST['host'];
                $port = $_POST['port'];
                $user = $_POST['user'];
                $password = $_POST['password'];
                $enabled = isset($_POST['enabled']) ? 'true' : 'false';
                $async = isset($_POST['async']) ? 'true' : 'false';

                if ($xpath->query("//newcamd-connector[@name='$name']")->length > 0) {
                    $msg = "Já existe um conector com o nome <b>{$name}</b>."; $msg_tipo = "warning";
                } else {
                    $newConn = $dom->createElement('newcamd-connector');
                    $newConn->setAttribute('name', $name);
                    $newConn->setAttribute('profile', $profile);
                    $newConn->setAttribute('enabled', $enabled);
                    $newConn->setAttribute('metric', '0'); 

                    $newConn->appendChild($dom->createElement('host', $host));
                    $newConn->appendChild($dom->createElement('port', $port));
                    $newConn->appendChild($dom->createElement('user', $user));
                    $newConn->appendChild($dom->createElement('password', $password));
                    $newConn->appendChild($dom->createElement('asynchronous', $async));

                    $connectorsNode->appendChild($newConn);
                    $novo_xml = $dom->saveXML();
                    
                    if (saveCspXml($csp_base_url, $user_csp, $pass_csp, $csp_auth, $novo_xml)) {
                        $msg = "Conector <b>{$name}</b> adicionado com sucesso!"; $msg_tipo = "success";
                        $xml_string = $novo_xml;
                    } else {
                        $msg = "Erro ao enviar o XML atualizado."; $msg_tipo = "danger";
                    }
                }
            }
            
            // EDITAR
             if ($acao === 'editar') {
                $old_name = $_POST['old_name'];
                $name = $_POST['name'];
                $profile = $_POST['profile'];
                $host = $_POST['host'];
                $port = $_POST['port'];
                $user = $_POST['user'];
                $password = $_POST['password'];
                $enabled = isset($_POST['enabled']) ? 'true' : 'false';
                $async = isset($_POST['async']) ? 'true' : 'false';

                $node_to_edit = $xpath->query("//newcamd-connector[@name='$old_name']")->item(0);
                
                if ($node_to_edit) {
                    if ($old_name !== $name && $xpath->query("//newcamd-connector[@name='$name']")->length > 0) {
                        $msg = "Já existe um conector com o nome <b>{$name}</b>."; $msg_tipo = "warning";
                    } else {
                        $node_to_edit->setAttribute('name', $name);
                        $node_to_edit->setAttribute('profile', $profile);
                        $node_to_edit->setAttribute('enabled', $enabled);

                        while ($node_to_edit->hasChildNodes()) {
                            $node_to_edit->removeChild($node_to_edit->firstChild);
                        }

                        $node_to_edit->appendChild($dom->createElement('host', $host));
                        $node_to_edit->appendChild($dom->createElement('port', $port));
                        $node_to_edit->appendChild($dom->createElement('user', $user));
                        $node_to_edit->appendChild($dom->createElement('password', $password));
                        $node_to_edit->appendChild($dom->createElement('asynchronous', $async));

                        $novo_xml = $dom->saveXML();
                        if (saveCspXml($csp_base_url, $user_csp, $pass_csp, $csp_auth, $novo_xml)) {
                            $msg = "Conector <b>{$name}</b> atualizado!"; $msg_tipo = "success";
                            $xml_string = $novo_xml;
                        } else {
                            $msg = "Erro ao atualizar o XML."; $msg_tipo = "danger";
                        }
                    }
                }
            }
        }
    }
}

// --- 4. PREPARAÇÃO DA TELA COM DADOS DE CONFIGURAÇÃO + STATUS ---
$connectors_by_profile = [];
$all_profiles = [];
$status_map = [];
$status_debug = "";

if (is_string($xml_string) && strpos($xml_string, 'ERRO_') === 0) {
    $msg = "Falha ao se comunicar com a CSP. <br><br><b>Diagnóstico:</b> " . htmlspecialchars(substr($xml_string, 10)); 
    $msg_tipo = "danger";
    $xml_string = false;
} elseif ($xml_string) {
    
    $status_map = getCspStatus($csp_base_url, $user_csp, $pass_csp, $csp_auth, $status_debug);

    $xml = @simplexml_load_string($xml_string);
    if ($xml) {
        $profiles = $xml->xpath('//ca-profiles/profile');
        if ($profiles) {
            foreach ($profiles as $prof) {
                $profileName = (string)$prof['name'];
                $all_profiles[$profileName] = $profileName;
            }
        }

        $connectors = $xml->xpath('//newcamd-connector');
        if ($connectors && count($connectors) > 0) {
            foreach ($connectors as $conn) {
                $prof = (string)$conn['profile'];
                $name = trim((string)$conn['name']);
                
                if (!isset($connectors_by_profile[$prof])) {
                    $connectors_by_profile[$prof] = [];
                }
                
                $estado_atual = $status_map[$name] ?? 'desconhecido';

                $connectors_by_profile[$prof][] = [
                    'name' => $name,
                    'host' => (string)$conn->host,
                    'port' => (string)$conn->port,
                    'user' => (string)$conn->user,
                    'password' => (string)$conn->password,
                    'enabled' => (string)$conn['enabled'],
                    'async' => isset($conn->asynchronous) ? (string)$conn->asynchronous : 'false',
                    'estado_conexao' => $estado_atual
                ];
            }
        }
    }
}
?>

<!DOCTYPE html>
<html lang="pt-br">
<head>

<?php include 'tema_global.php'; ?>

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Gerenciar Linhas CSP | <?= htmlspecialchars($nomePainel) ?></title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" rel="stylesheet">
    <style>
        :root { 
            --primary: <?= $corPrimaria ?>; 
            --bg-body: #151521; 
            --bg-card: #1e1e2d; 
            --text-color: #d0d2d6;
            --border-color: #2b2b40;
            --overlay-desk: rgba(0, 0, 0, 0.65); 
            --overlay-mob: rgba(0, 0, 0, 0.85); 
        }
        body.light-mode { 
            --bg-body: #f4f5f8; 
            --bg-card: #ffffff; 
            --text-color: #5e5873; 
            --border-color: #ebe9f1; 
            --overlay-desk: rgba(255, 255, 255, 0.1); 
            --overlay-mob: rgba(255, 255, 255, 0); 
        }
        body { background-color: var(--bg-body); color: var(--text-color); font-family: 'Segoe UI', sans-serif; overflow-x: hidden; margin: 0; }
        
        /* Sidebar Restourada com as mesmas especificações Premium */
        .sidebar { width: 260px; height: 100vh; position: fixed; background: var(--bg-card); border-right: 1px solid var(--border-color); z-index: 1050; padding: 20px; overflow-y: auto; transition: transform 0.3s ease, box-shadow 0.3s ease; }
        .sidebar .nav-link { white-space: nowrap !important; overflow: hidden; text-overflow: ellipsis; display: flex; align-items: center; color: #a6a6b7; padding: 12px 15px; border-radius: 8px; text-decoration: none; margin-bottom: 5px; font-weight: 500; transition: 0.2s; }
        .sidebar .nav-link:hover, .sidebar .nav-link.active { background: var(--primary); color: #fff; box-shadow: 0 4px 15px rgba(0,0,0,0.2); }
        .sidebar .nav-link i.fa-fw { margin-right: 8px; text-align: center; }
        .nav-group-title { font-size: 0.75rem; text-transform: uppercase; color: #5e5873; font-weight: 700; margin: 25px 0 10px 12px; letter-spacing: 1px; }
        
        /* Main Content ajustado para Flexbox p/ empurrar Rodapé */
        .main-content { margin-left: 260px; transition: 0.3s; display: flex; flex-direction: column; min-height: 100vh; }
        .top-header { background: linear-gradient(90deg, var(--bg-card) 0%, var(--overlay-desk) 100%), var(--primary); padding: 15px 30px; display: flex; align-items: center; justify-content: space-between; border-bottom: 1px solid rgba(255,255,255,0.1); margin-bottom: 30px;}
        .header-title { font-size: 1.3rem; font-weight: 800; color: #fff; text-transform: uppercase; letter-spacing: 1px; margin: 0; }

        /* Elementos Premium */
        .card-custom { background-color: var(--bg-card) !important; border: 1px solid var(--border-color) !important; border-radius: 12px; overflow: hidden; margin-bottom: 20px; box-shadow: 0 4px 15px rgba(0,0,0,0.05); }
        .card-header-profile { background: rgba(115, 103, 240, 0.1); border-bottom: 1px solid var(--border-color); padding: 15px 20px; font-weight: bold; color: var(--primary); text-transform: uppercase; display: flex; justify-content: space-between; align-items: center; }
        
        /* Tabela Dinâmica que respeita Tema Claro/Escuro DE VERDADE */
        .table-custom { width: 100%; margin-bottom: 0; border-collapse: separate; border-spacing: 0; background: transparent !important; }
        .table-custom th { background-color: var(--bg-card) !important; border-bottom: 1px solid var(--border-color) !important; color: #a6a6b7 !important; font-size: 0.8rem; text-transform: uppercase; font-weight: 700; padding: 15px; white-space: nowrap; }
        .table-custom td { background-color: var(--bg-card) !important; border-bottom: 1px solid var(--border-color) !important; color: var(--text-color) !important; vertical-align: middle; padding: 15px; font-size: 0.95rem; }
        .table-custom tbody tr:hover td { background-color: rgba(115, 103, 240, 0.08) !important; }

        /* Inputs Customizados Dinâmicos */
        .form-control, .form-select { background-color: rgba(0,0,0,0.1) !important; border: 1px solid var(--border-color) !important; color: var(--text-color) !important; border-radius: 8px; padding: 10px 15px; transition: 0.2s; }
        body.light-mode .form-control, body.light-mode .form-select { background-color: rgba(0,0,0,0.03) !important; }
        .form-control:focus, .form-select:focus { border-color: var(--primary) !important; box-shadow: 0 0 0 0.25rem rgba(115, 103, 240, 0.25) !important; background-color: transparent !important;}

        .header-actions { display: flex; gap: 10px; flex-wrap: nowrap; align-items: center; }
        .form-restart { display: inline-block; margin: 0; padding: 0; }

        @media (max-width: 992px) { 
            .sidebar { transform: translateX(-100%); } 
            .sidebar.show { transform: translateX(0); box-shadow: 5px 0 30px rgba(0,0,0,0.9); } 
            .main-content { margin-left: 0; } 
            .mobile-toggle { display: block !important; margin-right: 15px; } 
            
            .top-header { flex-direction: column; align-items: flex-start; gap: 15px; padding: 15px 20px; background: linear-gradient(var(--overlay-mob), var(--overlay-mob)), var(--primary); border-bottom: none; }
            .header-actions { width: 100%; display: flex; flex-direction: column; gap: 10px; }
            .form-restart { width: 100%; }
            .header-actions .btn { width: 100%; padding: 12px; font-size: 0.95rem; display: flex; justify-content: center; align-items: center; }
            .header-actions .btn i { margin-right: 8px !important; margin-bottom: 0; font-size: 1.1rem; }
        }
        
        .mobile-toggle { display: none; background: none; border: none; color: #fff; font-size: 1.5rem; }
        .overlay { display: none; position: fixed; inset: 0; background: rgba(0,0,0,0.7); z-index: 1040; backdrop-filter: blur(3px); }
        .overlay.show { display: block; }

        .status-dot { height: 10px; width: 10px; border-radius: 50%; display: inline-block; margin-right: 5px; }
        .status-connected { background-color: #28c76f; box-shadow: 0 0 8px #28c76f; }
        .status-disconnected { background-color: #ea5455; box-shadow: 0 0 8px #ea5455; }
        .status-connecting { background-color: #ff9f43; animation: blink 1s infinite alternate; }
        @keyframes blink { from { opacity: 1; } to { opacity: 0.3; } }
    </style>
</head>
<body>
<?php include 'menu.php'; ?>
<div class="overlay" id="overlay" onclick="toggleMenu()"></div>

<main class="main-content d-flex flex-column min-vh-100">
    <div class="top-header">
        <div class="d-flex align-items-center w-100">
            <button class="mobile-toggle" onclick="toggleMenu()"><i class="fas fa-bars"></i></button>
            <div class="header-title"><i class="fas fa-plug me-2"></i> Gerenciador CSP</div>
        </div>
        
        <?php if($xml_string !== false): ?>
        <div class="header-actions">
            <button class="btn btn-info fw-bold rounded-pill shadow-sm text-dark" onclick="abrirModalTutorial()">
                <i class="fas fa-terminal"></i> AUTO-RESTART
            </button>

            <form method="POST" class="form-restart">
                <input type="hidden" name="acao" value="reiniciar_csp">
                <button type="submit" class="btn btn-danger fw-bold rounded-pill shadow-sm" onclick="return confirm('ATENÇÃO: Vai desligar a CSP. Se o seu Linux tiver o Auto-Restart configurado, ela ligará sozinha. Tem a certeza?')">
                    <i class="fas fa-power-off"></i> <span class="d-none d-md-inline">REINICIAR</span> CSP
                </button>
            </form>

            <button class="btn btn-warning fw-bold rounded-pill shadow-sm text-dark" onclick="abrirModalMassa()">
                <i class="fas fa-exchange-alt"></i> ALTERAR EM MASSA
            </button>
            <button class="btn btn-light fw-bold rounded-pill shadow-sm text-primary" onclick="abrirModalAdicionar()">
                <i class="fas fa-plus"></i> NOVA LINHA
            </button>
        </div>
        <?php endif; ?>
    </div>

    <div class="container-fluid p-3 p-md-4 flex-grow-1">
        
        <?php if($msg): ?>
            <div class="alert alert-<?= $msg_tipo ?> alert-dismissible fade show border-0 shadow-sm fw-bold">
                <?= $msg ?>
                <button class="btn-close" data-bs-dismiss="alert"></button>
            </div>
        <?php endif; ?>

        <?php if ($xml_string && empty($connectors_by_profile)): ?>
            <div class="alert alert-warning fw-bold border-0 shadow-sm">Nenhum conector encontrado na configuração da CSP.</div>
        <?php endif; ?>

        <?php foreach ($connectors_by_profile as $profile => $connectors): ?>
            <div class="card card-custom shadow-lg">
                <div class="card-header-profile">
                    <span><i class="fas fa-server me-2"></i> OPERADORA: <?= htmlspecialchars($profile) ?></span>
                    <span class="badge bg-secondary shadow-sm"><?= count($connectors) ?> Conectores</span>
                </div>
                <div class="table-responsive">
                    <table class="table table-custom table-hover align-middle">
                        <thead>
                            <tr>
                                <th class="ps-4">Status / Nome</th>
                                <th>Host : Porta</th>
                                <th>Usuário</th>
                                <th>Conexão</th>
                                <th>Configuração</th>
                                <th class="text-end pe-4">Ações</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($connectors as $conn): ?>
                            <tr>
                                <td class="ps-4 fw-bold" style="color: var(--text-color);">
                                    <?php 
                                        if($conn['estado_conexao'] === 'connected' || $conn['estado_conexao'] === 'online') {
                                            echo '<span class="status-dot status-connected" title="Online (Conectado)"></span>';
                                        } elseif ($conn['estado_conexao'] === 'disconnected' || $conn['estado_conexao'] === 'wait' || $conn['estado_conexao'] === 'offline') {
                                            echo '<span class="status-dot status-disconnected" title="Offline (Desconectado)"></span>';
                                        } elseif ($conn['estado_conexao'] === 'connecting') {
                                            echo '<span class="status-dot status-connecting" title="A tentar conectar..."></span>';
                                        } else {
                                            echo '<i class="fas fa-question-circle text-muted me-1" title="Desconhecido"></i>';
                                        }
                                    ?>
                                    <?= htmlspecialchars($conn['name']) ?>
                                </td>
                                <td class="text-info font-monospace fw-bold"><?= htmlspecialchars($conn['host']) ?> : <span class="text-warning"><?= htmlspecialchars($conn['port']) ?></span></td>
                                <td style="color: var(--text-color); opacity: 0.8;"><?= htmlspecialchars($conn['user']) ?></td>
                                
                                <td>
                                    <?php if($conn['estado_conexao'] === 'connected' || $conn['estado_conexao'] === 'online'): ?>
                                        <span class="badge bg-success bg-opacity-10 text-success border border-success px-2 py-1">ONLINE</span>
                                    <?php elseif ($conn['estado_conexao'] === 'disconnected' || $conn['estado_conexao'] === 'wait' || $conn['estado_conexao'] === 'offline'): ?>
                                        <span class="badge bg-danger bg-opacity-10 text-danger border border-danger px-2 py-1">OFFLINE</span>
                                    <?php elseif ($conn['estado_conexao'] === 'connecting'): ?>
                                        <span class="badge bg-warning bg-opacity-10 text-warning border border-warning px-2 py-1">CONECTANDO</span>
                                    <?php else: ?>
                                        <span class="badge bg-secondary bg-opacity-10 text-secondary border border-secondary px-2 py-1">DESCONHECIDO</span>
                                    <?php endif; ?>
                                </td>

                                <td>
                                    <?php if ($conn['enabled'] === 'true' || $conn['enabled'] === '1'): ?>
                                        <span class="badge bg-success bg-opacity-10 text-success border border-success me-1 px-2 py-1">Ativo</span>
                                    <?php else: ?>
                                        <span class="badge bg-danger bg-opacity-10 text-danger border border-danger me-1 px-2 py-1">Inativo</span>
                                    <?php endif; ?>
                                    
                                    <?php if ($conn['async'] === 'true' || $conn['async'] === '1'): ?>
                                        <span class="badge bg-info bg-opacity-10 text-info border border-info px-2 py-1" title="Asynchronous">Async</span>
                                    <?php endif; ?>
                                </td>
                                <td class="text-end pe-4">
                                    <div class="d-flex gap-2 justify-content-end">
                                        <button class="btn btn-sm btn-outline-info shadow-sm rounded-3" onclick='abrirEditar(<?= json_encode(array_merge($conn, ['profile' => $profile])) ?>)' title="Editar">
                                            <i class="fas fa-pen"></i>
                                        </button>
                                        <form method="POST" class="m-0">
                                            <input type="hidden" name="acao" value="excluir">
                                            <input type="hidden" name="connector_name" value="<?= htmlspecialchars($conn['name']) ?>">
                                            <button class="btn btn-sm btn-outline-danger shadow-sm rounded-3" onclick="return confirm('Deseja excluir a linha <?= htmlspecialchars($conn['name']) ?>? (A CSP será recarregada)')" title="Excluir">
                                                <i class="fas fa-trash"></i>
                                            </button>
                                        </form>
                                    </div>
                                </td>
                            </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        <?php endforeach; ?>

    </div>
    
    <div class="mt-auto w-100">
        <?php include 'rodape.php'; ?>
    </div>
</main>

<div class="modal fade" id="modalTutorial" tabindex="-1">
    <div class="modal-dialog modal-dialog-centered modal-lg">
        <div class="modal-content border-secondary" style="background-color: var(--bg-card);">
            <div class="modal-header border-secondary">
                <h5 class="modal-title fw-bold text-info"><i class="fas fa-shield-alt me-2"></i> Instalação do Auto-Restart (Cão de Guarda)</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" style="filter: invert(1) grayscale(100%) brightness(200%);"></button>
            </div>
            <div class="modal-body" style="color: var(--text-color);">
                <p>Para que o botão de <b>REINICIAR CSP</b> funcione de forma automática e para que o seu servidor nunca fique offline caso a CSP trave, instale este script na sua máquina Linux.</p>
                <p class="text-warning small mb-3"><i class="fas fa-exclamation-triangle"></i> <b>Só precisa de fazer isto uma única vez!</b></p>
                
                <ol class="mb-4 opacity-75">
                    <li class="mb-2">Abra o seu terminal SSH (Putty, Bitvise, Termius, etc.) e faça login no servidor da CSP.</li>
                    <li class="mb-2">Clique no botão abaixo para copiar o código de instalação.</li>
                    <li class="mb-2">Cole o código no terminal (botão direito do mouse) e aperte <b>ENTER</b>.</li>
                </ol>

                <div class="position-relative">
                    <textarea id="codigoTutorial" class="form-control text-info font-monospace" rows="16" readonly style="resize:none; font-size:13px;">cd /usr/local/csp
cat > check_csp.sh << 'EOF'
#!/bin/bash
# Verifica se o processo do CSP (Java) esta a correr
if ! ps aux | grep -v grep | grep -iq "java"; then
    echo "CSP parada! Reiniciando agora..."
    cd /usr/local/csp
    ./cardproxy.sh start
    sleep 2
    if ! ps aux | grep -v grep | grep -iq "java"; then
        cd /usr/local/csp/csp
        ./cardproxy.sh start
    fi
fi
EOF
chmod +x check_csp.sh
(crontab -l 2>/dev/null | grep -v "check_csp.sh"; echo "* * * * * /usr/local/csp/check_csp.sh > /dev/null 2>&1") | crontab -
echo "CACHORRO DE GUARDA INSTALADO COM SUCESSO!"</textarea>
                </div>
            </div>
            <div class="modal-footer border-secondary">
                <button type="button" class="btn btn-secondary fw-bold shadow-sm rounded-pill px-4" data-bs-dismiss="modal">Fechar</button>
                <button type="button" class="btn btn-info fw-bold shadow-sm rounded-pill px-4 text-dark" onclick="copiarCodigoTutorial()"><i class="fas fa-copy me-1"></i> COPIAR CÓDIGO</button>
            </div>
        </div>
    </div>
</div>

<div class="modal fade" id="modalMassa" tabindex="-1">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content border-secondary" style="background-color: var(--bg-card);">
            <form method="POST">
                <input type="hidden" name="acao" value="substituir_massa">
                <div class="modal-header border-secondary">
                    <h5 class="modal-title fw-bold text-warning"><i class="fas fa-exchange-alt me-2"></i> Substituição em Massa</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" style="filter: invert(1) grayscale(100%) brightness(200%);"></button>
                </div>
                <div class="modal-body p-4">
                    <div class="alert alert-info small py-2 mb-4 border-0 shadow-sm fw-bold">
                        <i class="fas fa-info-circle me-1"></i> O sistema procurará em <b>todas</b> as operadoras e substituirá o valor antigo pelo novo.
                    </div>
                    
                    <div class="mb-3">
                        <label class="form-label small fw-bold" style="color: var(--text-color); opacity: 0.7;">O QUE DESEJA ALTERAR?</label>
                        <select name="campo" class="form-select" required>
                            <option value="host">URL / Host / DNS</option>
                            <option value="user">Usuário</option>
                            <option value="password">Senha</option>
                            <option value="port">Porta</option>
                        </select>
                    </div>

                    <div class="mb-3">
                        <label class="form-label small fw-bold" style="color: var(--text-color); opacity: 0.7;">VALOR ANTIGO (Procurar por:)</label>
                        <input type="text" name="valor_antigo" class="form-control" placeholder="Ex: clarofull.antigo.com" required>
                    </div>

                    <div class="mb-3">
                        <label class="form-label small fw-bold" style="color: var(--text-color); opacity: 0.7;">NOVO VALOR (Substituir por:)</label>
                        <input type="text" name="valor_novo" class="form-control" placeholder="Ex: clarofull.novo.com" required>
                    </div>
                </div>
                <div class="modal-footer border-secondary">
                    <button type="submit" class="btn btn-warning w-100 fw-bold py-2 shadow-sm rounded-pill text-dark" onclick="return confirm('Tem certeza? Isso alterará todas as linhas que possuírem o valor antigo. A CSP será recarregada.')">EXECUTAR SUBSTITUIÇÃO</button>
                </div>
            </form>
        </div>
    </div>
</div>

<div class="modal fade" id="modalLinha" tabindex="-1">
    <div class="modal-dialog modal-dialog-centered modal-lg">
        <div class="modal-content border-secondary" style="background-color: var(--bg-card);">
            <form method="POST" id="formLinha">
                <input type="hidden" name="acao" value="adicionar" id="inputAcao">
                <input type="hidden" name="old_name" id="inputOldName">
                
                <div class="modal-header border-secondary">
                    <h5 class="modal-title fw-bold" style="color: var(--text-color);" id="modalTitulo"><i class="fas fa-plus text-primary me-2"></i> Adicionar Nova Linha</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" style="filter: invert(1) grayscale(100%) brightness(200%);"></button>
                </div>
                <div class="modal-body p-4">
                    <div class="row g-3">
                        <div class="col-md-6 mb-2">
                            <label class="form-label small fw-bold" style="color: var(--text-color); opacity: 0.7;">NOME DA LINHA (ID ÚNICO)</label>
                            <input type="text" name="name" id="name" class="form-control" placeholder="Ex: CLARO-001" required>
                        </div>
                        <div class="col-md-6 mb-2">
                            <label class="form-label small fw-bold" style="color: var(--text-color); opacity: 0.7;">OPERADORA (PROFILE)</label>
                            <select name="profile" id="profile" class="form-select" required>
                                <?php foreach ($all_profiles as $prof): ?>
                                    <option value="<?= htmlspecialchars($prof) ?>"><?= htmlspecialchars($prof) ?></option>
                                <?php endforeach; ?>
                                <option value="__novo__">+ Novo Profile...</option>
                            </select>
                            <input type="text" id="novoProfileNome" class="form-control mt-2" placeholder="Digite o nome do novo profile" style="display: none;" disabled>
                        </div>
                    </div>
                    
                    <div class="row g-3">
                        <div class="col-md-8 mb-2">
                            <label class="form-label small fw-bold" style="color: var(--text-color); opacity: 0.7;">HOST / IP / URL</label>
                            <input type="text" name="host" id="host" class="form-control" placeholder="Ex: clarofull.linhas.top" required>
                        </div>
                        <div class="col-md-4 mb-2">
                            <label class="form-label small fw-bold" style="color: var(--text-color); opacity: 0.7;">PORTA</label>
                            <input type="number" name="port" id="port" class="form-control" placeholder="Ex: 22000" required>
                        </div>
                    </div>
                    
                    <div class="row g-3">
                        <div class="col-md-6 mb-2">
                            <label class="form-label small fw-bold" style="color: var(--text-color); opacity: 0.7;">USUÁRIO (USER)</label>
                            <input type="text" name="user" id="user" class="form-control" required>
                        </div>
                        <div class="col-md-6 mb-2">
                            <label class="form-label small fw-bold" style="color: var(--text-color); opacity: 0.7;">SENHA (PASSWORD)</label>
                            <input type="text" name="password" id="password" class="form-control" required>
                        </div>
                    </div>
                    
                    <div class="row mt-3">
                        <div class="col-md-6">
                            <div class="form-check form-switch d-flex align-items-center gap-2">
                                <label class="small fw-bold mb-0" style="color: var(--text-color);">ATIVAR LINHA</label>
                                <input class="form-check-input m-0" type="checkbox" id="enabled" name="enabled" style="width: 40px; height: 20px; cursor:pointer;" checked>
                            </div>
                        </div>
                        <div class="col-md-6 mt-3 mt-md-0">
                            <div class="form-check form-switch d-flex align-items-center gap-2">
                                <label class="small fw-bold mb-0" style="color: var(--text-color);">CONEXÃO ASSÍNCRONA</label>
                                <input class="form-check-input m-0" type="checkbox" id="async" name="async" style="width: 40px; height: 20px; cursor:pointer;" checked>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="modal-footer border-secondary">
                    <button type="submit" class="btn btn-primary w-100 fw-bold py-2 shadow-sm rounded-pill">SALVAR LINHA NA CSP</button>
                </div>
            </form>
        </div>
    </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
<script>
    function toggleMenu() { 
        document.getElementById('sidebar').classList.toggle('show'); 
        document.getElementById('overlay').classList.toggle('show'); 
    }
    
    document.getElementById('profile').addEventListener('change', function() {
        var novoInput = document.getElementById('novoProfileNome');
        if (this.value === '__novo__') {
            novoInput.style.display = 'block';
            novoInput.disabled = false;
            novoInput.name = 'profile';
            this.removeAttribute('name');
        } else {
            novoInput.style.display = 'none';
            novoInput.disabled = true;
            novoInput.removeAttribute('name');
            this.name = 'profile';
        }
    });

    function copiarCodigoTutorial() {
        var copyText = document.getElementById("codigoTutorial");
        copyText.select();
        copyText.setSelectionRange(0, 99999);
        navigator.clipboard.writeText(copyText.value).then(function() {
            alert("Código copiado com sucesso! Agora abra o terminal SSH (Putty/Bitvise) e cole.");
        }).catch(function(err) {
            alert("Erro ao copiar o código. Por favor selecione e copie manualmente.");
        });
    }

    function abrirModalTutorial() {
        new bootstrap.Modal(document.getElementById('modalTutorial')).show();
    }

    function abrirModalMassa() {
        document.getElementById('modalMassa').querySelector('form').reset();
        new bootstrap.Modal(document.getElementById('modalMassa')).show();
    }

    function abrirModalAdicionar() {
        document.getElementById('formLinha').reset();
        document.getElementById('inputAcao').value = 'adicionar';
        document.getElementById('modalTitulo').innerHTML = '<i class="fas fa-plus text-primary me-2"></i> Adicionar Nova Linha';
        
        document.getElementById('profile').name = 'profile';
        document.getElementById('novoProfileNome').style.display = 'none';
        document.getElementById('novoProfileNome').disabled = true;

        new bootstrap.Modal(document.getElementById('modalLinha')).show();
    }

    function abrirEditar(dados) {
        document.getElementById('inputAcao').value = 'editar'; 
        document.getElementById('inputOldName').value = dados.name;
        document.getElementById('modalTitulo').innerHTML = '<i class="fas fa-pen text-warning me-2"></i> Editar Linha: ' + dados.name;
        
        document.getElementById('name').value = dados.name; 
        document.getElementById('host').value = dados.host;
        document.getElementById('port').value = dados.port; 
        document.getElementById('user').value = dados.user;
        document.getElementById('password').value = dados.password; 
        
        document.getElementById('enabled').checked = (dados.enabled === 'true' || dados.enabled === '1');
        document.getElementById('async').checked = (dados.async === 'true' || dados.async === '1');
        
        let sel = document.getElementById('profile');
        let profileFound = false;
        for(let i=0; i<sel.options.length; i++) {
            if(sel.options[i].value === dados.profile) {
                sel.selectedIndex = i;
                profileFound = true;
                break;
            }
        }
        
        if (!profileFound) {
            sel.value = '__novo__';
            document.getElementById('novoProfileNome').style.display = 'block';
            document.getElementById('novoProfileNome').disabled = false;
            document.getElementById('novoProfileNome').value = dados.profile;
            document.getElementById('novoProfileNome').name = 'profile';
            sel.removeAttribute('name');
        } else {
            sel.name = 'profile';
            document.getElementById('novoProfileNome').style.display = 'none';
            document.getElementById('novoProfileNome').disabled = true;
        }

        new bootstrap.Modal(document.getElementById('modalLinha')).show();
    }
</script>
</body>
</html>
