<?php

namespace App\Controllers;
use CodeIgniter\API\ResponseTrait;
use CodeIgniter\Controller;
use CodeIgniter\HTTP\CLIRequest;
use CodeIgniter\HTTP\IncomingRequest;
use CodeIgniter\HTTP\RequestInterface;
use CodeIgniter\HTTP\ResponseInterface;
use Psr\Log\LoggerInterface;
use Exception;

//use CodeIgniter\Cache\CacheInterface;

/**
 * Class BaseController
 *
 * BaseController provides a convenient place for loading components
 * and performing functions that are needed by all your controllers.
 * Extend this class in any new controllers:
 *     class Home extends BaseController
 *
 * For security be sure to declare any new methods as protected or private.
 */
abstract class BaseController extends Controller
{
    /**
     * Instance of the main Request object.
     *
     * @var CLIRequest|IncomingRequest
     */
    protected $request;

    /**
     * An array of helpers to be loaded automatically upon
     * class instantiation. These helpers will be available
     * to all other controllers that extend BaseController.
     *
     * @var array
     */
    protected $helpers = [];
    private $cache_tag='NONE';

    private $cache_server;
    //private $cache_server='10.0.0.32';
    public  $current_env=0;
    public  $primary_image_sever='';
    public $server_tag='';
    public $wrenchboard=null;
    public $micro_service_net1;
    public $user_server_name ='';
    public $allSettings = [];

    public $show_extra_wallet = 0;
    /**
     * Constructor.
     */
    public function initController(RequestInterface $request, ResponseInterface $response, LoggerInterface $logger)
    {
        // Do Not Edit This Line
        parent::initController($request, $response, $logger);

        // Preload any models, libraries, etc, here.

        // E.g.: $this->session = \Config\Services::session();
        $this->cache_tag = $this->getSiteConfigurations("system.cache_tag");
        $this->wrenchboard = new  \App\Models\BackendModel();
        $this->current_env  = $this->getSiteConfigurations("system.live");
        $this->primary_image_sever = $this->getSiteConfigurations("system.primary_image_sever");
        $this->server_tag = $this->getSiteConfigurations("system.server_tag");
        $this->micro_service_net1 =  $this->getSiteConfigurations("system.micro_service_net1"); //"10.10.1
        $this->user_server_name =  $this->getSiteConfigurations("system.server_name"); // 'https://dev-users.wrenchboard.com';
        $this->show_extra_wallet =  $this->getSiteConfigurations("system.show_extra_wallet");

        $this->getSettings(''); // help create all settings data
//        $appConfig = config('Cache');
//        $appConfig->redis['host'] = $this->getSiteConfigurations("system.cache_host");
//        $this->cache_server =  cache()->initialize($appConfig);
//

       // var_dump($appConfig->redis['host']);
       // exit();
        //$this->cache_server = $this->getSiteConfigurations("system.cache_host");

//        $redis = [
//            'host'     => $this->cache_server,
//            'password' => '7f079034e166ecf52d82cbec9876e4dc8a154b0c37248f3fa1734d4eeab938d5',
//            'port'     => 6378,
//            'timeout'  => 0,
//            'database' => 0,
//            'prefix'  => 'WRB',
//        ];
//        //$this->load->driver('cache', $redis);

    }
    public function getIpData(){
        //$ip_loc="0.0.0.0";
        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'];
        }
        return $ip_loc;
    }



    public function saveCache($cacheKey,$data,$timeLine=5000){
        $cacheKey = $this->cache_tag."-".$cacheKey;
        // $cache = \Config\Services::cache();
        if (! $foo = cache($cacheKey)) {
            //  echo 'Saving to the cache!<br>';
            // cache()->save($cacheKey, $this->data_stringify($data), 3000);
            cache()->save($cacheKey, serialize($data), $timeLine);

            //serialize
        }
        $foo = cache()->get($cacheKey);
        //log_message('critical', "FROM Cache -> ".$foo );

    }

    public function getCache($cacheKey){
        $data = [];
        $cacheKey = $this->cache_tag."-".$cacheKey;
        if (cache($cacheKey)) {
            //   echo 'Getting Data From Cache!<br>';
            $data  = unserialize(cache()->get($cacheKey));
        }
        return $data;
    }

    public function deleteCache($cacheKey){
        $data = [];
        $cacheKey = $this->cache_tag."-".$cacheKey;
        try {
            if (cache($cacheKey)) {
                //   echo 'Getting Data From Cache!<br>';
                $data  = unserialize(cache()->delete($cacheKey));
            }
        } catch (Exception $e) {
            echo 'Caught exception: ',  $e->getMessage(), "\n";
        }

        return $data;
    }
    private function data_stringify($data) {
        switch (gettype($data)) {
            case 'string' : return '\''.addcslashes($data, "'\\").'\'';
            case 'boolean': return $data ? 'true' : 'false';
            case 'NULL'   : return 'null';
            case 'object' :
            case 'array'  :
                $expressions = [];
                foreach ($data as $c_key => $c_value) {
                    $expressions[] = $this->data_stringify($c_key).' => '.
                        $this->data_stringify($c_value);
                }
                return gettype($data) === 'object' ?
                    '(object)['.implode(', ', $expressions).']' :
                    '['.implode(', ', $expressions).']';
            default: return (string)$data;
        }
    }

    public function getSiteConfigurations($config_item){
        $wrenchboard = new  \App\Models\BackendModel();
        return  $wrenchboard->cfgReadChar($config_item);
    }

    public function specififBackendCall($action,$data){
        $in["action"] = $action;
        $wrenchboard = new  \App\Models\BackendModel();
        $ret = $wrenchboard->wrenchboard_api($data, $out);
        return $ret;
    }

    public function sessionCheckString($sessionid){
        $in["action"] = WRENCHBOARD_SESSION_CHECK;
        $in["sessionid"] = $sessionid;
        $in["member_id"] = 0; // just for capatibility
        $in["mode"] = 900;
        $wrenchboard = new  \App\Models\BackendModel();
        $ret = $wrenchboard->wrenchboard_api($in, $out);
        return $ret;
    }
    public function sessionCheck($sessionid,$member_id){
        $in["action"] = WRENCHBOARD_SESSION_CHECK;
        $in["sessionid"] = $sessionid;
        $in["member_id"] = $member_id;
        $in["mode"] = 0;
        $wrenchboard = new  \App\Models\BackendModel();
        $ret = $wrenchboard->wrenchboard_api($in, $out);
        return $ret;
    }
    public function endPointList(){

        $endpoints = [
            'apigate' => ['POST'],
            'generics' => ['POST'],
            'createuser' => ['POST'],
            'homebanners' => ['POST'],
            'verifysignuplink' => ['POST'],
            'completesignuplink' => ['POST'],
            'createmobileuser' => ['POST'],
            'completemobileuser' => ['POST'],
            'startresetpasword' => ['POST'],
            'stepresetpass' => ['POST'],
            'userlogin' => ['POST'],
            'qrlogin' => ['POST'],
            'authlogin' =>  ['POST'],
            'startjoblist' => ['POST'],
            'dashdata' => ['POST'],
            'getjobsdata' => ['POST'],
            'offerslist' => ['POST'],
            'offersresponse' => ['POST'],
            'activejoblist' => ['POST'],
            'loadprofile' => ['POST'],
            'updateprofile' => ['POST'],
            'account' => ['POST'],
            'message' => ['POST'],
            'jobmessage' => ['POST'],
            'cachecontacts'=> ['POST'],
            'pendingjob' => ['POST'],
            'paymenthx' => ['POST'],
            'purchasehx' => ['POST'],
            'getjob' => ['POST'],
            'mybanklist' => ['POST'],
            'countrybanks' =>['POST'],
            'sendmoney' => ['POST'],
            'sendinterest' => ['POST'],
            'waitinginterest' => ['POST'],
            'sendmoneyfee' => ['POST'],
            'getpendingjobs' => ['POST'],
            'taskmessage' => ['POST'],
            'sendtaskmessage' => ['POST'],
            'activejobmsglist' => ['POST'],
            'getwallets' => ['POST'],
            'sitecontact' => ['POST'],
            'signupcountry' => ['POST'],
            'userscards' => ['POST'],
            'blogdata' =>  ['POST'],
            'blogitem' =>  ['POST'],
            'couponhx' =>  ['POST'],
            'couponpending' =>  ['POST'],
            'couponredeem' =>  ['POST'],
            'sendinterestmessage' =>  ['POST'],
            'replyinterestmessage' => ['POST'],
            'disableaccount' => ['POST'],
            'myjobs' => ['POST'],
            'recipients' => ['POST'],
            'addrecipient' => ['POST'],
            'sendreferral' => ['POST'],
            'refferhx' => ['POST'],
            'accounttypes' => ['POST'],
            'jobmanageragree' => ['POST'],
            'jobmanagerlist' => ['POST'],
            'jobmanagerfiles' => ['POST'],
            'jobmanageroffers'=> ['POST'],
            'jobmanageractive'=> ['POST'],
            'jobmanagercreatejob'=> ['POST'],
            'jobmanagerupdatejob'=> ['POST'],
            'jobmanagerdeletejob'=> ['POST'],
            'jobgrouplist'=> ['POST'],
            'jobgroupadd'=> ['POST'],
            'groupmemberadd'=> ['POST'],
            'groupmemberdel'=> ['POST'],
            'activetaskslist' => ['POST'],
            'tasksreport' => ['POST'],
            'profilepasschange' => ['POST'],
            'starttopup' => ['POST'],
            'topupresult'=> ['POST'],
            'familylist' => ['POST'],
            'familywallet' => ['POST'],
            'familytransferstart' => ['POST'],
            'familyrewardhx' => ['POST'],
            'familybanners' => ['POST'],
            'familytransfer' => ['POST'],
            'familyadd' => ['POST'],
            'familyupdate' => ['POST'],
            'familymanage' => ['POST'],
            'pendingjobextend' => ['POST'],
            'pendingjobsendtome' => ['POST'],
            'pendingjobcancel' => ['POST'],
            'assigntask' => ['POST'],
            'assignmediatask' => ['POST'],
            'resources'=> ['POST'],
            'uploads'=> ['POST'],
            'marketmessage'=> ['POST'],
            'marketinterest'=> ['POST'],
            'activejobstatus'=> ['POST'],
            'activetaskstatus'=> ['POST'],
            'offersinterestlist' => ['POST'],
            'offersinterestproc' => ['POST'],
            'offerinterestmsg' => ['POST'],
            'offerinterestlistmsg' => ['POST'],
            'payprevcard' => ['POST'],
            'paynewcard' => ['POST'],
            'paylistcard' => ['POST'],
            'payremcard' => ['POST'],
            'mynotifications' => ['POST'],
            'familysampletasks' => ['POST'],
            'familysuggesttasks' => ['POST'],
            'familysuggestlist' => ['POST'],
            'familywaitingtasks' => ['POST'],
            'familyrelinvite' => ['POST'],
            'familyrellist' => ['POST'],
            'suggeststatus' => ['POST'],
            'startcredit' => ['POST'],
            'confirmcredit' => ['POST'],
            'setaccsettings' => ['POST'],
            'getaccsettings' => ['POST'],
            'mypageload' => ['POST'],
            'mypageintro' => ['POST'],
            'dashrecent' => ['POST'],
            'myfiles' => ['POST'],
            'reqdel' => ['POST'],
            'recentactivities' => ['POST'],
            'playground' => ['POST'],
            'preferences' => ['POST'],
            'setpreferences' => ['POST']
        ];
        return  $endpoints;
    }
    public function procOfferInterest($in) {
        $proc = $in['proc'];
        $in['interest'] = 0;
       if ( !isset($in["strict_timeline"]) ) {
            $in["strict_timeline"] =0;
        }
        switch ($proc) {
            case 'ACCEPT':
                $in['interest'] = JOB_INTEREST_ACCEPT;
                break;

            case 'REJECT':
                $in['interest'] = JOB_INTEREST_REJECT;
                break;

            case 'CANCEL':
                $in['interest'] = JOB_INTEREST_CANCEL;
                break;
        }
        $in["action"] =  WRENCHBOARD_JOB_PROC_INTEREST;
        return $in;

    }
    public function processJobStatus($data) {

        /*$data['member_id'] = $_SESSION['member_id']; // = $ret->email;
        $data['proc'] = $this->input->get('proc');
        $data['job_id'] = $this->input->get('jobID');
        $data['job_contract'] = $this->input->get('job_contract');
        $data['extension']
        */
       $incoming_job_action = $data['job_action'];

        $data['job_action'] = -1; // we dont know yet
        switch ($incoming_job_action) {
            case 'NOTIFY_COMPLETE':  // notify completed
                $data['job_action'] = CONTRACT_NOTIFY_COMPLETE;
                break;

            case 'NOTIFY_CANCEL':  // request cancel
            case 'REQUEST_CANCEL':  // request cancel
                $data['job_action'] = CONTRACT_REQUEST_CANCEL;
                break;

            case 'ACCEPT_COMPLETE':
                $data['job_action'] = CONTRACT_ACCEPT_COMPLETE;
                break;

            case 'REJECT_COMPLETE':
                $data['job_action'] = CONTRACT_REJECT_COMPLETE;
                break;

            case 'NOTIFY_REQEXTENT':
                $data['job_action'] = CONTRACT_REQUEST_TIMELINE;
                break;

            case 'EXTEND_TIMELINE':
                $data['job_action'] = CONTRACT_EXTEND_TIMELINE;
                break;

            case 'CANCEL_CONTRACT':
                $data['job_action'] = CONTRACT_CANCEL_CONTRACT;
                break;
        }
        $data['action'] = WRENCHBOARD_CONTRACT_STATUS;

        return $data;
    }

    public function doCacheStep($in, $out){

        switch ($in["action"]) {
            case WRENCHBOARD_ACCOUNT_LOGIN:
            case WRENCHBOARD_ACCOUNT_AUXLOGIN:
                if (isset($out["uid"]) && $out["uid"]!=''){
                    $endpoint = "SESSION-".$out["uid"];
                    $this->saveCache($endpoint,$out);
                }
                break;
        }
        //        $endpoint = "WRENCH_BLOG_DATA";
        //        $res1 = $this->getCache($endpoint);
        //        if (count($res1)==0){
        //            $rawData = $this->apiData();
        //            $res1= $rawData['payload']; //[0]['payload'];
        //            $this->saveCache($endpoint,$res1);
        //        }
        return 0;
    }

    public function sessionExcludedList(){

        $excludedPoint = [
            'apigate' => ['POST'],
            'generics' => ['POST'],
            'createuser' => ['POST'],
            'verifysignuplink' => ['POST'],
            'completesignuplink' => ['POST'],
            'createmobileuser' => ['POST'],
            'completemobileuser' => ['POST'],
            'startresetpasword' => ['POST'],
            'stepresetpass' => ['POST'],
            'userlogin' => ['POST'],
            'qrlogin' => ['POST'],
            'authlogin' =>  ['POST'],
            'startjoblist' => ['POST'],
            'sitecontact' => ['POST'],
            'signupcountry' => ['POST'],
            'blogdata' =>  ['POST'],
            'blogitem' =>  ['POST'],
        ];
        return  $excludedPoint;
    }

    public function APIcall($method, $url, $data) {
        if(!is_array($data)) $data =[]; //
        //  $curl = curl_init();
        $curl = curl_init($url);
        switch ($method) {
            case "GET":
                $params2 = '';
                foreach($data as $key2=>$value2)
                    $params2 .= $key2.'='.$value2.'&';

                $params2 = trim($params2, '&');
                $url = $url.'?'.$params2;// add param to URL
                log_message('critical', "API URL FINAL =>".$url );
                //curl_setopt($curl, CURLOPT_FRESH_CONNECT, true);
                //curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
                //curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($data));
                break;
            case "POST":
                curl_setopt($curl, CURLOPT_POST, 1);
                if ($data)
                  //  curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
                    curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($data));
                  //  curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($data));
                break;
            case "PUT":
                curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "PUT");
                if ($data)
                    curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
                break;
        }

        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_HTTPHEADER, array(
            'APIKEY: RegisteredAPIkey',
            'Content-Type: application/json',
        ));

        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
        $result = curl_exec($curl);

        if(!$result) {
            echo("Connection failure!");
        }
        curl_close($curl);
        return json_decode($result, true);
    }

    public function familyTypes(){
        return [
            array("ty"=>"Parent", "id"=>"PARENT", "tag"=>"fam_type_parent"),
            array("ty"=>"Relatives", "id"=>"RELATIVES", "tag"=>"fam_type_relatives"),
            array("ty"=>"Others", "id"=>"Others", "tag"=>"fam_type_others")
        ];
    }
    public function historyTypes(){
        return [
            array("ty"=>"Completed Jobs", "id"=>"COMPLETED_JOBS", "tag"=>"hist_type_completed_jobs"),
        ];
    }

    public function generativeTypes(){
        /*
        SELECT * from generative_activities;
 id |                 uid                  |        title         |               search_text                | status |           added
----+--------------------------------------+----------------------+------------------------------------------+--------+----------------------------
  1 | 4733e96b-7031-4684-bec3-f63da4417707 | General maths quiz   | create 10 maths questions with answers   |      1 | 2024-08-17 10:20:56.312351
  2 | 149b7a30-f089-48c3-b351-3eb90e417c4c | General science quiz | create 10 science questions with answers |      1 | 2024-08-17 10:21:08.790259
(2 rows)
wrenchboard=#
         */
        return [
            array("uid"=>"4733e96b-7031-4684-bec3-f63da4417707", "title"=>"General maths quiz"),
            array("uid"=>"149b7a30-f089-48c3-b351-3eb90e417c4c", "title"=>" General science quiz"),
        ];
    }
    public function summaryReturnData($in,$outResult, $extraOut=[]){
     //   log_message('critical', "summaryReturnData:: ********* IN   ".serialize($in) );
      //  log_message('critical', "summaryReturnData:: ********* OUT  ".serialize($outResult) );
        if ($in["action"] == -1 ){
            $final_out = $outResult;
        }
        else{
            $final_out = ( new \App\Models\ResultFormatter() )->processOutJson($in, $outResult);
        }

        if( isset( $extraOut['offers_list'])){
            $final_out["offers_list"] =  $extraOut['offers_list'];
        }

        if( isset( $extraOut['activetaskslist'])){
            $final_out["active_tasks_list"] =  $extraOut['activetaskslist'];
        }
        $final_out['user_server_name'] = $this->user_server_name;
        $final_out["environment"] =   $this->current_env + 0;
        $final_out["session_image_server"] =  $this->primary_image_sever;
        $final_out["server_tag"] =  $this->server_tag;
        $final_out["language"] = "en";
       //$final_out["ip_loc"] = $this->getIpData();
        $final_out["current_version"] = 20240306;
        $final_out["family_types"] = $this->familyTypes();
        $final_out["history_types"] = $this->historyTypes();
        $final_out["generative_types"] = $this->generativeTypes();
        $final_out["refer_link"] = "https://www.wrenchboard.com";
     //  log_message('critical', "summaryReturnData:: ********* FINAL OUT    ".serialize($final_out) );
          return json_encode( $final_out );
    }


    public function blogData($endpoint,$raw_array)
    {
        $res1 = $this->getCache($endpoint);
        if (count($res1)==0){
            $rawData = $this->apiData();
            $res1= $rawData['payload']; //[0]['payload'];
            $this->saveCache($endpoint,$res1);
        }
        return $res1;
    }

    protected $db;
    public $con_name = 'wrench_dockerblog'; // 'wrench_blog';

    protected function apiData($blog_id=0) :array {
        $this->db = \Config\Database::connect($this->con_name);
        $data = array();
        $extra_filter  = "";
        if ($blog_id > 0 ){
            $extra_filter  = " AND p1.id = $blog_id ";
        }

        try {
            $mysql = "SELECT  id, post_title, post_content,post_date,comment_count FROM wp_posts WHERE post_type='post' AND post_status = 'publish' ORDER BY post_date DESC LIMIT 9";
            $mysql = "SELECT p1.id AS id,  p1.*, wm2.meta_value FROM  wp_posts p1 LEFT JOIN   wp_postmeta wm1
            ON (wm1.post_id = p1.id AND wm1.meta_value IS NOT NULL AND wm1.meta_key = '_thumbnail_id' )    
            LEFT JOIN 
            wp_postmeta wm2
            ON (wm1.meta_value = wm2.post_id AND wm2.meta_key = '_wp_attached_file' AND wm2.meta_value IS NOT NULL   )
            WHERE
            p1.post_status='publish'
            AND p1.post_type='post' $extra_filter   
            ORDER BY p1.post_date DESC LIMIT 2000";

            log_message('critical', "BlogData Query -> ".$mysql );

            $query = $this->db->query($mysql);

            $data['payload']['blogdata'] = $query->getResult('array');
            $totalCount = count( $data['payload']['blogdata'] );

            $randomIndex =  rand(1, $totalCount);

            $data['payload']['featured']  =  $data['payload']['blogdata'][$randomIndex ];
            $data['payload']['blograndom'] = $this->BlogRandom();
            $data['payload']['image_url'] = 'https://blog.wrenchboard.com/wp-content/uploads/';
            $data['payload']['blog_url']  = 'https://blog.wrenchboard.com/';
            $data['payload']['total'] = $totalCount;
        } catch (Exception $ex) {

        }

        return $data;
    }

    private function BlogRandom(){

        $mysql ="
                SELECT p1.id AS blog_id,  p1.post_title AS title, 
                CONCAT('https://blog.wrenchboard.com/wp-content/uploads/',wm2.meta_value) AS banner FROM  wp_posts p1 LEFT JOIN   wp_postmeta wm1
                ON (wm1.post_id = p1.id AND wm1.meta_value IS NOT NULL AND wm1.meta_key = '_thumbnail_id' )    
                LEFT JOIN 
                wp_postmeta wm2
                ON (wm1.meta_value = wm2.post_id AND wm2.meta_key = '_wp_attached_file' AND wm2.meta_value IS NOT NULL   )
                WHERE
                p1.post_status='publish'
                AND p1.post_type='post' 
                ORDER BY RAND() DESC LIMIT 5
                ";
        log_message('critical', "BlogRandom Query -> ".$mysql );
        $query = $this->db->query($mysql);
        return $query->getResult('array');

    }

    protected function getSettings($settingkey, $defaultVal=''){
        $out=[];
        $in=[];
        $endpoint = "SETTINGS";
        $out = $this->getCache($endpoint);
        if (!is_array($out) || count($out)==0 ) {
            $local_url = "http://".$this->micro_service_net1.":3037/settings";
            $out = $this->APIcall('GET', $local_url, $in);
            if (count($out['result_list']) > 0 ){  // dont cache empty
                $this->saveCache($endpoint,$out,55500);
            }
        }

        if (is_array($out) && count($out['result_list']) > 0 ) {
            $this->allSettings =  $out['result_list'];
            foreach ($this->allSettings as $index => $item) {
                if ($item['name'] == $settingkey){
                    return $item['val'];
                }
            }
           // return  (isset($out['result_list'][$settingkey])) ? $out['result_list'][$settingkey]: $defaultVal;
        }
        return $defaultVal;
    }
}
