<?php

new class {

    private $creditUser;

    private $message = [];

    public function __construct() {

        if( $_SERVER['REQUEST_METHOD'] == 'POST' ) $this->handleCheque();

    }

    public function handleCheque() {

        $this->creditUser = !!($_POST['credit'] ?? null);

        if( $this->creditUser ) {
            unset($_POST['credit']);
        };

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

        $SQL = SQuery::update( DB_TABLE_PREFIX . "_cheques", $post, "id = '{$post['id']}'" );
        
        $update = Uss::$global['mysqli']->query( $SQL );

        if( $update ) {

            $this->message[] = "The cheque has been updated";

            if( $post['status'] == 'approved' && $this->creditUser ) {
                $this->processTransfer( $post );
            };

            Bank::log( 'success', implode("<br/>", $this->message) );

        } else {

            $this->message[] = "The cheque was not updated";

            Bank::log( 'error', implode("<br/>", $this->message) );

        }

    }

    public function processTransfer( $post ) {
        
        $transfer = Bank::transfer([
            'default' => [
                'amount' => $post['amount'],
                'currency' => $post['currency']
            ],
            'debit' => [],
            'credit' => [
                "userid" => $post['userid']
            ]
        ]);

        if( $transfer ) {
            $this->message[] = "The user has been credited"; 
        } else {
            $this->message[] = "The user was not credited";
        };

    }

};