<?php

$exchange = new class {

    protected $post;
    protected $user;
    protected $bankinfo;
    protected $table;

    public function __construct() {

        $this->user = Uss::$global['user'];
        $this->bankinfo = Uss::$global['usermeta']->get('bank:info', $this->user['id']);
        $this->table = DB_TABLE_PREFIX . "_exchanges";

        if( $_SERVER['REQUEST_METHOD'] != 'POST' ) return;

        $this->post = array_map(function($value) {
            return Uss::$global['mysqli']->real_escape_string( trim($value) );
        }, $_POST);
        
        $this->post['userid'] = $this->user['id'];

        $this->runExchange();

    }

    protected function runExchange() {

        $balance = Bank::getUserBalance( $this->user['id'], $this->post['paid_currency'] );
        $deposit = (float)$this->post['paid_amount'];

        if( $balance < $deposit ) {
            return Bank::log( "error", "Insufficient {$this->post['paid_currency']} Balance" );
        }

        # Insert Exchange Detail
        
        $SQL = SQuery::insert( $this->table, $this->post );
        $insert = Uss::$global['mysqli']->query( $SQL );

        if( $insert ) {
            $this->debitUser( Uss::$global['mysqli']->insert_id );
        } else {
            Bank::log( "error", "The exchange was not successful <br/> Please contact the support team" );
        }

    }

    protected function debitUser( int $exchange_id ) {

        $debited = Bank::transfer(array(
            "default" => [
                'amount' => $this->post['paid_amount'],
                'currency' => $this->post['paid_currency']
            ],
            "debit" => [
                'userid' => $this->post['userid']
            ]
        ));

        if( $debited ) {
            Bank::log( "success", "The exchange is pending. <br/> Your <span class='fw-semibold text-primary'>{$this->post['expected_currency']}</span> balance will soon be updated" );
        } else {
            $SQL = SQuery::delete( $exchangeTable, "id = {$exchange_id}" );
            Uss::$global['mysqli']->query( $SQL );
            Bank::log( "error", "Sorry! We could not resolve your account transaction" );
        }

    }

};