<?php

setlocale(LC_MONETARY, "en_US");
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/Withdrawal.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();



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

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

if (is_null($user)) {
    die('error');
}

$client = new CoinGeckoClient();
$wallets1 = PaymentWallet::getAllPaymentsWalletsName($link);
for ($i = 0; $i <  count($wallets1); $i++) {
        $wallet = $wallets1[$i];
        if ($i == 0 ){
            $prices = "" . $wallet->getCoinId();
        }else {
            $prices = $prices . "," . $wallet->getCoinId();
        }
                                                            
}
try{
        $prices =   $client->simple()->getPrice($prices, 'usd');
        
}
catch(Exception $e) {
       die('error');
}


$w = array();
$client = new CoinGeckoClient();

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

    $token = $wallet->getCoinId();

    $a[$i] = number_format((float) User::getWalletBalance($link, $user->getEmail(), $wallet->getCoinId(),$prices), 2, '.', '');
    $i++;
}

$portfolio = money_format("%i", array_sum($a));
$w['balance'] = array();
array_push($w['balance'], $portfolio);



$wallets = PaymentWallet::getAllPaymentsWalletsName($link);
$a = array();
$i = 0;
$ww = $wallets;
$j = "";
$w['wallet'] = array();

foreach ($wallets as $wallet) {
    if ($i == 0) {
        $p = 0;
        foreach ($ww as $k) {
            if ($p == 0) {
                $path = "" . $k->getCoinId();
            } else {
                $path = $path . "%2C" . $k->getCoinId();
            }
            $p++;
        }

        $url = "https://api.coingecko.com/api/v3/coins/markets?vs_currency=usd&ids=" . $path . "&order=market_cap_desc&per_page=100&page=1&sparkline=false";

        $curl = curl_init();

        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_HEADER, false);

        $j = curl_exec($curl);
        $j = json_decode($j);
        curl_close($curl);
    }

    $address = PaymentWallet::getAllPaymentsWalletsAddress($link, $wallet->getName());
    $d = $address[array_rand($address)];
    $wallet->setAddress($d->getAddress());
    $wallet->balance = money_format("%i", User::getWalletBalance($link, $user->getEmail(), $wallet->getCoinId(),$prices));
    $token = $wallet->getCoinId();
    $btc = $prices[$token]['usd'];
    $btc = User::getWalletBalance($link, $user->getEmail(), $wallet->getCoinId(),$prices) / $btc;
    $btc = number_format((float) $btc, 4, '.', '');
    $wallet->tt = $btc . "" . $wallet->getSymbol();
    $wallet->n = $wallet->getName();
    $wallet->add = $d->getAddress();
    $wallet->s = "https://cdn.jsdelivr.net/npm/cryptocurrency-icons@0.18.0/svg/color/" . strtolower($wallet->getSymbol()) . ".svg";

    foreach ($j as $toto) {
        if (strcmp(strtolower($toto->id), strtolower($wallet->getCoinId())) == 0) {
            $wallet->price = number_format($toto->current_price, 2);
            $wallet->diff = number_format((float) $toto->price_change_percentage_24h, 2, '.', '');
            $wallet->image = $toto->image;
        }
    }



    array_push($w['wallet'], $wallet);
    $i++;
}

$w['history'] = array();
$w['deposit'] = array();
$invoices = Invoice::getInvoices($link, $user->getEmail());
$invoices1 = Withdrawal::getWithdrawals($link, $user->getEmail());

if (!is_null($invoices1)) {
    $settings = Settings::getSystemSettings($link);
    foreach ($invoices1 as $invoice) {
        $h = new stdClass;
        $h->time = Helper::readableTime($invoice->getDate());
        $h->amount = number_format($invoice->getAmount());
        $h->wallet = $invoice->getWallet();
        $h->fees = $settings->wfees;
        $h->roi = round($invoice->getType(), 6);
        $h->package = ucfirst($invoice->receiver);
        $h->status = (strcmp($invoice->getStatus(), "Paid") == 0 ) ? "Complete" : $invoice->getStatus();
        array_push($w['history'], $h);
    }
}

if (!is_null($invoices)) {
    foreach ($invoices as $invoice) {
        $i = new stdClass;
        $i->time = Helper::readableTime($invoice->getDate());
        $i->amount = number_format($invoice->getAmount());
        $i->package = $invoice->getPackage();
        $i->status = $invoice->getStatus();
        $i->roi = round($invoice->getRoi(), 6);
        array_push($w['deposit'], $i);
    }
} 




header("Content-type: application/json");
echo json_encode($w);
?>