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

$dbPath = __DIR__ . '/api/.db.db';

if (!file_exists($dbPath)) {
    echo json_encode(['error' => 'Banco de dados não encontrado']);
    exit;
}

$db = new SQLite3($dbPath);

if ($_SERVER['REQUEST_METHOD'] === 'GET' && isset($_GET['action']) && $_GET['action'] === 'get_urls') {
    try {
        $result = $db->query("SELECT url FROM dns");
        $urls = [];

        while ($row = $result->fetchArray(SQLITE3_ASSOC)) {
            $urls[] = $row['url'];
        }

        echo json_encode(['urls' => $urls]);
    } catch (Exception $e) {
        echo json_encode(['error' => 'Erro ao consultar o banco de dados: ' . $e->getMessage()]);
    }
    exit;
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (isset($_POST['mac_address'], $_POST['username'], $_POST['password'], $_POST['dns_url'])) {
      
        error_log('Recebido dados: ' . json_encode($_POST));
        
        $macAddress = $_POST['mac_address'];
        $username = $_POST['username'];
        $password = $_POST['password'];
        $dnsUrl = $_POST['dns_url'];
        $pin = '0000';  

        // Validar formato de MAC address (XX:XX:XX:XX:XX:XX)
        if (!preg_match('/^[A-F0-9]{2}(:[A-F0-9]{2}){5}$/', $macAddress)) {
            echo json_encode(['success' => false, 'error' => 'Formato de MAC address inválido.']);
            exit;
        }

        // Verificar se a MAC address contém letras minúsculas
        if (preg_match('/[a-f]/', $macAddress)) {
            echo json_encode(['success' => false, 'error' => 'A MAC address deve usar apenas maiúsculas.']);
            exit;
        }

        try {
            $urlStmt = $db->prepare("SELECT id FROM dns WHERE url = :url");
            $urlStmt->bindValue(':url', $dnsUrl, SQLITE3_TEXT);
            $urlResult = $urlStmt->execute();
            $dnsId = $urlResult->fetchArray(SQLITE3_ASSOC)['id'] ?? null;

            if ($dnsId) {
                $insertStmt = $db->prepare("INSERT INTO playlist (mac_address, username, password, pin, dns_id) VALUES (:mac, :username, :password, :pin, :dns_id)");
                $insertStmt->bindValue(':mac', $macAddress, SQLITE3_TEXT);
                $insertStmt->bindValue(':username', $username, SQLITE3_TEXT);
                $insertStmt->bindValue(':password', $password, SQLITE3_TEXT);
                $insertStmt->bindValue(':pin', $pin, SQLITE3_TEXT);
                $insertStmt->bindValue(':dns_id', $dnsId, SQLITE3_INTEGER);

                $insertStmt->execute();

                echo json_encode(['success' => true]);
            } else {
                echo json_encode(['success' => false, 'error' => 'URL não encontrada.']);
            }
        } catch (Exception $e) {
            error_log('Erro ao processar a solicitação: ' . $e->getMessage());
            echo json_encode(['success' => false, 'error' => 'Erro ao processar a solicitação: ' . $e->getMessage()]);
        }
    } else {
        error_log('Dados incompletos: ' . json_encode($_POST));
        echo json_encode(['success' => false, 'error' => 'Dados incompletos.']);
    }
    exit;
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Activación por MAC</title>
    <style>
        body {
            margin: 0;
            font-family: Arial, sans-serif;
            background: linear-gradient(to right, #004895, #7b1cc6);
            height: 100vh;
            display: flex;
            justify-content: center;
            align-items: center;
        }

        .container {
            background-color: #fff;
            width: 90%;
            max-width: 400px;
            padding: 20px;
            box-shadow: 0 5px 15px rgba(0, 0, 0, 0.2);
            border-radius: 10px;
            text-align: center;
        }

        h1 {
            font-size: 20px;
            margin-bottom: 15px;
        }

        .logo {
            max-width: 80px;
            margin-bottom: 15px;
        }

        input, select {
            width: calc(100% - 20px);
            padding: 10px;
            margin-bottom: 15px;
            border: 1px solid #ccc;
            border-radius: 5px;
            font-size: 16px;
        }

        button {
            background-color: #007bff;
            color: white;
            border: none;
            padding: 10px;
            border-radius: 5px;
            width: 100%;
            cursor: pointer;
            font-size: 16px;
        }

        button:hover {
            background-color: #0056b3;
        }
    </style>
</head>
<body>
    <div class="container">
        <img src="img/logo.png?t=<?php echo time(); ?>" alt="Logo" class="logo">
        <h1>Activar clientes por MAC</h1>
        
        <form id="registrationForm">
            <input type="text" id="mac_address" name="mac_address" placeholder="Mac Address" required>
            <input type="text" id="username" name="username" placeholder="Username" required>
            <input type="text" id="password" name="password" placeholder="Password" required>
            <select id="dns_url" name="dns_url" required>
                <option value="" disabled selected>Seleccione una URL</option>
            </select>
            <button type="submit">Activar</button>
        </form>
    </div>

    <script>
        document.getElementById('registrationForm').addEventListener('submit', function (e) {
            e.preventDefault(); 
            const macAddress = document.getElementById('mac_address').value;
            const username = document.getElementById('username').value;
            const password = document.getElementById('password').value;
            const dnsUrl = document.getElementById('dns_url').value;

            // Validar formato de MAC address (XX:XX:XX:XX:XX:XX)
            const macRegex = /^[A-F0-9]{2}(:[A-F0-9]{2}){5}$/;
            if (!macRegex.test(macAddress)) {
                alert('¡Formato de MAC address inválido!. Use mayusculas y numeros. 12 caracteres como este Ejemplo XX:X:XX:XX:XX:XX');
                return;
            }

            // Validar se a MAC address contém letras minúsculas
            if (/[a-f]/.test(macAddress)) {
                alert('A MAC address deve usar apenas maiúsculas.');
                return;
            }

            if (!macAddress || !username || !password || !dnsUrl) {
                alert('Por favor, preencha todos os campos.');
                return;
            }

            fetch('', {
                method: 'POST',
                headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
                body: `mac_address=${encodeURIComponent(macAddress)}&username=${encodeURIComponent(username)}&password=${encodeURIComponent(password)}&dns_url=${encodeURIComponent(dnsUrl)}`
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    alert('Cadastro realizado com sucesso!');
                    window.location.reload(); 
                } else {
                    alert('Erro: ' + (data.error || 'Erro desconhecido.'));
                }
            })
            .catch(error => {
                console.error('Erro ao enviar o formulário:', error);
                alert('Erro ao enviar o cadastro. Tente novamente.');
            });
        });

        // Carregar as URLs disponíveis para o dropdown
        fetch('?action=get_urls')
            .then(response => response.json())
            .then(data => {
                if (data.urls && data.urls.length > 0) {
                    const dnsSelect = document.getElementById('dns_url');
                    data.urls.forEach(url => {
                        const option = document.createElement('option');
                        option.value = url;
                        option.textContent = url;
                        dnsSelect.appendChild(option);
                    });
                }
            })
            .catch(error => console.error('Erro ao carregar as URLs:', error));
    </script>
</body>
</html>
