<?php
if ($_SERVER['REQUEST_METHOD'] === 'POST') {

    if (isset($_POST['mac_address']) && isset($_POST['username']) && isset($_POST['password']) && isset($_POST['dns_url'])) {
        $macAddress = $_POST['mac_address'];
        $username = $_POST['username'];
        $password = $_POST['password'];
        $dnsUrl = $_POST['dns_url'];

        // Verificar si el MAC address tiene letras min���sculas
        if (preg_match('/[a-f]/', $macAddress)) {
            echo json_encode(['success' => false, 'error' => 'La direccion MAC debe usar solo mayusculas.']);
            exit;
        }

        $dbPath = __DIR__ . '/api/.db.db';
        $db = new SQLite3($dbPath);

        $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'];

        if ($dnsId) {

            $updateStmt = $db->prepare("UPDATE playlist SET username = :username, password = :password, dns_id = :dns_id WHERE mac_address = :mac");
            $updateStmt->bindValue(':mac', $macAddress, SQLITE3_TEXT);
            $updateStmt->bindValue(':username', $username, SQLITE3_TEXT);
            $updateStmt->bindValue(':password', $password, SQLITE3_TEXT);
            $updateStmt->bindValue(':dns_id', $dnsId, SQLITE3_INTEGER);

            $updateStmt->execute();

            echo json_encode(['success' => true]);
        } else {
            echo json_encode(['success' => false, 'error' => 'DNS URL no encontrada']);
        }
        exit;
    }

    // Consultar datos de la direcciion MAC
    $macAddress = $_POST['mac_address'];
    $dbPath = __DIR__ . '/api/.db.db';
    $db = new SQLite3($dbPath);

    $stmt = $db->prepare("SELECT p.username, p.password, d.url
                          FROM playlist AS p
                          JOIN dns AS d ON p.dns_id = d.id
                          WHERE p.mac_address = :mac");
    $stmt->bindValue(':mac', $macAddress, SQLITE3_TEXT);
    $result = $stmt->execute();

    $data = $result->fetchArray(SQLITE3_ASSOC);

    if ($data) {
        $urlStmt = $db->prepare("SELECT url FROM dns");
        $urlResult = $urlStmt->execute();

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

        $data['urls'] = $urls;
        echo json_encode($data);
        exit;
    } else {
        echo json_encode(['error' => 'MAC Address no encontrado']);
        exit;
    }
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Manage Playlists</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: #fff8;
            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 {
            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;
        }

        .message-box {
            display: none;
            background-color: #f9f9f9;
            border: 1px solid #ddd;
            padding: 15px;
            margin-top: 20px;
            text-align: left;
            border-radius: 5px;
        }

        .footer {
            margin-top: 20px;
            font-size: 14px;
            color: #000000;
        }

        .register-msg {
            margin-top: 20px;
            font-size: 16px;
            color: #333;
        }

        .register-btn {
            background-color: #28a745;
            color: white;
            border: none;
            padding: 10px;
            border-radius: 5px;
            cursor: pointer;
            font-size: 16px;
            margin-top: 10px;
        }

        .register-btn:hover {
            background-color: #218838;
        }
    </style>
</head>
<body>
     <div class="container">
        <img src="img/logo.png?t=<?php echo time(); ?>" alt="Logo" class="logo">
        <h1>Agregar o Editar Clientes por Mac!</h1>
        
        <form id="macForm">
            <input type="text" id="mac_address" name="mac_address" placeholder="Mac Address" required>
            <button type="submit">Login</button>
        </form>

        <div class="message-box" id="updateForm">
            <p><strong>Usuario:</strong> <input type="text" id="username" name="username" required></p>
            <p><strong>Contraseña</strong> <input type="text" id="password" name="password" required></p>
            <p><strong>DNS URL:</strong> 
                <select id="dns_url" name="dns_url" required>
                    <option value="" disabled selected>Selecione una URL</option>
                </select>
            </p>
            <button type="button" onclick="updateData()">Actualizar Datos</button>
        </div>

        <div class="register-msg" id="registerMsg" style="display: none;">
            <p>Hola MAC Address no encontrado, Desea Registrarlo?</p>
            <button class="register-btn" onclick="window.location.href='cadastro_cliente.php'">Registrar</button>
        </div>

        <div class="footer">
            Rgvip Rebrand ©2025 - Todos los derechos reservados.
        </div>
    </div>

    <script>
        document.getElementById('macForm').addEventListener('submit', function (e) {
            e.preventDefault();
            const macAddress = document.getElementById('mac_address').value;

            // Verificar si la direccion MAC contiene letras minusculas
            if (/[a-f]/.test(macAddress)) {
                alert('Porfavor usar MAYUSCULAS en las letras de la Mac Address.');
                return;
            }

            fetch('', {
                method: 'POST',
                headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
                body: 'mac_address=' + encodeURIComponent(macAddress)
            })
            .then(response => response.json())
            .then(data => {
                if (data.error) {
                    document.getElementById('registerMsg').style.display = 'block';
                } else {
                    document.getElementById('username').value = data.username;
                    document.getElementById('password').value = data.password;
                    const dnsSelect = document.getElementById('dns_url');
                    dnsSelect.innerHTML = '<option value="" disabled selected>Selecione una URL</option>';
                    data.urls.forEach(url => {
                        const option = document.createElement('option');
                        option.value = url;
                        option.textContent = url;
                        dnsSelect.appendChild(option);
                    });
                    document.getElementById('updateForm').style.display = 'block';
                    document.getElementById('macForm').style.display = 'none';
                }
            })
            .catch(error => {
                console.error('Erro:', error);
                alert('Erro ao buscar os dados.');
            });
        });

        function updateData() {
            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;

            if (!username || !password || !dnsUrl) {
                alert('Todos los campos deben ser ingresados.');
                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('Datos actualizados con Exito!');
                } else {
                    alert('Error al actualizar los datos: ' + (data.error || 'Erro desconhecido'));
                }
            })
            .catch(error => {
                console.error('Erro:', error);
                alert('Error al actualizar los datos.');
            });
        }
    </script>
</body>
</html>
