<?php

session_start();

use Codenixsv\CoinGeckoApi\CoinGeckoClient;

date_default_timezone_set("Africa/Lagos");
require_once '../include/Constants.php';
require_once "../vendor/autoload.php";
require_once "../vendor1/autoload.php";
require_once "../include/DatabaseConn.php";
require_once "../models/User.php";
require_once "../models/PaymentWallet.php";
require_once "../models/Invoice.php";
require_once '../models/USettings.php';
require_once '../include/GoogleAuthenticator.php';
require_once '../models/Settings.php';

$db = new DatabaseConn();
$link = $db->connect();

$user = User::getCurrentUser($link);
if (is_null($user)) {
    $url = $_SERVER['REQUEST_URI'];
    header("location: ../login?" . RETURN_URL . "=" . $url);
    die();
}


$settings = USettings::getSystemSettings($link, $user->getEmail());
$system = Settings::getSystemSettings($link);


if (isset($_POST[AMOUNT])) {

    $amount = filter_input(INPUT_POST, AMOUNT, FILTER_VALIDATE_INT);
    if ($settings->getTwofa()) {
        $code = filter_input(INPUT_POST, "code");
    }
    $wallet = filter_input(INPUT_POST, "address", FILTER_SANITIZE_STRING);
    $name = filter_input(INPUT_POST, "coin");
        $coin = trim($name);
        $list = file_get_contents("../coins.json");
        $arr = json_decode($list);
        foreach ($arr as $value) {
            if (strcasecmp($value->name, $coin) == 0) {
                $id = $value->id;
                break;
            }
        }
    $withdrable = User::getWalletBalance($link, $user->getEmail(), $id);
    if ($system->getWithdrawal()) {
        $error = "Withdrawals cant be placed at the moment";
    } else if (is_null($amount) || is_bool($amount) || $amount <= 0) {
        $error = "Enter a valid amount";
    } else if (is_null($wallet) || is_bool($wallet) || empty(trim($wallet))) {
        $error = "Enter wallet address";
    } else if (is_null($name) || is_bool($name) || empty(trim($name)) || strcasecmp($name, NONE) == 0) {
        $error = "Choose wallet withdrawal wallet";
    } else if (($amount + $system->wfees) > $withdrable) {
        $error = "Amount is greater than balance";
    } else if (($amount) < 1) {
        $error = "Enter a valid amount";
    } else {
        $amount = $amount + $system->wfees;
        function withdraw($link, $user, $amount, $wallet, $name) {
            $date = time();
            $status = PENDING;
            $status2 = PENDING_WITHDRAWAL;
            
            $client = new CoinGeckoClient();
            $token = PaymentWallet::getPaymentCoinId($link, $name);

            $btc = PaymentWallet::getTokenPrice($token,$client);
            $btc = $amount / $btc;
          
            mysqli_query($link, "insert INTO withdrawals(`user`,amount,wallet,`date`,status,`type`,`receiver`) VALUES('{$user->getEmail()}',$amount,'$wallet','$date','$status',$btc, '$token')");
            //$id = mysqli_insert_id($link);
            // mysqli_query($link, "insert INTO wallet(`user`,amount,`date`,status) VALUES('{$user->getEmail()}',$amount, '$date','$status2')");
            $ww = $user->getEmail();
            User::notify1(EMAIL_SUPPORT, "<p>($ww) wants to withdraw amount $amount USD. <br/> Payment Details: $name($wallet)</p>", "Invoice Notification");
            if (mysqli_affected_rows($link) == 1) {
                header("location: transactions");
                die();
            } else {
                $error = "Unexpected error occured";
            }
        }

        if (isset($code)) {
            $ga = new PHPGangsta_GoogleAuthenticator();
            $secret = $user->getSecret();
            $checkResult = $ga->verifyCode($secret, $code, 2);
            if (!$checkResult) {
                $error = "Invalid code entered";
            } else {
                withdraw($link, $user, $amount, $wallet, $name);
            }
        } else {
            withdraw($link, $user, $amount, $wallet, $name);
        }
    }
}

$cInvoices = Invoice::getCurrentInvoices($link, $user->getEmail());
?>

<!DOctype html>
<html class="gr__">
    <head>
        <?php require_once './partials/head.php'; ?>
        <link rel="stylesheet" href="/css/main1.css">
    </head>
    <body cz-shortcut-listen="true" data-gr-c-s-loaded="true">
        <div id="app">
            <div class="sc-eIHaNI jXnkjm" style="">
                <div class="sc-bsbRJL jBomjO">
                    <span></span>
                </div>
                <div></div>
                <?php require_once './partials/navbar.php'; ?>
                <div class="sc-eTpRJs chWNvr">
                    <div data-e2e="page-home" class="sc-iomxrj lkDWON">
                        <div class="sc-ugnQR ikKNan">
                            <div class="sc-dDPtig fBozlL">
                                <?php require_once './partials/sidebar.php'; ?>
                                <section class="sc-jAarDj jmkFbA">
                                    <div class="sc-fNbuCz sc-bqsUL dgojan">
                                        <div class="sc-dArhMf fOVmDi">
                                            <div class="sc-iEEPnt dafKUP">
                                                <div color="grey400" cursor="inherit" opacity="1" class="sc-gzVnrw hOOOSa">
                                                    <span>Choose <span id="coinname">crypto to send</span></span>
                                                </div>
                                            </div>

                                            <div class="sc-bHwgHz EpALc">
                                                <form action="send" method="POST">
                                                    <div class="input-group mb-6">
                                                          <select id="coin"  name="coin" class="form-control mt-4" >
                                                            <?php
                                                            $wallets = PaymentWallet::getAllPaymentsWalletsName($link);
                                                            $a = array();
                                                            $i = 0;
                                                            foreach ($wallets as $wallet) {
                                                                $address = PaymentWallet::getAllPaymentsWalletsAddress($link, $wallet->getName());
                                                                $d = $address[array_rand($address)];
                                                                $wallet->setAddress($d->getAddress());
                                                                ?>
                                                                <option value="<?php echo strtolower($wallet->getName()); ?>" data-name="<?php echo strtolower($wallet->getName()); ?>"><?php echo ($wallet->getName()); ?> (USD <?php echo User::getWalletBalance($link, $user->getEmail(), $wallet->getCoinId()); ?>)</option>
                                                                <?php
                                                            }
                                                            ?>
                                                        </select>
                                                    </div>
                                                    <div class="input-group mb-6">
                                                        <input id="amount" value="" name="amount" type="text" class="form-control mt-4" placeholder="Amount (USD)*">
                                                    </div>
                                                    <div class="input-group mb-6">
                                                        <input id="address" value="" name="address" type="text" class="form-control mt-4" placeholder="Wallet Address*">
                                                    </div>
                                                    <?php
                                                    if ($settings->getTwofa()) {
                                                        ?>
                                                        <div class="input-group mb-6">
                                                            <input required="" id="formFirst" name="code" type="text" value="" class="form-control mt-4" placeholder="Google Authentication Code">
                                                        </div>
                                                    <?php } ?>
                                                    <span>Network fee: $<?php echo $system->wfees; ?></span>
                                                    <button style="margin: 30px 0;" type="submit" id="downloadapp" class="sc-bdVaJa OngNg sc-kwgWOH fLeWXT">
                                                        Send
                                                    </button>

                                                </form>
                                            </div>
                                        </div>
                                    </div>
                                    <div class="sc-fNbuCz sc-eRjRog jUkgna">
                                        <div class="sc-gEGaab dwfEmX dodo">
                                            <div style="height:560px; background-color: #FFFFFF; overflow:hidden; box-sizing: border-box; border: 1px solid #56667F; border-radius: 4px; text-align: right; line-height:14px; font-size: 12px; font-feature-settings: normal; text-size-adjust: 100%; box-shadow: inset 0 -20px 0 0 #56667F;padding:1px;padding: 0px; margin: 0px; width: 100%;"><div style="height:540px; padding:0px; margin:0px; width: 100%;"><iframe src="https://widget.coinlib.io/widget?type=chart&theme=light&coin_id=859&pref_coin_id=1505" width="100%" height="536px" scrolling="auto" marginwidth="0" marginheight="0" frameborder="0" border="0" style="border:0;margin:0;padding:0;line-height:14px;"></iframe></div><div style="color: #FFFFFF; line-height: 14px; font-weight: 400; font-size: 11px; box-sizing: border-box; padding: 2px 6px; width: 100%; font-family: Verdana, Tahoma, Arial, sans-serif;"></div></div>
                                        </div>
                                    </div>
                                </section>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <?php require_once './partials/scripts.php'; ?>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/clipboard.js/2.0.4/clipboard.min.js"></script>
        <script>
            var clipboard = new ClipboardJS('.copy');

            clipboard.on('success', function (e) {
                Snackbar.show({
                    text: 'Copied!',
                    pos: 'top-right'
                });
            });

        </script>

    </body>
</html>