<?php
include "classes/class.loader.php";
$html = new html();
$html->bacground_emoji();
$calls = new functions();
$db = new db();
if(!isset($_SESSION['user_id'])){
    echo "<script>window.location.href='login.php';</script>";
}
$html->header();
$wallet_amount = $calls->get_wallet_amount($_SESSION['user_id']);
/**
 * @param array $data
 * @param null $passPhrase
 * @return string
 */
function generateSignature($data, $passPhrase = null)
{
    // Create parameter string
    $pfOutput = '';
    foreach ($data as $key => $val) {
        if ($val !== '') {
            $pfOutput .= $key . '=' . urlencode(trim($val)) . '&';
        }
    }
    // Remove last ampersand
    $getString = substr($pfOutput, 0, -1);
    if ($passPhrase !== null) {
        $getString .= '&passphrase=' . urlencode(trim($passPhrase));
    }
    return md5($getString);
}

// testing
// $merchant_id = '10000100';
// $mechhant_key = '46f0cd694581a';
// $passphrase = 'jt7NOE43FZPn';
// $link = "https://sandbox.payfast.co.za/eng/process";

// Live
$merchant_id = 23635991;
$mechhant_key = '5n8lir8uw1cun';
$passphrase = 'eWG123456789';
$link = "https://www.payfast.co.za/eng/process";



?>
<style>
    body {
        background-color: #bebebee7;
        color: white;
    }
</style>
<div class="home_container">
    <div class="container_wide">
        <h1>BUY CREDITS:</h1>
        <div class="data_container_for_adding">
            <?php

            // get park_packages
            $park_packages = $db->query("SELECT * FROM `park_prices` WHERE `status` = '1' AND `price` != '0' AND `name` != 'GROUP' ORDER BY price ASC");
            while ($package = $park_packages->fetch_assoc()) {

                $price = $package['price'] * 1.15;


                $data = array(
                    // Merchant details
                    'merchant_id' => $merchant_id,
                    'merchant_key' => $mechhant_key,
                    'return_url' => "https://unleashed.elegantwork.co.za/successfull.php?credits=$package[record_id]&zar=$price",
                    'cancel_url' => 'https://unleashed.elegantwork.co.za/home.php',
                    'notify_url' => "https://unleashed.elegantwork.co.za/send_notification.php?credits=$package[record_id]",
                    // Buyer details
                    'name_first' => $_SESSION['username'],
                    'email_address' => $_SESSION['email'],
                    // Transaction details
                    'amount' => $price,
                    'item_name' => "buy_credits"
                );
                $signature = generateSignature($data, $passphrase);

                ?>

                <div class="data_row">
                    <h1><?php echo $package['name']; ?></h1>
                    <h2>Credits : <?php echo $package['credits']; ?></h2>
                    <h1> R <?php echo  number_format($price,2); ?> inc</h1>

                    <form action="<?php echo $link; ?>" method="post">
                        <input type="hidden" name="signature" value="<?php echo $signature; ?>">
                        <input type="hidden" name="merchant_id" value="<?php echo $merchant_id; ?>">
                        <input type="hidden" name="merchant_key" value="<?php echo $mechhant_key; ?>">
                        <input type="hidden" name="amount" value="<?php echo $price; ?>">
                        <input type="hidden" name="item_name" value="<?php echo "buy_credits"; ?>">
                        <input type="hidden" name="name_first" value="<?php echo $_SESSION['username']; ?>">
                        <input type="hidden" name="email_address" value="<?php echo $_SESSION['email']; ?>">
                        <input type="hidden" name="return_url"
                            value="https://unleashed.elegantwork.co.za/successfull.php?credits=<?php echo $package['record_id']; ?>&zar=<?php echo $price; ?>">
                        <input type="hidden" name="cancel_url" value="https://unleashed.elegantwork.co.za/home.php">
                        <input type="hidden" name="notify_url"
                            value="https://unleashed.elegantwork.co.za/send_notification.php?credits=<?php echo $package['record_id']; ?>">
                        <!-- <input type="submit"  class="button" value="BUY NOW">
                      -->
                        <button>BUY NOW</button>

                    </form>

                    <?php if ($wallet_amount > 0) { ?>
                        <div class="line"></div>
                        <h1>Wallet</h1>
                        <h2> R <?php echo number_format($wallet_amount, 2); ?></h2>
                        <h2> -R <?php echo number_format($price, 2); ?></h2>
                        <div class="line"></div>
                        <h2> R<?php echo number_format($wallet_amount - $price, 2); ?></h2>
                        <form action="use_wallet.php" method="post">
                            <input name="credit_package" type="hidden" value="<?php echo $package['record_id']; ?>">
                            <button>USE WALLET</button>
                        </form>
                    <?php } ?>
                </div>
                <?php
            }
            ?>

        </div>
    </div>
</div>

  <div class="whatsapp-label">HELP</div>

    <!-- Floating button -->
    <a class="whatsapp-float" id="whatsappBtn" title="Message us on WhatsApp" target="_blank" rel="noopener noreferrer"
        href="#" aria-label="Open WhatsApp chat">
        <!-- WhatsApp SVG icon (official-looking) -->
        <svg viewBox="0 0 24 24" fill="none" aria-hidden="true" xmlns="http://www.w3.org/2000/svg">
            <path
                d="M20.52 3.48A11.9 11.9 0 0 0 12 0C5.373 0 .003 5.373.003 12 0 13.987.44 15.9 1.27 17.6L0 24l6.66-1.76a11.94 11.94 0 0 0 5.34 1.38h.01c6.627 0 12-5.373 12-12 0-3.19-1.24-6.18-3.48-8.04z"
                fill="#25D366" />
            <path
                d="M17.56 14.1c-.32-.16-1.9-.94-2.2-1.04-.3-.11-.52-.16-.74.16-.22.32-.86 1.04-1.06 1.25-.19.19-.39.21-.72.07-.32-.13-1.37-.51-2.61-1.62-.97-.86-1.62-1.92-1.81-2.24-.19-.32-.02-.49.14-.65.14-.14.32-.36.48-.54.16-.19.21-.32.32-.53.11-.21.05-.39-.03-.55-.08-.16-.74-1.78-1.02-2.44-.27-.64-.55-.55-.74-.56-.19-.01-.41-.01-.63-.01-.22 0-.58.08-.88.39-.3.31-1.15 1.12-1.15 2.73 0 1.6 1.18 3.14 1.34 3.36.16.22 2.32 3.66 5.62 5.12 3.3 1.46 3.3 0.97 3.9 0.91.6-.07 1.92-.78 2.19-1.53.27-.74.27-1.38.19-1.53-.08-.15-.3-.24-.62-.4z"
                fill="#fff" />
        </svg>
    </a>

    <script>
        // PHONE: user-provided local number (0645010642).
        // For reliable behaviour with wa.me we convert to international format.
        // South Africa country code = 27; remove leading zero from the local number.
        const localNumber = "0645010642";
        const intlNumber = localNumber.replace(/^0+/, ""); // removes leading zero(s)
        // If your country is South Africa, add 27 before the number:
        const countryCode = "27";
        const phoneForWA = countryCode + intlNumber; // -> "27645010642"

        // Prefilled message (exact text provided by user)
        const msg = "Good day Team, Please help with the following:";

        // Build links: prefer whatsapp:// for mobile apps, fallback to https://wa.me/ for web/mobile
        const encodedMsg = encodeURIComponent(msg);
        const waAppLink = "whatsapp://send?phone=" + phoneForWA + "&text=" + encodedMsg;
        const waWebLink = "https://wa.me/" + phoneForWA + "?text=" + encodedMsg;

        // Use web link by default (works on desktop & mobile); on some mobile browsers whatsapp:// may work.
        const anchor = document.getElementById("whatsappBtn");

        // Attempt to open app link on mobile — but final href will be web fallback.
        // We'll set href to web link so it also works in desktop browsers.
        anchor.href = waWebLink;

        // Optional: on mobile, try to open the app first then fallback to web.
        // (We do this by attempting to navigate to app scheme for short time.)
        function openWhatsAppPreferApp(e) {
            // On touch devices, try app; on desktop, just open web
            const isMobile = /Android|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent);
            if (!isMobile) return; // let default anchor behavior open new tab

            e.preventDefault();
            // Try app scheme
            const appUrl = waAppLink;
            const webUrl = waWebLink;

            // Create invisible iframe to try app URL (older technique)
            const start = Date.now();
            let didOpen = false;

            // For modern browsers, direct location change is OK.
            window.location = appUrl;

            // After short delay, navigate to web link (works as fallback)
            setTimeout(function () {
                // If still on the page, open web link
                // We guard to avoid double navigation in some environments
                if (Date.now() - start < 2000) {
                    window.location = webUrl;
                }
            }, 1500);
        }

        // Use the mobile-prefer behavior on click
        anchor.addEventListener("click", openWhatsAppPreferApp, { passive: false });
    </script>