<!DOCTYPE html>
<html>
<head>
    <title>Frozer Client - Subscriptions</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <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/subscriptions.css">
    <script src="https://kit.fontawesome.com/860f82f68e.js" crossorigin="anonymous"></script>
</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" href="/account.php"><img src="/images/icons/account.svg">Account</a>
            <a class="dashboard-button" id="selected" 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>Subscriptions</h1>
        </div>

        <div class="subscriptions-container">
                                                    
        </div>


        <div class="separator">
            <hr>
        </div>
        <div class="grid-container">
            <div class="grid-item center">
                <form class="redeem-license" id="redeemForm">
                    <div class="input-field">
                        <input type="text" id="licenseInput" name="license" required spellcheck="false" />
                        <label>License</label>
                    </div>
                    <div class="redeem-container">
                        <button class="redeem-button" type="submit">Redeem</button>
                    </div>
                </form>
            </div>
            <div class="grid-item">
                <div class="table-container">
                    <table>
                        <thead>
                            <tr>
                                <th>License</th>
                                <th>Type</th>
                                <th>Duration</th>
                                <th>Expiration</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($subscriptions as $sub): ?>
                                <tr>
                                    <td><?php echo htmlspecialchars($sub['license']); ?></td>
                                    <td><?php echo htmlspecialchars($sub['type']); ?></td>
                                    <td><?php echo $sub['duration'] > 1500 ? 'Lifetime' : htmlspecialchars($sub['duration']) . ' days'; ?></td>
                                    <td><?php echo convertTimestamp($sub['expiry']); ?></td>
                                </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
    <script src="js/tabButtons.js"></script>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/tsparticles-confetti@1.0.0/dist/tsparticles.confetti.bundle.min.js"></script>
    <script>
    $(document).ready(function() {
        $('#redeemForm').on('submit', function(event) {
            event.preventDefault();

            var licenseKey = $('#licenseInput').val();

            $.ajax({
                url: 'subscriptions.php',
                type: 'POST',
                data: { license: licenseKey },
                success: function(response) {
                    try {
                        var jsonResponse = typeof response === 'string' ? JSON.parse(response) : response;

                        if (jsonResponse.status === 'success') {
                            showResponse("Redeemed successfully", "#168512", 5000, "/subscriptions.php");

                            const duration = 5 * 1000,
                            animationEnd = Date.now() + duration,
                            defaults = { startVelocity: 30, spread: 360, ticks: 60, zIndex: 0 };

                            function randomInRange(min, max) {
                                return Math.random() * (max - min) + min;
                            }

                            const interval = setInterval(function () {
                                const timeLeft = animationEnd - Date.now();

                                if (timeLeft <= 0) {
                                    return clearInterval(interval);
                                }

                                const particleCount = 50 * (timeLeft / duration);

                                confetti(
                                    Object.assign({}, defaults, {
                                        particleCount,
                                        origin: { x: randomInRange(0.1, 0.3), y: Math.random() - 0.2 },
                                    })
                                );
                                confetti(
                                    Object.assign({}, defaults, {
                                        particleCount,
                                        origin: { x: randomInRange(0.7, 0.9), y: Math.random() - 0.2 },
                                    })
                                );
                            }, 250);
                        } else {
                            showResponse(jsonResponse.message, "#851212", 3000);
                        }
                    } catch (e) {
                        showResponse("An error occurred. Please try again.", "#851212", 3000);
                    }
                },
                error: function(xhr, status, error) {
                    showResponse("An error occurred. Please try again.", "#851212", 3000);
                }
            });
        });

        function showResponse(text, color, duration, redirectUrl) {
            var button = $(".redeem-button");
            button.text(text).css("background-color", color);

            if (redirectUrl) {
                setTimeout(function () {
                    window.location.href = redirectUrl;
                }, duration);
            } else {
                setTimeout(function () {
                    button.text("Redeem");
                    button.css("background-color", "");
                }, duration);
            }
        }

        function refreshSubscriptions() {
            $.ajax({
                url: 'subscriptions.php',
                type: 'GET',
                success: function(response) {
                    var jsonResponse = typeof response === 'string' ? JSON.parse(response) : response;

                    if (jsonResponse) {
                        $('tbody').empty();
                        jsonResponse.forEach(function(sub) {
                            var durationText = sub.duration > 1500 ? 'Lifetime' : sub.duration + " days";
                            var expiryDate = sub.expiry === null ? 'Never' : (sub.expiry > (Date.now() / 1000 + 86400 * 1500) ? 'Never' : new Date(sub.expiry * 1000).toLocaleDateString());
                            var row = `<tr>
                                         <td>${sub.license}</td>
                                         <td>${sub.type}</td>
                                         <td>${durationText}</td>
                                         <td>${expiryDate}</td>
                                     </tr>`;
                            $('tbody').append(row);
                        });
                    }
                }
            });
        }

        refreshSubscriptions();
        setInterval(refreshSubscriptions, 300000); 
    });

    function logout() {
        window.location.href = 'logout.php';
    }

    function goHome() {
        window.location.href = 'home.php';
    }
    </script>
</body>
</html>
