<?php
session_set_cookie_params([
    'lifetime' => 86400, // 1 day
    'path' => '/',
    'domain' => '',
    'secure' => false,
    'httponly' => true,
    'samesite' => 'Lax'
]);
session_start();

$correct_password = "n201cc";

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    if (!empty($_POST["password"]) && strtolower($_POST["password"]) === strtolower($correct_password)) {
        $_SESSION["authenticated"] = true;
    } else {
        $error = "Incorrect password. Try again.";
    }
}

if (!isset($_SESSION["authenticated"])): ?>
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <link rel="icon" href="prop_64.png" />
        <link rel="apple-touch-icon" href="prop.png">
        <title>Hangar Outlet Control - Login</title>
        <style>
            body {
                font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
                text-align: center;
                padding: 50px;
                background-color: #f4f4f4;
            }
            .error {
                color: #e74c3c;
                margin-top: 10px;
            }
            .card {
                max-width: 400px;
                margin: auto;
                padding: 20px;
                background: #fff;
                border-radius: 12px;
                box-shadow: 0 4px 10px rgba(0, 0, 0, 0.1);
            }
            input[type="text"], button {
                font-size: 1.2em;
                padding: 10px;
                margin-top: 10px;
                width: 100%;
                box-sizing: border-box;
                border-radius: 8px;
                border: 1px solid #ccc;
            }
            button {
                background-color: #3498db;
                color: white;
                border: none;
                cursor: pointer;
                transition: background-color 0.3s ease;
            }
            button:hover {
                background-color: #2980b9;
            }
        </style>
    </head>
    <body>
        <div class="card">
            <h2>Enter Password<br>(tail number)</h2>
            <?php if (isset($error)) echo "<p class='error'>$error</p>"; ?>
            <form method="post">
                <input type="text" name="password" required>
                <button type="submit">Submit</button>
            </form>
        </div>
    </body>
    </html>
    <?php exit; ?>
<?php endif; ?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Hangar Outlet Control</title>
    <link rel="icon" href="prop_64.png" />
    <link rel="apple-touch-icon" href="prop.png">
    <script>
        const deviceId = "e00fce68f54835a936287844";
        const accessToken = "5e5adaa8a3a789bdaf12ba05e6502316f7af4cdb";
        const apiUrl = "https://api.particle.io/v1/devices/" + deviceId;

        async function fetchDeviceData() {
            showPageLoader(true);
            let statusKnown = false;
            try {
                const response = await fetch(`${apiUrl}/data`, {
                    headers: { "Authorization": `Bearer ${accessToken}` }
                });
                if (!response.ok) throw new Error("API request failed");
                const data = await response.json();
                const result = JSON.parse(data.result);

                document.getElementById("signalStrength").innerText = Math.round(Number(result.CellStrength));
                document.getElementById("signalQuality").innerText = Math.round(Number(result.CellQuality));
                document.getElementById("temperature").innerText = Math.round(Number(result.TMP));

                const statusElement = document.getElementById("status");
                statusElement.innerText = result.RelayStatus ? "ON" : "OFF";
                statusElement.style.color = result.RelayStatus ? "#2ecc71" : "#e74c3c";

                updateButtonStates(result.RelayStatus);
                statusKnown = true;
            } catch (error) {
                console.error("Error fetching device data:", error);
                alert("Error fetching device data.");
            }
            if (!statusKnown) {
                document.getElementById("onButton").style.display = "inline-block";
                document.getElementById("offButton").style.display = "inline-block";
            }
            showPageLoader(false);
        }

        async function controlOutlet(state) {
            showButtonLoader(true);
            try {
                const response = await fetch(`${apiUrl}/control`, {
                    method: "POST",
                    headers: {
                        "Authorization": `Bearer ${accessToken}`,
                        "Content-Type": "application/x-www-form-urlencoded"
                    },
                    body: `arg=${state}`
                });
                if (!response.ok) throw new Error("API request failed");
                await fetchDeviceData();
                showToast(`Outlet turned ${state === 1 ? 'ON' : 'OFF'}`);
            } catch (error) {
                console.error("Error controlling outlet:", error);
                alert("Error controlling outlet.");
            }
            showButtonLoader(false);
        }

        function updateButtonStates(status) {
            const onButton = document.getElementById("onButton");
            const offButton = document.getElementById("offButton");

            onButton.style.display = status ? "none" : "inline-block";
            offButton.style.display = status ? "inline-block" : "none";

            onButton.style.backgroundColor = status ? "lightgray" : "#2ecc71";
            offButton.style.backgroundColor = status ? "#e74c3c" : "lightgray";
            onButton.style.color = status ? "gray" : "white";
            offButton.style.color = status ? "white" : "gray";
        }

        function showPageLoader(show) {
            document.getElementById("pageLoader").style.display = show ? "flex" : "none";
        }

        function showButtonLoader(show) {
            document.getElementById("buttonLoader").style.display = show ? "flex" : "none";
        }
        
        function showToast(message) {
            const toast = document.getElementById("toast");
            toast.innerText = message;
            toast.className = "show";
            setTimeout(() => {
                toast.className = toast.className.replace("show", "");
            }, 3000);
        }

        window.onload = fetchDeviceData;
    </script>
    <style>
        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            background-color: #f8f9fa;
            text-align: center;
            padding: 20px;
        }
        button {
            padding: 12px 24px;
            margin: 10px;
            border: none;
            border-radius: 8px;
            font-size: 1em;
            cursor: pointer;
            transition: all 0.3s ease;
            box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
        }
        button:hover {
            opacity: 0.9;
        }
        #pageLoader, #buttonLoader {
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            background: rgba(255, 255, 255, 0.9);
            width: 100%;
            height: 100%;
            display: none;
            align-items: center;
            justify-content: center;
            font-size: 1.5em;
            font-weight: bold;
            border-radius: 12px;
        }
        .status {
            font-size: 1.5em;
            margin-top: 20px;
        }
        #status {
            font-size: 1.1em;
            font-weight: bold;
        }
        .control-button {
            font-size: 1.2em;
        }
        .refresh-button {
            margin-left: 10px;
            cursor: pointer;
            font-size: 1.2em;
        }
        details {
            margin: 20px auto;
            font-size: 1em;
            width: fit-content;
        }
        #toast {
            visibility: hidden;
            min-width: 250px;
            background-color: #333;
            color: #fff;
            text-align: center;
            border-radius: 8px;
            padding: 16px;
            position: fixed;
            bottom: 30px;
            left: 50%;
            transform: translateX(-50%);
            z-index: 1000;
            font-size: 17px;
            opacity: 0;
            transition: opacity 0.5s, visibility 0.5s;
        }
        #toast.show {
            visibility: visible;
            opacity: 1;
        }
        .card {
            max-width: 400px;
            margin: auto;
            padding: 20px;
            background: #fff;
            border-radius: 12px;
            box-shadow: 0 4px 10px rgba(0, 0, 0, 0.1);
        }
    </style>
</head>
<body>
    <div class="card">
    <div id="pageLoader">Loading...</div>
    <h1>Hangar Outlet Control</h1>
    <details>
        <summary>Technical Info</summary>
        <p><strong>Signal Strength:</strong> <span id="signalStrength">-</span>%</p>
        <p><strong>Signal Quality:</strong> <span id="signalQuality">-</span>%</p>
        <p><strong>Temperature:</strong> <span id="temperature">-</span>°F</p>
    </details>
    <div id="toast"></div>
    <p class="status">Status: <span id="status">-</span> <span onclick="fetchDeviceData()" class="refresh-button">&#x21bb;</span></p>
    <div style="position: relative; margin-top: 10px;">
        <button id="onButton" class="control-button" onclick="controlOutlet(1)">Turn ON</button>
        <button id="offButton" class="control-button" onclick="controlOutlet(0)">Turn OFF</button>
        <div id="buttonLoader">Processing...</div>
    </div>
    </div>
</body>
</html>
