<?php

namespace App\Controllers;

use CodeIgniter\API\ResponseTrait;

class WrenchWallet extends BaseController
{
    protected  \App\Models\WrenchWalletModel $wrenchWalletModel;

    use ResponseTrait;

    public function __construct()
    {
        log_message('critical', "WrenchWallet Path GATE 001");
        $this->request = $request = \Config\Services::request();
        $this->wrenchWalletModel = new \App\Models\WrenchWalletModel($this->allSettings);
    }


    public function sendMoney(){

        $raw_json = file_get_contents('php://input');
        $in = json_decode($raw_json, true);

        $in["action"] = WRENCHBOARD_USER_SENDMONEY;
        $out["internal_return"] = 0;
        $in["InitiatingChannel"] = 7;
        $in["InitiatingPaymentMethodCode"] = "CA";
        $in["InitiatingCurrencyCode"] = '566'; // 566 - NRN - Naira
        $in["InitiatingEntityCode"] = "MBA";
        $in["transaction_id"] = "T" . rand(120000, 999999);
        $in["TerminatingPaymentMethodCode"] = "AC";
        $in["TerminatingCurrencyCode"] = '566'; // 566 - NRN - Naira
        $in["TerminatingCountryCode"] = 'NG'; // NG - Nigeria
        $in["bankid"] =  $in["recipientid"];
        $in["InitiatingAmount"] =  $in["amount"];
        $in["TerminatingAmount"] =  $in["amount"];

        $out=[];

        $ret = $this->wrenchboard->wrenchboard_api($in, $out);
        $out['internal_return'] = $ret;
        log_message('critical', "***** ***** WrenchWallet::sendMoney Ret = ".$ret );
        if ( isset($out['internal_return']) && isset( $out['confirmation'])  ){
            $endpoint = "SENDMONEY_".$in["assign_mode"]."-". $out["confirmation"];
            log_message('critical', "***** ***** WrenchWallet::sendMoney SENDMONEY_ = ".$endpoint );
            $this->saveCache($endpoint,$out,25000);
            $local_url = "http://".$this->micro_service_net1.":3037/eventSendMoney";
            $outX = $this->APIcall('POST', $local_url, ["message"=>$out]);

        }else
        {
            $fail_endpoint = "SENDMONEY_FAIL_".strtoupper( date("FDYjGis") );
            log_message('critical', "***** ***** WrenchWallet::sendMoney FAIL_OFFER = ".$fail_endpoint );
            $this->saveCache($fail_endpoint,$in,25000);
        }
        return $this->respond( $this->summaryReturnData($in,$out), 200);
    }

    public function index()
    {
        return [];
    }

    public function requestVirtualCard(){
        log_message('critical', "WrenchWallet::requestVirtualCard Path GATE ***");
        $raw_json = file_get_contents('php://input');
        $in = json_decode($raw_json, true);
        $in["action"] = WRENCHBOARD_VIRTUAL_CARDADD;
        $out=[];
        $ret = $this->wrenchboard->wrenchboard_api($in, $out);
        $out['internal_return'] = $ret;
        log_message('critical', "requestVirtualCard ********* ALL   ".serialize($out) );
        return $this->respond( $this->summaryReturnData($in,$out), 200);
    }

    public function requestFamilyVirtualCard(){
        log_message('critical', "WrenchWallet::requestFamilyVirtualCard Path GATE ***");
        $raw_json = file_get_contents('php://input');
        $in = json_decode($raw_json, true);
        $in["action"] = WRENCHBOARD_VIRTUAL_FAMILY_CARD;
        $out=[];
        $ret = $this->wrenchboard->wrenchboard_api($in, $out);
        $out['internal_return'] = $ret;
        log_message('critical', "requestFamilyVirtualCard ********* ALL   ".serialize($out) );
        return $this->respond( $this->summaryReturnData($in,$out), 200);
    }
    public function redeemOptions(){
        log_message('critical', "redeemOptions 0001");
        header('Access-Control-Allow-Origin: *');
        log_message('critical', "WrenchWallet Path GATE 001");
        $call_backend =  true;

        header("Access-Control-Allow-Headers: Origin, X-API-KEY, X-Requested-With, Content-Type, Accept, Access-Control-Request-Method, Access-Control-Allow-Headers, Authorization, observe, enctype, Content-Length, X-Csrf-Token");
        log_message('critical', "0003");
        header("Access-Control-Allow-Methods: GET, PUT, POST, DELETE, PATCH, OPTIONS");
        header("Access-Control-Allow-Credentials: true");
        header("Access-Control-Max-Age: 3600");
        header('content-type: application/json; charset=utf-8');
        $method = $_SERVER['REQUEST_METHOD'];

        $ip_loc  = $this->getIpData();



        if ($method == "OPTIONS") {
            header("HTTP/1.1 200 OK CORS");
            log_message('critical', " WrenchJobs()-> OPTIONS DIE*****" );
            die();
        }
        log_message('critical', "WrenchWallet Path GATE 003");
        //$request = service('request');
        // what is the endpoint
        $uri = urldecode(current_url(true));
        $findme = '?';
        $pos = strpos($uri, $findme);
        if ($pos > 5) {
            $uri = substr($uri, 0, $pos);
        }
        log_message('critical', "API-WrenchWallet URI -> ".$uri );
        $pieces = explode('/', $uri);
        $psc = count($pieces);

        $endpoint = $psc > 0 ? $pieces[$psc - 1] : '';
        log_message('critical', "Endpoint-> ".$endpoint );

        $endpoints =  $this->endPointList();
        $out = array();
        $res1 = [];

        $current_env  = $this->getSiteConfigurations("system.live");
        $primary_image_sever = $this->getSiteConfigurations("system.primary_image_sever");
        $server_tag = $this->getSiteConfigurations("system.server_tag");
        $micro_service_net1 =  $this->getSiteConfigurations("system.micro_service_net1"); //"10.10.10.120";

        //  echo "EXYTACT INPUT DATA HERE";
        $raw_json = file_get_contents('php://input');
        $raw_array = json_decode($raw_json, true);
        $local_out =[];
        if ($_SERVER['REQUEST_METHOD'] == 'GET') {
            log_message('critical', "Endpoint LOC2 HERE -> ".$endpoint );
            $get_param = $_GET['reqData'] ?? null;
            $raw_array = ($get_param!=null) ? json_decode($get_param, true):[];
        }

        $in  = $raw_array;

        $in["loc"] = $_SERVER["REMOTE_ADDR"];
        $out = array();


        $res1 = [];
        if (!array_key_exists($endpoint, $this->sessionExcludedList())) {
            // TOKEN VERIFICATION WILL GAPPEN
        }

        switch($endpoint) {
            case 'redeemoptions':
                $in["action"] = 'redeemoptions'; //WRENCHBOARD_ACCOUNT_JOBLIST;
                break;
        }
        $in["action"] = 'redeemoptions'; //WRENCHBOARD_ACCOUNT_JOBLIST;

        if ( $call_backend ==  true  && $in["action"] !='' ){
            $local_url = "http://".$micro_service_net1.":3037/redeemoptions";
            $out = $this->APIcall('GET', $local_url, $in);
        }
        else
        {
            $out =  $local_out;
        }



        $this->doCacheStep($in, $out);
        $final_out = $out; // start from all out
        $final_out["environment"] =  $current_env + 0; // force convert to interger  = $this->getSiteConfigurations("system.live");
        $final_out["session_image_server"] = $primary_image_sever; // ( $final_out["environment"] > 0 )? 'https://apigate.nebula.g1.wrenchboard.com/en/wrench/api/v1/getmedia/' : "https://apigate.lotus.g1.wrenchboard.com/en/wrench/api/v1/getmedia/";
        $final_out["server_tag"] = $server_tag;
        $final_out["language"] = "en";
        $final_out["ip_loc"] = $ip_loc;
        return json_encode( $final_out );
    }

//    private function getSettings($settingkey, $defaultVal=''){
//        $raw_json = file_get_contents('php://input');
//        $in = json_decode($raw_json, true);
//        $out=[];
//        $endpoint = "SETTINGS";
//        $out = $this->getCache($endpoint);
//        if (!is_array($out) || count($out)==0 ) {
//            $local_url = "http://".$this->micro_service_net1.":3037/settings";
//            $out = $this->APIcall('GET', $local_url, $in);
//            if (count($out['result_list']) > 0 ){  // dont cache empty
//                $this->saveCache($endpoint,$out,55500);
//            }
//        }
//
//        if (is_array($out) && count($out['result_list']) > 0 ) {
//            return  (isset($out['result_list'][$settingkey])) ? $out['result_list'][$settingkey]: $defaultVal;
//        }
//        return $defaultVal;
//    }
    //getKidWallet from parent side
    public function getKidWallet(){
        log_message('critical', "0001");
     //   header('Access-Control-Allow-Origin: *');
        log_message('critical', "WrenchWallet Path getKidWallet 001");
        $raw_json = file_get_contents('php://input');
        $in = json_decode($raw_json, true);
        $out=[];
        $endpoint = "WALLETS-USERS_KIDS-". str_replace('-','_',  $in["family_uid"]);
        $in["loc"] = $_SERVER["REMOTE_ADDR"];
        log_message('critical', "IN ARRAY for call 0001 -> ".serialize($in));
        $in["action"] = 'getkidswallets'; //WRENCHBOARD_ACCOUNT_JOBLIST;
        //log_message('critical', "before APIN call 0001");
        $out = $this->getCache($endpoint);
        if (!is_array($out) || count($out)==0 ){
       // if (  $in["action"] !='' ){
            $local_url = "http://".$this->micro_service_net1.":3037/getkidswallets";
            $out = $this->APIcall('GET', $local_url, $in);
            if( is_array($out['result_list']) && count($out['result_list']) > 0 ){  // dont cache empty
                $this->saveCache($endpoint,$out,60);
            }
        }

        if ( is_array($out) && isset($out['result_list'])){
            foreach ($out['result_list'] as $index=>$item){
                if ($item['code']=='USD'){
                    $out['result_list'][$index]['extra_actions'] =
                        [
                            'ADD_VIRTUAL_CARD' => $this->wrenchWalletModel->addVirtualCardWallet()
                        ];
                }
                else{
                    $out['result_list'][$index]['extra_actions'] =  [];
                }
            }
        }

        $extraWallet  =  $this->wrenchWalletModel->kidsExtraWallet();

        //$out["result_list"][] = $extraWallet;
        $out["wallet_cards"] = [];
        return $this->respond( $this->summaryReturnData($in,$out), 200);
    }
    public function getWallet(){
        $raw_json = file_get_contents('php://input');
        $in = json_decode($raw_json, true);
        $in["action"] = 'getwallets';
        $out=[];
        $endpoint = "WALLETS-USERS-". str_replace('-','_', $in["uid"]);

        $out = $this->getCache($endpoint);
        $previous_wallet = false;
        if (is_array($out) && is_array($out['result_list']) && count($out['result_list'])>0 ){
            $previous_wallet = true;
        }


        if (!$previous_wallet){
            $local_url = "http://".$this->micro_service_net1.":3037/getwallets";
            $out = $this->APIcall('GET', $local_url, $in);
            if ( is_array($out['result_list']) && count($out['result_list']) > 0 ){  // dont cache empty
                $previous_wallet = true;
                $this->saveCache($endpoint,$out,180);
            }
        }

        if ($previous_wallet ){
            foreach ($out['result_list'] as $index=>$item){
                if ($item['code']=='USD'  && $this->show_extra_wallet == 1 ){
                    $out['result_list'][$index]['extra_actions'] =
                        [
                            'ADD_VIRTUAL_CARD' => $this->wrenchWalletModel->addVirtualCardWallet()
                        ];
                }
                elseif ($item['code']=='NAIRA'){
                    $out['result_list'][$index]['extra_actions'] =
                        [
                            'SPEND_FROM_BALANCE' => $this->wrenchWalletModel->spendFromBalanceWallet()
                        ];
                }
                else{
                    $out['result_list'][$index]['extra_actions'] =  [];
                }
            }
        }

        if (  $previous_wallet ){
            $owner_country = $out["result_list"][0]['owner_country'];
           // $wallet_country  = $first_names = array_column($owner_country , 'country');;
            $auxWallet = $this->auxiliaryWallets($owner_country);
            foreach ($auxWallet as $item){
             //   $out["result_list"][] = $item;
            }
       }
        log_message('critical', "***** ***** WrenchJobs::getWallet Ret ");
        return $this->respond( $this->summaryReturnData($in,$out), 200);
    }

    private function auxiliaryWallets( $owner_country ): array {
        $auxWallet = [
            [
                "wallet_country" =>  ['US'],
                "amount" =>  0,
                "id" =>  1,
                "code" =>  "USD",
                "description" =>  "Add Virtual Debit Card",
                "symbol" =>  "$",
                "action_type" =>  "AC_AD_VIRTUAL_CARD",
                "lorder" =>  0,
                "country" =>  "",
                "processor" =>  9010,
                "current_balance" =>  0,
                "transfer_limit" =>  0,
                "wallet_uid" =>  "",
                "escrow" =>  0,
                "status" =>  $this->getSettings('ENABLE_EXTRA_WALLET', 0),
                "show_balance" => false,
                "rt_action_text" => "Add Card",
                "banner" => 'https://www.wrenchboard.com/assets/images/apps/wallet/wallet-card.jpg',
                "icon" => 'https://www.wrenchboard.com/assets/images/apps/wallet/icon/cards.png'
            ],
            [
                "wallet_country" =>  [],
                "amount" =>  0,
                "id" =>  1,
                "code" =>  "USD",
                "description" =>  "Wrench Token",
                "symbol" =>  "$",
                "action_type" =>  "AC_AD_WR_TOKEN",
                "lorder" =>  0,
                "country" =>  "",
                "processor" =>  9012,
                "current_balance" =>  0,
                "transfer_limit" =>  0,
                "wallet_uid" =>  "",
                "escrow" =>  0,
                "status" =>  $this->getSettings('ENABLE_EXTRA_WALLET', 0),
                "show_balance" => true,
                "rt_action_text" => "View",
                "banner" => 'https://www.wrenchboard.com/assets/images/apps/wallet/wallet-token.jpg',
                "icon" => 'https://www.wrenchboard.com/assets/images/apps/wallet/icon/token.png'
            ],
            [
                "wallet_country" =>  [],
                "amount" =>  0,
                "id" =>  1,
                "code" =>  "USD",
                "description" =>  "Wrench Points",
                "symbol" =>  "$",
                "action_type" =>  "AC_AD_WR_POINTS",
                "lorder" =>  0,
                "country" =>  "",
                "processor" =>  9014,
                "current_balance" =>  0,
                "transfer_limit" =>  0,
                "wallet_uid" =>  "",
                "escrow" =>  0,
                "status" =>  $this->getSettings('ENABLE_EXTRA_WALLET', 0),
                "show_balance" => true,
                "rt_action_text" => "Redeem",
                "banner" => 'https://www.wrenchboard.com/assets/images/apps/wallet/wallet-point.jpg',
                "icon" => 'https://www.wrenchboard.com/assets/images/apps/wallet/icon/point.png'
            ]
        ];
        log_message('critical', "***** ***** auxiliaryWallets::ALL ITEM ". serialize($auxWallet));
        log_message('critical', "***** ***** auxiliaryWallets::ITEM ENTER **********");
        $retArr=[];
        foreach ( $auxWallet as $item){
            if ( in_array(  $owner_country, $item['wallet_country']) && $item['status'] == 100 ){
                log_message('critical', "***** ***** auxiliaryWallets::ITEM ". serialize($item));
                $retArr[] =$item;
            }
        }

        return $retArr;
    }
    public function getEscrols(){
        log_message('critical', "0001");
        header('Access-Control-Allow-Origin: *');
        log_message('critical', "WrenchWallet Path GATE 001");
        $call_backend =  true;

        header("Access-Control-Allow-Headers: Origin, X-API-KEY, X-Requested-With, Content-Type, Accept, Access-Control-Request-Method, Access-Control-Allow-Headers, Authorization, observe, enctype, Content-Length, X-Csrf-Token");
        log_message('critical', "0003");
        header("Access-Control-Allow-Methods: GET, PUT, POST, DELETE, PATCH, OPTIONS");
        header("Access-Control-Allow-Credentials: true");
        header("Access-Control-Max-Age: 3600");
        header('content-type: application/json; charset=utf-8');
        $method = $_SERVER['REQUEST_METHOD'];

        $ip_loc  = $this->getIpData();



        if ($method == "OPTIONS") {
            header("HTTP/1.1 200 OK CORS");
            log_message('critical', " WrenchJobs()-> OPTIONS DIE*****" );
            die();
        }
        log_message('critical', "WrenchWallet Path GATE 003");
        //$request = service('request');
        // what is the endpoint
        $uri = urldecode(current_url(true));
        $findme = '?';
        $pos = strpos($uri, $findme);
        if ($pos > 5) {
            $uri = substr($uri, 0, $pos);
        }
        log_message('critical', "API-WrenchWallet URI -> ".$uri );
        $pieces = explode('/', $uri);
        $psc = count($pieces);

        $endpoint = $psc > 0 ? $pieces[$psc - 1] : '';
        log_message('critical', "Endpoint-> ".$endpoint );

        $endpoints =  $this->endPointList();
        $out = array();
        $res1 = [];

        $current_env  = $this->getSiteConfigurations("system.live");
        $primary_image_sever = $this->getSiteConfigurations("system.primary_image_sever");
        $server_tag = $this->getSiteConfigurations("system.server_tag");
        $micro_service_net1 =  $this->getSiteConfigurations("system.micro_service_net1"); //"10.10.10.120";

        //  echo "EXYTACT INPUT DATA HERE";
        $raw_json = file_get_contents('php://input');
        $raw_array = json_decode($raw_json, true);
        $local_out =[];
        if ($_SERVER['REQUEST_METHOD'] == 'GET') {
            log_message('critical', "Endpoint LOC2 HERE -> ".$endpoint );
            $get_param = $_GET['reqData'] ?? null;
            $raw_array = ($get_param!=null) ? json_decode($get_param, true):[];
        }

        $in  = $raw_array;

        $in["loc"] = $_SERVER["REMOTE_ADDR"];

        $in["action"] = 'getescrows'; //WRENCHBOARD_ACCOUNT_JOBLIST;

        if ( $call_backend ==  true  && $in["action"] !='' ){
            $local_url = "http://".$micro_service_net1.":3037/getescrows";
            $out = $this->APIcall('GET', $local_url, $in);
        }
        else
        {
            $out =  $local_out;
        }



        $this->doCacheStep($in, $out);
        $final_out = $out; // start from all out
        $final_out["environment"] =  $current_env + 0; // force convert to interger  = $this->getSiteConfigurations("system.live");
        $final_out["session_image_server"] = $primary_image_sever; // ( $final_out["environment"] > 0 )? 'https://apigate.nebula.g1.wrenchboard.com/en/wrench/api/v1/getmedia/' : "https://apigate.lotus.g1.wrenchboard.com/en/wrench/api/v1/getmedia/";
        $final_out["server_tag"] = $server_tag;
        $final_out["language"] = "en";
        $final_out["ip_loc"] = $ip_loc;
        return json_encode( $final_out );
    }


}