<?php
// session_start();
require("../includes/db_connect.php");
require_once("includes/session_token.php");


$url = "http://api.coinlayer.com/api/live?access_key=0f2d82a65368cd8ffd5faf501845884c&symbols=BTC,ETH,LTC,BCH,USDT";
// $jsonData = json_decode(file_get_contents($url), true);

$ch = curl_init();
curl_setopt ($ch, CURLOPT_URL, $url);
curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, 5);
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, true);
$contents = curl_exec($ch);
if (curl_errno($ch)) {
  echo curl_error($ch);
  echo "\n<br />";
  $contents = '';
} else {
  curl_close($ch);
}

if (!is_string($contents) || !strlen($contents)) {
echo "Failed to get contents.";
$contents = '';
}

$jsonData = json_decode($contents, true);

$btcRate = $jsonData['rates']['BTC'] ?? 1;
$bchRate = $jsonData['rates']['BCH'] ?? 1;
$ethRate = $jsonData['rates']['ETH'] ?? 1;
$ltcRate = $jsonData['rates']['LTC'] ?? 1;
$usdtRate = $jsonData['rates']['USDT'] ?? 1; 
$solRate = $jsonData['rates']['SOL'] ?? 1;


if (isset($_SESSION['trade_payment_method']) && isset($_SESSION['trade_amount'])) {

    $trade_payment_method = $_SESSION['trade_payment_method'];
    $trade_amount = $_SESSION['trade_amount'];
    
    $accountId = $_SESSION['usr_accountId'];

    if ($trade_payment_method != "BTC" && $trade_payment_method != "ETH" && $trade_payment_method != "SOL" && $trade_payment_method != "LTC" && $trade_payment_method != "ERC20" && $trade_payment_method != "TRC20") {
        die("Invalid request!");
    }

    $sql = "SELECT * FROM app_settings WHERE action IN(?,?,?,?,?,?)";
    $sth = $conn->prepare($sql, [PDO::ATTR_CURSOR => PDO::CURSOR_FWDONLY]);

    if ($sth->execute(['btc_address', 'eth_address', 'usdt_address', 'erc_address', 'trc_address', 'ltc_address'])) {

        while ($data = $sth->fetch(PDO::FETCH_ASSOC)) {
            $action =  $data['action'];
            $value =  $data['value'];
            if ($action == "btc_address") {
                $btc_address = $value;
            } else if ($action == "eth_address") {
                $eth_address = $value;
            } else if ($action == "usdt_address") {
                $usdt_address = $value;
            } else if ($action == "erc_address") {
                $erc_address = $value;
            } else if ($action == "trc_address") {
                $trc_address = $value;
            } else if ($action == "ltc_address") {
                $ltc_address = $value;
            }
        }

        $address = "default";
        $coin_amount = "default";

        if ($trade_payment_method == "BTC") {
            $btc_amount = round(($trade_amount / $btcRate), 8);
            $address = $btc_address;
            $coin_amount = $btc_amount;
        } else if ($trade_payment_method == "ETH") {
            $eth_amount = round(($trade_amount / $ethRate), 8);
            $address = $eth_address;
            $coin_amount = $eth_amount;
        } else if ($trade_payment_method == "TRC20") {
            $trc_amount = round($trade_amount, 8);
            $address = $trc_address;
            $coin_amount = $trc_amount;
        } else if ($trade_payment_method == "ERC20") {
            $erc_amount = round($trade_amount, 8);
            $address = $erc_address;
            $coin_amount = $erc_amount;
        } else if ($trade_payment_method == "SOL") {
            $usdt_amount = round(($trade_amount / $usdtRate), 8);
            $address = $usdt_address;
            $coin_amount = $usdt_amount;
        } else if ($trade_payment_method == "LTC") {
            $ltc_amount = round(($trade_amount / $ltcRate), 8);
            $address = $ltc_address;
            $coin_amount = $ltc_amount;
        }

        $invoice_sql
            = "INSERT INTO invoices (accountId, package, method, usd_amount, coin_amount, address, receipt, status) VALUES (?,?,?,?,?,?,?,?)";

        $create_invoice = $conn->prepare($invoice_sql)->execute([$accountId, "Deposit", $trade_payment_method, $trade_amount, $coin_amount, $address, "default", 0]);

        if ($create_invoice) {

            $sql = "SELECT * FROM invoices WHERE accountId = ? ORDER BY date DESC LIMIT 1";
            $sth = $conn->prepare($sql, [PDO::ATTR_CURSOR => PDO::CURSOR_FWDONLY]);
            $sth->execute([$accountId]);
            $invoices = $sth->fetchAll();

            foreach ($invoices as $key => $value) {

                unset($_SESSION['trade_payment_method']);
                unset($_SESSION['trade_amount']);

                $id = $value['id'];

                $url = "invoice-details?receipt-id=" . $id . "&accountId=" . $accountId;

                header('Location: ' . $url);
                exit();
            }
        } else {
            die("An unexpected error occurred while creating invoice. Please try again.");
        }
    } else {
        die("An unexpected error occurred while creating invoice. Please try again.");
    }
} else {
    redirect();
}

function redirect()
{
    header('Location: account');
    exit();
}


?>

<!DOCTYPE html>
<html lang="en">

<head>
    <title>Processing Deposit</title>

    <?php require("includes/header.php"); ?>



    <?php require("includes/footer.php"); ?>

    </body>

</html>