<?php

namespace App\Controllers;

use CodeIgniter\HTTP\RequestInterface;
use CodeIgniter\API\ResponseTrait;

class WrenchApi extends BaseController
{
    use ResponseTrait;
    protected $request;
    public function __construct()
    {
        $this->request = $request = \Config\Services::request();
    }
    public function index()
    {
        return [];
    }

    /*
   this.usrData = {action:22010,
          member_id: this.sessionDataProviderService.member_id,
          uid: this.sessionDataProviderService.member_uid,
          sessionid: this.sessionDataProviderService.session ,
          raw_contacts: contactResult }
"name":{"family":"Higgins","prefix":"","given":"Daniel","suffix":"Jr.","display":"Daniel Higgins Jr.","middle":""},
"contactId":"AB211C5F-9EC9-429F-9466-B9382FF61035",
 */
    private function processContacts( $in ){
        log_message('critical', "************************ cachecontacts   0001   ".serialize($in));

        $inx =[];
        $inx["member_id"] = $in["member_id"];
        $inx["uid"] = $in["uid"];
        $inx["sessionid"] = $in["sessionid"];
        $raw_contacts = $in["raw_contacts"];

        foreach ( $raw_contacts["contacts"] as $rows){
            $firstname =  $rows["name"]["given"];
            $lastname =  $rows["name"]["family"];
            $contactid =  $rows["contactId"];
            log_message('critical', "************************ $firstname   $lastname   $contactid");
        }
    }
    private function prepareEndPointData($endpoint, $in, &$call_backend=true,&$local_out=[]){
        switch ($endpoint) {
            case 'mypageload':
                $in["action"] =  WRENCHBOARD_ACCOUNT_MYPAGE;
                break;
            case 'mypageintro':
                $in["action"] =  WRENCHBOARD_ACCOUNT_PAGEINTRO;
                break;
            case 'preferences':
                $in["action"] =  WRENCHBOARD_ACCOUNT_PREFERENCES;
                //preferences // define('WRENCHBOARD_ACCOUNT_PREFERENCES',      11065);
                break;
            case 'setpreferences':
                $in["action"] =   WRENCHBOARD_ACCOUNT_UPDATE_PREFS;
                break;
            case 'cachecontacts':
                log_message('critical', "************************ cachecontacts   0001   ".serialize($in));
                $this->processContacts( $in );

                break;
            case 'myfiles':
                $in["action"] =  WRENCHBOARD_MYFILES_LIST;
                break;
            case 'setaccsettings':
                $in["action"] =  WRENCHBOARD_USER_SETTINGS;
                break;
            case 'getaccsettings':
                $in["action"] =  WRENCHBOARD_GETUSER_SETTINGS;
                break;

            case 'mynotifications':
                $in["action"] =  WRENCHBOARD_ACCOUNT_NOTIFICATIONS;
                break;
            case 'payprevcard':
                $in["action"] =  WRENCHBOARD_USER_USESAVEDCC;
                break;
            case 'paynewcard':
                $in["action"] =  WRENCHBOARD_USER_ADNEWCC;
                break;
            case 'paylistcard':
                $in["action"] =  WRENCHBOARD_USER_CARDLIST;
                break;
            case 'payremcard':
                $in["action"] =  WRENCHBOARD_USER_CARDREMV;
                break;
            case 'offerinterestmsg':
                $in["action"] =  WRENCHBOARD_JOB_MRKTINT_QUEST;
                break;
            case 'offerinterestlistmsg':
                $in["action"] =  WRENCHBOARD_JOB_INT_QUESTLST;
                break;
            case 'offersinterestproc':
                $in = $this->procOfferInterest($in);
                break;
            case 'offersinterestlist':
                $in["action"] =  WRENCHBOARD_JOB_OFFER_INTLIST;
                break;
            case 'activejobstatus':
            case 'activetaskstatus':
                $in = $this->processJobStatus($in);
                break;
            case 'marketmessage':
                $in["action"] =  WRENCHBOARD_JOB_SEND_QUESTION;
                break;

            case 'marketinterest':
                $in["action"] =  WRENCHBOARD_JOB_SEND_INTEREST;
                break;

            case 'assignmediatask':
            case 'assigntask':
                $in["bypass"] = 0;
                $in["action"] =  WRENCHBOARD_JOB_OFFER_SYSTEM;
                break;

            case 'pendingjobextend':
                $in["action"] =  WRENCHBOARD_JOB_EXTEND_EXPIRE;
                break;

            case 'pendingjobsendtome':
                $in["action"] =  WRENCHBOARD_JOB_RESEND_MESSAGE;
                break;

            case 'pendingjobcancel':
                $in["action"] =  WRENCHBOARD_JOB_CANCEL_OFFER;
                break;
            case 'familysampletasks':
                $in["action"] =  WRENCHBOARD_FAMILY_SAMPLETASKS;
                break;
            case 'familysuggesttasks':
                if (!isset($in["banner"])){
                    $in["banner"] = 'default.jpg';
                }
                $in["action"] =  WRENCHBOARD_FAMILY_SGGESTTASKS;
                break;
            case 'familywaitingtasks':
                $in["action"] =  WRENCHBOARD_FAMILY_SGGESTWAITING;
                break;
            case 'familysuggestlist':
                $in["action"] =  WRENCHBOARD_FAMILY_SGGESTLIST;
                break;
            case 'familyrelinvite':
                $in["action"] = WRENCHBOARD_FAMILY_RELINVITE;
                break;
            case 'familyrellist':
                $in["action"] = WRENCHBOARD_FAMILY_RELLIST;
                break;
            case 'suggeststatus':
                $in["action"] =  WRENCHBOARD_FAMILY_SGGESTSTATUS;
                break;
            case 'familylist':
                $in["action"] =  WRENCHBOARD_FAMILY_LIST;
                break;

            case 'familywallet':
                $in['action'] = WRENCHBOARD_FAMILY_WALLET;
                break;

            case 'familytransferstart':
                $in['action'] = WRENCHBOARD_FAMILY_TRANSFERSTART;
                break;

            case 'familytransfer':
                $in['action'] = WRENCHBOARD_FAMILY_TRANSFER;
                break;
            case 'familybanners':
                $call_backend = false;

                $local_out = [
                    'result'=>'100',
                    'data'=> $this->childBanners()
                ];

              //  $local_out["result_list"] = $this->childBanners();
               // $local_out["result_list777777"] = $this->childBanners();
                break;

            case 'familyrewardhx':
                $in['action'] =  WRENCHBOARD_FAMILY_TRANSFERHX;
                break;

            case 'activetaskslist':
                $in["action"] =  WRENCHBOARD_JOB_USERACTIVE;
                break;
            case 'tasksreport':
                $in["action"] =  WRENCHBOARD_JOB_REPORT;
                break;
            case 'familyadd':
                $in["action"] =  WRENCHBOARD_FAMILY_ADD;
                break;

            case 'familyupdate':
                $in["action"] =  WRENCHBOARD_FAMILY_UPDATE;
                break;

            case 'familymanage':
                $in["action"] =  WRENCHBOARD_FAMILY_MANAGE;
                break;
            case 'jobmanageractive':
                $in["job_mode"] = $in["job_mode"] ?? "ACTIVE";
                $in["action"] =  WRENCHBOARD_JOB_ACTIVE;
                break;
            case 'jobmanagercreatejob':
                $in["action"] =  WRENCHBOARD_JOB_CREATEJOB;
                $in["job_mode"] = ADD_JOB;
                break;
            case 'jobmanagerupdatejob':
                $in["action"] =  WRENCHBOARD_JOB_CREATEJOB;
                $in["job_mode"] = UPDATE_JOB;
                break;
            case 'jobmanagerdeletejob':
                $in["action"] =  WRENCHBOARD_JOB_DELETEJOB;
                break;
            case 'jobmanageroffers':
                $in["action"] =  WRENCHBOARD_JOB_OFFERS;
                break;
            case 'stepresetpass':
                if($in['step']==300){
                    $in["action"] =  WRENCHBOARD_COMPLETE_PASSWORDRESET;
                }
                if($in['step']==200){
                    $in["action"] =  WRENCHBOARD_VERIFY_PASSWD_RESETLINK;
                }
                break;
            case 'starttopup':
                $in["action"] =  WRENCHBOARD_ACCOUNT_PREPARE_TOPUP;
                break;
            case 'topupresult':
                $in["action"] =  WRENCHBOARD_ACCOUNT_TOPUP_RESULT;
                break;
            case 'profilepasschange':
                $in["action"] =  WRENCHBOARD_PROFILE_RESETPASS;
                break;
            case 'addrecipient':
                $in["action"] =  WRENCHBOARD_ACCOUNT_ADD_RECIPEINT;
                break;
            case 'jobmanageragree':
                $in["action"] =  WRENCHBOARD_JOB_POSTAGREE;
                break;
            case 'jobmanagerfiles':
                $in["action"] = 13012; // WRENCHBOARD_JOB_JOBFILES; -- cannot get contsants to work
                break;
            case 'jobmanagerlist':
                $in["action"] =  WRENCHBOARD_JOB_LISTJOBS;
                break;
            case 'jobgrouplist':
                $in["action"] =  WRENCHBOARD_JOB_JOBGROUPS;
                break;
            case 'jobgroupadd':
                // WRENCHBOARD_JOB_JOBGROUPADD
                $in["action"] =  WRENCHBOARD_JOB_CREATE_GROUP;
               // $in["action"] =  0;
                break;
            case 'groupmemberadd':
                $in["action"] =  WRENCHBOARD_JOB_GROUP_MEMBER;
                break;
            case 'groupmemberdel':
                $in["action"] =  WRENCHBOARD_JOB_DELETE_GROUPMEMBER;
                break;
            case 'homebanners':
                $in["action"] =  WRENCHBOARD_ACCOUNT_HOMEBANNERS ;
                break;
            case 'verifysignuplink':
                $in["action"] =  WRENCHBOARD_VERIFY_PENDING_LINK ;
                break;
            case 'disableaccount':
                $in['action'] = WRENCHBOARD_USER_DELETEACC;
                break;
            case 'replyinterestmessage':
                $in["action"] =  WRENCHBOARD_JOB_REPLY_QUESTION;
                break;
            case 'sendinterestmessage':
                // $in['offer_code'] = $this->input->get('offer_code');
                $in['yourmessage'] = $in["question"];
                //$in['member_id'] = $_SESSION['member_id']; // just maing sure
                $in['msg_type'] = 'JOB';
                // $in['action'] = WRENCHBOARD_JOB_SEND_QUESTION;

                $in["action"] = WRENCHBOARD_JOB_SEND_QUESTION;
                break;
            case 'couponredeem':
                $in["action"] = WRENCHBOARD_COUPON_REDEEM;
                break;
            case 'couponpending':
                $in["action"] = WRENCHBOARD_COUPON_PENDLIST;
                break;
            case 'couponhx':
                $in["action"] = WRENCHBOARD_COUPON_MEMLIST;
                break;
            case 'signupcountry':
                $in["action"] = WRENCHBOARD_SIGNUP_COUNTRY;
                // checi if in cache if not read
                $local_out = [
                    'result'=>'100',
                    'signup_country'=>[
                        ['NG', 'Nigeria'],
                        ['US', 'United States']
                    ]
                ];
               // $call_backend =  true; we will call backend
                break;
            case 'blogitem':
                $blogData = (new \App\Models\ResultFormatter() )->getBlogItem();
                $local_out = [
                    'result'=>'100',
                    'blog_data'=> $blogData
                ];
                $call_backend =  false;
                break;
            case 'blogdata':
                $blogData = (new \App\Models\ResultFormatter() )->getBlogData();
                $local_out = [
                    'result'=>'100',
                    'blog_data'=> $blogData
                ];
                $call_backend =  false;
                break;
            case 'userscards':
                $in["action"] =  WRENCHBOARD_CARDS_GETCARDLIST;
                $local_out = [
                    'result'=>'100',
                    'result_list'=>[
                        ['title'=>'This is your coupon',
                            'description'=>'This is the description of the description',
                            'card_type'=>'COUPON',
                            'card_style' =>'card1',
                            'card_icon' =>'icon1',
                            'assign_id'=> 0,
                            'Nigeria'],
                        ['title'=>'A Recommended Story',
                            'description'=>'This is the description of the description',
                            'card_type'=>'BLOG',
                            'card_style' =>'card2',
                            'card_icon' =>'icon1',
                            'assign_id'=> 0,
                            'United States'],
                        ['title'=>'You have a new task sent to you',
                            'description'=>'This is the description of the description',
                            'card_type'=>'NEWTASK',
                            'card_style' =>'card1',
                            'card_icon' =>'icon1',
                            'assign_id'=> 0,
                            'United States'],
                        ['title'=>'You just Earned some token',
                            'description'=>'This is the description of the description',
                            'card_type'=>'TOKEN',
                            'card_style' =>'card2',
                            'card_icon' =>'icon1',
                            'assign_id'=> 0,
                            'United States']
                    ]
                ];
                // $call_backend =  false;

                break;
            case 'myjobs': $in["action"] = WRENCHBOARD_ACCOUNT_JOBLIST;
                break;
            case 'sitecontact':
                $local_out =  ['result'=>'100','msg'=>'Received'];
                $call_backend =  false;
                break;
            case 'generics':
            case 'apigate':
                //$in["action"] = WRENCHBOARD_ACCOUNT_LOGIN;
                break;
            case 'startjoblist': $in["action"] = WRENCHBOARD_START_JOBLIST;
                if (!array_key_exists("limit",$in)) $in["limit"] = 10;
                if (!array_key_exists("page",$in))  $in["page"]  = 1;
                break;

            case 'createmobileuser': $in["action"] = WRENCHBOARD_CREATE_MOBILEUSER;
                $in["loc"] = $_SERVER["REMOTE_ADDR"];
                $in["news"] = 0;
                $in["terms"] = 1;
                $in["mobile"] = "MOBILE";
                break;
            case 'completesignuplink': $in["action"] = WRENCHBOARD_COMPLETE_MOBILEUSER;
                $in["loc"] = $_SERVER["REMOTE_ADDR"];
                $in["news"] = 0;
                $in["terms"] = 1;
                $in["mobile"] = "WEB";
                break;
            case 'completemobileuser': $in["action"] = WRENCHBOARD_COMPLETE_MOBILEUSER;
                $in["loc"] = $_SERVER["REMOTE_ADDR"];
                break;

            case 'startresetpasword':
                $in["action"] = WRENCHBOARD_RESET_PASSWORD;
                $in["rloc"] =  'WRENCHBOARD_RESET_PASSWORD'.rand(1000,9999);
                break;
            case 'createuser': $in["action"] = WRENCHBOARD_ACCOUNT_PENDING;
                $in["street1"] = $in["streetaddress"];
                $in["zipcode"] = $in["zip"];
                if (!isset($in["country"]) || $in["country"]==""){
                    $in["country"] = "US";
                }
                $in["loc"] = $_SERVER["REMOTE_ADDR"];
                $in["mobile"] = "MOBILE";
                break;
            case 'activejoblist': $in["action"] = WRENCHBOARD_MOBILE_ACTIVEJOB;
                break;
            case 'message': $in["action"] = WRENCHBOARD_MOBILE_MESSAGE;

                break;
            case 'jobmessage':
                $in["action"] = WRENCHBOARD_MOBILE_JOB_MESSAGE;
                break;
            case 'paymenthx': $in["action"] = WRENCHBOARD_MOBILE_PAYMENTHX;

                break;
            case 'purchasehx':  $in["action"] = WRENCHBOARD_MOBILE_PURCHASEHX;
                break;
            case 'getjobsdata': $in["action"] = WRENCHBOARD_ACCOUNT_JOBLIST;
                break;

            case 'qrlogin':
                $in["action"] = WRENCHBOARD_ACCOUNT_QRLOGIN;
                $in["login_mode"] = MOBILE_LOGIN;
                $pieces = explode("@", $in['username']);
                if ( count($pieces) == 3 ){
                    $in['member_uid'] = $pieces[0];
                    $in['member_username'] = $pieces[1];
                    $in['family_uid'] = $pieces[2];
                }
                log_message('critical', "************************ qrlogin   0001   ".$in['member_uid']);
                break;
            case 'userlogin': $in["action"] = WRENCHBOARD_ACCOUNT_LOGIN;
                    if (!isset($in["login_mode"])){
                        $in["login_mode"] = MOBILE_LOGIN;
                    }
                break;
            case 'authstart': 
                $externalOAuth2 = new \App\Models\ExternalOAuth2Model();
                $in["loc"] = $_SERVER["REMOTE_ADDR"];
                $in = $externalOAuth2->prepareOauthEndPointData($endpoint, $in, $call_backend, $local_out);
                // $in["action"] must be set by prepareOauthEndPointData call
            break;
            case 'dashdata': $in["action"] = WRENCHBOARD_ACCOUNT_DASHDATA;
                break;
            case 'offerslist': $in["action"] = WRENCHBOARD_MOBILE_OFFERSLIST;
                break;

            case 'offersresponse': $in["action"] = WRENCHBOARD_MOBILE_OFFERSRESP;
                break;

            case 'loadprofile': $in["action"] = WRENCHBOARD_MOBILE_LOADPROFILE;
                break;
            case 'updateprofile': $in["action"] = WRENCHBOARD_MOBILE_UPDATEPROFILE;
                break;
            case 'account': $in["action"] = WRENCHBOARD_MOBILE_ACCOUNT;
                break;
            case 'getpendingjobs':
                $in["action"] = WRENCHBOARD_ACCOUNT_PENDJOB;
                break;
            case 'pendingjob':

                break;
            case 'getjob':

                break;

            case 'mybanklist':$in["action"] = WRENCHBOARD_USER_GETBANKLIST;
                break;
            case 'sendmoney':$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"];
                break;
            case 'sendinterest':$in["action"] = WRENCHBOARD_USER_SENDJOBINT;
                $out["internal_return"] = 0;
                break;
            case 'waitinginterest':
                $in["action"] = WRENCHBOARD_JOB_WAITING_INT;
                break;
            case 'sendmoneyfee': $in["action"] = WRENCHBOARD_SMONEY_PROCFEE;
                break;
            case 'taskmessage': $in["action"] = WRENCHBOARD_MOBILE_TASKMESSAGE;
                break;
            case 'sendtaskmessage': $in["action"] = WRENCHBOARD_MOBILE_SENDTASKMESSAGE;
                break;
            case 'activejobmsglist':
                $in["action"] =  WRENCHBOARD_CONTRACT_MSGLIST;
                break;
            case 'getwallets': $in["action"] = WRENCHBOARD_ACCOUNT_WALLETS;
                break;
            case WRENCHBOARD_ACCOUNT_PRICE_COMBO:    break ;  //    11171);
            case WRENCHBOARD_ACCOUNT_JOBPOST_DURATION:    break ;  //11173);
            case 'recipients': $in["action"] = WRENCHBOARD_ACCOUNT_USER_RECIPEINT;  break;  // 11175);
            case 'accounttypes': $in["action"] = WRENCHBOARD_ACCOUNT_ACCOUNT_TYPES;    break ;  //  11177);
            case WRENCHBOARD_ACCOUNT_COUNTRY_COMBO:    break ;  //  11179);
            case WRENCHBOARD_ACCOUNT_JOB_COUNTRY:    break ;  //    11181);
            case 'sendreferral': $in["action"] =WRENCHBOARD_ACCOUNT_SENDREFER;  break;
            case 'refferhx': $in["action"] =WRENCHBOARD_ACCOUNT_REFFERHX; break;
            case 'countrybanks':    $in["action"] =WRENCHBOARD_ACCOUNT_COUNTRY_BANKS; break;
            case 'reqdel':
                // some actions
                break;
            case 'recentactivities':
               $in["action"] =  WRENCHBOARD_ACCOUNT_RECENTS;
            break;
        }
        $in["pid"] = 100;
        return $in;
    }
    public function apigate(){
        log_message('critical', "0001");
        header('Access-Control-Allow-Origin: *');
        log_message('critical', "MainApi Path GATE 001");
        $call_backend =  true;
        /*
        //header("Access-Control-Allow-Origin: http://localhost:9057 ");
        header('Access-Control-Expose-Headers: Access-Control-Allow-Origin');
        //header('Access-Control-Allow-Credentials: true ');
        //header("Access-Control-Allow-Headers: Cache-Control, Pragma, Origin, Authorization, Content-Type, X-Requested-With");
        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');
        header('Access-Control-Allow-Methods: POST, GET, PUT, DELETE, OPTIONS');
        header('Content-type: application/json');
        */

        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'];

//        if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
//            $ip_loc = $_SERVER['HTTP_CLIENT_IP'];
//        } elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
//            $ip_loc = $_SERVER['HTTP_X_FORWARDED_FOR'];
//        } else {
//            $ip_loc = $_SERVER['REMOTE_ADDR'];
//        }

        $ip_loc  = $this->getIpData();

        if ($method == "OPTIONS") {
            header("HTTP/1.1 200 OK CORS");
            log_message('critical', " apigate()-> 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");

        //  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"] == "POST") {  // if upload lets modify all the data
            if ( $endpoint == 'uploads'){

                try {

                    log_message('critical', "ENDPOINT TESTING UPLOAD-> ".$endpoint );
                    $local_out=["step_msg"=>'Yes the upload endpoint was started ********'];
                    $call_backend = false; // will be decided after file is saved
                    //$fl_in=[];
                    $raw_json = file_get_contents('php://input');
                    $raw_array = json_decode($raw_json, true);
                    $raw_array["call_backend"] = $call_backend;
                    $raw_array["system_primary_uploads"] = $this->getSiteConfigurations("system.primary_uploads");
                    $out = ( new \App\Models\UploadManager() )->reciveUpload($raw_array, $local_out);
                    $local_out=["step_msg"=>'Yes the upload endpoint was completed ********'];

                    $call_backend = $out["call_backend"];
                    $in["message"] = $raw_array["message"] =  $out["message"];
                    //$raw_array["file_data"] = $out['file_data'] = $in['file_data'] ="";  // no need to carry raw file data anymore - saved or cached ath this point
                    if (is_array($raw_array) && array_key_exists("file_data", $raw_array)) unset($raw_array["file_data"]);
                    if (is_array($out) && array_key_exists("file_data", $out)) unset($out["file_data"]);
                    if (is_array($int) && array_key_exists("file_data", $in)) unset($in["file_data"]);
                } catch (Exception $e) {
                    $error =  'Caught exception: '.  $e->getMessage();
                    log_message('critical', "ERROR ENDPOINT TESTING UPLOAD-> ".$error );
                }

            }
            if (isset($_FILES) && is_array($_FILES) && count($_FILES)>0)    {
                $raw_array = array_merge($_POST,$_FILES);
            }
        }

        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;
        //log_message('critical', "wrenchboard_api-CALL RAW DATA".serialize($raw_array) );
        //-- move to another module start


        $in["loc"] = $_SERVER["REMOTE_ADDR"];
        $in  = $this->prepareEndPointData($endpoint, $raw_array,$call_backend,$local_out);
       // log_message('critical', "wrenchboard_api-CALL PREPARE DATA".serialize($in) );

        $ecludedEndpoints =  $this->sessionExcludedList();
        $out = array();
        $res1 = [];
        if (!array_key_exists($endpoint, $ecludedEndpoints)) {
        // we need to check session now
            if ( $this->sessionCheck($in["sessionid"],$in["member_id"]) != PHP_API_OK){
                $call_backend = false;
                $local_out["status_msg"] = "invalid_session_msg";
                $local_out['internal_return'] = "-9999"; // PHP_INVALID_SESSION;
              //  log_message('critical', "***** ***** wrenchboard_api-CALL sessionCheck FAIL".serialize($local_out) );
                return json_encode( $local_out );
            }
        }

        if ( $call_backend ==  true  && $in["action"] !='' ){
           // $wrenchboard = new  \App\Models\BackendModel();
            $ret = $this->wrenchboard->wrenchboard_api($in, $out);
            $out['internal_return'] = $ret;
        }
        else
        {
            $out =  $local_out;
        }

        $this->doCacheStep($in, $out);
//        $final_out = ( new \App\Models\ResultFormatter() )->processOutJson($in, $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["session_image_server"] = "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;
//        $final_out["current_version"] = 20240306;
//        $final_out["family_types"] = $this->familyTypes();
//        $final_out["history_types"] = $this->historyTypes();
//        //return json_encode( ( new \App\Models\ResultFormatter() )->processOutJson($in, $out));
        return  $this->summaryReturnData($in,$out); //json_encode( $final_out );

    }

    private function childBanners(): array
    {
        $bannerArray = array(
            "pending" => [
                'banner' => [
                    'image'=> 'bannerimage.png',
                    'icon'=> 'bannerimage.icon',
                    'style'=> 'style1',
                    'text'=> 'This is Banner Main text',
                ]
            ],
            "current" => [
                'banner' => [
                    'image'=> 'bannerimage.png',
                    'icon'=> 'bannerimage.icon',
                    'style'=> 'style2',
                    'text'=> 'This is Banner Main text',
                ]
            ],
            "recommend" => [
                'banner' => [
                    'image'=> 'bannerimage.png',
                    'icon'=> 'bannerimage.icon',
                    'style'=> 'style3',
                    'text'=> 'This is Banner Main text',
                ]
            ],
            "another1task" => [
                'banner' => [
                    'image'=> 'bannerimage.png',
                    'icon'=> 'bannerimage.icon',
                    'style'=> 'style4',
                    'text'=> 'This is Banner Main text',
                ]
            ],
            "pastdue" => [
                'banner' => [
                    'image'=> 'bannerimage.png',
                    'icon'=> 'bannerimage.icon',
                    'style'=> 'style5',
                    'text'=> 'This is Banner Main text',
                ]
            ],
        );

        return $bannerArray;
    }


}
