<?php

$loan = new class {

    protected $table;

    public function __construct() {

        $this->table = DB_TABLE_PREFIX . "_loans";

        if( $_SERVER['REQUEST_METHOD'] == 'POST' ) {

            $this->updateLoan();

        };

    }

    public function updateLoan() {

        $_POST = array_map( array(Uss::$global['mysqli'], 'real_escape_string'), $_POST );

        $this->loan = Udash::fetch_assoc( $this->table, $_POST['id'] );

        if( empty($this->loan) ) {
            return Bank::log( 'error', "The associated loan could not be found" );
        }

        if( $_POST['status'] != 'delete' ) {

            $SQL = SQuery::update( $this->table, array('status' => $_POST['status']), "id = '{$this->loan['id']}'" );

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

            if( $updated ) {

                $message = "The loan status has been updated";

                if( $_POST['status'] == 'approved' && empty($this->loan['funded']) ) {

                    $transfer = Bank::transfer([
                        'default' => [
                            'amount' => $this->loan['amount']
                        ],
                        'credit' => [
                            'userid' => $this->loan['userid']
                        ]
                    ]);

                    if( $transfer ) {

                        $SQL = SQuery::update( $this->table, [
                            "funded" => 1
                        ], "id = {$this->loan['id']}");

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

                        $message .= "<br/> User account has been funded";

                    } else {

                        $message .= "<br/> User account was not funded. You may need to fund the account manually";

                    };

                };

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

            } else {

                Bank::log( 'error', "The loan status was not updated" );

            }

        } else {

            $SQL = SQuery::delete( $this->table, "id = '{$this->loan['id']}'" );

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

            $message = $deleted ? "The loan has been deleted" : "The loan could not be deleted";

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

        }

    }

};