<?php

namespace App\Controllers;

class WrenchDashRecent extends BaseController
{

    public function apigate(){
        log_message('critical', "WrenchDashRecent-Gate");
        header('Access-Control-Allow-Origin: *');
        log_message('critical', "0002");
        $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'];
        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
            return json_encode([
                'message' => 'Endpoint not found.',
                'URI' => $uri,
            ]);
        }

        //  echo "EXYTACT INPUT DATA HERE";
        $raw_json = file_get_contents('php://input');
        $raw_array = json_decode($raw_json, true);
        log_message('critical', "WrenchDashRecent-Gate 003");
        $local_out =[];
        if ($_SERVER["REQUEST_METHOD"] == "POST") {  // if upload lets modify all the data
            if (isset($_FILES) && is_array($_FILES) && count($_FILES)>0)    {
                $raw_array = array_merge($_POST,$_FILES);
            }
        }
        log_message('critical', "WrenchDashRecent-Gate 004");
        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', "WrenchDashRecent-CALL RAW DATA".serialize($raw_array) );
        //-- move to another module start

        log_message('critical', "WrenchTransactions-Gate 005 ->".$endpoint);

        $in =  $this->rawDataToInData($raw_array);
        $in["loc"] = $_SERVER["REMOTE_ADDR"];
        log_message('critical', "WrenchDashRecent-CALL PREPARE DATA".serialize($in) );

        switch ($endpoint){

            case 'dashrecent':
                log_message('critical', "WrenchDashRecent-Gate 006 ->".$endpoint);
                $call_backend =  false;
                $this->dashRecent($in,$out);
               // $in["action"] = WRENCHBOARD_USER_STARTCREDIT;
                break;

            case 'confirmcredit':
                // Confrim
                break;
        }



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

        return json_encode( ( new \App\Models\ResultFormatter() )->processRecentOutJson($in, $out));
       // return $this->response->setJson($response);
    }

    public function processRecentOutJson($in, $out) {

        $action = $in["action"];
        switch($action){
            case WRENCHBOARD_FAMILY_SGGESTLIST:
            case WRENCHBOARD_FAMILY_SGGESTWAITING:
                $total = $out["total_record"];
                $res = array(
                    "status" => $out["status"],
                    "total_record" => ($total - 1),
                    "internal_return" => $out["internal_return"],
                    "result_list" => array(),
                );
                for ($i = 0; $i < $total; $i++) {
                    $key = sprintf("%05d", $i);
                    $status_no =  $out["status_${key}"];
                    $statusTxt  = $this->suggestedStatusText($status_no);
                    $res["result_list"][] = array(
                        "uid" => $out["uid_${key}"],
                        "family_uid" => $out["family_uid_${key}"],
                        "description" => $out["description_${key}"],
                        "title" => $out["title_${key}"],
                        "added" => $out["added_${key}"],
                        "status" => $out["status_${key}"],
                        "status_text" => $statusTxt ,
                        "banner" => $out["banner_${key}"],
                    );
                }
                break;

        }
        return $res;
    }
    private function dashRecent($in,$out){
       // $ret = 0;
        $in["action"] =  WRENCHBOARD_ACCOUNT_DASHRECENT; // WRENCHBOARD_FAMILY_SGGESTWAITING;
        $ret = $this->callBackEndData($in,$out);


        return $ret;
    }
    private function callBackEndData($in, $out){
        log_message('critical', "WrenchDashRecent-Gate 007 ->");
        $wrenchboard = new  \App\Models\BackendModel();
        $ret = $wrenchboard->wrenchboard_api($in, $out);
        $out['internal_return'] = $ret;
        return $ret;
    }
    private function rawDataToInData($in){


        return $in;
    }

}