<?php

require 'config.php';

require 'layout/header.php';

session_start();

security::InitSecurity();

member::checkLoggedInUser();

security::Bearer(Bearer::LOGIN);

require 'layout/menu.php';

$packages = package::getpacks();

$chars = query::Select(TABLE_CHAR, ['account_id' => $_SESSION['account_id']]);

util::clearSelectChar();

$_SESSION['csrf'] = util::GenerateCSRF();

?>

<head>
    <script src="https://js.stripe.com/v3/"></script>
</head>

<style>
    .description-box {
        width: 250px;
        height: 400px;
        display: flex;
        align-items: center;
        justify-content: center;
        transition: opacity 0.3s;
        overflow: auto;
    }

    .description-box p {
        white-space: pre-wrap;
        /* This preserves whitespace and line breaks */
        text-align: left;
        /* Align text to the left */
    }

    .hidden {
        opacity: 0;
        pointer-events: none;
    }
</style>

<body class="bg-gray-900 text-gray-100 flex items-center justify-center h-screen">
    <div class="container mx-auto p-8">
        <div class="bg-gray-800 p-8">
            <form id="donateForm" action="checkout.php" method="post">
                <div class="pb-5 flex item-center">
                    <div class="w-full flex">
                        <div style="width: 33%;"></div>
                        <div class="flex w-10/12 justify-center" style="width: 34%;">
                            <?php require 'svg/donate.php'; ?>
                        </div>
                        <div class="relative" style="width: 33%;">
                            <div class="flex justify-end">
                                <select name="character" class="bg-gray-900 text-gray-300 p-3 rounded-lg right-0">
                                    <?php
                                    foreach ($chars as $char) {
                                        echo '<option value="' . $char['char_id'] . '">' . $char['name'] . '</option>';
                                    }
                                    ?>
                                </select>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6 overflow-auto scroll-hide" style="height: 55%;">
                    <?php foreach ($packages as $package) : ?>
                        <label class="package-card bg-gray-700 p-6 rounded-lg shadow-lg text-center relative" for="package<?= $package['id'] ?>" onclick="selectPackage(<?= $package['id'] ?>)">
                            <?php if ($package['recommended']) : ?>
                                <span class="absolute top-0 right-0 m-2 text-xs font-semibold bg-yellow-400 text-gray-900 px-2 py-1 rounded">แนะนำ</span>
                            <?php endif; ?>
                            <img src="<?= $package['img'] ?>" alt="Package <?= $package['id'] ?>" class="w-16 h-16 mx-auto mb-4">
                            <h3 class="text-xl font-bold mb-2"><?= $package['name'] ?></h3>
                            <p class="text-sm text-gray-300 mb-4"><?= $package['description'] ?></p>
                            <?php if (!empty($package['items'])) : ?>
                                <div class="flex flex-wrap justify-center mb-4">
                                    <?php foreach ($package['items'] as $item) : ?>
                                        <div class="item-card bg-gray-600 p-2 m-2 rounded-lg flex items-center relative" onmouseover="showDescription(event, `<?= addslashes($item['item_id']) ?>` ,`<?= addslashes($item['item_name']) ?>` ,`<?= addslashes($item['item_data']) ?>`,`<?= addslashes($item['item_refine']) ?>`,`<?= addslashes($item['item_pic']) ?>`)" onmouseout="hideDescription(event)">
                                            <img src="<?php echo $item['item_pic'] ?>" alt="<?= $item['item_name'] ?>" class="w-6 h-6 mr-2">
                                            <div class="text-xs">
                                                <p><?= $item['item_quantity'] ?> ea.</p>
                                            </div>
                                        </div>
                                    <?php endforeach; ?>
                                </div>
                            <?php endif; ?>
                            <input type="radio" name="cashValue" value="<?= $package['price'] ?>" id="package<?= $package['id'] ?>" class="mb-4 hidden">
                            <input type="hidden" name="csrf" value="<?= $_SESSION['csrf'] ?>">
                        </label>
                    <?php endforeach; ?>
                </div>

                <div class="mt-6 text-center -mb-6">
                    <button type="submit" name="submit" value="submit" id="submitb" class="text-white bg-blue-700 hover:bg-blue-800 focus:ring-4 focus:ring-blue-300 font-medium rounded-lg text-sm px-5 py-2.5 dark:bg-blue-600 dark:hover:bg-blue-700 focus:outline-none dark:focus:ring-blue-800">ยืนยัน</button>
                </div>
            </form>
        </div>
    </div>
    <div id="descriptionBox" class="description-box hidden fixed bg-gray-800 text-gray-100 p-4 rounded-lg shadow-lg overflow-auto flex justify-between">
        <p id="descriptionText"></p>
    </div>
</body>

<script>
    function showDescription(event, id, name, description, refine, item_pic) {
        const descriptionBox = document.getElementById('descriptionBox');
        const descriptionText = document.getElementById('descriptionText');

        description = description.replace(/\^000000/g, '<span style="color: #FFFFFF;">');

        description = description.replace(/\^([0-9A-Fa-f]{6})/g, '<span style="color:#$1">');

        const imgUrl = `${item_pic}`;

        const imgTag = `<img src="${imgUrl}" alt="Item Image" class="mx-auto mb-4" style="height: 100px; width: 75px;">`;

        let nameTag = '';

        if (refine > 0)
            nameTag = `<h3 class="text-xl font-bold mb-2 text-center">${name} [+${refine}]</h3>`;
        else
            nameTag = `<h3 class="text-xl font-bold mb-2 text-center">${name}</h3>`;

        const content = `${imgTag}${nameTag}<div>${description}</div>`;

        descriptionText.innerHTML = content;
        descriptionBox.style.top = `${event.clientY + 20}px`;
        descriptionBox.style.left = `${event.clientX}px`;
        descriptionBox.classList.remove('hidden');
    }

    function hideDescription() {
        const descriptionBox = document.getElementById('descriptionBox');
        descriptionBox.classList.add('hidden');
    }

    function selectPackage(packageNumber) {
        const packages = document.querySelectorAll('.package-card');
        packages.forEach(package => package.classList.remove('selected'));

        const selectedPackage = document.querySelector('#package' + packageNumber).parentElement;
        selectedPackage.classList.add('selected');

        document.getElementById('package' + packageNumber).checked = true;
    }

    document.getElementById('donateForm').addEventListener('submit', function(event) {
        const selectedPackage = document.querySelector('input[name="cashValue"]:checked');
        if (!selectedPackage) {
            event.preventDefault();
            ShowCancelToast();
        }
    });

    $(document).ready(function() {
        // เติมเงินเสร็จสมบูรณ์
        const sid = new URLSearchParams(window.location.search).get('sid');

        if (sid) {
            const sumb = document.getElementById("submitb");
            sumb.disabled = true;
            sumb.classList.remove("bg-blue-700");
            sumb.classList.add("bg-gray-700")
            ShowSuccessToast();
        }

        const code = new URLSearchParams(window.location.search).get('code');

        if (code === 'error')
            generalError("เกิดข้อผิดพลาด");
        
        if (code === 'char')
            generalError("กรุณาสร้างตัวละครก่อน");

        // clear
        window.history.replaceState({}, document.title, window.location.pathname);
    });
</script>

<?php

require 'layout/footer.php';

?>