<?php

namespace App\Controllers;

define('WRB_CRONJOB_JOBDUE_REMINDER',771);
define('WRB_CRONJOB_JOBDUE_PAYMENTS',772);
define('WRB_CRONJOB_SIGNUP_ALERT', 773);
define('WRB_CRONJOB_PASTDUE_ALERT',774);
define('WRB_CRONJOB_OFFER_REFUND_ALERT',775);
define('WRB_CRONJOB_PENDOFFER_ALERT',776);
define('WRB_CRONJOB_NOTIFICATIONS', 777) ;
define('WRB_CRONJOB_GROUPJOBS', 778);
define('WRB_CRONJOB_TESTNOTIFICATIONS', 779);
define('WRB_CRONJOB_SCHEULETRANSFER', 780);
define('WRB_CRONJOB_PROCESSTRANSFER', 781);
define('WRB_CRONJOB_APPEMAILS',       782);
define('WRB_CRONJOB_REFRESHBLOG', 783);
define('WRB_CRONJOB_PROCESS_VUSA', 784);

define('WRB_CRONJOB_AUTO_OFFEREXPIRE', 785);
define('WRB_CRONJOB_HOLIDAY_BROADCAST', 786);
define('WRB_CRONJOB_PROCESS_PROMO', 788);


define('WRB_CRONJOB_PENDINGSM', 790) ;

class AirFlow extends BaseController
{

    public function flowNewAccount(){

        $raw_json = file_get_contents('php://input');
        $in = json_decode($raw_json, true);
        $out =[];
        log_message('critical', "AirFlow::flowNewAccount ********* ALL   ".serialize($in) );
        return  []; //json_encode( $final_out );
    }

    public function flowRefreshResources(){

        $raw_json = file_get_contents('php://input');
        $in = json_decode($raw_json, true);
        $out =[];
        log_message('critical', "AirFlow::flowRefreshResources ********* ALL   ".serialize($in) );
        return  []; //json_encode( $final_out );
    }


    public function flowAppEmails(){
        $raw_json = file_get_contents('php://input');
        $in = json_decode($raw_json, true);
        $in["action"] = WRB_JOB_CRONJOB;  //WRB_CRONJOB_AUTO_OFFEREXPIRE
        $in["call_action"] =  WRB_CRONJOB_APPEMAILS;
        $out =[];
        log_message('critical', "AirFlow::flowAppEmails ********* ALL   ".serialize($in) );
        $ret['WRB_CRONJOB_APPEMAILS'] = (new  \App\Models\BackendModel())->wrenchboard_api($in, $out);
        return  []; //json_encode( $final_out );

    }
    public function flowHolidayBroadCast(){
        $raw_json = file_get_contents('php://input');
        $in = json_decode($raw_json, true);
        $in["action"] = WRB_JOB_CRONJOB;  //WRB_CRONJOB_AUTO_OFFEREXPIRE
        $in["call_action"] =  WRB_CRONJOB_HOLIDAY_BROADCAST;
        $out =[];
        log_message('critical', "AirFlow::flowOfferMissed ********* ALL   ".serialize($in) );
        $ret['WRB_CRONJOB_HOLIDAY_BROADCAST'] = (new  \App\Models\BackendModel())->wrenchboard_api($in, $out);
        return  []; //json_encode( $final_out );
    }
    public function flowOfferPending(){

        $raw_json = file_get_contents('php://input');
        $in = json_decode($raw_json, true);
        $out =[];
        log_message('critical', "AirFlow::flowOfferPending ********* ALL   ".serialize($in) );
        return $this-> offersreminders();
     //   return  []; //json_encode( $final_out );
    }

    public function flowDueReminder(){

        $raw_json = file_get_contents('php://input');
        $in = json_decode($raw_json, true);
        $out =[];
        log_message('critical', "AirFlow::flowDueReminder ********* ALL   ".serialize($in) );
        return $this->jobLevelAlerts();

      //  return  []; //json_encode( $final_out );
    }

    public function flowOfferMissed(){
        $raw_json = file_get_contents('php://input');
        $in = json_decode($raw_json, true);
        $in["action"] = WRB_JOB_CRONJOB;  //WRB_CRONJOB_AUTO_OFFEREXPIRE
        $in["call_action"] =  WRB_CRONJOB_AUTO_OFFEREXPIRE;
        $out =[];
        log_message('critical', "AirFlow::flowOfferMissed ********* ALL   ".serialize($in) );
        $ret['WRB_CRONJOB_AUTO_OFFEREXPIRE'] = (new  \App\Models\BackendModel())->wrenchboard_api($in, $out);
        return  []; //json_encode( $final_out );
    }

    public function flowInterestcount(){
        $raw_json = file_get_contents('php://input');
        $in = json_decode($raw_json, true);
        $out =[];
        log_message('critical', "AirFlow::flowInterestcount ********* CRON ");
        $in["action"] = "LOCAL_CALL_NO_ACTION";
        $endpoint = "WRENCH_JOB_INTEREST_COUNT";
        $res1 = $this->getCache($endpoint);
        if (count($res1)==0){
            $local_url = "http://".$this->micro_service_net1.":3033/interestCount";
            $out = $this->APIcall('GET', $local_url, $in);
            $this->saveCache($endpoint,$out,480);
        }
        return  []; //json_encode( $final_out );
    }



    public function flowStripeCard():array{
        log_message('critical', "AirFlow::flowStripeCard ********* IN CALL   " );
        $raw_json = file_get_contents('php://input');
        $in = json_decode($raw_json, true);
        $out =[];

        /* GET LIST IN THE LIMIT AT STATUS */
        $in['limit'] = 2;
        $in['status'] = CARD_REQUESTED;
        $local_url = "http://".$this->micro_service_net1.":3038/cardapplications";
        $out = $this->APIcall('POST', $local_url, $in);
        log_message('critical', "AirFlow::flowStripeCard ********* ALL   ".serialize($out) );
        foreach ($out['result_list'] as $index=>$item){
            if ( $item['request_id'] !='' && $item['request_uid'] !=''){
                $local_url = "http://".$this->micro_service_net1.":3038/createCardHolder";
                $out = $this->APIcall('POST', $local_url, $item);
            }
        }

        //LET US GET TEH AGREEMENT FIXED
        $in['limit'] = 2;
        $in['status'] = CARD_HOLDER_CREATED;  // pick from holders
        $local_url = "http://".$this->micro_service_net1.":3038/cardapplications";
        $outX = $this->APIcall('POST', $local_url, $in);
        log_message('critical', "AirFlow::flowStripeCard ********* ALL   ".serialize($outX) );
        foreach ($outX['result_list'] as $index=>$item){
            if ( $item['request_id'] !='' && $item['request_uid'] !=''){
                $item['aggrement_ip'] = '76.209.103.227';
                $local_url = "http://".$this->micro_service_net1.":3038/acceptterms";
                $out = $this->APIcall('POST', $local_url, $item);
            }
        }

        //LET US CREATE THE CARDS NOW
        $in['limit'] = 2;
        $in['status'] = CARD_OWNER_ACTIVE;  // pick from holders
        $local_url = "http://".$this->micro_service_net1.":3038/cardapplications";
        $outY = $this->APIcall('POST', $local_url, $in);
        log_message('critical', "AirFlow::flowStripeCard ********* ALL   ".serialize($outY) );
        foreach ($outY['result_list'] as $index=>$item){
            if ( $item['request_id'] !='' && $item['request_uid'] !=''){
                $item['aggrement_ip'] = '76.209.103.227';
                $local_url = "http://".$this->micro_service_net1.":3038/createcard";
                $out = $this->APIcall('POST', $local_url, $item);
            }
        }
        // work on the list

        //LET US ACTIVATE THE CARDS NOW
        $in['limit'] = 2;
        $in['status'] = CARD_ASSIGNED;  // pick from holders
        $local_url = "http://".$this->micro_service_net1.":3038/cardapplications";
        $outZ = $this->APIcall('POST', $local_url, $in);
        log_message('critical', "AirFlow::flowStripeCard ********* ALL   ".serialize($outZ) );
        foreach ($outZ['result_list'] as $index=>$item){
            if ( $item['request_id'] !='' && $item['request_uid'] !=''){
                $item['aggrement_ip'] = '76.209.103.227';
                $local_url = "http://".$this->micro_service_net1.":3038/activate";
                $out = $this->APIcall('POST', $local_url, $item);
            }
        }

        //LET US CREATE THE WALLET NOW
        $in['limit'] = 2;
        $in['status'] = CARD_ACTIVATE_CARD;  // pick from holders
        $local_url = "http://".$this->micro_service_net1.":3038/cardapplications";
        $outZ = $this->APIcall('POST', $local_url, $in);
        log_message('critical', "AirFlow::flowStripeCard ********* ALL   ".serialize($outZ) );
        foreach ($outZ['result_list'] as $index=>$in){
            if ( $in['request_id'] !='' && $in['request_uid'] !=''){
                $in["action"] =WRB_JOB_CRONJOB;
                $in['call_action'] = WRB_CRONJOB_PROCESS_VUSA;
                $in['one_limit'] = 3;
                 $this->wrenchboard->wrenchboard_api($in, $out);
            }
        }

        log_message('critical', "AirFlow::flowStripeCard ********* ALL   ".serialize($in) );
        return  []; //json_encode( $final_out );
    }
    public function flowApproveReminder(){

        $raw_json = file_get_contents('php://input');
        $in = json_decode($raw_json, true);
        $out =[];
        log_message('critical', "AirFlow::flowApproveReminder ********* ALL   ".serialize($in) );
        return  []; //json_encode( $final_out );
    }

    public function flowAutoMarket01(){

        $raw_json = file_get_contents('php://input');
        $in = json_decode($raw_json, true);
        $out =[];

        log_message('critical', "AirFlow::flowAutoMarket01 ********* ALL   ".serialize($in) );
        $in["loc"] = $_SERVER["REMOTE_ADDR"];
        $in['action'] = WRENCHBOARD_MARKET_PLAN01_START;
        $in['limit']     = 10;
        $ret['WRENCHBOARD_MARKET_PLAN01_START'] = (new  \App\Models\BackendModel())->wrenchboard_api($in, $out);
        return  []; //json_encode( $final_out );
    }

    public function flowProcessTransfer(){

        $raw_json = file_get_contents('php://input');
        $in = json_decode($raw_json, true);
        $out =[];
        log_message('critical', "AirFlow::flowProcessTransfer ********* ALL   ".serialize($in) );
        $in["loc"] = $_SERVER["REMOTE_ADDR"];
        $in['action'] = WRB_JOB_CRONJOB;
        $in['call_action'] = WRB_CRONJOB_PROCESSTRANSFER;
        $in['one_limit'] = 10; //remove this
        $in['limit']     = 10;
        $ret['WRB_CRONJOB_PROCESSTRANSFER'] = (new  \App\Models\BackendModel())->wrenchboard_api($in, $out);
        return  []; //json_encode( $final_out );
    }

    public function flowScheduleTransfer(){

        $raw_json = file_get_contents('php://input');
        $in = json_decode($raw_json, true);
        $out =[];
        // ALTER TABLE money_transfer ADD proc INT DEFAULT 0;
        // SELECT initiatingamount, status, added,proc FROM money_transfer WHERE added > (now() - interval '3000 minutes') AND status = 0 ORDER BY id DESC LIMIT 100;
        log_message('critical', "AirFlow::flowScheduleTransfer ********* ALL   ".serialize($in) );
        $in["loc"] = $_SERVER["REMOTE_ADDR"];
        $in['action'] = WRB_JOB_CRONJOB;
        $in['call_action'] = WRB_CRONJOB_SCHEULETRANSFER;

        $in['one_limit'] = 10; //remove this
        $in['limit']     = 10;
        $ret['WRB_CRONJOB_SCHEULETRANSFER'] = (new  \App\Models\BackendModel())->wrenchboard_api($in, $out);
        return  []; //json_encode( $final_out );
    }
    public function flowTestNotifications(){

        $raw_json = file_get_contents('php://input');
        $in = json_decode($raw_json, true);
        $out =[];
        log_message('critical', "AirFlow::flowTestNotifications ********* ALL   ".serialize($in) );
        $in["loc"] = $_SERVER["REMOTE_ADDR"];
        $in['action'] = WRB_JOB_CRONJOB;
        $in['call_action'] = WRB_CRONJOB_TESTNOTIFICATIONS;
        $in['one_limit'] = 10; //remove this
        $in['limit']     = 10;
        $ret['WRB_CRONJOB_TESTNOTIFICATIONS'] = (new  \App\Models\BackendModel())->wrenchboard_api($in, $out);
        return  []; //json_encode( $final_out );
    }

    public function flowPromoProcess(){
        log_message('critical', "***** ***** AirFlow::flowPromoProcess ****" );
        $raw_json = file_get_contents('php://input');
        $in = json_decode($raw_json, true);
        $out =[];
        log_message('critical', "AirFlow::flowPromoProcess ********* ALL   ".serialize($in) );
        $in["loc"] = $_SERVER["REMOTE_ADDR"]; //
        $in["action"] =WRB_JOB_CRONJOB;
        $in['call_action'] = WRB_CRONJOB_PROCESS_PROMO;
        $in['one_limit'] = 10; //remove this
        $in['limit']     = 10;
        $ret['WRB_CRONJOB_PROCESS_PROMO'] = (new  \App\Models\BackendModel())->wrenchboard_api($in, $out);
        return  []; //json_encode( $final_out );
    }
    public function flowSendNotifications(){

        $raw_json = file_get_contents('php://input');
        $in = json_decode($raw_json, true);
        $out =[];
        log_message('critical', "AirFlow::flowApproveReminder ********* ALL   ".serialize($in) );
        $in["loc"] = $_SERVER["REMOTE_ADDR"];
        $in["action"] =WRB_JOB_CRONJOB;
        $in['call_action'] = WRB_CRONJOB_NOTIFICATIONS;
        $in['one_limit'] = 10; //remove this
        $in['limit']     = 10;
        $ret['WRB_CRONJOB_NOTIFICATIONS'] = (new  \App\Models\BackendModel())->wrenchboard_api($in, $out);
        return  []; //json_encode( $final_out );
    }


    public function flowSignupReport(){

        $raw_json = file_get_contents('php://input');
        $in = json_decode($raw_json, true);
        $out =[];
        $in["action"] =WRB_JOB_CRONJOB;
       // $wrenchboard = new  \App\Models\BackendModel();
        $in['call_action'] = WRB_CRONJOB_SIGNUP_ALERT;
        $in['one_limit'] = 3;
       // $ret['WRB_CRONJOB_SIGNUP_ALERT'] = $wrenchboard->wrenchboard_api($in, $out);
        $ret['WRB_CRONJOB_SIGNUP_ALERT'] = (new  \App\Models\BackendModel())->wrenchboard_api($in, $out);
        // $out['internal_return'] = $ret;
        $out = $ret;
        log_message('critical', "AirFlow::flowSignupReport ********* ALL   ".serialize($in) );
        return  []; //json_encode( $final_out );
    }

    public function flowRefreshBlog(){
        $raw_json = file_get_contents('php://input');
        $in = json_decode($raw_json, true);
        $out =[];
        $endpoint = "WRENCH_BLOG_DATA";
        $res1 = $this->getCache($endpoint);
        if (count($res1)==0){
            $rawData = $this->apiData(0);
            $res1= $rawData['payload']; //[0]['payload'];
            $this->saveCache($endpoint,$res1);
        }

        $in['action'] = WRB_JOB_CRONJOB;
        $in['call_action'] = WRB_CRONJOB_REFRESHBLOG;


        foreach ( $res1['blograndom'] AS $item){
            $item['action'] = WRB_JOB_CRONJOB;
            $item['call_action'] = WRB_CRONJOB_REFRESHBLOG;
            $ret_update = (new  \App\Models\BackendModel())->wrenchboard_api($item, $outX);
        }
        log_message('critical', "AirFlow::flowRefreshBlog ********* ALL   ".serialize($in) );
        return  []; //json_encode( $final_out );
    }

    private function jobLevelAlerts(){
        $in["action"] =WRB_JOB_CRONJOB;
        $wrenchboard = new  \App\Models\BackendModel();

        $in['call_action'] = WRB_CRONJOB_JOBDUE_REMINDER;
        $in['one_limit'] = 3;
        $ret['WRB_CRONJOB_JOBDUE_REMINDER'] = $wrenchboard->wrenchboard_api($in, $out);

//
//        $in['call_action'] = WRB_CRONJOB_PENDOFFER_ALERT;
//        $in['one_limit'] = 3;
//        $ret['WRB_CRONJOB_PENDOFFER_ALERT'] = $wrenchboard->wrenchboard_api($in, $out);

        $in['call_action'] = WRB_CRONJOB_JOBDUE_PAYMENTS;
        $in['one_limit'] = 3;
        $ret['WRB_CRONJOB_JOBDUE_PAYMENTS'] = $wrenchboard->wrenchboard_api($in, $out);


        $in['call_action'] = WRB_CRONJOB_PASTDUE_ALERT;
        $in['one_limit'] = 3;
        $ret['WRB_CRONJOB_PASTDUE_ALERT'] = $wrenchboard->wrenchboard_api($in, $out);

        $in['call_action'] = WRB_CRONJOB_OFFER_REFUND_ALERT;
        $in['one_limit'] = 1;
        $ret['WRB_CRONJOB_OFFER_REFUND_ALERT'] = $wrenchboard->wrenchboard_api($in, $out);

        // $out['internal_return'] = $ret;
        $out = $ret;

        log_message('critical', "WrenchCrons ===> 0001");
        //$response = []; //json_decode($complete, true);
        return $this->response->setJson($out);
    }

    public function offersreminders(){
        log_message('critical', "WrenchCrons ===> offersreminders ******** 0001");
        $in["action"] =WRB_JOB_CRONJOB;
        $wrenchboard = new  \App\Models\BackendModel();

        $in['call_action'] = WRB_CRONJOB_PENDOFFER_ALERT;
        $in['one_limit'] = 10;
        $in['mode'] = 100;
        $ret['WRB_CRONJOB_PENDOFFER_ALERT_100'] = $wrenchboard->wrenchboard_api($in, $out);


        $in['call_action'] = WRB_CRONJOB_PENDOFFER_ALERT;
        $in['one_limit'] = 10;
        $in['mode'] = 200;  // 12 hours before expritation
        $ret['WRB_CRONJOB_PENDOFFER_ALERT_200'] = $wrenchboard->wrenchboard_api($in, $out);


        $in['call_action'] = WRB_CRONJOB_PENDOFFER_ALERT;
        $in['one_limit'] = 10;
        $in['mode'] = 300;  // 6h hours before expritation
        $ret['WRB_CRONJOB_PENDOFFER_ALERT_300'] = $wrenchboard->wrenchboard_api($in, $out);


        // $out['internal_return'] = $ret;
        $out = $ret;

        log_message('critical', "WrenchCrons ===> 0001");
        //$response = []; //json_decode($complete, true);
        return $this->response->setJson($out);
    }


    public function smTransmitProcess() {
        $proc = $this->input->get('proc');
        $sendmoney_id = $this->input->get('sendmoney_id');

        switch ($proc) {
            case 'TRANSMIT':
                $mysql = "SELECT m.id,mp.confirmation, m.added,"
                    . "'Transfer from '||me.firstname||' '||me.lastname||'<br>'||me.email AS narration,"
                    . "sr.firstname,sr.lastname,sr.account_no,be.code AS bank_code, m.initiatingamount*0.01 AS Amount,m.fee*0.01 AS Fee "
                    . "FROM money_transfer m "
                    . "LEFT JOIN members me ON me.id=m.member_id "
                    . "LEFT JOIN sendmoney_recipient sr ON sr.id=m.recipientid "
                    . "LEFT JOIN members_payments mp ON mp.what_sendmoney = m.id "
                    . "LEFT JOIN bank_entity_codes be ON be.code=sr.bank_code WHERE m.id=" . $sendmoney_id;

                $query = $this->db->query($mysql);
                $row = $query->row_array();
                /*
                  This is te place to call the Fluuerwve API for testing
                 */
                $this->load->helper('FlutterWave');
                $out = flutterwave_api($row);
                if (is_array($out) && $out['result'] > 0) {
                    $data["trans_code"] = $this->input->get('tcode');
                    $data["trans_tref"] = $this->input->get('tref');
                    $data["sendmoney_id"] = $sendmoney_id;
                    $data['action'] = WRENCHBOARD_SMONEY_BKOPROC;
                    $data['action_mode'] = SMONEY_PROCC_INTERSWITCH;
                    $this->load->model('backend_model');
                    $out = array();
                    $this->backend_model->wrenchboard_api($data, $out);  //THis calls he backend - dont worry about it for now.
                    echo $out['status'];
                } else {
                    if (is_array($out) && array_key_exists('status',$out)) {
                        echo $out['status'];
                    } else {
                        var_dump($out); // Unexpected failure
                    }
                }
                break;

            case 'CHECK':
                $mysql = "SELECT response -> 'data' -> 'data' AS \"data\" FROM flutterwave WHERE money_transfer_id=".((int)$sendmoney_id)." ORDER BY created DESC LIMIT 1";
                $query = $this->db->query($mysql);
                $row = $query->row_array();
                if (is_array($row) && count($row)>0) {
                    $this->load->helper('FlutterWave');
                    $data = json_decode($row['data'], true);
                    $out = flutterwave_api_check($data);
                    if (is_array($out) && $out['result'] > 0) {
                        echo $out['status'];
                    } else {
                        if (is_array($out) && array_key_exists('status',$out)) {
                            echo $out['status'];
                        } else {
                            var_dump($out); // Unexpected failure
                        }
                    }
                } else {
                    echo "No flutterwave transfer found!";
                }

                break;
        }
    }
}