<?php

namespace App\Controllers;
use CodeIgniter\API\ResponseTrait;

class WrenchMedia extends BaseController
{
    protected $db;
    public $con_name = 'wrench_blog';
    use ResponseTrait;
    protected $request;
    public $savePath = WRENCHBOARD_UPLOAD_PATH;  // not in use

    public function __construct()
    {
        $this->request = $request = \Config\Services::request();
        //define('WRENCHBOARD_UPLOAD_PATH',    '/opt/wrenchboard/TEST/');
        $this->savePath= '/opt/wrenchboard/TEST/';
        $this->savePath= $this->getSiteConfigurations("system.primary_uploads"); // correct location

    }

    public function index()
    {
        $envID = getenv('ENV_ID');
    }

    public function endPointList(){

        $endpoints = [
            'getmedia' => ['POST'],
        ];

        return $endpoints;
    }

    const WRENCH_FILE_PROFILE   =    100;
    const WRENCH_FILE_MYFILE    =    200;
    const WRENCH_FILE_CONTRACTS =    300;
    const WRENCH_FILE_FAMILY    =    400;

    const WRENCH_FILE_FAMILYBANNER    =    410;
    const WRENCH_FILE_JOB       =    500;
    const WRENCH_FILE_JOBFILE    =   600;

    public function apigate(){
        log_message('critical', "Media gate Path GATE 001");
        $call_backend = false;
        $uriSegments = explode("/", parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH));
        $segLen  =  count($uriSegments);
        $micro_service_net1 =  $this->getSiteConfigurations("system.micro_service_net1"); //"10.10.10.120";

        if ( $segLen < 4 ){
            return;
        }
        log_message('critical', "Media gate Path GATE 002 - Segemtn Found");

        $sessionId =  $uriSegments[$segLen-3];
        $fileSection =  $uriSegments[$segLen-2];
        $fileUID =  $uriSegments[$segLen-1];

        $supportedSections = ['reward'=>10, 'profile'=>100,'myfile'=>200,'contracts'=>300,'family'=>400,'familybanner'=> WRENCH_FILE_FAMILYBANNER,'job'=>500, 'jobfile'=> 600];
        if (!array_key_exists($fileSection, $supportedSections)) {
            log_message('critical', "Media gate Path GATE 003 - Fail Segment Types");
            $file = FCPATH.'/assets/images/error.png';
            header('Content-Type: image/png');
            readfile($file);
            exit();
        }
        else{
           // echo "all good";
            log_message('critical', "Media gate Path GATE 003 - Pass Segment Types");
        }
        /*
        *
         *  VERIFY ALL PARAMETERS ARE GOOD
            #define WRENCH_FILE_PROFILE       100
            #define WRENCH_FILE_MYFILE        200
            #define WRENCH_FILE_CONTRACTS     300
            #define WRENCH_FILE_FAMILY        400
            #define WRENCH_FILE_JOB          500
        */

        /*
           if( $this->sessionCheckString($sessionId)== PHP_API_OK ){
               log_message('critical', "Media gate Path GATE 004 - Pass Session Test");
           }
           else{
           //     return 0;  for now - no session
               log_message('critical', "Media gate Path GATE 004 - Fail Session Test");
           }
      */
        log_message('critical', "Media gate Path GATE 005 - Ready to File File ****");

//        $file = FCPATH.'/assets/images/books.png';
//        // header('Content-Type: image/jpeg');
//        header('Content-Type: image/png');
//        readfile($file);
//
//        exit();


            $data = [
                'action' => WRENCHBOARD_GET_MEDIA,
                'sessionid' => $sessionId,
                'file_section' => $supportedSections[$fileSection],
                'file_uid' => $fileUID,
                'file_section_no' =>$supportedSections[$fileSection]
            ];

            if ($data["action"] !=''){
                $wrenchboard = new  \App\Models\BackendModel();
                $ret = $wrenchboard->wrenchboard_api($data, $out);
                $out['internal_return'] = $ret;
            }


        $selectedFile="";
        $selectedFile_CACHE_KEY='';
        $error_file ="error.png";

        switch($supportedSections[$fileSection]){
            case 10:
                $error_file ="error_reward.png";
                break;
            case WRENCH_FILE_CONTRACTS:
                // $thisContactFolder = $this->savePath.'CONTRACTS/'.$in["contract"];
                $selectedFile = $this->savePath.'CONTRACTS/'.$out["contract"]."/". $out["saved_file_name"];
                $selectedFile_CACHE_KEY= 'CONTRACTS-'.$out["contract"]."-". $out["saved_file_name"];
                $error_file ="contract_error.png";
                break;
            case WRENCH_FILE_PROFILE:
                ///opt/wrenchboard/TEST/PROFILE/3119b744-42ad-4834-bb83-b737588754ca/PORTRAIT
                $selectedFile = $this->savePath.'PROFILE/'.$out["member_uid"]."/PORTRAIT/". $out["saved_file_name"];
                $selectedFile_CACHE_KEY= 'PROFILE-'.$out["member_uid"]."-PORTRAIT-". $out["saved_file_name"];
                $error_file ="profile_error.png";
                break;

            case WRENCH_FILE_FAMILY:
                ///opt/wrenchboard/TEST/PROFILE/3119b744-42ad-4834-bb83-b737588754ca/FAMILY/3119b744-42ad-4834-bb83-b737588754ca/
                $selectedFile = $this->savePath.'PROFILE/'.$out["member_uid"]."/FAMILY/".$out["family_uid"]."/". $out["saved_file_name"];
                $selectedFile_CACHE_KEY= 'FAMILY-'.$out["member_uid"]."-FAMILY-".$out["family_uid"]."-". $out["saved_file_name"];
                $error_file ="family_error.png";
                break;
            case WRENCH_FILE_FAMILYBANNER:
                $selectedFile = $this->savePath.'PROFILE/'.$out["member_uid"]."/FAMBANNER/". $out["saved_file_name"];
                $selectedFile_CACHE_KEY= 'FAMILYBANNER-'.$out["member_uid"]."-FAMBANNER_". $out["saved_file_name"];
                $error_file ="familybanner_error.jpg";
                break;

            case WRENCH_FILE_MYFILE:
                $selectedFile = $this->savePath.'PROFILE/'.$out["member_uid"]."/MYFILES/". $out["saved_file_name"];
                $selectedFile_CACHE_KEY = 'PROFILE-'.$out["member_uid"]."-MYFILES_". $out["saved_file_name"];
                break;

            case WRENCH_FILE_JOB:
                $selectedFile = $this->savePath.'PROFILE/'.$out["member_uid"]."/JOBS/". $out["saved_file_name"];
                $selectedFile_CACHE_KEY = 'JOB-'.$out["member_uid"]."-JOBS-". $out["saved_file_name"];
                $error_file ="job_error.png";
                break;

            case WRENCH_FILE_JOBFILE:
                $selectedFile = $this->savePath.'TASKFILE/'.$out["job_uid"]."/". $out["saved_file_name"];
                $selectedFile_CACHE_KEY = 'JOBFILE-'.$out["job_uid"]."-". $out["uid"];
                $error_file ="job_error.png";
                break;
        }
        // MAKE SURE FOLDER AS PER PROCESS IS AVAILABLE
        log_message('critical', "wrenchboard_api-CALL MEDIA selectedFile DATA  --->     ".$selectedFile );
        $old_limit = ini_set( "memory_limit", "300M" );
       if ( $out["saved_file_name"] =='' || !file_exists( $selectedFile) && $selectedFile_CACHE_KEY !=''){
           log_message('critical', "wrenchboard_api-CALL MEDIA selectedFile DATA  ERROR NO FOUND--->     ".$selectedFile );

           $file = FCPATH.'/assets/images/'.$error_file;
           // header('Content-Type: image/jpeg');
           header('Content-Type: image/png');
           readfile($file);
        }
       else
       {
       log_message('critical', "BEFORE CACHE********* :: ".$selectedFile_CACHE_KEY);
       if (isset($selectedFile) && $selectedFile!=''){
           $selectedFile_CACHE_KEY  = str_replace("/\/", "_", $selectedFile_CACHE_KEY);
           $selectedFile_CACHE_KEY  = str_replace("-", "_", $selectedFile_CACHE_KEY);
           $selectedFile_CACHE_KEY  = str_replace(".", "_", $selectedFile_CACHE_KEY);
           $endpoint = "SECUREFILE-".$selectedFile_CACHE_KEY;
           $this->saveCache($endpoint,$out,10000);
       }


           log_message('critical', "FILE **************************   --->0003");
           $filename = basename($out["saved_file_name"]);
           $file_extension = strtolower(substr(strrchr($filename,"."),1));
           switch( $file_extension ) {
               case "gif": $ctype="image/gif"; break;
               case "png": $ctype="image/png"; break;
               case "jpeg":
               case "jpg": $ctype="image/jpeg"; break;
               case "svg": $ctype="image/svg+xml"; break;
               case "mp4": $ctype="application/octet-stream"; break;
               // case "mp4": $ctype="video/mp4"; break;
               default:
           }

           $LOAD_LOCAL =  false;
           $localF = array("gif", "png", "jpeg", "jpg", "svg");
           if (in_array( $file_extension, $localF)) {
               $LOAD_LOCAL = true;
           }


           log_message('critical', "AFTER CACHE*********");
            if (
                $supportedSections[$fileSection] == WRENCH_FILE_CONTRACTS 
                || $supportedSections[$fileSection] == WRENCH_FILE_MYFILE
                || $LOAD_LOCAL){
                   log_message('critical', "FILE **************************   --->0001");
                   if (file_exists($selectedFile)) {
                    log_message('critical', "FILE **************************   --->0002");
                    header('Content-Description: File Transfer');
                    header('Content-Type: application/octet-stream');
                    header('Content-Disposition: attachment; filename="'.basename($selectedFile).'"');
                    header('Expires: 0');
                    header('Cache-Control: must-revalidate');
                    header('Pragma: public');
                    header('Content-Length: ' . filesize($selectedFile));
                    readfile($selectedFile);
                    exit;
                }
                exit();
            }



           if( $file_extension) {
               $local_url = "http://".$micro_service_net1.":3036/myfile/".$out["flie_uid"];
               log_message('critical', "FILE URL =====  --->     ".$local_url );
               return ["aaaa"=>$local_url];
           }
           log_message('critical', "FILE **************************   --->0004");
           header('Content-type: ' . $ctype);
           readfile($selectedFile);
       }
        ini_set( "memory_limit", $old_limit );




       // exit();

//
//        $file = $selectedFile; // 'books.png';
//
//        if (file_exists($file)) {
//            header('Content-Description: File Transfer');
//            header('Content-Type: application/octet-stream');
//            header('Content-Disposition: attachment; filename="'.basename($file).'"');
//            header('Expires: 0');
//            header('Cache-Control: must-revalidate');
//            header('Pragma: public');
//            header('Content-Length: ' . filesize($file));
//            readfile($file);
//            exit;
//        }


    }


}
