<?php

class wallet extends basicFunction
{
    use table_names;

    public function createDeposit($investment, $currency, $package, $amt)
    {
        $vals = [$investment, $currency, $package, $amt];
        $if_empty = $this->if_empty($vals);
        if (!$if_empty) {
            return $this->errorMsgs(1);
        }
        $user = $this->selectWhereDlt($this->user_tb, 'unique_id', $_SESSION[$this->user_session])[0];

        $investment_exist = $this->selectWhereDlt($this->investment_plan_tb, 'unique_id', $investment);
        if (count($investment_exist) < 1) {
            return $this->errorMsgs(15);
        }
        $currency_exist = $this->selectWhereDlt($this->currencies_tb, 'unique_id', $currency);
        if (count($currency_exist) < 1) {
            return $this->errorMsgs(15);
        }

        $user_address = $this->selectWhere2CondDlt($this->user_wallet_tb, 'user_id', $user['unique_id'], 'coin_id', $currency);
        if (empty($user_address[0]['address'])) {
            return $this->errorMsgs(22);
        }

        $package_exist = $this->selectWhereDlt($this->package_tb, 'unique_id', $package);
        if (count($package_exist) < 1) {
            return $this->errorMsgs(15);
        }
        if ($amt < $package_exist[0]['min_amt'] || $amt > $package_exist[0]['max_amt']) {
            return ['error' => 1, 'msg' => 'Error! Amount is below or above package limit!.'];
        }
        $balance = $this->get_balance($user['unique_id']);
        if ($balance < 1 || $amt > $balance) {
            return $this->errorMsgs(21);
        }

        $response = $this->api_call('https://min-api.cryptocompare.com/data/price?fsym=' . $currency_exist[0]['symbol'] . '&tsyms=USD&api_key=' . $this->crypto_compare_api_key);

        if (empty($response)) {
            return $this->errorMsgs(15);
        }
        $amt_in_coin = $this->convert_to_crypto($response, $amt);
        $unique_id = $this->rand_id();
        $date_created = $this->todayDate();
        $query = "INSERT INTO $this->transaction_tb VALUES (null,
    '" . mysqli_real_escape_string($this->connectDb(), $unique_id) . "',
    '" . mysqli_real_escape_string($this->connectDb(), $user['unique_id']) . "',
    '" . mysqli_real_escape_string($this->connectDb(), $investment) . "',
    '" . mysqli_real_escape_string($this->connectDb(), $currency) . "',
    '" . mysqli_real_escape_string($this->connectDb(), $package) . "',
    '" . mysqli_real_escape_string($this->connectDb(), $amt) . "',
    '" . mysqli_real_escape_string($this->connectDb(), $amt_in_coin) . "',
    '" . mysqli_real_escape_string($this->connectDb(), 'confirmed') . "',
    '" . mysqli_real_escape_string($this->connectDb(), 'null') . "',
    '" . mysqli_real_escape_string($this->connectDb(), 0) . "',
    '" . mysqli_real_escape_string($this->connectDb(), 0) . "',
    '" . mysqli_real_escape_string($this->connectDb(), 0) . "',
    '" . mysqli_real_escape_string($this->connectDb(), $date_created) . "',
    '" . mysqli_real_escape_string($this->connectDb(), $date_created) . "') ";
        mysqli_close($this->connectDb());
        if (!$this->sqlQuery($query)) {
            return $this->errorMsgs(14);
        }

        $transfer_funds_From_wallet = $this->remove_investment_From_Wallet($user,$currency,$amt);
        if ($transfer_funds_From_wallet) {
            return $this->successMsg('Investment');
        } else {
            return $this->errorMsgs(14);
        }

    }

    public function remove_investment_From_Wallet($user,$coin_id,$amt_in_usd)
    {
        
        $unique_id = $this->rand_id();
        $date_created = $this->todayDate();

        $query = "INSERT INTO $this->wallet_tb VALUES (null,
    '" . mysqli_real_escape_string($this->connectDb(), $unique_id) . "',
    '" . mysqli_real_escape_string($this->connectDb(), $user['unique_id']) . "',
    '" . mysqli_real_escape_string($this->connectDb(), $coin_id) . "',
    '" . mysqli_real_escape_string($this->connectDb(), 'null') . "',
    '" . mysqli_real_escape_string($this->connectDb(), $amt_in_usd) . "',
    '" . mysqli_real_escape_string($this->connectDb(), 'my_purchase') . "',
    '" . mysqli_real_escape_string($this->connectDb(), 'withdrawal') . "',
    '" . mysqli_real_escape_string($this->connectDb(), 'confirmed') . "',
    '" . mysqli_real_escape_string($this->connectDb(), 'null') . "',
    '" . mysqli_real_escape_string($this->connectDb(), 'null') . "',
    '" . mysqli_real_escape_string($this->connectDb(), 0) . "',
    '" . mysqli_real_escape_string($this->connectDb(), $date_created) . "',
    '" . mysqli_real_escape_string($this->connectDb(), $date_created) . "') ";
        mysqli_close($this->connectDb());
        return $this->sqlQuery($query);
    }

    public function user_top_up($coin_id, $amt_in_usd)
    {
        // print_r(json_encode('$_FILES'));
        // return '_FILES';
        $vals = [$coin_id, $amt_in_usd];
        $if_empty = $this->if_empty($vals);
        if (!$if_empty) {
            return $this->errorMsgs(1);
        }
        $user = $this->selectWhereDlt($this->user_tb, 'unique_id', $_SESSION[$this->user_session])[0];

        $coin_exist = $this->selectWhereDlt($this->currencies_tb, 'unique_id', $coin_id);
        if (count($coin_exist) < 1) {
            return $this->errorMsgs(15);
        }
        // $user_address = $this->selectWhere2CondDlt($this->user_wallet_tb, 'user_id', $user['unique_id'], 'coin_id', $coin_id);
        // if (empty($user_address[0]['address'])) {
        //     return $this->errorMsgs(22);
        // }
        $response = $this->api_call('https://min-api.cryptocompare.com/data/price?fsym=' . $coin_exist[0]['symbol'] . '&tsyms=USD&api_key=' . $this->crypto_compare_api_key);

        if (empty($response)) {
            return $this->errorMsgs(15);
        }
        $amt_in_coin = $this->convert_to_crypto($response, $amt_in_usd);
        $unique_id = $this->rand_id();
        $date_created = $this->todayDate();

        $query = "INSERT INTO $this->wallet_tb VALUES (null,
    '" . mysqli_real_escape_string($this->connectDb(), $unique_id) . "',
    '" . mysqli_real_escape_string($this->connectDb(), $user['unique_id']) . "',
    '" . mysqli_real_escape_string($this->connectDb(), $coin_id) . "',
    '" . mysqli_real_escape_string($this->connectDb(), $amt_in_coin) . "',
    '" . mysqli_real_escape_string($this->connectDb(), $amt_in_usd) . "',
    '" . mysqli_real_escape_string($this->connectDb(), 'my_deposit') . "',
    '" . mysqli_real_escape_string($this->connectDb(), 'top_up') . "',
    '" . mysqli_real_escape_string($this->connectDb(), 'pending') . "',
    '" . mysqli_real_escape_string($this->connectDb(), 0) . "',
    '" . mysqli_real_escape_string($this->connectDb(), 'null') . "',
    '" . mysqli_real_escape_string($this->connectDb(), 0) . "',
    '" . mysqli_real_escape_string($this->connectDb(), $date_created) . "',
    '" . mysqli_real_escape_string($this->connectDb(), $date_created) . "') ";
        mysqli_close($this->connectDb());
        if ($this->sqlQuery($query)) {
            return [
                'error' => 0,
                'txn_id' => $unique_id,
                'site_root' => $this->the_site_root,
            ];
        } else {
            return $this->errorMsgs(14);
        }
    }

    public function admin_top_up($amt_in_usd, $user_id)
    {
        $vals = [$amt_in_usd];
        $if_empty = $this->if_empty($vals);
        if (!$if_empty) {
            return $this->errorMsgs(1);
        }
        $user = $this->selectWhereDlt($this->user_tb, 'unique_id', $user_id)[0];
        if (count($user_id) < 1) {
            return $this->errorMsgs(15);
        }

        $unique_id = $this->rand_id();
        $date_created = $this->todayDate();

        $query = "INSERT INTO $this->wallet_tb VALUES (null,
    '" . mysqli_real_escape_string($this->connectDb(), $unique_id) . "',
    '" . mysqli_real_escape_string($this->connectDb(), $user['unique_id']) . "',
    '" . mysqli_real_escape_string($this->connectDb(), 'null') . "',
    '" . mysqli_real_escape_string($this->connectDb(), 'null') . "',
    '" . mysqli_real_escape_string($this->connectDb(), $amt_in_usd) . "',
    '" . mysqli_real_escape_string($this->connectDb(), 'bonus') . "',
    '" . mysqli_real_escape_string($this->connectDb(), 'top_up') . "',
    '" . mysqli_real_escape_string($this->connectDb(), 'confirmed') . "',
    '" . mysqli_real_escape_string($this->connectDb(), 0) . "',
    '" . mysqli_real_escape_string($this->connectDb(), $date_created) . "',
    '" . mysqli_real_escape_string($this->connectDb(), 0) . "',
    '" . mysqli_real_escape_string($this->connectDb(), $date_created) . "',
    '" . mysqli_real_escape_string($this->connectDb(), $date_created) . "') ";
        mysqli_close($this->connectDb());
        if ($this->sqlQuery($query)) {
            return $this->successMsg2('Account Top Up');
        } else {
            return $this->errorMsgs(14);
        }
    }


    public function user_withdraw_from_balance($coin_id, $amt_in_usd)
    {
        $vals = [$coin_id, $amt_in_usd];
        $if_empty = $this->if_empty($vals);
        if (!$if_empty) {
            return $this->errorMsgs(1);
        }
        $user = $this->selectWhereDlt($this->user_tb, 'unique_id', $_SESSION[$this->user_session])[0];

        $coin_exist = $this->selectWhereDlt($this->currencies_tb, 'unique_id', $coin_id);
        if (count($coin_exist) < 1) {
            return $this->errorMsgs(15);
        }
        $user_address = $this->selectWhere2CondDlt($this->user_wallet_tb, 'user_id', $user['unique_id'], 'coin_id', $coin_id);
        if (empty($user_address[0]['address'])) {
            return $this->errorMsgs(22);
        }

        $balance = $this->get_balance($user['unique_id']);
        if ($balance < 1 || $amt_in_usd > $balance) {
            return $this->errorMsgs(21);
        }
        $user_address = $this->selectWhere2CondDlt($this->user_wallet_tb, 'user_id', $user['unique_id'], 'coin_id', $coin_id);
        if (empty($user_address[0]['address'])) {
            return $this->errorMsgs(22);
        }

        $unique_id = $this->rand_id();
        $date_created = $this->todayDate();

        $query = "INSERT INTO $this->wallet_tb VALUES (null,
    '" . mysqli_real_escape_string($this->connectDb(), $unique_id) . "',
    '" . mysqli_real_escape_string($this->connectDb(), $user['unique_id']) . "',
    '" . mysqli_real_escape_string($this->connectDb(), $coin_id) . "',
    '" . mysqli_real_escape_string($this->connectDb(), 'null') . "',
    '" . mysqli_real_escape_string($this->connectDb(), $amt_in_usd) . "',
    '" . mysqli_real_escape_string($this->connectDb(), 'my_withdraw') . "',
    '" . mysqli_real_escape_string($this->connectDb(), 'withdrawal') . "',
    '" . mysqli_real_escape_string($this->connectDb(), 'pending') . "',
    '" . mysqli_real_escape_string($this->connectDb(), 'null') . "',
    '" . mysqli_real_escape_string($this->connectDb(), 'null') . "',
    '" . mysqli_real_escape_string($this->connectDb(), 0) . "',
    '" . mysqli_real_escape_string($this->connectDb(), $date_created) . "',
    '" . mysqli_real_escape_string($this->connectDb(), $date_created) . "') ";
        mysqli_close($this->connectDb());
        if ($this->sqlQuery($query)) {
            return $this->successMsg2('Funds withdrawal');
        } else {
            return $this->errorMsgs(14);
        }
    }
    public function admin_withdraw_from_balance($amt_in_usd, $user_id)
    {
        $vals = [$amt_in_usd];
        $if_empty = $this->if_empty($vals);
        if (!$if_empty) {
            return $this->errorMsgs(1);
        }
        $user = $this->selectWhereDlt($this->user_tb, 'unique_id', $user_id)[0];
        if (count($user_id) < 1) {
            return $this->errorMsgs(15);
        }

        $balance = $this->get_balance($user['unique_id']);
        // return $balance;
        if ($balance < 1 || $amt_in_usd > $balance) {
            return $this->errorMsgs(21);
        }

        $unique_id = $this->rand_id();
        $date_created = $this->todayDate();

        $query = "INSERT INTO $this->wallet_tb VALUES (null,
    '" . mysqli_real_escape_string($this->connectDb(), $unique_id) . "',
    '" . mysqli_real_escape_string($this->connectDb(), $user['unique_id']) . "',
    '" . mysqli_real_escape_string($this->connectDb(), 'null') . "',
    '" . mysqli_real_escape_string($this->connectDb(), 'null') . "',
    '" . mysqli_real_escape_string($this->connectDb(), $amt_in_usd) . "',
    '" . mysqli_real_escape_string($this->connectDb(), 'admin_withdraw') . "',
    '" . mysqli_real_escape_string($this->connectDb(), 'withdrawal') . "',
    '" . mysqli_real_escape_string($this->connectDb(), 'confirmed') . "',
    '" . mysqli_real_escape_string($this->connectDb(), 'null') . "',
    '" . mysqli_real_escape_string($this->connectDb(), $date_created) . "',
    '" . mysqli_real_escape_string($this->connectDb(), 0) . "',
    '" . mysqli_real_escape_string($this->connectDb(), $date_created) . "',
    '" . mysqli_real_escape_string($this->connectDb(), $date_created) . "') ";
        mysqli_close($this->connectDb());
        if ($this->sqlQuery($query)) {
            return $this->successMsg2('Funds withdrawal');
        } else {
            return $this->errorMsgs(14);
        }
    }

    public function withdraw_from_interest($txn_id, $amount)
    {
        $vals = [$txn_id, $amount];
        $if_empty = $this->if_empty($vals);
        if (!$if_empty) {
            return $this->errorMsgs(1);
        }

        $user = $this->selectWhereDlt($this->user_tb, 'unique_id', $_SESSION[$this->user_session])[0];
        $balance = $this->get_balance_for_txn($txn_id);
        if ($balance < 1 || $amount > $balance) {
            return $this->errorMsgs(21);
        }
        $txn_exist = $this->getDataDlt($txn_id, $this->transaction_tb);
        $user_address = $this->selectWhere2CondDlt($this->user_wallet_tb, 'user_id', $user['unique_id'], 'coin_id', $txn_exist['coin_type_id']);
        if (empty($user_address[0]['address'])) {
            return $this->errorMsgs(22);
        }

        $unique_id = $this->rand_id();
        $date_created = $this->todayDate();
        $query = "INSERT INTO $this->wallet_tb VALUES (null,
    '" . mysqli_real_escape_string($this->connectDb(), $unique_id) . "',
    '" . mysqli_real_escape_string($this->connectDb(), $user['unique_id']) . "',
    '" . mysqli_real_escape_string($this->connectDb(), $txn_exist['coin_type_id']) . "',
    '" . mysqli_real_escape_string($this->connectDb(), 'null') . "',
    '" . mysqli_real_escape_string($this->connectDb(), $amount) . "',
    '" . mysqli_real_escape_string($this->connectDb(), 'investment_interest') . "',
    '" . mysqli_real_escape_string($this->connectDb(), 'top_up') . "',
    '" . mysqli_real_escape_string($this->connectDb(), 'confirmed') . "',
    '" . mysqli_real_escape_string($this->connectDb(), 'null') . "',
    '" . mysqli_real_escape_string($this->connectDb(), $date_created) . "',
    '" . mysqli_real_escape_string($this->connectDb(), 0) . "',
    '" . mysqli_real_escape_string($this->connectDb(), $date_created) . "',
    '" . mysqli_real_escape_string($this->connectDb(), $date_created) . "') ";
        mysqli_close($this->connectDb());
        if ($this->sqlQuery($query)) {

            $updated_interest = $balance - $amount;
            $fields = ['interest_in_usd'];
            $values = [$updated_interest];
            $update_interest = $this->update_tbs($this->transaction_tb, $fields, $values, $txn_id);
            if ($update_interest['error'] == 1) {
                return $update_interest;
            }

            return $this->successMsg('Withdrawal');
        } else {
            return $this->errorMsgs(14);
        }
    }

    public function get_balance_for_txn($txn_id)
    {
        $txn_exist = $this->selectWhereDlt($this->transaction_tb, 'unique_id', $txn_id);
        if (count($txn_exist) > 0) {
            $balance = $txn_exist[0]['interest_in_usd'];
            return $balance;
        }
        return 0;
    }

    public function confirm($id)
    {
        $vals = [$id];
        $if_empty = $this->if_empty($vals);
        if (!$if_empty) {
            return $this->errorMsgs(15);
        }
        $deposit_exist = $this->selectWhereDlt($this->wallet_tb, 'unique_id', $id);
        if (count($deposit_exist) < 1) {
            return $this->errorMsgs(15);
        }
        $date_created = $this->todayDate();
        $fields = ['status', 'date_confirmed'];
        $values = ['confirmed', $date_created];
        $update_txn = $this->update_tbs($this->wallet_tb, $fields, $values, $id);
        if ($update_txn['error'] == 1) {
            return $update_txn;
        }

        $is_referred = $this->selectWhereDlt($this->user_details, 'user_unique_id', $deposit_exist[0]['user_id'])[0];
        if (!empty($is_referred['referrer'])) {
            $percentage = $this->calc_referr_percentage($deposit_exist[0]['amt_in_usd']);
            $unique_id = $this->rand_id();


            $query = "INSERT INTO $this->wallet_tb VALUES (null,
        '" . mysqli_real_escape_string($this->connectDb(), $unique_id) . "',
        '" . mysqli_real_escape_string($this->connectDb(), $is_referred['referrer']) . "',
        '" . mysqli_real_escape_string($this->connectDb(), $deposit_exist[0]['coin_type_id']) . "',
        '" . mysqli_real_escape_string($this->connectDb(), 'null') . "',
        '" . mysqli_real_escape_string($this->connectDb(), $percentage) . "',
        '" . mysqli_real_escape_string($this->connectDb(), 'affiliate_bonus') . "',
        '" . mysqli_real_escape_string($this->connectDb(), 'top_up') . "',
        '" . mysqli_real_escape_string($this->connectDb(), 'confirmed') . "',
        '" . mysqli_real_escape_string($this->connectDb(), 'null') . "',
        '" . mysqli_real_escape_string($this->connectDb(), $date_created) . "',
        '" . mysqli_real_escape_string($this->connectDb(), 0) . "',
        '" . mysqli_real_escape_string($this->connectDb(), $date_created) . "',
        '" . mysqli_real_escape_string($this->connectDb(), $date_created) . "') ";
            mysqli_close($this->connectDb());
            if ($this->sqlQuery($query)) {
                return $this->successMsg2('Deposit Confirmation');
            } else {
                return $this->errorMsgs(14);
            }
        }

        return $this->successMsg2('Deposit Confirmation');
    }

    public function confirm_withdrawal($id)
    {
        $vals = [$id];
        $if_empty = $this->if_empty($vals);
        if (!$if_empty) {
            return $this->errorMsgs(15);
        }
        $deposit_exist = $this->selectWhereDlt($this->wallet_tb, 'unique_id', $id);
        if (count($deposit_exist) < 1) {
            return $this->errorMsgs(15);
        }
        $date_created = $this->todayDate();
        $fields = ['status', 'date_confirmed'];
        $values = ['confirmed', $date_created];
        $update_txn = $this->update_tbs($this->wallet_tb, $fields, $values, $id);
        if ($update_txn['error'] == 1) {
            return $update_txn;
        }

        return $this->successMsg2('Withdrawal Confirmation');
    }

    public function unconfirm($id)
    {
        $vals = [$id];
        $if_empty = $this->if_empty($vals);
        if (!$if_empty) {
            return $this->errorMsgs(15);
        }
        $deposit_exist = $this->selectWhereDlt($this->wallet_tb, 'unique_id', $id);
        if (count($deposit_exist) < 1) {
            return $this->errorMsgs(15);
        }
        $fields = ['status', 'date_confirmed'];
        $values = ['pending', null];
        $update_txn = $this->update_tbs($this->wallet_tb, $fields, $values, $id);
        if ($update_txn['error'] == 1) {
            return $update_txn;
        }

        return $this->successMsg3('Transaction Unconfirmed');
    }

    public function delete($id)
    {
        $vals = [$id];
        $if_empty = $this->if_empty($vals);
        if (!$if_empty) {
            return $this->errorMsgs(15);
        }
        $fields = ['is_deleted'];
        $values = ['1'];
        $delete_txn = $this->update_tbs($this->wallet_tb, $fields, $values, $id);
        if ($delete_txn['error'] == 1) {
            return $delete_txn;
        }
        return $this->dltSuccessMsg();
    }

    public function get_balance($user_id)
    {
        $top_ups = 0;
        $withdraws = 0;
        $top_up_exist = $this->selectWhere3CondDlt($this->wallet_tb, 'user_id', $user_id, 'action_type', 'top_up', 'status', 'confirmed');
        if (count($top_up_exist) > 0) {
            foreach ($top_up_exist as $e) {
                $top_ups += $e['amt_in_usd'];
            }
        }

        $withdrawals_exist = $this->selectWhere2CondDlt($this->wallet_tb, 'user_id', $user_id, 'action_type', 'withdrawal');
        if (count($withdrawals_exist) > 0) {
            foreach ($withdrawals_exist as $e) {
                $withdraws += $e['amt_in_usd'];
            }
        }
        if ($top_ups > 0) {
            $balance = $top_ups - $withdraws;
            return $balance;
        } else {
            return 0;
        }
    }



    public function get_total_withdrawals($user_id)
    {
        $withdraws = 0;

        $withdrawals_exist = $this->selectWhere2CondDlt($this->wallet_tb, 'user_id', $user_id, 'action_type', 'withdrawal');
        if (count($withdrawals_exist) > 0) {
            foreach ($withdrawals_exist as $e) {
                $withdraws += $e['amt_in_usd'];
            }
        }
        if ($withdraws > 0) {
            return $withdraws;
        } else {
            return 0;
        }
    }
    
    public function user_amt_in_investments($user_id)
    {
        $amt = 0;
        $all_deposits = $this->selectWhere2CondDlt($this->transaction_tb,'status','confirmed','user_id',$user_id);
        foreach ($all_deposits as $e ) {
            $amt += $e['amt_in_usd'];
        }
        return $amt;
    }


    /**
     * Function to convert crypto_compare response to crypto equivalent.
     *
     * 
     */
    public function convert_to_crypto($response, $amt_in_usd)
    {
        // the api returns the equivalent of 1 of the coin in usd
        $equiv = $response['USD'];
        $amt_in_coin = $amt_in_usd / $equiv;
        return $amt_in_coin;
    }
}
$wallet = new wallet();
