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

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

$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,
    mac_address TEXT,
    FOREIGN KEY (dns_id) REFERENCES dns(id)
)");

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

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));
}

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 {
            $stmt = $adb->prepare("SELECT id, dns_id, m3u_url, mac_address 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 = $code_info['dns_id'];
                $mac_registrado = $code_info['mac_address'];

                if (empty($mac_registrado) || $mac_registrado === $mac_formatado) {
                    if (empty($mac_registrado)) {
                        $update = $adb->prepare("UPDATE codes SET mac_address = :mac WHERE id = :id");
                        $update->bindValue(':mac', $mac_formatado, SQLITE3_TEXT);
                        $update->bindValue(':id', $code_info['id'], SQLITE3_INTEGER);
                        $update->execute();
                    }
                    inserirPlaylist($adb, $dns_id, $mac_formatado, $m3u_url, $codigo);
                } else {
                    echo "<div class='error-message'>⚠️ ESTE CÓDIGO JÁ ESTÁ EM USO POR OUTRO DISPOSITIVO.</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>";
        }
    }
}

function inserirPlaylist($adb, $dns_id, $mac, $m3u_url, $codigo) {
    $parsed_url = parse_url($m3u_url);
    parse_str($parsed_url['query'] ?? '', $params);

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

    if ($username && $password) {
        $stmt_dns = $adb->prepare("SELECT title FROM dns WHERE id = :id");
        $stmt_dns->bindValue(':id', $dns_id, SQLITE3_INTEGER);
        $result_dns = $stmt_dns->execute();
        $dns_info = $result_dns->fetchArray(SQLITE3_ASSOC);

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

        $stmt_insert = $adb->prepare("INSERT INTO playlist 
            (dns_id, mac_address, username, password, pin, link, type, url)
            VALUES (:dns_id, :mac, :username, :password, :pin, '', :type, :url)");
        $stmt_insert->bindValue(':dns_id', $dns_id, SQLITE3_INTEGER);
        $stmt_insert->bindValue(':mac', $mac, SQLITE3_TEXT);
        $stmt_insert->bindValue(':username', $username, SQLITE3_TEXT);
        $stmt_insert->bindValue(':password', $password, SQLITE3_TEXT);
        $stmt_insert->bindValue(':pin', $codigo, SQLITE3_TEXT);
        $stmt_insert->bindValue(':type', $dns_info['title'], SQLITE3_TEXT);
        $stmt_insert->bindValue(':url', $m3u_url, SQLITE3_TEXT);

        if ($stmt_insert->execute()) {
            header("Location: cadastro_sucesso.php?mac=" . urlencode($mac) .
                "&usuario=" . urlencode($username) .
                "&senha=" . urlencode($password) .
                "&servidor=" . urlencode($dns_info['title']));
            exit();
        } else {
            echo "<div class='error-message'>⚠️ ERRO AO INSERIR NA PLAYLIST.</div>";
        }
    } else {
        echo "<div class='error-message'>⚠️ URL SEM USERNAME OU SENHA.</div>";
    }
}

$mac = $_GET['mac'] ?? ($_GET['device_id'] ?? '');
$mac_formatado = formatarMac($mac);

$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; text-align: center;
        }
        .info-text { color: #AAA; font-size: 0.8rem; margin-top: 5px; text-align: center; }
    </style>
</head>
<body>
<div id="particles"></div>
<div class="form-container">
    <h2>CADASTRO VIA CÓDIGO 🔑</h2>
    <form method="post">
        <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>
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);
        (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>

