<?php

namespace App\Controllers;

use CodeIgniter\API\ResponseTrait;

class WrenchJobs extends BaseController
{
    use ResponseTrait;
    public function __construct()
    {
        $this->request = $request = \Config\Services::request();
    }

    public function verifyCompletedHx(){
        //http://localhost:3033/completedHx
        $raw_json = file_get_contents('php://input');
        $in = json_decode($raw_json, true);
        $in["action"] = -1;
        $out=[];
        $endpoint = "COMPLETED_HX-". $in["uid"];

     //   $out = $this->getCache($endpoint);
        if ( count($out)==0 ){
            $local_url = "http://".$this->micro_service_net1.":3033/completedHx";
            $out = $this->APIcall('GET', $local_url, $in);
            $this->saveCache($endpoint,$out,3000);
            $out['internal_return'] = 0; // just backwad comaptobility
            log_message('critical', "***** ***** WrenchJobs::verifyCompletedHx Cache Done:::Ret ");
        }
        $out["checked_value"] = $this->CheckUidInCompletedHx($in["offer_depend_uid"],  $out['result_list']); // test the value now
        log_message('critical', "***** ***** WrenchJobs::verifyCompletedHx Ret ");
        return $this->respond( $this->summaryReturnData($in,$out), 200);
    }

    private function CheckUidInCompletedHx($offer_depend_uid, $resArr) : bool {
        $ret = false;
        if ( !is_array(($resArr))) return $ret;

        foreach ($resArr as $key => $value) {
            // $arr[3] will be updated with each value from $arr...
            //echo "{$key} => {$value} ";
            log_message('critical', "***** WrenchJobs::CheckUidInCompletedHx  $offer_depend_uid ".$value["job_uid"]);
            if ($offer_depend_uid==$value["job_uid"]) $ret = true;
        }
        return $ret;
    }

    private function refreshJobsData(){
        $in =[
                'limit' =>  60,
                'page' =>  1
        ];
        $endpoint =   $endpoint = "MARKET_JOB_DATA";
        $local_url = "http://".$this->micro_service_net1.":3033/marketjobs";
        $out = $this->APIcall('GET', $local_url, $in);
        // dont cache junk
        if ( is_array($out) && is_array($out["result_list"]) && count($out["result_list"]) > 0){
            $this->deleteCache($endpoint);
            $this->saveCache($endpoint,$out,1440);
        }
    }
    public function getJobsData() {
        $raw_json = file_get_contents('php://input');
        $in = json_decode($raw_json, true);
        $in["action"] = -1; // bad number - we dont want formating WRENCHBOARD_ACCOUNT_JOBLIST; dont send this line , the formater will be confused
        $out=[];
        $endpoint = "MARKET_JOB_DATA"; // All jobs Data
        log_message('critical', "ENTER ***** ***** WrenchJobs::getJobsData IN ");
        try {

                $out = $this->getCache($endpoint);
                $countItem  = 0;
                if( is_array($out)){
                    $countItem = count($out);
                }

                if (  $countItem == 0 ){
                    $local_url = "http://".$this->micro_service_net1.":3033/marketjobs";
                    $out = $this->APIcall('GET', $local_url, $in);
                    // dont cache junk
                    if ( is_array($out) && is_array($out["result_list"]) && count($out["result_list"]) > 0){
                        $this->saveCache($endpoint,$out,360);
                    }
                    $out['internal_return'] = 0; // just backwad comaptobility
                    log_message('critical', "***** ***** WrenchJobs::getJobsData Cache Done:::Ret ");
                }

                $endpointW = "WALLETS-COUNTRY-". str_replace('-','_', $in["uid"]);
                // $endpointW = "USER_WALLET_COUNTRY-". $in["uid"];
                $outW = $this->getCache($endpointW);
                // I need your wallet country here
                if ( !is_array($outW["result_list"])){
                    $local_urlW = "http://".$this->micro_service_net1.":3033/walletcountry";
                    $outW = $this->APIcall('GET', $local_urlW, $in);
                    if ( is_array($outW["result_list"]) && count($outW["result_list"]) > 0){
                        $this->saveCache($endpointW,$outW,15660);
                    }
                }

                $filter_job_list =[];
                $wallet_country  = $first_names = array_column($outW['result_list'], 'country');;
                foreach ($out['result_list'] as $item) {
                    if ( in_array(  $item['job_country'], $wallet_country) ){
                        log_message('critical', "***** ***** WrenchJobs::ITEM ". serialize($item));
                        $filter_job_list[] = $item;
                    }
                }
                log_message('critical', "***** ***** WrenchJobs::JOB AFTER FILTER  Ret ". serialize($filter_job_list));

                $out['result_list'] = $filter_job_list;

                // Fileter result_list to wallet country
                $endpoint = "WRENCH_JOB_INTEREST_COUNT";
                $int_list  =  $this->getCache($endpoint)["result_list"];
                $out["interest_list"] = ( isset($int_list) && is_array($int_list) ) ? $int_list : [];

        } catch (Exception $e) {
             $errMsg =  ' JOB DATA ERROR **** Caught exception: '.  $e->getMessage();
             log_message('critical', $errMsg);
        }
        log_message('critical', "END ***** ***** WrenchJobs::getJobsData Ret ");
        return $this->respond( $this->summaryReturnData($in,$out), 200);
    }

    public function interestStats(){
        $raw_json = file_get_contents('php://input');
        $in = json_decode($raw_json, true);
        $in["action"] =  WRENCHBOARD_JOB_STATS_INTEREST;
        $out=[];
        $endpoint = "CLIENT_STATS-". $in["client_uid"];

        $out = $this->getCache($endpoint);
        if ( count($out)==0 ){
            $ret = $this->wrenchboard->wrenchboard_api($in, $out);
            $this->saveCache($endpoint,$out,15000);
            $out['internal_return'] = $ret;
            log_message('critical', "***** ***** WrenchJobs::interestStats Cache Done:::Ret ". $ret);
        }
        log_message('critical', "***** ***** WrenchJobs::interestStats Ret ");
        return $this->respond( $this->summaryReturnData($in,$out), 200);
    }

    public function contractHx(){
        $raw_json = file_get_contents('php://input');
        $in = json_decode($raw_json, true);
        $endpoint = "USER_CONTRACT_HX-". $in["uid"];
        $out = $this->getCache($endpoint);
        if ( count($out)==0 ){
            $local_url = "http://".$this->micro_service_net1.":3033/contractHx";
            $out = $this->APIcall('GET', $local_url, $in );
            $this->saveCache($endpoint,$out,360);
        }
        return $this->respond( $this->summaryReturnData($in,$out), 200);
    }


    public function recentPastDueJobs(){
        $raw_json = file_get_contents('php://input');
        $in = json_decode($raw_json, true);
        $in["action"] = WRENCHBOARD_JOB_RECENTPASTDUE;
        $in["nocache"] = $in["nocache"] ?? false;
        $out =[];

        //$wrenchboard = new  \App\Models\BackendModel();

            $in["limit"] = 10;
            $in["page"] = 0;
            $in["offset"] = 0;
            $in["allstatus"] =0;
            $ret= $this->wrenchboard->wrenchboard_api($in, $out);
            $out['internal_return'] = $ret;

        return $this->respond( $this->summaryReturnData($in,$out), 200);

       // $res = ( new \App\Models\ResultFormatter() )->processOutJson($in, $out);
       // return  $res['result_list'];
    }

    public function sendJobInterest(){
        $raw_json = file_get_contents('php://input');
        $in = json_decode($raw_json, true);
        $in["action"] =  WRENCHBOARD_JOB_SEND_INTEREST;
        $out=[];

        $ret = $this->wrenchboard->wrenchboard_api($in, $out);
        $out['internal_return'] = $ret;
        log_message('critical', "***** ***** WrenchJobs::sendJobInterest Ret = ".$ret );
        if ( isset($out['internal_return'])
            && $out["internal_return"] > 0
            && isset( $out['offer_code'])  ){
            $endpoint = "INTEREST_MSG-".$in["offer_code"]."-". $out["member_id"];
            log_message('critical', "***** ***** WrenchJobs::sendJobInterest INTEREST_MSG_ = ".$endpoint );
            $this->saveCache($endpoint,$out,25000);
            $local_url = "http://".$this->micro_service_net1.":3030/eventInterest";
            $outX = $this->APIcall('POST', $local_url, ["message"=>$out]);
        }
        return $this->respond( $this->summaryReturnData($in,$out), 200);
    }
    public function assignTask(){

        $raw_json = file_get_contents('php://input');
        $in = json_decode($raw_json, true);
        $in["action"] = WRENCHBOARD_JOB_OFFER_SYSTEM;

        if ( !isset($in["strict_timeline"])){
            $in["strict_timeline"] = 0;
        }
        $out=[];

        $ret = $this->wrenchboard->wrenchboard_api($in, $out);
        $out['internal_return'] = $ret;
        log_message('critical', "***** ***** WrenchJobs::assignTask Ret = ".$ret );
        if ( isset($out['internal_return']) && isset( $out['offer_code'])  ){
            $this->refreshJobsData();
            $endpoint = "NEW_OFFER_".$in["assign_mode"]."-". $out["offer_code"];
            log_message('critical', "***** ***** WrenchJobs::assignTask NEW_OFFER_ = ".$endpoint );
            $this->saveCache($endpoint,$out,25000);
            $local_url = "http://".$this->micro_service_net1.":3033/jobAdded";
            $outX = $this->APIcall('POST', $local_url, ["message"=>$out]);

        }else
        {
            $fail_endpoint = "FAIL_OFFER_".$in["assign_mode"]."-".$in["job_uid"];
            log_message('critical', "***** ***** WrenchJobs::assignTask FAIL_OFFER = ".$fail_endpoint );
            $this->saveCache($fail_endpoint,$in,25000);
        }
        return $this->respond( $this->summaryReturnData($in,$out), 200);
    }
    public function index()
    {
        return [];
    }


    public function apigate(){
        log_message('critical', "0001");
        header('Access-Control-Allow-Origin: *');
        log_message('critical', "WrenchJobs 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();
        }

        //$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-GATE URI -> ".$uri );
        $pieces = explode('/', $uri);
        $psc = count($pieces);

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

        $endpoints =  $this->endPointList();
        $out = array();
        $res1 = [];
        if (array_key_exists($endpoint, $endpoints)) {
        } else {
            http_response_code(404);
            // tell the user product does not exist
            echo json_encode([
                'message' => 'Endpoint not found.',
                'URI' => $uri,
            ]);
        }

        $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', "Enpoint 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 'getjobsdata':
                $in["action"] = 'marketjobs'; //WRENCHBOARD_ACCOUNT_JOBLIST;
                break;
        }


        if ( $call_backend ==  true  && $in["action"] !='' ){
            $local_url = "http://".$micro_service_net1.":3033/marketjobs";
            $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 );
    }


//    public function APIcall($method, $url, $data) {
//        //  $curl = curl_init();
//        $curl = curl_init($url);
//        switch ($method) {
//            case "POST":
//                curl_setopt($curl, CURLOPT_POST, 1);
//                if ($data)
//                    curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
//                break;
//            case "PUT":
//                curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "PUT");
//                if ($data)
//                    curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
//                break;
//        }
//
//        curl_setopt($curl, CURLOPT_URL, $url);
//        curl_setopt($curl, CURLOPT_HTTPHEADER, array(
//            'APIKEY: RegisteredAPIkey',
//            'Content-Type: application/json',
//        ));
//
//        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
//        curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
//        $result = curl_exec($curl);
//
//        if(!$result) {
//            echo("Connection failure!");
//        }
//        curl_close($curl);
//        return json_decode($result, true);
//    }



}