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

        $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 não encontrada']);
        }
        exit;
    }


    $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 não 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, #e52d27, #b31217);
            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 {
            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: #777;
        }

        .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" alt="Logo" class="logo">
        <h1>Adicionar ou Alterar Clientes!</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>Username:</strong> <input type="text" id="username" name="username" required></p>
            <p><strong>Password:</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 uma URL</option>
                </select>
            </p>
            <button type="button" onclick="updateData()">Atualizar Dados</button>
        </div>

        <div class="register-msg" id="registerMsg" style="display: none;">
            <p>Olá MAC Address não encontrado, Deseja cadastrar?</p>
            <button class="register-btn" onclick="window.location.href='cadastro_cliente.php'">Cadastrar</button>
        </div>

        <div class="footer">
            Desenvolvido por WCTV APPS ©2025 - All rights reserved.
        </div>
    </div>

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

            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 uma 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 os campos devem ser preenchidos.');
                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('Dados atualizados com sucesso!');
                } else {
                    alert('Erro ao atualizar dados: ' + (data.error || 'Erro desconhecido'));
                }
            })
            .catch(error => {
                console.error('Erro:', error);
                alert('Erro ao atualizar os dados.');
            });
        }
    </script>
</body>
</html>
