<?php

class Monetary {

    const TEMP_DIR = MONETARY_DIR . "/templates";
    protected static $QRContent = [];
    
    public static function handleDepositRequest() {

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

        $method = self::getMethod( $_GET['method'] );

        $post = $_POST;

        array_walk_recursive($post, function(&$value) {
            $value = Uss::$global['mysqli']->real_escape_string($value);
        });

        $post['userid'] = Uss::$global['user']['id'];
        $post['detail'] = json_encode( $method['detail'] + ['medium' => $method['medium']] );
        $post['tx_ref'] = uniqid('TNX');
        $post['rate'] = (float)$post['rate'];

        $SQL = SQuery::insert( DB_TABLE_PREFIX . "_deposits", $post );
        $insert = Uss::$global['mysqli']->query( $SQL );

        if( $insert ) {

            if( $method['medium'] != 'bank') {
                $message = "Your deposit of {$post['usd_amount']} USD ({$post['rate']} BTC) has been sent <br/>";
            } else {
                $message = "Your bank deposit of {$post['usd_amount']} USD has been sent <br/>";
            };

            $message .= "Reference ID: <span class='text-info'>{$post['tx_ref']}</span> <br/>
            You will be credited once the deposit is confirmed";

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

        } else {

            $message = "Your deposit detail was not sent. <br/> Please contact the support team if the problem persist";

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

        };


    }


    public static function getMethod( int $id ) {

        $key = Uss::$global['mysqli']->real_escape_string( $id );
        $SQL = SQuery::select( DB_TABLE_PREFIX . "_payment_methods", "id = '{$key}'");
        $method = Uss::$global['mysqli']->query( $SQL )->fetch_assoc();
        if( $method ) $method['detail'] = json_decode( $method['detail'], true );
        
        return $method;

    }


    public static function cardApply() {
        
        if( $_SERVER['REQUEST_METHOD'] != 'POST' ) return;

        $expiry = (new DateTime("+3 years"))->format('m/y');
        
        $entry = ( $_POST['card-vendor'] == 'mastercard' ) ? 5 : 4;

        $cardinfo = array(
            "card_type" => $_POST['card-type'],
            "vendor" => $_POST['card-vendor'],
            "cvv" => mt_rand(100, 999),
            "card_number" => $entry . mt_rand(100000000000000, 999999999999999),
            "expiry" => $expiry,
            "userid" => Uss::$global['user']['id']
        );  

        $SQL = SQuery::insert( DB_TABLE_PREFIX . "_cards", $cardinfo );

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

        if( $insert ) {
            Bank::log('success', "Your application was successful");
        } else {
            Bank::log('error', "Your application failed. </br> Please contact the support to resolve any issues");
        };

    }


    public static function getActiveCard( int $userid ) {

        $SQL = SQuery::select( DB_TABLE_PREFIX . "_cards", "status IN( 'active', 'pending' ) AND userid = {$userid}" );

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

        $data = $result->fetch_assoc();
        
        if( !$data || $data['status'] == 'pending' ) return $data;

        $bankinfo = Uss::$global['usermeta']->get('bank:info', Uss::$global['user']['id']);

        $data += array(
            "client_name" => ucwords( $bankinfo['bio']['firstname'] . " " . $bankinfo['bio']['lastname'] ),
            "class-name" => ''
        );

        if( $data['vendor'] == 'mastercard' ) {
            $data['color'] = 'danger';
            $data['logo'] = 'mastercard-logo.png';
        } else {
            $data['color'] = 'success';
            $data['logo'] = 'visa-logo.png';
        };

        return $data;

    }

    public static function getQRCode( ?array $method ) {

        if( !$method || $method['medium'] != 'crypto' ) {
            return;
        };

        $network = $method['network'];
        $detail = $method['detail'];
        $name = ucwords( str_replace("_", " ", array_keys($detail)[0]) );
        $wallet = array_values($detail)[0];
        
        ob_start();
        require_once Bank::LIB_DIR . "/phpqrcode/qrlib.php";
        QRCode::png($wallet, false, QR_ECLEVEL_L, 5);
        $image = ob_get_clean();
        header("Content-type: text/html");

        self::$QRContent = [
            "src" => "data:image/png;base64," . base64_encode($image),
            "content" => $wallet,
            "title" => $name
        ];

    }

    public static function flushQRCode() {
        if( empty(self::$QRContent) ) {
            return;
        };
        $qr = self::$QRContent;
        echo "
            <div class='pt-3'>
                <h5 class='text-info'>{$qr['title']}</h5>
                <figure><img src='{$qr['src']}' class='img-fluid'></figure>
                <div class='text-muted'>{$qr['content']}</div>
            </div>
        ";
    }

}