<?php
session_start();
include "../../connect/db.php";
csrf_verify();

// Idempotency check
if (isset($_SESSION['last_deposit_time']) && (time() - $_SESSION['last_deposit_time']) < 30) {
    echo "deposit_in_progress";
    exit();
}
$_SESSION['last_deposit_time'] = time();
 $chap = $_SESSION['chap'];

// Assuming you have processed the bank details and are ready to return the modal content
$coin = $_POST['coin'];
$amount = $_POST['amount'];

$sql11 = mysqli_query($mysqli,"SELECT * FROM users WHERE email = '$chap' ");
	
$row11 = mysqli_fetch_assoc($sql11);





$sqlnew = mysqli_query($mysqli,"SELECT * FROM wallet WHERE currency = '$coin' ");
	
$rowz = mysqli_fetch_assoc($sqlnew);













$d_o_t = date("Y-m-d");	

$account_num = $row11['account_num'];
$currency = $row11['usercurrency'];


$seed = str_split('ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'); // and any other characters
shuffle($seed); // probably optional since array_is randomized; this may be redundant
$rand = '';
foreach (array_rand($seed, 7) as $k) $rand .= $seed[$k];								            
$transId =  $rand; 













// Cryptocurrency logos from CoinGecko
$cryptoLogos = [
    'stellar' => 'https://cryptologos.cc/logos/stellar-xlm-logo.png',
    'tether' => 'https://assets.coingecko.com/coins/images/325/large/Tether-logo.png',
    'bitcoin' => 'https://assets.coingecko.com/coins/images/1/large/bitcoin.png',
    'bitcoin-cash' => 'https://assets.coingecko.com/coins/images/780/large/bitcoin-cash-circle.png?1696501932',
    'litecoin' => 'https://assets.coingecko.com/coins/images/2/large/litecoin.png',
    'ripple' => 'https://i.pinimg.com/originals/e6/9d/92/e69d92c8f36c37c84ecf8104e1fc386d.png',
    'tron' => 'https://cdn-icons-png.flaticon.com/512/12114/12114250.png'
];

// Get conversion rates
$url = 'https://api.coingecko.com/api/v3/simple/price?ids=bitcoin,stellar,tether,bitcoin-cash,litecoin,ripple,tron&vs_currencies=usd';
$response = file_get_contents($url);
$data = json_decode($response, true);

function convertAmount($amount, $coin, $data) {
    if (array_key_exists($coin, $data)) {
        $conversionRate = $data[$coin]['usd']; // Price of 1 unit of the coin in USD
        return $amount / $conversionRate; // Amount of the coin you can get for the given amount in USD
    } else {
        return 0; // Default value if the coin is not found
    }
}

// Example usage
$amountInUSD = $amount;
$selectedCoin = $coin; // The selected coin, e.g., 'bitcoin'
$convertedValue = convertAmount($amountInUSD, $selectedCoin, $data);










// Prepare and bind
$kay = mysqli_query($mysqli, "INSERT INTO transactions2 (trans_id, user, description, date, type, status, img, amount,scope,amount_cur) 
VALUES ('$transId', '$account_num', 'Crypto deposit of $amount', '$d_o_t', 'Crypto','Pending', 'null', '$amount','$coin','$convertedValue')");

















// Create the modal content
?>

<!-- Confirm Deposit Modal -->
<!-- Confirm Deposit Modal -->
<div class='modal fade' id='detailsModal' tabindex='-1' aria-labelledby='detailsModalLabel' aria-hidden='true'>
    <div class="modal-dialog modal-dialog-centered modal-lg">
        <div class="modal-content">
            <div class="modal-body modal-body-lg">
                <div class="nk-block-head nk-block-head-xs text-center">
                    <h5 class="nk-block-title">Confirm Deposit</h5>
                    <div class="nk-block-text">
                        <div class="caption-text">You are about to get <strong><?=number_format($convertedValue, 8)?></strong> <?=$coin?> for <strong>890</strong> USD*</div>
                        <span class="sub-text-sm">Exchange rate: 1 <?=$coin?> = <?=$convertedValue?> USD</span>
                    </div>
                </div>
                <div class="nk-block">
                    <div class="buysell-overview">
                        <ul class="buysell-overview-list">
                            <li class="buysell-overview-item">
                                <span class="pm-title">Deposit To</span>
                                <span class="pm-currency">
                                    <img src="<?=$cryptoLogos[$selectedCoin]?>" style="height:30px;width:30px"/> 
                                    <span><?=$coin?></span></span>
                            </li>
                            <li class="buysell-overview-item">
                                <span class="pm-title">Total</span>
                                <span class="pm-currency"><?=$amount?><?=$currency?></span>
                            </li>
                        </ul>
                        <div class="sub-text-sm">* Our transaction fee are included.</div>
                    </div>
                    <div class="text text-center">
                        <strong>Carefully follow the procedures below for successful investment.</strong>
                    </div>
                    <center>
                        <div style="padding-top: 10px; height: 200px; width: 230px;" class="">
                            <img src="https://qrcode.tec-it.com/API/QRCode?data=<?=$rowz['wallet_address']?>" rel="nofollow" alt="qr code" style="height:150px;width:150px">
                        </div>
                    </center>
                    <p class="text-center">
                        <strong>Amount: <?=$coin?><?=number_format($convertedValue, 8)?> <br></strong>
                        Scan the QR code above or copy and pay <span id="atPay"></span> to this <strong><code><?=$coin?></code></strong> address below: <br>
                    </p>
                    <div class="nk-refwg-url">
                        <div class="form-control-wrap">
                            <div class="form-clip clipboard-init" data-clipboard-target="#add" data-success="Copied" data-text="Copy Link">
                                <em class="clipboard-icon icon ni ni-copy"></em> 
                                <span class="clipboard-text">Copy</span>
                            </div>
                            <div class="form-icon">
                                <em class="icon ni ni-link-alt"></em>
                            </div>
                            <input type="text" class="form-control copy-text" id="add" value="<?=$rowz['wallet_address']?>">
                        </div>
                    </div>
                    <p></p>
                    <strong class="text-danger">Please Note*<br></strong>
                    <p class="text-left text-muted"><em class="icon ni ni-info-fill"></em> Please ensure you deposit the exact amount of cryptocurrency before confirming your transaction.</p>
                    <p class="text-left text-muted"><em class="icon ni ni-info-fill"></em> Incase the current session closed after you made payment, you can always start a new transaction with the exact amount you deposited.</p>
                    <p class="text-left text-muted"><em class="icon ni ni-info-fill"></em> Our customer care representatives are always available for support.</p>
                    <strong>Already made payment of USDT <?=number_format($convertedValue, 8)?> to the wallet address above<em class="icon ni ni-help-fill"></em></strong>
                    <form>
                        <div class="form-group">
                            <input type="hidden" name="coin" value="USDT">
                            <input type="hidden" name="amount" value="<?=number_format($convertedValue, 8)?>">
                            <strong for="address">Click the button below to confirm transaction.</strong>
                            <input type="text" class="form-control" name="address" id="address" placeholder="Sender Wallet address(Optional)">
                        </div>
                        <div id="depositResult"></div>
                        <div class="form-actions right">
                            <button type="submit" class="btn btn-raised btn-primary btn-block actionBtn">
                                Confirm Transaction
                            </button>
                            <div class="buysell-field form-action text-center">
                                <div class="pt-3">
                                    <a href="#" data-dismiss="modal" class="link link-danger">Cancel Order</a>
                                </div>
                            </div>
                        </div>
                    </form><!-- .nk-block -->
                </div><!-- .modal-body -->
            </div>
        </div>
    </div>

<!-- Success Modal -->
<!-- Second Modal (successModal) -->
<div class="modal fade" id="successModal" tabindex="-1" aria-labelledby="successModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content text-center">
            <div class="modal-body">
                <div class="nk-modal">
                    <em class="nk-modal-icon icon icon-circle icon-circle-xxl ni ni-check bg-success"></em>
                    <h4 class="nk-modal-title">Successful!</h4>
                    <div class="nk-modal-text">
                        <p class="caption-text">Crypto deposit of <strong><?=$coin?><?=number_format($convertedValue, 8)?></strong> on your <strong> Deutsche Bank Holdings Delaware  Checking Account</strong> has been received. You will receive an automatic notification once your transaction is confirmed on the blockchain Network. This usually takes up to 15 minutes.</p>
                    </div>
                    <div class="nk-modal-action-lg">
                        <ul class="btn-group gx-4">
                            <li><a href="crypto" class="btn btn-lg btn-mw btn-primary">Done</a></li>
                        </ul>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Include jQuery and Bootstrap JS -->
<!-- jQuery -->
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<!-- Bootstrap JS -->
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.bundle.min.js"></script>


<script>
$(document).ready(function () {
    // When the confirm transaction button is clicked
    $('.actionBtn').on('click', function (e) {
        e.preventDefault(); // Prevent the form from submitting

        // Hide the current modal
        $('#detailsModal').modal('hide');

        // Show the success modal
        $('#successModal').modal('show');
    });
});
</script>
