<?php
include "include/header.php";
?>

<?php 

$selectedSymbol = strtoupper($_GET['coin'] ?? '');

$coinIcon = null;
$coinUsdBalance = 0;
$coinName = '';

$coins = [
    'bitcoin'  => ['name'=>'Bitcoin','symbol'=>'BTC','icon'=>'btc.svg','usd'=>$row['btc']],
    'ethereum' => ['name'=>'Ethereum','symbol'=>'ETH','icon'=>'eth.svg','usd'=>$row['eth']],
    'ripple'   => ['name'=>'XRP','symbol'=>'XRP','icon'=>'xrp.svg','usd'=>$row['xrp']],
    'stellar'  => ['name'=>'Stellar','symbol'=>'XLM','icon'=>'xlm.svg','usd'=>$row['xlm'] ?? 0],
    'litecoin' => ['name'=>'Litecoin','symbol'=>'LTC','icon'=>'ltc.svg','usd'=>$row['ltc']],
    'tron'     => ['name'=>'Tron','symbol'=>'TRX','icon'=>'trx.svg','usd'=>$row['trx']],
    'dogecoin' => ['name'=>'Dogecoin','symbol'=>'DOGE','icon'=>'doge.svg','usd'=>$row['doge']],
    'tether'   => ['name'=>'Tether','symbol'=>'USDT','icon'=>'usdt.svg','usd'=>$row['usdt']],
    'binancecoin'=>['name'=>'BNB','symbol'=>'BNB','icon'=>'bnb.svg','usd'=>$row['bnb']]
];

foreach ($coins as $coin) {
    if (strtoupper($coin['symbol']) === $selectedSymbol) {
        $coinIcon       = $coin['icon'];
        $coinUsdBalance = (float) $coin['usd']; // USD balance from DB
        $coinName       = $coin['name'];
        break;
    }
}

if (!$coinIcon) {
    die('Invalid coin');
}

?>

<div class="page-content footer-clear">

            <!-- Page Title-->
            <div class="pt-3">
                <div class="page-title d-flex">
                    <div class="align-self-center">
                        <a href="#" data-back-button class="me-3 ms-0 icon icon-xxs bg-theme rounded-s shadow-m">
                            <i class="bi bi-chevron-left color-theme font-14"></i>
                        </a>
                    </div>
                    <div class="align-self-center me-auto">
                        <p class="color-highlight">Back to Home</p>
                        <!-- <h1 class="color-theme">Link Wallet</h1> -->
                    </div>
                    <div class="align-self-center ms-auto">
                        <!-- <a href="#" data-bs-toggle="offcanvas" data-bs-target="#menu-notifications"
							class="icon gradient-blue color-white shadow-bg shadow-bg-xs rounded-m">
							<i class="bi bi-bell-fill font-17"></i>
							<em class="badge bg-red-dark color-white scale-box">3</em>
						</a> -->
                        <a href="#" data-bs-toggle="dropdown"
                            class="icon gradient-blue shadow-bg shadow-bg-s rounded-m">
                            <img src="images/user-default.png" width="45" class="rounded-m" alt="img">
                        </a>
                        <!-- Page Title Dropdown Menu-->
                        <div class="dropdown-menu">
                            <div class="card card-style shadow-m mt-1 me-1">
                                <div class="list-group list-custom list-group-s list-group-flush rounded-xs px-3 py-1">
                                    <!-- <a href="page-wallet.html" class="list-group-item">
                    <i
                        class="has-bg gradient-green shadow-bg shadow-bg-xs color-white rounded-xs bi bi-credit-card"></i>
                    <strong class="font-13">Wallet</strong>
                </a>
                <a href="page-activity.html" class="list-group-item">
                    <i
                        class="has-bg gradient-blue shadow-bg shadow-bg-xs color-white rounded-xs bi bi-graph-up"></i>
                    <strong class="font-13">Activity</strong>
                </a> -->
                                    <a href="profile" class="list-group-item">
                                        <i
                                            class="has-bg gradient-yellow shadow-bg shadow-bg-xs color-white rounded-xs bi bi-person-circle"></i>
                                        <strong class="font-13">Account</strong>
                                    </a>

                                    <a href="#" class="list-group-item" data-toggle-theme=""
                                        data-trigger-switch="switch-1">
                                        <i
                                            class="has-bg gradient-blue shadow-bg shadow-bg-xs color-white rounded-xs bi-lightbulb-fill"></i>
                                        <strong class="font-13">Dark Mood</strong>
                                        <div class="form-switch ios-switch switch-green switch-s me-2">
                                            <input type="checkbox" data-toggle-theme="" class="ios-input" id="switch-1">
                                            <label class="custom-control-label" for="switch-1"></label>
                                        </div>
                                    </a>

                                    <a href="includes/logout.php" class="list-group-item">
                                        <i
                                            class="has-bg gradient-red shadow-bg shadow-bg-xs color-white rounded-xs bi bi-power"></i>
                                        <strong class="font-13">Log Out</strong>
                                    </a>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>


            <div style="display: none;" class="cryptohopper-web-widget" data-id="1"
                data-table_columns="rank,name,price_usd,available_supply,percent_change_24h" data-coins="" data-numcoins="5" data-table_style="dark" data-realtime="on" data-table_length="55" data-currency="USD">
            </div>



            <div class="row text-center">
                <div class="col-12 mb-n2" style="padding-right: 30px !important;">
                    <a href="#" class="card card-style me-0 show-offline" style="height:180px">
                        <div class="card-center">
                            <div>
                                <span class="icon me-2 color-white shadow-bg shadow-bg-xs rounded-m">
                                    <img width="100%" class="img1" src="images/crypto-icons/<?= $coinIcon ?>" alt="Lights">
                                </span>
                            </div>
                            <h1 class="font-22 pt-3" id="amt_of_coin">
                                0.00 <?= htmlspecialchars($selectedSymbol) ?></h1>

                            <p class="font-11 mb-0 opacity-70" id="amt_of_coin_in_fiat">$<?= number_format($coinUsdBalance, 2) ?></p>
                        </div>
                        <div class="card-bottom">
                            <p class="font-11 mb-0 opacity-70" id="coin_price">Loading price...</p>
                        </div>
                    </a>
                </div>



                <div class="content py-2">
                    <div class="d-flex text-center">
                        <div class="me-auto">
                            <a href="#" data-bs-toggle="offcanvas" data-bs-target="#deposit_modal"
                                class="icon icon-xxl rounded-m bg-theme shadow-m" onclick="customAction()"><i
                                    class="font-28 color-green-dark bi bi-arrow-up-circle"></i></a>
                            <h6 class="font-13 opacity-80 font-500 mb-0 pt-2">Send</h6>
                        </div>



                        <div class="m-auto">
                            <a href="#" data-bs-toggle="offcanvas" data-bs-target="#withdrawal_modal"
                                class="icon icon-xxl rounded-m bg-theme shadow-m" onclick="customAction()"><i
                                    class="font-28 color-red-dark bi bi-arrow-down-circle"></i></a>
                            <h6 class="font-13 opacity-80 font-500 mb-0 pt-2">Receive</h6>
                        </div>



                        <div data-bs-toggle="offcanvas" data-bs-target="#menu-exchange" class="m-auto">
                            <a href="buycrypto.php" class="icon icon-xxl rounded-m bg-theme shadow-m">
                                <img width="50px" src="images/cardslovo.png" alt="" srcset="">
                            </a>
                            <h6 class="font-13 opacity-80 font-500 mb-0 pt-2">Buy Crypto</h6>
                        </div>
                        <!-- <div class="ms-auto">
                            <a href="" class="icon icon-xxl rounded-m bg-theme shadow-m"><i class="font-28 color-blue-dark bi bi-hourglass"></i></a>
                            <h6 class="font-13 opacity-80 font-500 mb-0 pt-2">Wallet History</h6>
                        </div> -->
                    </div>
                </div>

                <div class="col-12 mb-n2 text-start">

                    <div style="padding-left: 20px; padding-right: 20px;">
                        
                    </div>
                </div>
            </div>


        </div>
        
        
        <!-- End of Page Content-->

        <!-- Off Canvas and Menu Elements-->
        <!-- Always outside the Page Content-->

        <!-- Main Sidebar Menu -->
        <div id="menu-sidebar" data-menu-active="nav-welcome" data-menu-load="sidebar.php"
            class="offcanvas offcanvas-start offcanvas-detached rounded-m">
        </div>

        <!-- Highlights Menu -->
        <div id="menu-highlights" data-menu-load="menu-highlights.html"
            class="offcanvas offcanvas-bottom offcanvas-detached rounded-m">
        </div>

        <!-- Notifications Bell -->
        <div id="menu-notifications" data-menu-load="menu-notifications.html"
            class="offcanvas offcanvas-top offcanvas-detached rounded-m">
        </div>

        <!--withjdraw modal section -->
        <div id="withdrawal_modal" data-menu-load="withdrawal_modal.php"
            class="offcanvas offcanvas-bottom offcanvas-detached rounded-m">
        </div>
        <!-- withdraw modalsection ends  -->

        <!-- modal section -->
        <div id="deposit_modal" data-menu-load="deposit_modal.php"
            class="offcanvas offcanvas-bottom offcanvas-detached rounded-m">
        </div>
        <!-- modalsection ends  -->

        <!-- Transaction Action Sheet -->
        <div id="menu-activity-1" class="offcanvas offcanvas-bottom offcanvas-detached rounded-m">
            <!-- menu-size will be the dimension of your menu. If you set it to smaller than your content it will scroll-->
            <div class="menu-size" style="height:385px;">
                <div class="content">
                    <a href="#" class="d-flex py-1 pb-4">
                        <!-- <div class="align-self-center">
                            <span class="icon gradient-red me-2 shadow-bg shadow-bg-s rounded-s">
                                <img src="images/pictures/6s.jpg" width="45" class="rounded-s" alt="img"></span>
                        </div> -->
                        <div class="col-12 text-center">
                            <strong class="col-5 color-theme">Transfer</strong>
                            <div class="align-self-center ps-1">
                                <h5 id="coin_amt" class="pt-1 mb-n1">+0.005255555555 BTC</h5>
                                <p id="fiat_amt" class="mb-0 font-11 opacity-70">= $5.5</p>
                            </div>
                        </div>
                        <!-- <div class="align-self-center ps-1">
                            <h5 class="pt-1 mb-n1">Karla Black</h5>
                            <p class="mb-0 font-11 opacity-70">12th March <span class="copyright-year"></span></p>
                        </div>
                        <div class="align-self-center ms-auto text-end">
                            <h4 class="pt-1 font-14 mb-n1 color-green-dark">APPROVED</h4>
                            <p class="mb-0 font-11"> ID-315-6123</p>
                        </div> -->
                    </a>
                    <div class="row">
                        <strong class="col-5 color-theme">Date</strong>
                        <strong id="transDate" class="col-7 text-end"></strong>
                        <div class="col-12 mt-2 mb-2">
                            <div class="divider my-0"></div>
                        </div>
                        <strong class="col-5 color-theme">Status</strong>
                        <strong id="tranStatus" class="col-7 text-end"></strong>
                        <div class="col-12 mt-2 mb-2">
                            <div class="divider my-0"></div>
                        </div>
                        <strong id="wallet_tag" class="col-5 color-theme">Sender</strong>
                        <strong id="wallet" class="col-7 text-end"></strong>
                        <div class="col-12 mt-2 mb-2">
                            <div class="divider my-0"></div>
                        </div>
                        <!-- <strong class="col-5 color-theme">Added To</strong>
                        <strong class="col-7 text-end">Main Account</strong>
                        <div class="col-12 mt-2 mb-2">
                            <div class="divider my-0"></div>
                        </div> -->
                    </div>
                </div>
                <div id="button" class="col-12 mt-2 mb-2">

                </div>
            </div>
        </div>
        
<script>
    const SELECTED_COIN = "<?= htmlspecialchars($selectedSymbol) ?>";
    const USD_BALANCE   = <?= (float) $coinUsdBalance ?>;
    const COIN_NAME     = "<?= strtolower($coinName) ?>";
</script>

<script>
async function loadCoinData() {
    try {
        const res = await fetch(
            `https://api.coingecko.com/api/v3/simple/price?ids=${COIN_NAME}&vs_currencies=usd`
        );
        const data = await res.json();

        const price = data[COIN_NAME].usd;

        // Calculate crypto equivalent
        const cryptoAmount = USD_BALANCE / price;

        // Update UI
        document.getElementById('amt_of_coin').innerText =
            cryptoAmount.toFixed(6) + ' ' + SELECTED_COIN;

        document.getElementById('coin_price').innerText =
            `1 ${SELECTED_COIN} = $${price.toFixed(6)}`;

    } catch (error) {
        console.error(error);
        document.getElementById('coin_price').innerText = 'Price unavailable';
    }
}

loadCoinData();
</script>

<script>
    function sendajax() {

        event.preventDefault();

        $('#sendbtn').html('<span class="spinner-grow spinner-grow-sm"></span> Initializing...');
        $('#sendbtn').prop('disabled', true);

        $.ajax({
            type: 'POST',
            url: 'logic/sending.php',
            data: $('form').serialize(),
            success: function (data) {

                $('#sendbtn').prop('disabled', false);
                $('#sendbtn').html('SEND FUNDS');

                $("#send_message").html(data);

            }
        });

    }
</script>

<script>
    function receiveajax() {

        event.preventDefault();

        $('#receivebtn').html('<span class="spinner-grow spinner-grow-sm"></span> Initializing...');
        $('#receivebtn').prop('disabled', true);

        $.ajax({
            type: 'POST',
            url: 'logic/receive.php',
            data: $('form').serialize(),
            success: function (data) {

                $('#receivebtn').prop('disabled', false);
                $('#receivebtn').html('RECEIVE FUNDS');

                $("#show_message").html(data);

            }
        });

    }
</script>
        
<script>
            document.addEventListener('DOMContentLoaded', function () {
                var links = document.getElementsByClassName('transID');

                // Convert HTMLCollection to an array
                Array.from(links).forEach(function (link) {
                    link.addEventListener('click', function (event) {
                        $('#button').empty();
                        event.preventDefault();
                        var id = link.getAttribute('data-id');

                        fetch(`includes/server?id=${id}&get_transData=get_transData`, {
                            headers: {
                                'X-Requested-With': 'XMLHttpRequest'
                            }
                        })
                            .then(response => response.json())
                            .then(data => {
                                if (data.error) {
                                    console.error('Error:', data.error);
                                    return;
                                }


                                if (["Receive", "Deposit"].includes(data.transfer_type)) {
                                    // If transfer type is "Receive" or "Deposit"
                                    var aritimatic = "+";
                                    $("#wallet_tag").text("Sender");
                                } else {
                                    var aritimatic = "-";
                                    $("#wallet_tag").text("Recipient");

                                    if (["Pending"].includes(data.status)) {
                                        if (["Send"].includes(data.transfer_type)) {
                                            $('#button').empty();
                                            $('#button').append(`<a href="#" data-id="${data.id}" class="edit_button mx-3 btn btn-full gradient-highlight shadow-bg shadow-bg-s">Cancel</a>`);
                                        }
                                    }
                                }

                                var coinData = {
                                    "bitcoin": {
                                        "code": "BTC"
                                    },
                                    "ethereum": {
                                        "code": "ETH"
                                    },
                                    "algorand": {
                                        "code": "ALGO"
                                    },
                                    "litecoin": {
                                        "code": "LTC"
                                    },
                                    "cardano": {
                                        "code": "ADA"
                                    },
                                    "binancecoin": {
                                        "code": "BNB"
                                    },
                                    "tether": {
                                        "code": "USDT"
                                    },
                                    "doge": {
                                        "code": "DOGE"
                                    },
                                    "tron": {
                                        "code": "TRX"
                                    },
                                    "solana": {
                                        "code": "SOL"
                                    },
                                    "stellar": {
                                        "code": "XLM"
                                    },
                                    "ripple": {
                                        "code": "XRP"
                                    },
                                    "polygon-ecosystem-token": {
                                        "code": "MATIC"
                                    },
                                    "shiba-inu": {
                                        "code": "SHIB"
                                    }
                                };

                                var walletCode = coinData[data.coin] ? coinData[data.coin].code : "Unknown";
                                $("#coin_amt").text(`${aritimatic}${data.coin_amt} ${walletCode}`);
                                var currencysymbol = $("#currencysymbol").val();
                                $("#fiat_amt").text(`=${currencysymbol}${data.coin_amt_in_fiat}`);
                                $("#transDate").text(formatDate(data.date));



                                if (["Pending"].includes(data.status)) {
                                    // If transfer type is "Receive" or "Deposit"

                                    $("#tranStatus").addClass('color-yellow-dark').removeClass('color-green-dark');
                                    //iconElement.addClass('bi-arrow-down-circle').removeClass('bi-arrow-up-right-circle');
                                } else if (["Cancelled"].includes(data.status)) {
                                    $("#tranStatus").removeClass('color-green-dark').removeClass('color-yellow-dark');
                                } else {
                                    // If transfer type is something else (e.g., Send or Transfer)
                                    $("#tranStatus").addClass('color-green-dark').removeClass('color-yellow-dark');
                                    //iconElement.addClass('bi-arrow-up-right-circle').removeClass('bi-arrow-down-circle');

                                }

                                $("#tranStatus").text(data.status);

                                //$("#wallet").text(data.wallet);


                                // Ensure updateWallet is called with valid data
                                updateWallet(data.wallet); // Example wallet address

                                // Function to format wallet address
                                function formatWallet(wallet) {
                                    return wallet.substring(0, 5) + "..." + wallet.slice(-5);
                                }

                                // Function to update wallet display
                                function updateWallet(wallet) {
                                    $("#wallet")
                                        .text(formatWallet(wallet)) // Show shortened version
                                        .attr("data-full", wallet) // Store full address for copying
                                        .css("cursor", "pointer"); // Indicate it's clickable
                                }


                            })
                            .catch(error => console.error('Error fetching data:', error));
                    });
                });
            });

            // Use event delegation to handle dynamically created elements
            $(document).on("click", "#wallet", function () {
                var fullWallet = $(this).attr("data-full");

                if (!fullWallet) {
                    console.error("Wallet address not found!");
                    return;
                }

                // Check if clipboard API is available
                if (navigator.clipboard && navigator.clipboard.writeText) {
                    // Copy the full wallet address to clipboard
                    navigator.clipboard.writeText(fullWallet)
                        .then(() => {
                            iziToast.success({
                                position: 'topCenter',
                                message: `Wallet address copied!`,
                            });
                        })
                        .catch(err => console.error("Error copying text:", err));
                } else {
                    console.error("Clipboard API not supported!");
                }
            });


            $(document).ready(function () {
                // Use event delegation for dynamically added elements
                $(document).on('click', '.edit_button', function (e) {
                    e.preventDefault(); // Prevent default link behavior

                    const id = $(this).data('id'); // Get the ID from the data attribute
                    console.log(id);

                    $(this).html('<span class="spinner-border spinner-border-sm" role="status" aria-hidden="true"></span> Processing, please wait...')
                        .css("pointer-events", "none"); // Prevent multiple clicks

                    $.ajax({
                        url: 'includes/server', // Make sure this points to your actual backend script
                        type: 'POST',
                        data: {
                            transferID_data: id
                        },
                        success: function (response) {
                            // Create a form and submit it programmatically


                        },
                        error: function (xhr, status, error) {
                            console.error("Error processing transaction:", error);
                        }
                    });


                });
            });
        </script>
        
        <script>
        function customAction() {
            const coinId = $("#coinId").val();
            $(".walletselect").val(coinId);
            // console.log("Selected Wallet:", coinId);
            // $(".walletselect").prop("disabled", true);
            // Make it "readonly" by disabling interaction
            $(".walletselect").on("mousedown", function (e) {
                e.preventDefault(); // Prevents dropdown from opening
            });
        };
    </script>
    
    <script>
    $(document).ready(function () {
        if ($('#coinId').val()) {
            // console.log($('#coinId').val());
            var currencysymbol = $('#currencysymbol').val();
            var currencyCode = $('#currencyCode').val();
            // var amt_of_coin = $("#amt_of_coin").text().match(/[\d.]+/)[0];
            var amt_of_coin = parseFloat($("#amt_of_coin").text().match(/[\d.]+/)[0]);


            //var amt_of_coin_in_fiat = $("#amt_of_coin_in_fiat").text().match(/[\d.]+/)[0];
            setTimeout(function () {
                var coinid = $('#coinId').val()
                const coins = [coinid];

                coins.forEach(function (coin) {
                    const el = $(`[data-live-price="${coin}"] span`)[0];

                    if (el) {
                        let oldPrice = $(el).text();
                        //console.log(amt_of_coin);
                        // console.log(`First Price: ${oldPrice}`);
                        $('#coin_price').text(`1 ${coinid.toUpperCase()} = ${currencysymbol}${oldPrice}`);
                        oldPricefloat = oldPrice.replace(/[^0-9.]/g, ''); ////rmove alpahbetsa 
                        var newPriceFloat = parseFloat(oldPricefloat); ///make float
                        const priceInFiatCurrency = amt_of_coin * newPriceFloat;

                        // console.log(priceInFiatCurrency);
                        const formattedPrice = parseFloat(priceInFiatCurrency).toLocaleString(undefined, {
                            minimumFractionDigits: 2,
                            maximumFractionDigits: 3
                        });
                        $('#amt_of_coin_in_fiat').text(`${currencysymbol}${formattedPrice}`);


                        const observer = new MutationObserver(function (mutationsList) {
                            for (let mutation of mutationsList) {
                                if (mutation.type === "childList") {
                                    let newPrice = $(el).text();
                                    if (newPrice !== oldPrice) {
                                        //console.log(`${coin.toUpperCase()} Price changed:`, newPrice);
                                        oldPrice = newPrice;
                                        $('#coin_price').text(`1 ${coinid.toUpperCase()} = ${currencysymbol}${oldPrice}`);
                                        oldPricefloat = oldPrice.replace(/[^0-9.]/g, ''); ////rmove alpahbetsa 
                                        var newPriceFloat = parseFloat(oldPricefloat); ///make float
                                        const priceInFiatCurrency = amt_of_coin * newPriceFloat;

                                        // console.log(priceInFiatCurrency);
                                        const formattedPrice = parseFloat(priceInFiatCurrency).toLocaleString(undefined, {
                                            minimumFractionDigits: 2,
                                            maximumFractionDigits: 3
                                        });
                                        $('#amt_of_coin_in_fiat').text(`${currencysymbol}${formattedPrice}`);

                                    }
                                }
                            }
                        });

                        observer.observe(el, {
                            childList: true
                        });
                    } else {
                        console.log(`❗ ${coin.toUpperCase()} price element not found`);
                    }
                });
            }, 2000);
        } else {
            console.log("no coin id");
        }
    });
</script>



<script src="scripts/bootstrap.min.js"></script>
<script src="scripts/custom.js"></script>
</body>