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

$adb = new SQLite3('./api/studiolivecode.db');

// Tabela de códigos atualizada com dns_id
$adb->exec("CREATE TABLE IF NOT EXISTS codes (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    dns_id INTEGER NOT NULL,
    code TEXT NOT NULL,
    m3u_url TEXT NOT NULL,
    FOREIGN KEY (dns_id) REFERENCES dns(id)
)");

// Tabela DNS mantida como estava
$adb->exec("CREATE TABLE IF NOT EXISTS dns (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    title TEXT NOT NULL,
    url TEXT NOT NULL
)");

// Função para formatar MAC address
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));
}

// Processar formulário
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (isset($_POST['codigo'])) {
        $mac = $_POST['mac'] ?? '';
        $codigo = trim($_POST['codigo'] ?? '');
        $mac_formatado = formatarMac($mac);
        
        if ($codigo == '') {
            echo "<div class='error-message'>⚠️ CÓDIGO DE CADASTRO NÃO INFORMADO.</div>";
        } else {
            // Busca atualizada para usar dns_id
            $stmt = $adb->prepare("SELECT dns_id, m3u_url FROM codes WHERE code = :code");
            $stmt->bindValue(':code', $codigo, SQLITE3_TEXT);
            $result = $stmt->execute();
            $code_info = $result->fetchArray(SQLITE3_ASSOC);

            if ($code_info && isset($code_info['m3u_url'])) {
                $m3u_url = $code_info['m3u_url'];
                $dns_id_associado = $code_info['dns_id']; // Agora usando dns_id

                // Extrair parâmetros da URL
                $parsed_url = parse_url($m3u_url);
                parse_str($parsed_url['query'], $params);

                $usuario = $params['username'] ?? '';
                $senha = $params['password'] ?? '';
                $tipo = $params['type'] ?? 'm3u';

                if ($usuario && $senha) {
                    $servidor_id = $dns_id_associado;
                    $stmt_dns = $adb->prepare("SELECT title, url FROM dns WHERE id = :id");
                    $stmt_dns->bindValue(':id', $servidor_id, SQLITE3_INTEGER);
                    $result_dns = $stmt_dns->execute();
                    $dns_info = $result_dns->fetchArray(SQLITE3_ASSOC);

                    if (!$dns_info) {
                        echo "<div class='error-message'>⚠️ CONEXÃO DNS NÃO ENCONTRADA.</div>";
                        exit();
                    }

                    $stmt_playlist = $adb->prepare("INSERT INTO playlist
                        (dns_id, mac_address, username, password, pin, link, type, url)
                        VALUES
                        (:dns_id, :mac_address, :username, :password, :pin, :link, :type, :url)");

                    $stmt_playlist->bindValue(':dns_id', $servidor_id, SQLITE3_INTEGER);
                    $stmt_playlist->bindValue(':mac_address', $mac_formatado, SQLITE3_TEXT);
                    $stmt_playlist->bindValue(':username', $usuario, SQLITE3_TEXT);
                    $stmt_playlist->bindValue(':password', $senha, SQLITE3_TEXT);
                    $stmt_playlist->bindValue(':pin', $codigo, SQLITE3_TEXT);
                    $stmt_playlist->bindValue(':link', '', SQLITE3_TEXT);
                    $stmt_playlist->bindValue(':type', $dns_info['title'], SQLITE3_TEXT);
                    $stmt_playlist->bindValue(':url', $m3u_url, SQLITE3_TEXT);

                    if ($stmt_playlist->execute()) {
                        header("Location: cadastro_sucesso.php?mac=" . urlencode($mac_formatado) .
                                    "&usuario=" . urlencode($usuario) .
                                    "&senha=" . urlencode($senha) .
                                    "&servidor=" . urlencode($dns_info['title']));
                        exit();
                    } else {
                        echo "<div class='error-message'>⚠️ ERRO AO CADASTRAR NO BANCO.</div>";
                    }
                } else {
                    echo "<div class='error-message'>⚠️ URL INVÁLIDA (SEM USERNAME/SENHA).</div>";
                }
            } else {
                echo "<div class='error-message'>⚠️ CÓDIGO INVÁLIDO OU NÃO CADASTRADO.</div>";
            }
        }
    }
    elseif (isset($_POST['renovar'])) {
        $mac = $_POST['mac_renovar'] ?? '';
        $mac_formatado = formatarMac($mac);
        
        $stmt = $adb->prepare("SELECT link FROM playlist WHERE mac_address = :mac AND link LIKE 'http%'");
        $stmt->bindValue(':mac', $mac_formatado, SQLITE3_TEXT);
        $result = $stmt->execute();
        $row = $result->fetchArray(SQLITE3_ASSOC);
        
        if ($row && !empty($row['link'])) {
            header("Location: " . $row['link']);
            exit();
        } else {
            echo "<div class='error-message'>⚠️ LINK DE RENOVAÇÃO NÃO ENCONTRADO PARA ESTE DISPOSITIVO.</div>";
        }
    }
}

// Obter MAC do parâmetro e formatar
$mac = $_GET['mac'] ?? ($_GET['device_id'] ?? '');
$mac_formatado = formatarMac($mac);

// Verificar se existe link de renovação
$temRenovacao = false;
$payUrl = '';
if (!empty($mac_formatado)) {
    $stmt = $adb->prepare("SELECT link FROM playlist WHERE mac_address = :mac AND link LIKE 'http%'");
    $stmt->bindValue(':mac', $mac_formatado, SQLITE3_TEXT);
    $result = $stmt->execute();
    $row = $result->fetchArray(SQLITE3_ASSOC);
    
    if ($row && !empty($row['link'])) {
        $temRenovacao = true;
        $payUrl = $row['link'];
    }
}
?>

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>CADASTRO VIA CÓDIGO</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        
        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            background: #000;
            color: #fff;
            display: flex;
            justify-content: center;
            align-items: center;
            min-height: 100vh;
            overflow: hidden;
            position: relative;
        }
        
        #particles {
            position: absolute;
            width: 100%;
            height: 100%;
            z-index: 0;
        }
        
        .particle {
            position: absolute;
            background-color: rgba(255, 0, 0, 0.6);
            border-radius: 50%;
            pointer-events: none;
        }
        
        .form-container {
            background: rgba(20, 20, 20, 0.9);
            padding: 25px;
            border-radius: 15px;
            width: 95%;
            max-width: 400px;
            box-shadow: 0 10px 25px rgba(0, 0, 0, 0.5);
            position: relative;
            z-index: 1;
            backdrop-filter: blur(5px);
            border: 1px solid rgba(255, 0, 0, 0.2);
        }
        
        h2 {
            text-align: center;
            margin-bottom: 20px;
            color: #FF4444;
            font-size: 1.8rem;
            text-transform: uppercase;
        }
        
        label {
            display: block;
            margin-top: 15px;
            font-size: 0.9rem;
            color: #CCC;
            font-weight: bold;
        }
        
        input {
            width: 100%;
            padding: 12px 15px;
            margin-top: 8px;
            border-radius: 8px;
            border: none;
            background: rgba(30, 30, 30, 0.8);
            color: #FFF;
            font-size: 1rem;
            border: 1px solid rgba(255, 0, 0, 0.3);
            text-transform: uppercase;
        }
        
        input:focus {
            outline: none;
            border-color: #FF4444;
            box-shadow: 0 0 0 2px rgba(255, 0, 0, 0.2);
        }
        
        button {
            width: 100%;
            padding: 14px;
            margin-top: 10px;
            background: linear-gradient(135deg, #FF4444, #CC0000);
            color: #FFF;
            font-weight: bold;
            border: none;
            border-radius: 8px;
            font-size: 1rem;
            cursor: pointer;
            text-transform: uppercase;
            letter-spacing: 1px;
            transition: all 0.3s;
        }
        
        button:hover {
            transform: translateY(-2px);
            box-shadow: 0 5px 15px rgba(255, 0, 0, 0.4);
        }
        
        button.renovar-btn {
            background: linear-gradient(135deg, #4CAF50, #2E7D32);
            margin-top: 15px;
        }
        
        button.renovar-btn:hover {
            box-shadow: 0 5px 15px rgba(76, 175, 80, 0.4);
        }
        
        button:disabled {
            background: #555;
            cursor: not-allowed;
            transform: none;
            box-shadow: none;
        }
        
        .error-message {
            color: #FF6B6B;
            padding: 10px;
            margin: 10px 0;
            background: rgba(255, 0, 0, 0.1);
            border-radius: 5px;
            border-left: 3px solid #FF4444;
            font-size: 0.9rem;
            text-transform: uppercase;
            font-weight: bold;
        }
        
        .info-text {
            color: #AAA;
            font-size: 0.8rem;
            margin-top: 5px;
            text-align: center;
        }
        
        .form-container, button {
            animation: glow 2s infinite alternate;
        }
        
        @keyframes glow {
            from {
                box-shadow: 0 0 5px rgba(255, 0, 0, 0.3);
            }
            to {
                box-shadow: 0 0 15px rgba(255, 0, 0, 0.5);
            }
        }
    </style>
</head>
<body>
    <div id="particles"></div>
    
    <div class="form-container">
        <h2>CADASTRO VIA CÓDIGO 🔑</h2>
        <form method="post" id="formCadastro">
            <label>ENDEREÇO MAC:</label>
            <input type="text" name="mac" value="<?php echo htmlspecialchars($mac_formatado); ?>" readonly>

            <label>CÓDIGO DE CADASTRO:</label>
            <input type="text" name="codigo" placeholder="DIGITE O CÓDIGO" required>

            <button type="submit">CADASTRAR 📲</button>
        </form>
        
        <?php if ($temRenovacao): ?>
            <form method="post" style="margin-top: 20px;">
                <input type="hidden" name="mac_renovar" value="<?php echo htmlspecialchars($mac_formatado); ?>">
                <button type="submit" name="renovar" class="renovar-btn">
                    RENOVAR ASSINATURA 🔄
                </button>
                <div class="info-text">
                    Clique para renovar sua assinatura existente
                </div>
            </form>
        <?php else: ?>
            <button type="button" disabled class="renovar-btn" style="margin-top: 20px;">
                RENOVAÇÃO INDISPONÍVEL
            </button>
            <div class="info-text">
                Nenhum link de renovação encontrado
            </div>
        <?php endif; ?>
    </div>

    <script>
        // Animação das partículas
        document.addEventListener('DOMContentLoaded', function() {
            const particlesContainer = document.getElementById('particles');
            const particleCount = 30;
            
            for (let i = 0; i < particleCount; i++) {
                const particle = document.createElement('div');
                particle.classList.add('particle');
                particle.style.width = `${Math.random() * 4 + 2}px`;
                particle.style.height = particle.style.width;
                particle.style.left = `${Math.random() * 100}vw`;
                particle.style.top = `${Math.random() * 100}vh`;
                particle.style.opacity = Math.random() * 0.5 + 0.3;
                particlesContainer.appendChild(particle);
                
                // Animação
                (function(p) {
                    let x = parseFloat(p.style.left);
                    let y = parseFloat(p.style.top);
                    const speedX = (Math.random() - 0.5) * 0.5;
                    const speedY = (Math.random() - 0.5) * 0.5;
                    
                    function move() {
                        x += speedX;
                        y += speedY;
                        if (x < 0 || x > 100 || y < 0 || y > 100) {
                            x = Math.random() * 100;
                            y = Math.random() * 100;
                        }
                        p.style.left = `${x}vw`;
                        p.style.top = `${y}vh`;
                        requestAnimationFrame(move);
                    }
                    move();
                })(particle);
            }
        });
    </script>
</body>
</html>