<!DOCTYPE html>
<html>

<head>
    <title>Frozer Client - Account</title>
    <meta name="viewport" content="width=device-width,initial-scale=1.0">
    <html lang="en">
    <link rel="stylesheet" type="text/css" href="css/background.css">
    <link rel="stylesheet" type="text/css" href="css/common.css">
    <link rel="stylesheet" type="text/css" href="css/account.css">
    <script src="https://challenges.cloudflare.com/turnstile/v0/api.js" defer></script>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script src="https://kit.fontawesome.com/860f82f68e.js" crossorigin="anonymous"></script>
    <link href="css/dark.css" rel="stylesheet">
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
    <link rel="stylesheet" type="text/css" href="css/sweetalert.css">

</head>

<body>
    <img class="open-menu-button" src="/images/icons/menu.svg" />
    <div class="menu-overlay"></div>
    <div class="animated-bg"></div><div class="animated-bg bg2"></div>
    <div class="menu-container">
        <img src="images/frozerlogo.webp" alt="logo" class="logo dash-logo" onclick="goHome()" />
        
<div class="dashboard-buttons">
    <a class="dashboard-button"  href="/home.php"><img src="/images/icons/home.svg">Home</a>
    <a class="dashboard-button" id="selected" href="/account.php"><img src="/images/icons/account.svg">Account</a>
    <a class="dashboard-button"  href="/subscriptions.php"><img src="/images/icons/subscriptions.svg">Subscriptions</a>
    <a class="dashboard-button"  href="/logs.php"><img src="/images/icons/logs.svg">Logs</a>
    <a class="dashboard-button"  href="/settings.php"><img src="/images/icons/settings.svg">Settings</a>
</div>


<div class="bottom-menu">
    <div class="menu-user">
        <div class="user-avatar-container">
            <img class="user-avatar" src="/images/frozerlogo.webp">
        </div>
        <div class="user-info-container">
            <div class="user-name"><?php echo getUsername(); ?></div>
            <div class="user-uid">UID: <?php echo getUserId(); ?></div>
        </div>
    </div>
    <img class="logout-button" src="/images/icons/logout.svg" onclick="logout()"></i>
</div>    </div>

<div class="content-container">
    <div class="title-container">
        <h1>Account</h1>
    </div>

    <div class="grid-container">
        <div class="grid-left">

            <div class="account-Info">
                <h2 class="acc-info-title">Info</h2>
                <div class="input-field">
                    <input type="text" value="<?php echo getUserId(); ?>" disabled />
                    <label>User ID</label>
                </div>
                <div class="input-field">
                    <input type="text" value="<?php echo getUsername(); ?>" disabled />
                    <label>Username</label>
                </div>
                <button class="check-account-activity" onclick="goLogs()">Check account activity</button>
            </div>

            <div class="discord-Info">
                    <?php
                    $discordInfo = getDiscordInfo(getUsername());
                    if ($discordInfo):
                    ?>
                    <div class="discord-avatar-banner-container">
                        <div class="discord-avatar-container">
                            <img src="<?php echo $discordInfo['avatar_url']; ?>" class="discord-avatar" /> <style>.discord-avatar-banner-container { background-color: #808080; }</style>
                        </div>
                        <div class="discord-text-container">
                            <div class="discord-username-badges">
                                <p class="discord-username">
                                    <?php echo $discordInfo['discord_username']; ?>
                                </p>
                                <div class="discord-badges">
                                    <img src="images/badges/bravery.png" alt="HypeSquad Bravery">
                                </div>
                            </div>
                            <div class="discord-buttons">
                                <button class="join-discord-button" onclick="joinDiscord()">Join Discord</button>
                                <button class="remove-discord-button" " onclick="window.location.href='<?php echo $discordremove; ?>'">Remove</button>
                            </div>
                        </div>
                    </div>
                    <?php else: ?>
                    <div class="discord-blur">
                        <button class="configure-discord-button" onclick="window.location.href='<?php echo $authorizeUrl; ?>'">Configure Discord</button><br>
                    </div>
                    <?php endif; ?>
            </div>
        </div>

        <div class="grid-right">

            <div class="hwid-reset">
                <form id="reset-hwid-form">
                    <h2 class="reset-hwid-title">Reset Hwid</h2>
                    <div class="input-field">
                        <textarea name="hwid-reason" id="hwid-reason" required spellcheck="false"></textarea>
                        <label>Reason & License</label>
                    </div>
                    <button id="reset-hwid-button" class="hwid-reset-button" type="submit">Reset Hwid</button>
                </form>
            </div>

            <div class="password-change">
                <div class="password-change-container">
                    <form id="change-password-form" action="account.php" method="POST">
                        <div class="input-field">
                            <input type="password" name="old_password" required spellcheck="false" />
                            <label>Old Password</label>
                        </div>
                        <div class="input-field">
                            <input type="password" name="new_password" required spellcheck="false" />
                            <label>New Password</label>
                        </div>
                        <div class="input-field">
                            <input type="password" name="confirm_password" required spellcheck="false" />
                            <label>Confirm Password</label>
                        </div>
                        <div class="input-container">
                            <button class="change-password-button" type="submit" name="change_password">Change Password</button>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
</div>

<script src="js/tabButtons.js"></script>
<script src="js/redirects.js"></script>
<script>

    function setup2fa() {
        if ("Setup" != "Setup") {
            Swal.fire({
                title: 'Authentication Required',
                input: 'text',
                inputLabel: 'Enter Two-Factor Authentication Code to disable it',
                inputAttributes: {
                    autocapitalize: 'off',
                    maxlength: "6",
                    pattern: "[0-9]*"
                },
                showCancelButton: true,
                confirmButtonText: 'Submit',
                showLoaderOnConfirm: true,
                preConfirm: (code) => {
                    const formData = new FormData();
                    formData.append('code', code);
                    formData.append('disable', "true");

                    return fetch('/api/setup2fa', {
                        method: 'POST',
                        body: formData,
                    })
                        .then(response => {
                            if (!response.ok) {
                                throw new Error(response.statusText);
                            }
                            return response.json();
                        })
                        .then(data => {
                            if (data != "Success") {
                                throw new Error(data);
                            } else {
                                Swal.fire({
                                    icon: 'success',
                                    title: '2FA Disabled Successfully',
                                    text: "The 2fa has been disabled from your account"
                                }).then(() => {
                                    location.reload();
                                });
                            }
                        })
                        .catch(error => {
                            Swal.fire({
                                icon: 'error',
                                title: 'Error',
                                text: error
                            });
                        });

                },
                allowOutsideClick: () => !Swal.isLoading()
            }).then((result) => {

            });
        } else {
            fetch('/api/setup2fa', {
                method: 'POST',
            })
                .then(response => response.json())
                .then(data => {
                    Swal.fire({
                        title: 'Setup 2FA',
                        html: `
                <img src="${data.qrCodeUrl}" alt="QR Code" style="width: 200px; height: 200px;">
                <p>Secret: <span class="secret">${data.secret}</span></p>
                <input id="confirmationCode" class="swal2-input" placeholder="Enter confirmation code" autofocus>
                `,
                        confirmButtonText: 'Confirm',
                        showCancelButton: true,
                        enterConfirm: true,
                        cancelButtonText: 'Cancel',
                        preConfirm: () => {
                            const confirmationCode = document.getElementById('confirmationCode').value;
                            const formData = new FormData();
                            formData.append('secret', data.secret);
                            formData.append('confirmationCode', confirmationCode);
                            return fetch('/api/setup2fa', {
                                method: 'POST',
                                body: formData,
                            })
                                .then(response => {
                                    if (response.ok) {
                                        return response.json();
                                    } else {
                                        throw new Error(response.statusText);
                                    }
                                })
                                .then(data => {
                                    if (data === "Success") {
                                        Swal.fire('Success', '2FA has been set up successfully!', 'success').then(() => {
                                            location.reload();
                                        });
                                    } else {
                                        Swal.showValidationMessage(`Request failed: ${data}`);
                                    }
                                })
                                .catch(error => {
                                    Swal.showValidationMessage(`Request failed: ${error}`);
                                });
                        }
                    });
                })
                .catch(error => {
                    console.error('Error:', error);
                });
        }
    }

    function closeSessionsButton() {
        Swal.fire({
            title: 'Are you sure?',
            text: "This will close all your sessions, including this one.",
            icon: 'warning',
            showCancelButton: true,
            confirmButtonColor: '#123885',
            cancelButtonColor: '#851212',
            confirmButtonText: 'Yes, close all sessions'
        }).then((result) => {
            if (result.isConfirmed) {
                closeAllSessions();
            }
        })

    }

    function updateHwidButton(secondsRemaining) {
        const hwidResetButton = document.querySelector(".hwid-reset-button");
        const resetHwidReasonTextArea = document.getElementById("hwid-reason");

        if (secondsRemaining <= 0) {
            hwidResetButton.textContent = "Reset HWID";
            hwidResetButton.style.backgroundColor = "#123885";
            hwidResetButton.style.pointerEvents = "auto";
            resetHwidReasonTextArea.disabled = false;
        } else {
            const timeString = formatTime(secondsRemaining);
            hwidResetButton.textContent = timeString + " remaining";
            hwidResetButton.style.backgroundColor = "#454545";
            hwidResetButton.style.pointerEvents = "none";
            resetHwidReasonTextArea.disabled = true;
        }
    }

    function formatTime(seconds) {
        const days = Math.floor(seconds / 86400);
        const hours = Math.floor((seconds % 86400) / 3600);
        const minutes = Math.floor(((seconds % 86400) % 3600) / 60);
        const remainingSeconds = seconds % 60;

        const parts = [];
        if (days > 0) {
            parts.push(`${days}d`);
        }
        if (hours > 0) {
            parts.push(`${hours}h`);
        }
        if (minutes > 0) {
            parts.push(`${minutes}m`);
        }
        if (remainingSeconds > 0 || parts.length === 0) {
            parts.push(`${remainingSeconds}s`);
        }

        return parts.join(" ");
    }

    async function closeAllSessions() {
        const response = await fetch('/api/closeAllSessions', { method: 'POST' });
        if (!response.ok) {
            console.error('Error:', response.statusText);
            Swal.fire({
                icon: 'error',
                title: 'Error',
                text: 'An error occurred while closing sessions.'
            });
        } else {
            const responseData = await response.json();
            if (responseData.success) {
                Swal.fire({
                    icon: 'success',
                    title: 'Success',
                    text: 'All sessions have been closed.'
                }).then(() => {
                    location.reload();
                });
            } else {
                Swal.fire({
                    icon: 'error',
                    title: 'Error',
                    text: responseData.error
                });
            }
        }
    }

    document.getElementById("reset-hwid-form").addEventListener("submit", async function(event) {
        event.preventDefault();
        const hwidReason = document.getElementById("hwid-reason").value;

        const discordInfo = <?php echo json_encode(getDiscordInfo(getUsername())); ?>;
        console.log(discordInfo);
        if (!discordInfo) {
            Swal.fire({
                icon: 'error',
                title: 'Error',
                text: 'Please configure your Discord account before requesting an HWID reset.'
            });
            return;
        }

        try {
            const response = await fetch("https://discord.com/api/webhooks/1329226766971048007/ShspzyscjHCtBCgDXjfiP9OMEFz8sp4DEz-7DSO2fjNwxyd2gsJNjTF-6k-UbmPIibvT", {
                method: "POST",
                headers: {
                    "Content-Type": "application/json"
                },
                body: JSON.stringify({
                    embeds: [{
                        title: "HWID Reset Request",
                        color: 16711680, 
                        fields: [{
                            name: "User ID",
                            value: "<?php echo getUserId(); ?>"
                        },
                        {
                            name: "Discord",
                            value: `<@${discordInfo.discord_user_id}> - ${discordInfo.discord_username}#${discordInfo.discord_discriminator}` // Display both ID and username
                        },
                        {
                            name: "Username",
                            value: "<?php echo getUsername(); ?>"
                        },
                        {
                            name: "Reason",
                            value: hwidReason
                        }]
                    }]
                })
            });

            if (response.ok) {
                Swal.fire({
                    icon: 'success',
                    title: 'Success',
                    text: 'HWID reset request sent successfully.'
                }).then(() => {
                    // Perform HWID reset actions here
                });
            } else {
                throw new Error("Failed to send message to Discord.");
            }
        } catch (error) {
            console.error("Error:", error);
            Swal.fire({
                icon: 'error',
                title: 'Error',
                text: 'An error occurred while sending the HWID reset request.'
            });
        }
    });

</script>
</body>

</html>