<?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();

$ee = filter_input(INPUT_POST, "email", FILTER_VALIDATE_EMAIL);

$user = User::getCurrentUser($link, $ee);

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_FLOAT);
    
    $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";
        die($error);
    } else if (is_null($amount) || is_bool($amount) || $amount <= 0) {
        $error = "Enter a valid amount";
        die($error);
    } else if (is_null($wallet) || is_bool($wallet) || empty(trim($wallet))) {
        $error = "Enter wallet address";
        die($error);
    } else if (is_null($name) || is_bool($name) || empty(trim($name)) || strcasecmp($name, NONE) == 0) {
        $error = "Choose wallet withdrawal wallet";
        die($error);
    } else if (($amount + $system->wfees) > $withdrable) {
        $error = "Amount is greater than balance";
        die($error);
    } else if (($amount) < 1) {
        $error = "Enter a valid amount";
        die($error);
    } 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) {
                
                die("OK");
            } else {
                $error = "Unexpected error occured";
                die($error);
            }
        }

        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());
?>