<?php

$deposit = new class {

    public function __construct() {

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

        $this->updateDeposit();

    }

    public function updateDeposit() {

        $deposit = Udash::fetch_assoc( DB_TABLE_PREFIX . "_deposits", $_POST['id'] );

        if( !$deposit ) {
            return Bank::log('error', "Sorry! The deposit data could not be found");
        };

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

        $SQL = SQuery::update( DB_TABLE_PREFIX . "_deposits", $post, "id = '{$deposit['id']}'" );

        $update = Uss::$global['mysqli']->query( $SQL );

        if( !$update )  {
            Bank::log( 'error', "The deposit was not updated!" );
        } else {

            $message = "The deposit has been updated <br/>";

            if( $post['status'] == 'approved' && empty($deposit['paid']) ) {

                $tx = [
                    'transfers' => [
                        "amount" => $post['usd_amount'],
                        "tx_ref" => uniqid() . Core::keygen(15),
                        'tx_region' => 'local',
                        'tx_charge' => 0,
                        'tx_status' => 'success',
                    ]
                ];

                $tx['transfer_meta'] = [
                    "tx_ref" => $tx['transfers']['tx_ref'],
                    'account_number' => Uss::$global['usermeta']->get('bank:number', $deposit['userid']),
                    'tx_type' => 'credit',
                    'amount' => $tx['transfers']['amount'],
                    'status' => 0
                ];

                try {

                    foreach( $tx as $table => $data ) {

                        $SQL = SQuery::insert( DB_TABLE_PREFIX . "_{$table}", $data );
                        $insert = Uss::$global['mysqli']->query( $SQL );

                        if( !$insert ) {
                            throw new Exception("Error...");
                        };

                    }

                    $message .= "User has been credited \${$tx['transfers']['amount']}";

                    $SQL = SQuery::update( DB_TABLE_PREFIX . "_deposits", ['paid' => 1], "id = {$deposit['id']}" );

                    Uss::$global['mysqli']->query( $SQL );

                } catch(Exception $e) {

                    $message .= "User was not credited: <br/> {$e->getMessage()}";

                };

            };

            Bank::log( 'success', $message );

        }

    }

};