<?php
session_start();

use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\SMTP;
use PHPMailer\PHPMailer\Exception;
use Codenixsv\CoinGeckoApi\CoinGeckoClient;


require_once '../include/Constants.php';
require_once "../vendor/autoload.php";
require_once "../vendor1/autoload.php";
require_once "../include/DatabaseConn.php";
require_once "../models/PaymentWallet.php";
require_once "../models/User.php";
require_once '../models/USettings.php';
require_once '../models/Settings.php';
require_once '../models/Invoice.php';
require_once '../include/GoogleAuthenticator.php';
require_once '../models/News.php';
require_once '../include/Helper.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();
}


if (isset($_POST["coin"])) {
    $amount = filter_input(INPUT_POST, "amount", FILTER_VALIDATE_FLOAT);
    $coin = filter_input(INPUT_POST, "coin", FILTER_SANITIZE_STRING);
    if (is_null($amount) || is_bool($amount) || $amount < 1) {
        $error = "Please input an amount";
    } else if (is_null($coin) || is_bool($coin) || empty($coin)) {
        $error = "Please select crypto";
    }
    if (!isset($error)) {
        $client = new CoinGeckoClient();
        $coin = trim($coin);
        $list = file_get_contents("../coins.json");
        $arr = json_decode($list);
        foreach ($arr as $value) {
            if (strcasecmp($value->name, $coin) == 0) {
                $symbol = $value->symbol;
                $name = $value->name;
                $id = $value->id;
                break;
            }
        }
        
        $token = PaymentWallet::getTokenPrice($id,$client);
        
        $token = $amount / $token;
       
        $invoice = new Invoice();
        $invoice->setAmount($amount);
        $invoice->setDate(time());
        $invoice->setUser($user->getEmail());
        $invoice->setPackage($name);
        $invoice->setIType($id);
        $invoice->setRoi($token);
        $invoice->setDays(3);
        $invoice->setPaymentMode($name);
        $response = Invoice::createInvoice($invoice, $link);
        if (!is_null($response)) {
            $ww = $user->getEmail();
            User::notify1(EMAIL_SUPPORT, "<p>($ww) has created an invoice with amount $amount USD for $coin deposit</p>", "Invoice Notification");
            $_SESSION['coin'] = $id;
            $_SESSION['amount'] = $amount;
            header("location: payment");
            die();
        } else {
            $error = "An unexpected error occured.";
        }
    }
}

$news = News::getNewsPage($link);
$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 receive</span></span>
                                                </div>
                                            </div>

                                            <div class="sc-bHwgHz EpALc">
                                                <form action="receive" 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()); ?></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>
                                                    <button type="submit" id="downloadapp" style="background-color: #3375BB; border-color: #3375BB;" class="sc-bdVaJa OngNg sc-kwgWOH fLeWXT">
                                                        Generate Address
                                                    </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 src="https://cdn.jsdelivr.net/npm/select2@4.0.13/dist/js/select2.min.js"></script>
        <script>
            var clipboard = new ClipboardJS('.copy');

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

        </script>

    </body>
</html>