<?php

namespace App\Controllers;

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

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

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

        //  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'){
              // we will not
            }
            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";
                //    $out['internal_return'] = PHP_INVALID_SESSION;
            }
        }
//#define WRENCHBOARD_ACCOUNT_PLAYGROUND       11201


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

        $out["layer_menu"] = [
            [
                "name"=>"Featured",
                "icon"=> "clock",
                "action" => "ni-idea",
                "tab" => "featured"
            ],
            [
                "name"=>"Collections",
                "icon"=> "clock",
                "action" => "ni-idea",
                "tab" => "collections"
            ],
            [
                "name"=>"Shared",
                "icon"=> "clock",
                "action" => "ni-idea",
                "tab" => "shared"
            ],
        ];

        $out["featured"][] =[
           "name" => "Your interest",
           "banner" => "If any banner is needed ",
           "item_list" =>  $this->apiFeaturedData()
        ];

        $out["collections"][] =[
            "name" => " There is name Collections",
            "banner" => "If any banner is needed ",
            "item_list" =>  $this->apiCollectionData()
        ];

        $out["shared"][] =[
            "name" => " There is name Shared",
            "banner" => "If any banner is needed ",
            "item_list" =>  $this->apiSharedData()
        ];

        $out["result_list"][] =[
            "name" => " There is name 3333",
            "banner" => "If any banner is needed ",
            "item_list" =>  $this->apiExtraData()
        ];
        $out["result_list"][] =[
            "name" => " There is name 3333",
            "banner" => "If any banner is needed ",
            "item_list" =>  $this->apiExtraData()
        ];
        $out["result_list"][] =[
            "name" => " There is name 3333",
            "banner" => "If any banner is needed ",
            "item_list" =>  $this->apiExtraData()
        ];


        $this->doCacheStep($in, $out);
        return json_encode( ( new \App\Models\ResultFormatter() )->processOutJson($in, $out));

    }
    private function prepareEndPointData($endpoint, $in, &$call_backend=true,&$local_out=[]){
        switch ($endpoint) {
            case 'playground':
                $in["action"] =  WRENCHBOARD_ACCOUNT_PLAYGROUND;
                break;
        }
        $in["pid"] = 100;
        return $in;
    }

    private function apiFeaturedData():array{
        $data=[];
        $data["item"][] = array(
            "banner" => "I have no idea",
            "media" => "http://commondatastorage.googleapis.com/gtv-videos-bucket/sample/BigBuckBunny.mp4",
            "title" => "Big Duck Bunny Animation",
            "description" => "Big Buck Bunny tells the story of a giant rabbit with a heart bigger than himself. <br> When one sunny day three rodents rudely harass him, something snaps... and the rabbit ain't no bunny anymore! In the typical cartoon tradition he prepares the nasty rodents a comical revenge.",
        );

        $data["item"][] = array(
            "banner" => "I have no idea",
            "media" => "http://commondatastorage.googleapis.com/gtv-videos-bucket/sample/ElephantsDream.mp4",
            "title" => "Elephant Dream",
            "description" => "The first Blender Open Movie from 2006",
        );

        $total = 1;
        for ($i = 0; $i < $total; $i++) {
            $key = sprintf("%05d", $i);
            $data["item"][] = array(
                "banner" => "I have no idea",
                "media" => "http://commondatastorage.googleapis.com/gtv-videos-bucket/sample/BigBuckBunny.mp4",
                "title" => "This Featured  dummy text ".$key,
                "description" => "Random gibberish text to use in web pages, site templates and in typography demos. Get rid of Lorem Ipsum forever. A tool for web designers who want to save time. ".$key,
            );
        }
        return $data;
    }

    private function apiSharedData():array {
        $data=[];
        $total = 0;
        for ($i = 0; $i < $total; $i++) {
            $key = sprintf("%05d", $i);
            $data["item"][] = array(
                "banner" => "I have no idea",
                "title" => "This Shared  dummy text ".$key,
                "description" => "Random gibberish text to use in web pages, site templates and in typography demos. Get rid of Lorem Ipsum forever. A tool for web designers who want to save time. ".$key,
            );
        }
        return $data;
    }
    private function apiCollectionData():array {
        $data=[];
        $total = 0;
        for ($i = 0; $i < $total; $i++) {
            $key = sprintf("%05d", $i);
            $data["item"][] = array(
                "banner" => "I have no idea",
                "title" => "This Collection  dummy text ".$key,
                "description" => "Random gibberish text to use in web pages, site templates and in typography demos. Get rid of Lorem Ipsum forever. A tool for web designers who want to save time. ".$key,
            );
        }
        return $data;
    }

    private function apiExtraData():array {
        $data = [];
        $total = rand(1,3);
        for ($i = 0; $i < $total; $i++) {
            $key = sprintf("%05d", $i);
            $data["item"][] = array(
                "banner" => "I have no idea",
                "title" => "This is faq title dummy text ".$key,
                "description" => "Random gibberish text to use in web pages, site templates and in typography demos. Get rid of Lorem Ipsum forever. A tool for web designers who want to save time. ".$key,
            );
        }
        return $data;
    }

}
