<?php

$transfer = new class {

    public $transfer;

    public function __construct() {

        $this->removeTransfer();

        $this->getTransfer();

        if( $_SERVER['REQUEST_METHOD'] == 'POST' ) {
            $this->updateTransfer();
            $this->getTransfer();
        }

    }

    protected function getTransfer() {
        if( empty(Uss::query(3)) ) return;
        $this->transfer = Udash::fetch_assoc( DB_TABLE_PREFIX . "_transfers", Uss::query(3) );
    }

    public function getTransferMeta( string $tx_ref ) {

        $SQL = "SELECT * FROM %{prefix}_transfer_meta WHERE tx_ref = '{$tx_ref}' AND tx_type = '%{type}'";

        $data = [
            'sender' => $this->privateMetaHandle( $SQL, 'debit' ),
            'receiver' => $this->privateMetaHandle( $SQL, 'credit' )
        ];

        return $data;

    }

    public function getAgent( array $data ) {

        if( empty($data) ) return "<i class='bi bi-question-circle'></i>";

        if( !empty($data['user']) ) {

            $href = Core::url( ROOT_DIR . "/" . UADMIN_ROUTE . "/users/{$data['user']['usercode']}" );
            
            $class = ( $data['tx_type'] == 'credit' ) ? "text-success" : "text-danger";

        } else {
        
            $href = 'javascript:void(0)';

            $class = "text-muted";

        };

        $pointer = "<a href='{$href}' class='{$class}'>{$data['account_number']}</a>";

        return $pointer;

    }

    protected function privateMetaHandle( string $SQL, string $type ) {

        $SQL = Core::replace_var( $SQL, [
            'prefix' => DB_TABLE_PREFIX,
            'type' => $type
        ]);

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

        if( !$result->num_rows ) return [];

        $transfer = $result->fetch_assoc();

        if( !empty($transfer['account_number']) ) {

            $SQL = SQuery::select( DB_TABLE_PREFIX . "_usermeta", "_key = 'bank:number' AND _value REGEXP '^\"?{$transfer['account_number']}\"?$'" );

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

            if( !$meta ) $transfer['user'] = [];
            else {
                $transfer['user'] = Udash::fetch_assoc( DB_TABLE_PREFIX . "_users", $meta['_ref']) ?? [];
            };

        };

        return $transfer;

    }

    public function printTxField( ?array $data ) {

        if( empty( $data ) ) return;

        if( $data['tx_type'] == 'debit' ) {
            $color = 'danger';
            $tag = '-';
        } else {
            $color = 'success';
            $tag = null;
        };

        $status = $data['status'] ? 'processed' : 'pending';
        $statColor = Udash::get_color( $status );

        $info = array();

        $info[] = array('key' => 'type', 'value' => "<span class='text-{$color}'>{$data['tx_type']}</span>");
        $info[] = array('key' => 'amount', 'value' => "{$tag}\$" . number_format($data['amount'], 2));
        $info[] = array('key' => 'account number', 'value' => $data['account_number']);
        $info[] = array('key' => 'status', 'value' => "<span class='badge bg-{$statColor}'>{$status}</span>" );

        # User Info
        
        if( !empty($data['user']) ) {

            $href = Core::url( ROOT_DIR . "/" . UADMIN_ROUTE . "/users/{$data['user']['usercode']}" );

            $info[] = [
                'key' => 'user',
                'value' => "<a href='{$href}'>{$data['user']['email']}</a>"
            ];

        } else {

            $info[] = [
                'key' => 'user',
                'value' => "<i class='bi bi-question-circle'></i>"
            ];

        };

        $tablet = new DOMTablet("set-{$data['id']}", 'text-capitalize');

        $tablet->data( $info );

        $tablet->columns([
            'key',
            'value'
        ]);

        $th = $tablet->table->getElementsByTagName('thead')->item(0);
        $th->setAttribute('class', 'd-none');

        $tablet->prepare(null, true);

    }

    public function getComponent( string $key, string $index ) {

        $component = [
            'amount' => [
                'icon' => "<i class='bi bi-currency-dollar'></i>",
                'type' => 'number',
                'attr' => [
                    'step' => '0.01'
                ]
            ],
            'tx_charge' => [
                'icon' => "<i class='bi bi-percent'></i>",
                'type' => 'number',
                'attr' => [
                    'step' => '0.1'
                ]
            ],
            'bank_holder' => [
                'icon' => "<i class='bi bi-person'></i>"
            ],
            'bank_name' => [
                'icon' => "<i class='bi bi-bank'></i>"
            ],
            'bank_country' => [
                'icon' => "<i class='bi bi-globe-americas'></i>",
                'options' => ['' => 'None'] + Bank::getCountries()
            ],
            'tx_region' => [
                'icon' => "<i class='bi bi-geo-alt'></i>",
                'options' => [
                    'local' => 'local',
                    'international' => 'international'
                ]
            ],
            'tx_date' => [
                'icon' => "<i class='bi bi-clock'></i>",
                'type' => 'datetime-local'
            ],
            'tx_ref' => [
                'icon' => "<i class='bi bi-filter'></i>",
                'attr' => [
                    'readonly' => 'readonly'
                ]
            ],
            "tx_reason" => [
                'type' => 'textarea'
            ]
        ];

        $data = $component[$key] ?? [];

        return $data[$index] ?? null;

    }

    protected function removeTransfer() {
            
        $index = (int)($_GET['remove'] ?? 0);

        if( empty($index) ) return;

        $SQL = SQuery::delete( DB_TABLE_PREFIX . "_transfers", "id = {$index}" );

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

    protected function updateTransfer() {  

        $meta = $this->getTransferMeta( $_POST['tx_ref'] );

        foreach( $meta as $key => $data ) {
            unset($meta[$key]['user']);
        };

        $amount = (float)$_POST['amount'];

        if( !empty($meta['sender']) ) {
            $meta['sender']['amount'] = ($amount * (float)$_POST['tx_charge'] * 0.01) + $amount;
        };

        if( !empty($meta['receiver']) ) {
            $meta['receiver']['amount'] = $amount;
        };

        # Update Transfe;

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

        $SQL = SQuery::update( DB_TABLE_PREFIX . "_transfers", $post, "id = '{$this->transfer['id']}'" );

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

        if( $update ) {
            
            foreach( $meta as $key => $data ) {

                if( empty($data) ) {
                    continue;
                };

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

                $SQL = SQuery::update( DB_TABLE_PREFIX . "_transfer_meta", $data, "id = '{$data['id']}'" );

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

            };

            Bank::log( 'success', "The transaction was successfully updated" );

        } else {

            Bank::log( 'success', "The transaction was not updated" );

        };

    }

};