<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>WiFi Configuration</title>
    <link rel="icon" type="image/x-icon" href="/static/images/favicon.ico">
    <style>
        body {
            font-family: Arial, sans-serif;
            padding: 0;
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: flex-start;
            min-height: 50vh;
            margin: 0;
            background-color: #f0f0f0;
        }
        h1 {
            margin-top: 30px;
            font-size: 36px;
            color: #333;
        }
        .button-container {
            display: flex;
            justify-content: center;
            gap: 20px;
            margin-top: 20px;
        }
        .button-container .btn {
            padding: 10px 20px;
            font-size: 18px;
            cursor: pointer;
            background-color: #007bff;
            color: white;
            border: none;
            border-radius: 5px;
            text-decoration: none;
        }
        .button-container .btn:hover {
            background-color: #0056b3;
        }
        .scan-container {
            margin-top: 20px;
        }
        .scan-container .btn {
            background-color: #28a745;
        }
        .scan-container .btn:hover {
            background-color: #218838;
        }
        .connect-container {
            margin-top: 20px;
        }
        .connect-container .btn {
            background-color: #ffc107;
        }
        .connect-container .btn:hover {
            background-color: #e0a800;
        }
        .network-list {
            margin-top: 20px;
            width: 80%;
            max-height: 200px;
            overflow-y: auto;
            border: 1px solid #ccc;
            background-color: white;
        }
        .network-list table {
            width: 100%;
            border-collapse: collapse;
            table-layout: auto;
        }
        .network-list th, .network-list td {
            padding: 8px;
            text-align: left;
            border-bottom: 1px solid #ddd;
            white-space: nowrap;
        }
        .network-list th {
            background-color: #f2f2f2;
        }
        .network-list tr.selected {
            background-color: #d1e7dd;
        }
        .status {
            margin-top: 20px;
            font-size: 18px;
            color: #555;
        }
        .home-btn {
            position: absolute;
            top: 20px;
            left: 20px;
            padding: 10px 20px;
            background-color: #6c757d;
            color: white;
            text-decoration: none;
            border-radius: 5px;
        }
        .home-btn:hover {
            background-color: #5a6268;
        }
        .placeholder-img {
            position: absolute;
            top: 20px;
            right: 20px;
        }
        .placeholder-img img {
            top: 20px;
            width: 70px;
            height: 70px;
        }
    </style>
</head>
<body>
    <a href="/" class="home-btn">Home</a>
    <div class="placeholder-img">
        <img src="/static/images/atalogo.png">
    </div>
    <h1>WiFi Connection</h1>
    <div class="button-container">
        <button class="btn" onclick="scanWifi()">Scan for Networks</button>
        <button class="btn" onclick="cancelScan()">Cancel</button>
    </div>
    <div class="scan-container">
        <div id="scanStatus" class="status"></div>
    </div>
    <div class="network-list">
        <table id="networksTable">
            <thead>
                <tr>
                    <th>SSID</th>
                    <th>Freq</th>
                    <th>Signal</th>
                </tr>
            </thead>
            <tbody>
                <!-- List of networks will be appended here -->
            </tbody>
        </table>
    </div>
    <div class="connect-container">
        <button class="btn" onclick="connectToNetwork()">Connect</button>
    </div>
    <div class="status" id="connectionStatus"></div>
    <script>
        function scanWifi() {
            console.log("Starting WiFi scan...");
            document.getElementById('scanStatus').innerText = "Scanning for networks...";
            fetch('/scan_wifi')
                .then(response => response.json())
                .then(data => {
                    console.log("Scan complete. Data received:", data);
                    document.getElementById('scanStatus').innerText = "Scan complete.";
                    let tableBody = document.getElementById('networksTable').getElementsByTagName('tbody')[0];
                    tableBody.innerHTML = '';
                    data.networks.forEach(network => {
                        let row = tableBody.insertRow();
                        let cell1 = row.insertCell(0);
                        let cell2 = row.insertCell(1);
                        let cell3 = row.insertCell(2);
                        cell1.textContent = network.ssid;
                        cell2.textContent = network.Freq;
                        cell3.textContent = network.signal;
                        row.addEventListener('click', function() {
                            const rows = document.querySelectorAll('#networksTable tbody tr');
                            rows.forEach(r => r.classList.remove('selected'));
                            row.classList.add('selected');
                        });
                    });
                })
                .catch(error => {
                    console.error("Error during scan:", error);
                    document.getElementById('scanStatus').innerText = "Error during scan.";
                });
        }

        function cancelScan() {
            console.log("Cancelling scan...");
            document.getElementById('scanStatus').innerText = "Scan cancelled.";
        }

        function connectToNetwork() {
            console.log("Attempting to connect to network...");
            const table = document.getElementById('networksTable');
            const selectedRow = table.querySelector('tbody tr.selected');
            if (!selectedRow) {
                document.getElementById('connectionStatus').innerText = "Please select a network to connect to.";
                return;
            }
            const ssid = selectedRow.cells[0].textContent;
            const password = prompt("Enter the WiFi password for " + ssid + ":");
            if (!password) {
                document.getElementById('connectionStatus').innerText = "Connection cancelled.";
                return;
            }
            fetch('/connect_wifi', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({ ssid: ssid, password: password })
            })
                .then(response => response.json())
                .then(data => {
                    console.log("Connection attempt result:", data);
                    document.getElementById('connectionStatus').innerText = data.message;
                    if (data.success) {
                        checkInternetAccess();
                    }
                })
                .catch(error => {
                    console.error("Error during connection attempt:", error);
                    document.getElementById('connectionStatus').innerText = "Error during connection attempt.";
                });
        }

        function checkInternetAccess() {
            fetch('/check_internet_access')
                .then(response => response.json())
                .then(data => {
                    const statusMessage = data.success ? "Internet Access Ok" : "No Internet Access";
                    document.getElementById('connectionStatus').innerText = statusMessage;
                })
                .catch(error => {
                    console.error("Error checking internet access:", error);
                    document.getElementById('connectionStatus').innerText = "Error checking internet access.";
                });
        }
    </script>
</body>
</html>
