<?php
ini_set("display_errors", 1);
error_reporting(E_ALL);

$adb = new SQLite3('ibo_panel.db');

// --- CRIAÇÃO DE TABELAS E SINCRONIZAÇÃO ---
$adb->exec("CREATE TABLE IF NOT EXISTS dns (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    title TEXT NOT NULL,
    url TEXT NOT NULL
)");

$adb->exec("CREATE TABLE IF NOT EXISTS playlist (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    dns_id INTEGER,
    mac_address TEXT NOT NULL,
    username TEXT NOT NULL,
    password TEXT NOT NULL,
    pin TEXT NOT NULL,
    link TEXT,
    device_key TEXT,
    last_used INTEGER DEFAULT (strftime('%s','now'))
)");

function sqliteTableHasColumn($adb, $table, $column) {
    $result = $adb->query("PRAGMA table_info(" . $table . ")");
    while ($row = $result->fetchArray(SQLITE3_ASSOC)) {
        if (($row['name'] ?? '') === $column) return true;
    }
    return false;
}

if (!sqliteTableHasColumn($adb, 'playlist', 'device_key')) {
    $adb->exec("ALTER TABLE playlist ADD COLUMN device_key TEXT");
}

function formatarMac($mac) {
    $mac_limpo = strtoupper(preg_replace('/[^A-Fa-f0-9]/', '', $mac));
    $mac_limpo = substr($mac_limpo, 0, 12);
    return implode(':', str_split($mac_limpo, 2));
}

// --- LÓGICA DE REDIRECIONAMENTO DIRETO (PROTEÇÃO CONTRA LOOP E NOT FOUND) ---
$mac = $_GET['mac'] ?? ($_GET['device_id'] ?? '');
$mac_formatado = formatarMac($mac);

if (!empty($mac_formatado)) {
    // Busca o primeiro link disponível para este MAC
    $stmt_check = $adb->prepare("SELECT link FROM playlist WHERE mac_address = :mac AND link IS NOT NULL AND link != '' LIMIT 1");
    $stmt_check->bindValue(':mac', $mac_formatado, SQLITE3_TEXT);
    $check_result = $stmt_check->execute();
    $user_data = $check_result->fetchArray(SQLITE3_ASSOC);

    if ($user_data && !empty($user_data['link'])) {
        $link_final = trim($user_data['link']);
        
        // SÓ REDIRECIONA SE O LINK FOR DIFERENTE DA PÁGINA ATUAL
        if (strpos($link_final, 'cadastro_cliente.php') === false) {
            // Garante que o link tenha http ou https para não dar "Not Found"
            if (!preg_match("~^(?:f|ht)tps?://~i", $link_final)) {
                $link_final = "http://" . $link_final;
            }
            header("Location: " . $link_final);
            exit();
        }
    }
}

// --- FUNÇÕES DE APOIO ---
function getDNSList($adb) {
    $result = $adb->query("SELECT id, title, url FROM dns ORDER BY title");
    $dns_list = [];
    while ($row = $result->fetchArray(SQLITE3_ASSOC)) {
        $dns_list[] = $row;
    }
    return $dns_list;
}

function getCadastrosExistentes($adb, $mac_formatado) {
    $stmt = $adb->prepare("SELECT p.*, d.title as dns_title 
                          FROM playlist p 
                          LEFT JOIN dns d ON p.dns_id = d.id 
                          WHERE p.mac_address = :mac 
                          ORDER BY p.last_used DESC, p.id DESC");
    $stmt->bindValue(':mac', $mac_formatado, SQLITE3_TEXT);
    $result = $stmt->execute();
    
    $cadastros = [];
    while ($row = $result->fetchArray(SQLITE3_ASSOC)) {
        $cadastros[] = $row;
    }
    return $cadastros;
}

// --- PROCESSAMENTO DE FORMULÁRIOS (POST) ---
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (isset($_POST['cadastrar'])) {
        $mac = $_POST['mac'] ?? '';
        $device_key = trim($_POST['device_key'] ?? '');
        $dns_id = $_POST['dns_id'] ?? 0;
        $usuario = trim($_POST['usuario'] ?? '');
        $senha = trim($_POST['senha'] ?? '');
        $mac_formatado = formatarMac($mac);
        
        $errors = [];
        if ($dns_id == 0) $errors[] = "SERVIDOR DNS NÃO SELECIONADO";
        if ($usuario == '') $errors[] = "USUÁRIO NÃO INFORMADO";
        if ($senha == '') $errors[] = "SENHA NÃO INFORMADA";
        
        if (empty($errors)) {
            $stmt_insert = $adb->prepare("INSERT INTO playlist (dns_id, mac_address, username, password, pin, link, device_key, last_used) VALUES (:dns_id, :mac_address, :username, :password, :pin, :link, :device_key, strftime('%s','now'))");
            $stmt_insert->bindValue(':dns_id', $dns_id, SQLITE3_INTEGER);
            $stmt_insert->bindValue(':mac_address', $mac_formatado, SQLITE3_TEXT);
            $stmt_insert->bindValue(':username', $usuario, SQLITE3_TEXT);
            $stmt_insert->bindValue(':password', $senha, SQLITE3_TEXT);
            $stmt_insert->bindValue(':pin', '0000', SQLITE3_TEXT);
            $stmt_insert->bindValue(':link', '', SQLITE3_TEXT);
            $stmt_insert->bindValue(':device_key', $device_key, SQLITE3_TEXT);
            
            if ($stmt_insert->execute()) {
                header("Location: " . $_SERVER['PHP_SELF'] . "?mac=" . urlencode($mac) . "&success=1");
                exit();
            }
        }
    }

    if (isset($_POST['atualizar'])) {
        $id = $_POST['id'] ?? 0;
        $dns_id = $_POST['dns_id'] ?? 0;
        $usuario = trim($_POST['usuario'] ?? '');
        $senha = trim($_POST['senha'] ?? '');
        $device_key = trim($_POST['device_key'] ?? '');
        
        $stmt_update = $adb->prepare("UPDATE playlist SET dns_id = :dns_id, username = :username, password = :password, device_key = CASE WHEN :device_key <> '' THEN :device_key ELSE device_key END, last_used = strftime('%s','now') WHERE id = :id");
        $stmt_update->bindValue(':dns_id', $dns_id, SQLITE3_INTEGER);
        $stmt_update->bindValue(':username', $usuario, SQLITE3_TEXT);
        $stmt_update->bindValue(':password', $senha, SQLITE3_TEXT);
        $stmt_update->bindValue(':device_key', $device_key, SQLITE3_TEXT);
        $stmt_update->bindValue(':id', $id, SQLITE3_INTEGER);
        
        echo json_encode(['success' => $stmt_update->execute()]);
        exit();
    }

    if (isset($_POST['excluir'])) {
        $id = $_POST['id'] ?? 0;
        $stmt = $adb->prepare("DELETE FROM playlist WHERE id = :id");
        $stmt->bindValue(':id', $id, SQLITE3_INTEGER);
        echo json_encode(['success' => $stmt->execute()]);
        exit();
    }
}

$device_key_atual = trim($_GET['device_key'] ?? '');
$dns_list = getDNSList($adb);
$cadastros_existentes = getCadastrosExistentes($adb, $mac_formatado);
$tem_cadastros = !empty($cadastros_existentes);
$success_cadastro = isset($_GET['success']) && $_GET['success'] == 1;
?>

<!DOCTYPE html>
<html lang="pt-br">
<head>
    <meta charset="UTF-8">
    <title>CADASTRO DO CLIENTE</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <style>
        * { margin: 0; padding: 0; box-sizing: border-box; }
        body { font-family: sans-serif; background: #000; color: #fff; min-height: 100vh; overflow-x: hidden; position: relative; }
        #particles { position: fixed; width: 100%; height: 100%; z-index: 0; }
        .particle { position: absolute; background-color: rgba(255, 0, 0, 0.6); border-radius: 50%; pointer-events: none; }
        .container { max-width: 800px; margin: 0 auto; padding: 20px; position: relative; z-index: 1; }
        .header { text-align: center; margin-bottom: 30px; }
        h1 { color: #FF4444; font-size: 2.2rem; text-transform: uppercase; margin-bottom: 10px; }
        .mac-display { background: rgba(255, 68, 68, 0.1); padding: 15px; border-radius: 8px; text-align: center; border: 1px solid rgba(255, 68, 68, 0.3); font-weight: bold; margin-bottom: 20px; }
        .section { background: rgba(20, 20, 20, 0.9); padding: 25px; border-radius: 15px; border: 1px solid rgba(255, 0, 0, 0.2); margin-bottom: 30px; }
        .section-title { color: #FF4444; font-size: 1.5rem; margin-bottom: 20px; text-transform: uppercase; }
        .form-group { margin-bottom: 15px; display: flex; flex-direction: column; }
        label { margin-bottom: 8px; font-size: 0.9rem; color: #CCC; }
        input, select { padding: 12px; border-radius: 8px; border: 1px solid rgba(255, 0, 0, 0.3); background: #1e1e1e; color: #fff; }
        button { padding: 14px; background: linear-gradient(135deg, #FF4444, #CC0000); color: #fff; border: none; border-radius: 8px; font-weight: bold; cursor: pointer; text-transform: uppercase; width: 100%; transition: 0.3s; }
        button:hover { transform: translateY(-2px); box-shadow: 0 5px 15px rgba(255,0,0,0.4); }
        .cadastro-item { background: rgba(40,40,40,0.8); padding: 15px; border-radius: 10px; border: 1px solid rgba(255,68,68,0.2); margin-bottom: 15px; cursor: pointer; }
        .cadastro-header { display: flex; justify-content: space-between; color: #FFA726; font-weight: bold; margin-bottom: 10px; }
        .success-message { color: #4CAF50; background: rgba(76,175,80,0.1); padding: 10px; border-radius: 5px; text-align: center; margin-bottom: 15px; font-weight: bold; }
        /* Modal simples */
        .modal { display: none; position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(0,0,0,0.8); z-index: 1000; justify-content: center; align-items: center; }
        .modal-content { background: #1e1e1e; width: 90%; max-width: 500px; padding: 30px; border-radius: 15px; border: 2px solid #FF4444; }
        .modal-actions { display: flex; gap: 10px; margin-top: 20px; }
        .delete-btn { background: #C62828; }
        .edit-btn { background: #F57C00; }
    </style>
</head>
<body>
    <div id="particles"></div>
    <div class="container">
        <div class="header">
            <h1>CADASTRO DO CLIENTE</h1>
            <div class="mac-display">MAC: <?php echo htmlspecialchars($mac_formatado); ?></div>
            <?php if ($success_cadastro) echo '<div class="success-message">✅ CADASTRO REALIZADO COM SUCESSO!</div>'; ?>
        </div>

        <div class="section">
            <div class="section-title">📝 NOVO CADASTRO</div>
            <form method="post">
                <input type="hidden" name="mac" value="<?php echo htmlspecialchars($mac_formatado); ?>">
                <input type="hidden" name="device_key" value="<?php echo htmlspecialchars($device_key_atual); ?>">
                <div class="form-group">
                    <label>SERVIDOR DNS:</label>
                    <select name="dns_id" required>
                        <option value="0">-- SELECIONE --</option>
                        <?php foreach ($dns_list as $dns) echo "<option value='{$dns['id']}'>".htmlspecialchars($dns['title'])."</option>"; ?>
                    </select>
                </div>
                <div class="form-group">
                    <label>USUÁRIO:</label>
                    <input type="text" name="usuario" required>
                </div>
                <div class="form-group">
                    <label>SENHA:</label>
                    <input type="text" name="senha" required>
                </div>
                <button type="submit" name="cadastrar">CADASTRAR NOVO 📲</button>
            </form>
        </div>

        <?php if ($tem_cadastros): ?>
        <div class="section">
            <div class="section-title">📋 CADASTROS EXISTENTES</div>
            <?php foreach ($cadastros_existentes as $c): ?>
                <div class="cadastro-item" onclick="abrirModal(this)" 
                     data-id="<?php echo $c['id']; ?>" data-dns="<?php echo $c['dns_id']; ?>" 
                     data-user="<?php echo htmlspecialchars($c['username']); ?>" data-pass="<?php echo htmlspecialchars($c['password']); ?>">
                    <div class="cadastro-header">
                        <span><?php echo htmlspecialchars($c['dns_title'] ?? 'N/A'); ?></span>
                        <span style="color:#888">ID: <?php echo $c['id']; ?></span>
                    </div>
                    <div style="font-size: 0.9rem">
                        Usuário: <?php echo htmlspecialchars($c['username']); ?> | PIN: <?php echo htmlspecialchars($c['pin']); ?>
                    </div>
                </div>
            <?php endforeach; ?>
        </div>
        <?php endif; ?>
    </div>

    <div class="modal" id="editModal">
        <div class="modal-content">
            <h2 style="color:#FFA726; margin-bottom:15px">EDITAR CADASTRO</h2>
            <form id="editForm">
                <input type="hidden" id="editId">
                <div class="form-group">
                    <label>SERVIDOR:</label>
                    <select id="editDnsId">
                        <?php foreach ($dns_list as $dns) echo "<option value='{$dns['id']}'>".htmlspecialchars($dns['title'])."</option>"; ?>
                    </select>
                </div>
                <div class="form-group">
                    <label>USUÁRIO:</label>
                    <input type="text" id="editUsuario">
                </div>
                <div class="form-group">
                    <label>SENHA:</label>
                    <input type="text" id="editSenha">
                </div>
                <div class="modal-actions">
                    <button type="button" class="delete-btn" onclick="excluirCadastro()">EXCLUIR</button>
                    <button type="button" class="edit-btn" onclick="atualizarCadastro()">SALVAR</button>
                </div>
                <button type="button" style="background:#444; margin-top:10px" onclick="fecharModal()">FECHAR</button>
            </form>
        </div>
    </div>

    <script>
        let modal = document.getElementById('editModal');
        function abrirModal(el) {
            document.getElementById('editId').value = el.dataset.id;
            document.getElementById('editDnsId').value = el.dataset.dns;
            document.getElementById('editUsuario').value = el.dataset.user;
            document.getElementById('editSenha').value = el.dataset.pass;
            modal.style.display = 'flex';
        }
        function fecharModal() { modal.style.display = 'none'; }
        
        function atualizarCadastro() {
            const fd = new FormData();
            fd.append('atualizar', '1');
            fd.append('id', document.getElementById('editId').value);
            fd.append('dns_id', document.getElementById('editDnsId').value);
            fd.append('usuario', document.getElementById('editUsuario').value);
            fd.append('senha', document.getElementById('editSenha').value);
            fetch('', { method: 'POST', body: fd }).then(() => location.reload());
        }

        function excluirCadastro() {
            if(!confirm('Excluir?')) return;
            const fd = new FormData();
            fd.append('excluir', '1');
            fd.append('id', document.getElementById('editId').value);
            fetch('', { method: 'POST', body: fd }).then(() => location.reload());
        }

        // Partículas simples
        const canvas = document.getElementById('particles');
        for (let i = 0; i < 20; i++) {
            const p = document.createElement('div');
            p.className = 'particle';
            p.style.width = p.style.height = Math.random() * 5 + 'px';
            p.style.left = Math.random() * 100 + 'vw';
            p.style.top = Math.random() * 100 + 'vh';
            canvas.appendChild(p);
        }
    </script>
</body>
</html>