<?php

namespace App\Controllers;

class WrenchBanners extends BaseController
{
    public function __construct()
    {
        $this->request = $request = \Config\Services::request();
    }
    public function index()
    {
        return [];
    }
/*
 {
    "action": 11200,
    "member_id": "379",
    "uid": "5c2f7660-2214-4c75-98b0-12e44c0d7e78",
    "sessionid": "800EBCB2C336A6954BB4FA589988092434B6221CBCCF9E1D92F09D9E10CA77AC",
    "limit": 30,
    "offset": 0
}
 */
//    public function familyBanners(){
//
//        $raw_json = file_get_contents('php://input');
//        $in = json_decode($raw_json, true);
//
//        $in["action"] = WRENCHBOARD_FAMILY_HOMEBANNERS;
//        $endpoint = "FAMILY_BANNERS-". $in["uid"]; // str_pad($in["uid"], 12, "0", STR_PAD_LEFT);
//        $out = $this->getCache($endpoint); // try find in cache
//               if ( count($out) == 0 ){
//                   $local_url = "http://".$this->micro_service_net1.":3032/familybanners";
//                   $out = $this->APIcall('GET', $local_url, $in);
//                   log_message('critical', "familyBanners ********* ALL   ".serialize($out["result_list"]) );
//                   log_message('critical', "familyBanners ********* COUNT ".serialize(count($out["result_list"])) );
//                   $this->saveCache($endpoint,$out,1500);
//               }
//        return  $this->summaryReturnData($in,$out); //json_encode( $final_out );
//    }
//activetaskslist
    private function bannerGetActiveTasks($in){
        $in["action"] = WRENCHBOARD_JOB_USERACTIVE;
        $in["nocache"] = $in["nocache"] ?? false;

        $endpoint = "BANNERS_ACTIVETASK-".str_replace("-", "_", $in["uid"]);
        if ($in["nocache"]) $this->deleteCache($endpoint);
        $wrenchboard = new  \App\Models\BackendModel();

        $out = $this->getCache($endpoint);
        if (count($out)==0){
            $in["limit"] = 10;
            $in["page"] = 0;
            $in["offset"] = 0;
            $in["allstatus"] =0;
            $ret= $wrenchboard->wrenchboard_api($in, $out);
            $out['internal_return'] = $ret;
            $this->saveCache($endpoint,$out,100);
        }
        $res = ( new \App\Models\ResultFormatter() )->processOutJson($in, $out);
        return  $res['result_list'];
    }
    private function bannerGetOffers($in){
        $in["action"] = WRENCHBOARD_MOBILE_OFFERSLIST;
        $endpoint = "BANNERS_OFFERS-". str_replace("-", "_", $in["uid"]);
        $wrenchboard = new  \App\Models\BackendModel();

        $in["nocache"] = $in["nocache"] ?? false;
        if ($in["nocache"]) $this->deleteCache($endpoint);
        $out = $this->getCache($endpoint);
        if (count($out)==0){
            $in["limit"] = 10;
            $in["page"] = 0;
            $ret= $wrenchboard->wrenchboard_api($in, $out);
            $out['internal_return'] = $ret;
            $this->saveCache($endpoint,$out,100);
        }
        $res = ( new \App\Models\ResultFormatter() )->processOutJson($in, $out);
        return  $res['result_list'];
    }
    public function usersBanners(){
        $raw_json = file_get_contents('php://input');
        $in = json_decode($raw_json, true);
        $out =[];
        $in["action"] =  WRENCHBOARD_ACCOUNT_HOMEBANNERS;

        try{

            if (isset($in["uuid"]) && $in["uuid"] !='' ){
                $in["uid"]=$in["uuid"];
            }

            $in["nocache"] = $in["nocache"] ?? false;
            $endpoint = "ACCOUNT-HOMEBANNERS-".str_replace("-", "_", $in["uid"]);
            if ($in["nocache"]) $this->deleteCache($endpoint);

            $out = $this->getCache($endpoint); // try find in cache
            $previous_banners = false;
            if (is_array($out) && count($out)> 0 /*&& is_array($out['result_list']) && count($out['result_list'])>0*/ ){
                $previous_banners = true;
            }


            if ( !$previous_banners ){
                $ret = $this->wrenchboard->wrenchboard_api($in, $out);
                $out['internal_return'] = $ret;
                log_message('critical', "usersBanners ********* ALL   ".serialize($out) );
                // dont cache junks
                if (is_array($out) /* && is_array($out['result_list']) && count($out['result_list'])>0 */) {
                    $this->saveCache($endpoint, $out, 1500);
                    $previous_banners = true;
                }
            }

            $extra_out["offers_list"] = $this->bannerGetOffers($in);
            $extra_out["activetaskslist"] = $this->bannerGetActiveTasks($in);

        } catch (Exception $e) {
            $errMsg =  ' BANNER DATA ERROR **** Caught exception: '.  $e->getMessage();
            log_message('critical', $errMsg);
        }


        return   $this->summaryReturnData($in,$out, $extra_out); //json_encode( $final_out );
    }
    public function apigate(){
        log_message('critical', "0001");
        header('Access-Control-Allow-Origin: *');
        log_message('critical', "WrenchBanners 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 'familybanners':
                $in["action"] = 'familybanners'; //WRENCHBOARD_ACCOUNT_JOBLIST;
                break;
        }

        if ( $call_backend ==  true  && $in["action"] !='' ){
            $local_url = "http://".$this->micro_service_net1.":3032/familybanners";
            $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 );
        return  $this->summaryReturnData($in,$out); //json_encode( $final_out );

    }

}