Untitled

mail@pastecode.io avatar
unknown
plain_text
2 years ago
65 kB
3
Indexable
Never
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);


class Apiv2 extends CI_Controller{

    public function __construct(){
        parent::__construct();
    }

    public function index_get(){
        echo '404 NOT FOUND';
    }
    
    public function get_active_device(){
        $file = file_get_contents('php://input');
        $json = json_decode($file, true);
        if ($json['apikey'] == 'we4567talk') {
            $wa_host = $json['host'];
            $wa_port = $json['port'];
            $url_server = $wa_host.":".$wa_port;
            $device = $this->data->gets("device", "where status = 'active' and enabled = 1 and url_server = '$url_server'", "device.id as id, device.name as name, device.scan_request as scan_request, device.scan as scan");
            $data_response = null;
            if(!is_null($device)){
                $data_response = array(
                    'status'  => 'ok',
                    'message' => 'Message Received',
                    'data' => $device
                );
            }else {
                $data_response = array(
                    'status'  => 'failed',
                    'message' => 'No device found',
                    'data' => ""
                );
            }
            echo json_encode($data_response);   
        }
    }



    

    public function save_message(){
        $file = file_get_contents('php://input');
        $json = json_decode($file, true);
        echo "--start save_message-- apikey";
        print_r($file);
        print_r($json);
        echo "--end save_message--";

        if ($json['apikey'] == 'we4567talk') {
            $type = $json['data']['type'] ? $json['data']['type'] :"";

            $message_id   = isset($json['data']['message_id'])  ? $json['data']['message_id'] : "";
            $related_message_id   = isset($json['data']['related_message_id'])  ? $json['data']['related_message_id'] : "";
            $from = $json['data']['from'];
            $to   = $json['data']['to'];
            $author   = isset($json['data']['author'])  ? $json['data']['author'] : "";

            $customer_name   = isset($json['data']['customer_name'])  ? $json['data']['customer_name'] : "";
            $message   = isset($json['data']['message'])  ? $json['data']['message'] : "";
            
            $timestamp   = isset($json['data']['timestamp'])  ? $json['data']['timestamp'] : "";
            $device_type   = isset($json['data']['device_type'])  ? $json['data']['device_type'] : "";
            
            $client   = isset($json['client'])  ? $json['client'] : "";

            $device = $this->data->get('device', "WHERE name = '$json[client]'");
            $device_number = $this->fx->deviceNumber($device->info);
            $user_id = $device->user_id;
            $message_inbound = "";
            $data_message = "";

            

            if(!isset($device)){
                $data_response = array(
                    'status'  => 'FAIL',
                    'message' => 'device no detected',
                    'data_raw' => ""
                );
                
                echo json_encode($data_response);
                return null;
            }

            $customer = $this->fx->checkNewNumber($user_id, $from, $customer_name);
            if ($type == 'text') {
                $data_message = array(
                    'message_id'         => $message_id,
                    'device_id'          => $device->id,
                    'user_id'            => $device->user_id,
                    'related_message_id' => $related_message_id,
                    'type'               => $type,
                    'sender'             => $from,
                    'receiver'           => $to,
                    'message'            => $this->fx->check_message($message),
                    'status'             => 'receiver',
                    'author'             => $author,
                    'created'            => date("Y-m-d H:i:s", $timestamp),
                    'device_type'            => $device_type,
                );
            }
            
            if ($type == 'list_response') {
                $selected_row_id  = isset($json['data']['selected_row_id'])  ? $json['data']['selected_row_id'] : "";
                $selected_row_title  = isset($json['data']['selected_row_title'])  ? $json['data']['selected_row_title'] : "";
                $selected_row_description  = isset($json['data']['selected_row_description'])  ? $json['data']['selected_row_description'] : "";

                // ubah status is_chat_with_bot

                $id_customer = $this->fx->getIdByPhone($from);             
                $data_statics = $this->data->gets('static_list_item',"where status = 'active' order by sort ASC");
                
                foreach ($data_statics as $static){             
                    $title =  $static->title;
                    $is_chat_with_bot = $static->is_chat_with_bot;  
                    
                    if ($title == $selected_row_title  && $is_chat_with_bot == 1 )
                    {
                        
                        // $customer_title = $static->title ;
                        $data_update  = array(
                            'status' => 'Received',
                            'is_chat_with_bot' => 1,
                        );
                        $this->data->update('customer', $data_update, $id_customer);
                    }
                }
                


                $data_message = array(
                    'message_id'         => $message_id,
                    'device_id'          => $device->id,
                    'user_id'            => $device->user_id,
                    'related_message_id' => $related_message_id,
                    'type'               => $type,
                    'sender'             => $from,
                    'receiver'           => $to,
                    'message'            => $this->fx->check_message($selected_row_title),
                    'status'             => 'receiver',
                    'author'             => $author,
                    'created'            => date("Y-m-d H:i:s", $timestamp),
                    'device_type'            => $device_type,
                    'list_selected_row_id'            => $selected_row_id,
                    'list_selected_title'            => $selected_row_title,
                    'list_selected_description'            => $selected_row_description,
                );
                // print_r($data_message);
                // die();
            }

         
            
            
            // $message_inbound_id = 10;
            $is_chat_with_bot = $this->custChatWith($from);

            if ($is_chat_with_bot == 0){
                $message_inbound = $this->data->set("message_inbound", $data_message);
                $message_inbound_id = $message_inbound->id;
                $this->fx->bot_message($client, $from, $type, $message, $customer_name, $message_inbound_id);
            }

            $data_title_static = $this->data->get('static_list_item',"Where is_chat_with_bot = '$is_chat_with_bot'");

            //untuk greeting start chat
            if ($is_chat_with_bot == 1 && $selected_row_title == $data_title_static->title ){
                $message_inbound = $this->data->set("message_inbound", $data_message);
                $message_inbound_id = $message_inbound->id;
                $this->fx->bot_message($client, $from, $type, $message, $customer_name, $message_inbound_id);
            }
            //untuk live chat
            if ($is_chat_with_bot == 1){
                $this->fx->live_message($client, $from, $type, $message, $customer_name, $message_inbound_id);
            }

            $data_response = array(
                'status'  => 'OK',
                'message' => 'Message Received',
                'data_raw' => $data_message
            );
            echo json_encode($data_response);




             //static reply
            // if ($selected_row_title == 'Hubungkan Ke Customer Service' && $is_chat_with_bot == 1){
            //     $message = 'Admin akan membalas silakan ditunggu ya';
            //     $this->fx->bot_message($client, $from, $type, $message, $customer_name, $message_inbound_id);

            // }
           

           
            
            
            
        
            
            // $this->pusher_add($user_id, $customer_name, $from, $type, $message);
            // $device = $this->data->get('device', "JOIN user ON device.user_id = user.id WHERE device.name = '$client'", "user.url_chat");
            // if (!is_null($device) && !is_null($device->url_chat)) {
            //     $param_sendz = array(
            //         'device'          => $client,
            //         'message_id'         => $message_id,
            //         'related_message_id' => $related_message_id,
            //         'type'               => $type,
            //         'sender'             => $from,
            //         'receiver'           => $to,
            //         'message'            => $message,
            //         'author'             => $author,
            //         'created'            => $timestamp,
            //     );
            //     $response = $this->fx->send_api($device->url_chat, $param_sendz);
            // }
                     
            // if ($type == 'text') {
            //     $this->fx->bot_message_donasi($client, $from, $type, $message);
            // }

            


            // if ($type == 'text' || $type == 'media' || $type == 'location') {
                // if($diffSession > 1){
                //     echo "old sesion";
                //     $this->fx->bot_message($client, $from, $type, $message);
                // }else {
                //     echo "new session";
                //     $this->fx->bot_message_greeting($client, $from, $type, $message);
                // }
            // }
            
            
        }else{
            echo $file;
            
        }
    }




    public function saveOutbound(){
        $file = file_get_contents('php://input');
        $json = json_decode($file, true);
        // echo "--start save_message outbound--";
        // print_r($json);
        $data =  isset($json['data']) ? $json['data'] : "";
        $type =  isset($data['type']) ? $data['type'] : "";
        $from =  isset($data['from']) ? $data['from'] : "";
        $to =  isset($data['to']) ? $data['to'] : "";

        $from = explode("@", $from)[0];
        $to = explode("@", $to)[0];

        $inbound_id =  isset($data['inbound_id']) ? $data['inbound_id'] :  "";
        $autoreplyId =  isset($data['autoreply_id']) ? $data['autoreply_id'] : "";
        $messageTimestamp =  isset($data['message_timestamp']) ? $data['message_timestamp'] : "";
        
        $_data =  isset($data['_data']) ? $data['_data'] : "" ;
        $_data_id =  isset($_data['id'])  ? $_data['id'] : "";
        $message_id =  isset($_data_id['id']) ? $_data_id['id'] : "";
        $from_me =  isset($_data_id['fromMe']) ? $_data_id['fromMe'] : "";

        $list =  isset($_data['list']) ? $_data['list'] : "" ;
        $list_sections =  isset($list['sections']) ? $list['sections'] : "";
        // echo '>> from_me'.$from_me.'<<'; 
        // echo '>>autoreplyId '.$autoreplyId.'<<'; 
        // echo '>>message_id '.$message_id.'<<'; 
        // print_r(json_encode($list));
        
        if($type == 'image'){
            
        }
        if($type == 'list'){

        }

        if(isset($from_me)){
            $data_message = array(
                'message_inbound_id'  => $inbound_id,
                'autoreply_id'      => $autoreplyId,
                'message_id'     => $message_id,
                'sender'         => $from,
                'receiver'       => $to,
                'list_sections'       => json_encode($list_sections),
                // 'status'         => 'sender', kolom status ga akan digunakan
                'created'        => date("Y-m-d H:i:s"),
                'message_timestamp'        => $messageTimestamp,
            ); 
            $this->data->set('message_outbound', $data_message);
            $dataResponse = array(
                'success'  => true,
                'message' => 'save outbound ok',
            ); 
            echo json_encode($dataResponse);
        }

        // echo "--end save_message outbound--";
    }


    public function getPusherKey(){
        $file = file_get_contents('php://input');
        $json = json_decode($file, true);
        $clientDeviceId = $json['client_device_id'] != "" || $json['client_device_id'] != null ? $json['client_device_id'] : "";
        
        $data = $this->data->get("client_device", "WHERE id = $clientDeviceId");

        $pusherChannel = $data->pusher_channel;
        $pusherKey = $data->pusher_key;

        $dataResponse = array(
            'success'  => true,
            'message' => 'OK',
            'data' => [
                'pusherKey' => $pusherKey,
                'pusherChannel' => $pusherChannel
            ]
        ); 

        echo json_encode($dataResponse);
    }



    public function delete(){
        $file = file_get_contents('php://input');
        $json = json_decode($file, true);
        $key = $json['access_key'] != "" || $json['access_key'] != null ? $json['access_key'] : "";
        $client = $json['device_name'] != "" || $json['device_name'] != null ? $json['device_name'] : "";
        $this->clientDevice->checkAccesKey($key); 
        $device = $this->clientDevice->checkDeviceName($client);

        //load outbound


    }

    public function saveOutboundAnswer(){

        $file = file_get_contents('php://input');
        $json = json_decode($file, true);

        // echo "--start save_message outbound--";
        $data =  isset($json['data']) ? $json['data'] : "";
        $type =  isset($data['type']) ? $data['type'] : "";
        $from =  isset($data['from']) ? $data['from'] : "";
        $to =  isset($data['to']) ? $data['to'] : "";
        $step = isset($data['step'])? $data['step'] : 0;
        $questionId = isset($data['autoreply_id']) ? $data['autoreply_id'] :  0;

        $from = explode("@", $from)[0];
        $to = explode("@", $to)[0];

        $inbound_id =  isset($data['inbound_id']) ? $data['inbound_id'] :  "";
        $autoreplyId =  isset($data['autoreply_id']) ? $data['autoreply_id'] : "";
        $messageTimestamp =  isset($data['message_timestamp']) ? $data['message_timestamp'] : "";
        
        $_data =  isset($data['_data']) ? $data['_data'] : "" ;
        $_data_id =  isset($_data['id'])  ? $_data['id'] : "";
        $message_id =  isset($_data_id['id']) ? $_data_id['id'] : "";
        $from_me =  isset($_data_id['fromMe']) ? $_data_id['fromMe'] : "";

        $list =  isset($_data['list']) ? $_data['list'] : "" ;
        $list_sections =  isset($list['sections']) ? $list['sections'] : "";
        // echo '>> from_me'.$from_me.'<<'; 
        // echo '>>autoreplyId '.$autoreplyId.'<<'; 
        // echo '>>message_id '.$message_id.'<<'; 
        // print_r(json_encode($list));
        

        if(isset($from_me)){
            $data_message = array(
                'message_inbound_answer_id' => $inbound_id,
            );
            
            $this->data->set('message_outbound_answer', $data_message);
            $dataResponse = array(
                'success'  => true,
                'message' => 'save outbound ok',
            ); 
            echo json_encode($dataResponse);
        }
    }

    public function saveInboundAnswer(){
        $file = file_get_contents('php://input');
        $json = json_decode($file, true);

        print_r("JSON SAVEINBOUND ANSWER");
        print_r($json);
        // die();
        

        if ($json === "" || $json === null) {
            return;
        }

        $key = $json['access_key'] != "" || $json['access_key'] != null ? $json['access_key'] : "";
        $client = $json['device_name'] != "" || $json['device_name'] != null ? $json['device_name'] : "";
        $this->clientDevice->checkAccesKey($key); 
        $device = $this->clientDevice->checkDeviceName($client);

        $type = $json['data']['type'] ? $json['data']['type'] : "";
        $message_id   = isset($json['data']['message_id'])  ? $json['data']['message_id'] : "";
        $related_message_id   = isset($json['data']['related_message_id'])  ? $json['data']['related_message_id'] : "";
        $from = $this->fx->phoneCleaning($json['data']['from'], "@"); 
        $author   = isset($json['data']['author'])  ? $json['data']['author'] : ""; 
        $customerName   = isset($json['data']['customer_name'])  ? $json['data']['customer_name'] : "";
        $message   = isset($json['data']['message'])  ? $json['data']['message'] : "";
        $timestamp   = isset($json['data']['timestamp'])  ? $json['data']['timestamp'] : "";
        $flowType = isset($json['data']['flow_type']) ? $json['data']['flow_type'] : "";
        $locLat = isset($json['data']['latitude']) ? $json['data']['latitude'] : "";
        $locLng = isset($json['data']['longitude'])  ? $json['data']['longitude'] : "";
        $locName = isset($json['data']['loc_name']) ? $json['data']['loc_name'] : "";
        $locAddress = isset($json['data']['loc_address'])  ? $json['data']['loc_address'] : "";



        $to = $this->fx->phoneCleaning($device->client_device_phone, ":");
        $clientDeviceId = $device->client_device_id;
        $adminDeviceId = $device->admin_device_id;
        $data_message = "";

         // Blokir no device sebagai sender
         $noDevices = $this->data->gets("client_device", "WHERE status = 1");
         foreach ($noDevices as $nd) {
             $noDevice = $nd->phone;
             if ($from == $noDevice) {
                 return;
             }
         }

        $customer = $this->customer->check($adminDeviceId, $from, $customerName);
        $customerIsRegis = $customer->is_register;

        if ($type == 'text') {  
            $rawData = $this->messageInbound->prepareForText($message_id, $clientDeviceId, $from, $to, $message, $timestamp);
            $data = json_decode($rawData);
            $data_message = $data->data_message;
        }elseif ($type == 'current_location') {
            $rawData = $this->messageInbound->prepareForCurrentLocationNasional($message_id, $clientDeviceId, $from, $to, $locLat, $locLng, $locName, $locAddress, $timestamp);
            $data = json_decode($rawData);
            $data_message = $data->data_message;
        }

        $dataInboundAnswer = [
            'type' => $data_message->type,
            'message' => isset($data_message->message) ? $data_message->message : "",
            'sender' => $data_message->sender,
            'receiver' => $data_message->receiver,
            'loc_lat' => isset($data_message->loc_lat) ? $data_message->loc_lat : 0,
            'loc_lng' => isset($data_message->loc_lng) ? $data_message->loc_lng : 0,
            'loc_name' => isset($data_message->loc_name) ? $data_message->loc_name : "",
            'loc_address' => isset($data_message->loc_address) ? $data_message->loc_address : "",
            'created' => date("Y-m-d H:i:s"),
            'updated' => date("Y-m-d H:i:s"),
        ];
        $inboundAnsware = $this->data->set("message_inbound_answer", $dataInboundAnswer);
        $inboundAnsware = json_decode($inboundAnsware);
        
        $inboundAnswareData = $inboundAnsware->data;

        if($customerIsRegis == null){
            // Belum registrasi
            print_r("Belum Regis");
        
            $this->fx->processAutoreplyNasional($device, $inboundAnswareData, $customerName);
        }else{
            // Sudah registrasi
            $this->fx->processAutoreplyIsRegis($device, $inboundAnswareData, $customerName);
        }

            
    }

    public function saveInbound(){
        
        $file = file_get_contents('php://input');
        $json = json_decode($file, true);

        if ($json === "" || $json === null) return;


        $response = array();

        $key = $json['access_key'] != "" || $json['access_key'] != null ? $json['access_key'] : "";
        $client = $json['device_name'] != "" || $json['device_name'] != null ? $json['device_name'] : "";
        $this->clientDevice->checkAccesKey($key); 
        $device = $this->clientDevice->checkDeviceName($client);

        $type = $json['data']['type'] ? $json['data']['type'] :"";
        $message_id   = isset($json['data']['message_id'])  ? $json['data']['message_id'] : "";
        $related_message_id   = isset($json['data']['related_message_id'])  ? $json['data']['related_message_id'] : "";
        $from = $this->fx->phoneCleaning($json['data']['from'], "@"); 
        $author   = isset($json['data']['author'])  ? $json['data']['author'] : ""; 
        $customerName   = isset($json['data']['customer_name'])  ? $json['data']['customer_name'] : "";
        $message   = isset($json['data']['message'])  ? $json['data']['message'] : ""; 
        $caption   = isset($json['data']['caption'])  ? $json['data']['caption'] : ""; 
        $fileType   = isset($json['data']['filetype'])  ? $json['data']['filetype'] : ""; 
        $fileName   = isset($json['data']['media_origin_filename'])  ? $json['data']['media_origin_filename'] : ""; 
        $timestamp   = isset($json['data']['timestamp'])  ? $json['data']['timestamp'] : ""; 
        $locLat   = isset($json['data']['latitude'])  ? $json['data']['latitude'] : ""; 
        $locLng   = isset($json['data']['longitude'])  ? $json['data']['longitude'] : ""; 
        $locName   = isset($json['data']['loc_name'])  ? $json['data']['loc_name'] : ""; 
        $locAddress   = isset($json['data']['loc_address'])  ? $json['data']['loc_address'] : ""; 
        $b64   = isset($json['data']['b64'])  ? $json['data']['b64'] : "";

        $selected_row_id  = isset($json['data']['selected_row_id'])  ? $json['data']['selected_row_id'] : "";
        $selected_row_title  = isset($json['data']['selected_row_title'])  ? $json['data']['selected_row_title'] : "";
        $selected_row_description  = isset($json['data']['selected_row_description'])  ? $json['data']['selected_row_description'] : "";

        // Blokir no device sebagai sender yang sesuai komunitas nya
        $clientIdCommunity = $this->data->get("client_device", "left join device on device.id = client_device.device_id WHERE device.name = '$client'", "client_id");
        $clientIdCommunity = $clientIdCommunity->client_id;
      
        $noDevices = $this->data->gets("client_device", "WHERE status = 1 AND client_id = '$clientIdCommunity'");
        foreach ($noDevices as $nd) {
            $noDevice = $nd->phone;
            if ($from == $noDevice) {
                return;
            }
        }

        $to = $this->fx->phoneCleaning($device->client_device_phone, ":");
        $clientDeviceId = $device->client_device_id;
        $adminDeviceId = $device->admin_device_id;
        $clientId = $device->client_id;
        $media_name = $from . "_" . $to . "_" . time();
        $saveMedia = "";
        $message_inbound = "";
        $data_message = "";
        $customer = $this->customer->check($adminDeviceId, $from, $customerName);
        $customerIsRegis = $customer->is_register;
        $custClient = $this->clientDevice->loadGetByCustPhone($from,$to);
        $isNasional = $this->regionModel->loadCheckNasional($clientId);
        $isNasional = json_decode($isNasional, false);
        $isNasional = $isNasional->success;
        $custClient = json_decode($custClient, false);
        $custClientData = $custClient->data;
        $custClientId = $custClientData->clientId;
        $customerGroup = $this->data->get('customer_group',"WHERE customer_id = $customer->id");
        $reqLiveChat = $customerGroup->request_livechat;
        $customerId = $customerGroup->customer_id;
        

        // START PREPARE DATA TO MESSAGE INBOUND
        // cek b64
        if($b64 != "" && $reqLiveChat == 0){
            $saveMedia = $this->fx->saveMedia($b64, $media_name); 
        }elseif($b64 != "" && $reqLiveChat != 0 ){
            $saveMedia = $this->fx->saveMediaLiveChat($b64, $media_name); 
        }

        if ($type == 'text') { 
            $rawData = $this->messageInbound->prepareForText($message_id, $clientDeviceId, $from, $to, $message, $timestamp);
            $data = json_decode($rawData);
            $data_message = $data->data_message;
            $chatWithAgent = $data->chat_with_agent;
            
        }

        if ($type == 'image') { 
            $data_message =  $this->messageInbound->prepareForImage($message_id, $clientDeviceId, $from, $to, $caption, $saveMedia, $fileType, $timestamp);
        }  

        if ($type == 'video') {
           $data_message =  $this->messageInbound->prepareForVideo($message_id, $clientDeviceId, $from, $to, $caption, $saveMedia, $fileType, $timestamp);
        }
        if ($type == 'document') {
            $data_message =  $this->messageInbound->prepareForDocument($message_id, $clientDeviceId, $from, $to, $fileName, $saveMedia, $fileType, $timestamp);
        }
        if ($type == 'current_location') { 
            $data_message =  $this->messageInbound->prepareForCurrentLocation($message_id, $clientDeviceId, $from, $to, $locLat, $locLng, $locName, $locAddress, $timestamp);
        }
        if ($type == 'live_location') { 
            $data_message =  $this->messageInbound->prepareForLiveLocation($message_id, $clientDeviceId, $from, $to, $locLat, $locLng, $locName, $caption, $timestamp);
        }
        if ($type == 'list_response') {
            
            $rawData =  $this->messageInbound->prepareForListResponse($message_id, $clientDeviceId, $from, $to, $selected_row_id, $selected_row_title, $selected_row_description, $timestamp);
            $data = json_decode($rawData);
            $data_message = $data->data_message;
            $toAgent = $data->to_agent;
            
             
            //  if ($chatWithAgent == 1 && $selected_row_title == $data_title_static->title ){
            //     // $message_inbound = $this->data->set("message_inbound", $data_message);
            //     // $message_inbound_id = $message_inbound->id;
            //     $message = "greeting_start_cs";
            //     $this->fx->bot_message($client, $from, $type, $message, $customerName, 0);
            // }
            
            // print_r($data_message);
            // die();
        }

        // END PREPARE DATA TO MESSAGE INBOUND

   
        
        if ($reqLiveChat == 0){
            $messageInbound = $this->data->set("message_inbound", $data_message);
            $messageInbound = json_decode($messageInbound, false);
            if($messageInbound->success == true){
                if ($customerIsRegis == null && $clientId == $custClientId && $isNasional == true) {
                    print_r("Customer tidak teregistrasi");
                    $messageInboundData = $messageInbound->data;
                    $this->fx->processAutoreplyNotRegistered($device, $messageInboundData, $customerName,$customerId,$adminDeviceId);
                } else if ($customerIsRegis == 1 && $clientId == $custClientId && $isNasional == true){
                    print_r("Customer sudah terdaftar");
                    $messageInboundData = $messageInbound->data;
                    $this->fx->processAutoreply($device, $messageInboundData, $customerName,$customerId,$adminDeviceId);
                }else{
                    $messageInboundData = $messageInbound->data;
                    $this->fx->processAutoreplyGlobal($device, $messageInboundData, $customerName,$customerId,$adminDeviceId);
                }
                }
        }

        
        //untuk live chat
        if ($reqLiveChat != 0){
            echo "start livechat";
            $this->fx->live_message_v2($clientDeviceId, $adminDeviceId, $to, $from, $type, $message,$reqLiveChat,$saveMedia);
        }

        $data_response = array(
            'status'  => 'OK',
            'message' => 'Message Received',
            'data_raw' => $data_message
        );

        echo json_encode($data_response);
    }




    

    function custChatWith($form){
        $customer = $this->data->get('customer', "WHERE phone = '$form'");
        return $customer->is_chat_with_bot;
    }

    

    function time_Diff_Minutes($startTime, $endTime) {
        $to_time = strtotime($endTime);
        $from_time = strtotime($startTime);
        $minutes = ($to_time - $from_time) / 60; 
        return ($minutes < 0 ? 0 : abs($minutes));   
    } 

    public function createSession($cust_id){
        $start = date("Y-m-d H:i:s");
        $end = date("Y-m-d H:i:s", strtotime('+5 minutes'));
        $data = array(
            'cust_id' => $cust_id, 
            'start' => $start,
            'end' => $end,
        );
        // print_r($data);
        $this->data->set("customer_session", $data);
    }

    public function checkCustSession($cust_id, $phone_number){
        echo "checkCustSession";
        
        $customer_session = $this->data->get('customer_session', "join customer on customer.id = customer_session.cust_id WHERE customer.phone  = '$phone_number' order by customer_session.id desc
        limit 1");


        $end = $customer_session->end;
        $now = date("Y-m-d H:i:s");
        $diff = $this->time_Diff_Minutes($now, $end);
        
        $status = false;
        if($diff <= 1){
            //new session, new greeting
            $this->createSession($cust_id);   
        }
        return $diff;
    }
    
   
    



    


    

    public function status()
    {
        $file = file_get_contents('php://input');
        $json = json_decode($file, true);
        if ($json['apikey'] == 'we4567talk') {
            $data = array(
                'status_code' => $json['data']['ack'],
                'status'      => $json['data']['status'],
                'message_id'  => $json['data']['message_id'],
                'created'     => date("Y-m-d H:i:s", $json['data']['timestamp']),
            );
            $insert        = $this->data->set("message_status", $data);
            $data_response = array(
                'status'  => 'OK',
                'message' => 'Status Received'
            );
            echo json_encode($data_response);
        }else{
            echo 'error';
        }
    }

    public function qr_timeout()
    {
        $file = file_get_contents('php://input');
        $json = json_decode($file, true);
        if ($json['apikey'] == 'we4567talk') {
            $device = $this->data->get('device', "WHERE name = '$json[client]'");
            $data_update  = array(
                'scan_request' => 'on',
            );
            $this->data->update('device', $data_update, $device->id);
            $data = array(
                'client' => $json['client']
            );
            $this->fx->pusherSend('wetalk_whatsapp', 'qr-timeout', $data);
            $data_response = array(
                'status'  => 'OK',
                'message' => 'QR Timeout'
            );
            echo json_encode($data_response);
        }else{
            echo 'error';
        }
    }

    public function get_qr()
    {
        $file = file_get_contents('php://input');
        $json = json_decode($file, true);

        $deviceName = $json['device_name'];

        $getDeviceId = $this->data->get("device", "WHERE name = '$deviceName'");
        $getDeviceId = $getDeviceId->id;

        $getClientId = $this->data->get('client_device', "WHERE device_id = $getDeviceId and status = 1");
        $getClientId = $getClientId->id;

        $getAdminId = $this->data->get('admin_device', "WHERE client_device_id = $getClientId");
        $getAdminId = $getAdminId->client_id;

        // echo "getAdminId $getAdminId";
        $device_    = $this->adminDevice->loadDeviceAdmin($getAdminId); 
        // print_r($device_);
        $device = json_decode($device_);
        $message = $device->message == false ? $device->message : "";
        $deviceData = $device->data;
        if (!is_null($deviceData)) {
            $deviceName = $deviceData->device_name; 
            $accessKey = $deviceData->client_device_access_key; 
            $scanRequest = $deviceData->client_device_scan_request; 
            $scan = $deviceData->client_device_scan;
            $urlServer = $deviceData->device_url_server;
            $clientDeviceId = $deviceData->client_device_id;
            $clientDevicePusherChannel = $deviceData->client_device_pusher_channel;

            if($accessKey == $json['access_key']){
                $data = array(
                    'qr' => $json['qr'],
                    'device_name' => $json['device_name']
                );
                // $this->fx->pusherSend('wetalk_whatsapp', 'get-qr', $data);
                $this->fx->pusherSendv2($clientDevicePusherChannel, 'get-qr', $data, $clientDeviceId);
                $data_response = array(
                    'status'  => 'OK',
                    'message' => 'QR Received'
                );
                
                echo json_encode($data_response);
            }else {
                echo "wrong access key";
            }
        }else {
            echo "no device";
        }
    }

    // public function testPg(){
    //     $order_id = rand();
    //     $amount = 30000;
    //     $responsex = $this->fx->get_payment_url($order_id, $amount);
    //     print_r($responsex);
    // }

    function notify_success(){
        $file = file_get_contents('php://input');
        $json = json_decode($file, true);
        
        $payment_data = [
            'outbound_id' => 10
        ];
        $chat        = $this->data->set("transactions", $payment_data);

        $data_response = array(
            'status'  => 'ok',
            'message' => 'success payment'
        ); 
        echo json_encode($data_response); 
    }
    function notify_failure(){
        $file = file_get_contents('php://input');
        $json = json_decode($file, true);

        $data_response = array(
            'status'  => 'ok',
            'message' => 'failed payment'
        ); 
        echo json_encode($data_response); 
    }

    

    function tes_midtrans_config(){
        $this->fx->get_payment_url("","");
    }


    public function scan(){
        $file = file_get_contents('php://input');
        $json = json_decode($file, true);
        
        $deviceId = $json['device_id'];

        $getIdClient = $this->data->get("client_device", "WHERE device_id = $deviceId and status = 1");
        $getIdClient = $getIdClient->id;

        $getAdminDevice = $this->data->get('admin_device', "WHERE client_device_id = $getIdClient");
        $getAdminDevice = $getAdminDevice->client_id;

        $device_    = $this->adminDevice->loadDeviceAdmin($getAdminDevice);  
        $device = json_decode($device_);

        $message = $device->message == false ? $device->message : "";
        $deviceData = $device->data;
        if (!is_null($deviceData)) {
            $deviceName = $deviceData->device_name; 
            $accessKey = $deviceData->client_device_access_key; 
            $scanRequest = $deviceData->client_device_scan_request; 
            $scan = $deviceData->client_device_scan;
            $urlServer = $deviceData->device_url_server;
            $clientDeviceId = $deviceData->client_device_id;
            $clientDevicePusherChannel = $deviceData->client_device_pusher_channel;
            if ($scanRequest == 'on') { 
                $paramSend = array(
                    'deviceName' => $deviceName,
                    'isLegacy' => true
                );
                $response = $this->fx->sendApi($urlServer.'/session/add', $paramSend);
                // print_r($response);
                // die;
                if (strpos($response, 'Connection refused') == true) {
                    $response = array(
                        'success'  => false,
                        'message' => '-',
                        'data' => 'connection_refused'
                    );
                }
                $json = json_decode($response, true);
                if(!empty($json)){  
                    if ($json['success'] == true) {
                        $qr = $json['data']['qr'];
                        $deviceName = $json['data']['deviceName']; 
    
                        $data = array(
                            'qr' => $qr,
                            'deviceName' => $deviceName
                        ); 
                        // $this->fx->pusherSend('wetalk_whatsapp', 'get-qr', $data);
                        $this->fx->pusherSendv2($clientDevicePusherChannel, 'get-qr', $data, $clientDeviceId);
                        // echo $deviceName;
                        $response = array(
                            'success'  => true,
                            'message' => 'ok',
                            'data' => $deviceName
                        );
                    }
                }else {
                    $response = array(
                        'success'  => false,
                        'message' => '-',
                        'data' => 'error'
                    );
                }
            }else {
                $response = array(
                    'success'  => false,
                    'message' => '-',
                    'data' => 'already_connect'
                ); 
            }
        } else {
            $response = array(
                'success'  => false,
                'message' => '-',
                'data' => 'no device data'
            ); 
        }

        echo json_encode($response);     
    }

    public function updateConfigId(){
        $file = file_get_contents('php://input');
        $json = json_decode($file, true);

        $response = array();
        $key = $json['access_key'] != "" || $json['access_key'] != null ? $json['access_key'] : "";
        $client = $json['device_name'] != "" || $json['device_name'] != null ? $json['device_name'] : "";
        $this->clientDevice->checkAccesKey($key); 
        $device = $this->clientDevice->checkDeviceName($client);

        $deviceId =  $device != null ? $device->device_id : 0;
        $clientDeviceId =  $device != null ? $device->client_device_id : 0;
        $noHp =$json['id'];
        $isBusiness =$json['is_business'];
        
        $response = null;
        if($deviceId > 0 && $clientDeviceId > 0){

            $dataUpdate = array(
                'phone' => $noHp,
                'is_business' => $isBusiness,
                'updated' => date('Y-m-d H:i:s')
            );
            $this->data->update("client_device", $dataUpdate, $clientDeviceId);

            $dataUpdate = array(
                'updated' => date('Y-m-d H:i:s')
            );
            $this->data->update("device", $dataUpdate, $deviceId);

            $response = array(
                'status'  => 'OK',
                'message' => 'Config id updated'
            );
        }else {
            $response = array(
                'status'  => 'FAIL',
                'message' => 'Config device not updated'
            );
        }
        echo json_encode($response);       
    }

    public function updateConfigName(){
        $file = file_get_contents('php://input');
        $json = json_decode($file, true);
        
        $response = array();
        $key = $json['access_key'] != "" || $json['access_key'] != null ? $json['access_key'] : "";
        $client = $json['device_name'] != "" || $json['device_name'] != null ? $json['device_name'] : "";
        $this->clientDevice->checkAccesKey($key); 
        $device = $this->clientDevice->checkDeviceName($client);

 
        $deviceId =  $device != null ? $device->device_id : 0;
        $clientDeviceId =  $device != null ? $device->client_device_id : 0;
        $name = $json['name'];
        $isBusiness = $json['is_business'];

        if($deviceId > 0 && $clientDeviceId > 0){
            $clientDataUpdate = array(
                'push_name' => $name,
                'is_business' => $isBusiness,
                'updated' => date('Y-m-d H:i:s')
            );
            $this->data->update("client_device", $clientDataUpdate, $clientDeviceId);

            $dataUpdate = array(
                'updated' => date('Y-m-d H:i:s')
            );
            $this->data->update("device", $dataUpdate, $deviceId);


            $response = array(
                'status'  => 'OK',
                'message' => 'Config name updated'
            );
        }else {
            $response = array(
                'status'  => 'FAIL',
                'message' => 'Config device not updated'
            );
        }
        echo json_encode($response);
      
    }

    public function updateConfigPlatform()
    {
        $file = file_get_contents('php://input');
        $json = json_decode($file, true);

        $response = array();
        $key = $json['access_key'] != "" || $json['access_key'] != null ? $json['access_key'] : "";
        $client = $json['device_name'] != "" || $json['device_name'] != null ? $json['device_name'] : "";
        $this->clientDevice->checkAccesKey($key); 
        $device = $this->clientDevice->checkDeviceName($client);
        
        $deviceId =  $device != null ? $device->device_id : 0;
        $clientDeviceId =  $device != null ? $device->client_device_id : 0;
        $platform = $json['platform'];
        $isBusiness = $json['is_business'];

        if($deviceId > 0 && $clientDeviceId > 0){
            $dataUpdate = array(
                'platform' => $platform,
                'is_business' => $isBusiness,
                'updated' => date('Y-m-d H:i:s')
            );
            $this->data->update("client_device", $dataUpdate, $clientDeviceId);

            $dataUpdate = array(
                'updated' => date('Y-m-d H:i:s')
            );
            $this->data->update("device", $dataUpdate, $deviceId);

            $response = array(
                'status'  => 'OK',
                'message' => 'Config platform updated'
            );
        }else {
            $response = array(
                'status'  => 'FAIL',
                'message' => 'Config device not updated'
            );
        }
        
        echo json_encode($response);
      
    }

    
    public function updateConfigScan(){
        $file = file_get_contents('php://input');
        $json = json_decode($file, true);

        $response = array();
        $key = $json['access_key'] != "" || $json['access_key'] != null ? $json['access_key'] : "";
        $client = $json['device_name'] != "" || $json['device_name'] != null ? $json['device_name'] : "";
        $this->clientDevice->checkAccesKey($key); 
        $device = $this->clientDevice->checkDeviceName($client);
        
        $deviceId =  $device != null ? $device->device_id : 0;
        $clientDeviceId =  $device != null ? $device->client_device_id : 0;
        $clientDevicePusherChannel =  $device != null ? $device->client_device_pusher_channel : 0;
        
        $data  = array(
            'scan'   => $json['scan'],
            'scan_request'   => $json['scan'] == 'on' ? 'on' : 'off',
            'updated' => date('Y-m-d H:i:s'),
        );
        $this->data->update('client_device', $data, $clientDeviceId);

        $dataUpdate = array(
            'updated' => date('Y-m-d H:i:s')
        );
        $this->data->update("device", $dataUpdate, $deviceId);

        $data_pusher = array(
            'scan'   => $json['scan'],
            'client' => $client
        );
        // $this->fx->pusherSend('wetalk_whatsapp', 'config-scan', $data_pusher);
        $this->fx->pusherSendv2($clientDevicePusherChannel, 'config-scan', $data_pusher, $clientDeviceId);

        $data_response = array(
            'status'  => 'OK',
            'message' => 'Config scan updated'
        );
        echo json_encode($data_response);
        
    }

    

    public function disconnected(){
        $file = file_get_contents('php://input');
        $json = json_decode($file, true);

        $response = array();
        $key = $json['access_key'] != "" || $json['access_key'] != null ? $json['access_key'] : "";
        $client = $json['device_name'] != "" || $json['device_name'] != null ? $json['device_name'] : "";
        $this->clientDevice->checkAccesKey($key); 
        $device = $this->clientDevice->checkDeviceName($client);

        $deviceId =  $device != null ? $device->device_id : 0;
        $clientDeviceId =  $device != null ? $device->client_device_id : 0;
        $clientDevicePusherChannel =  $device != null ? $device->client_device_pusher_channel : 0;

        $response = null;
        if($deviceId > 0 && $clientDeviceId > 0){
            $dataUpdate = array(
                'scan' => 'on',
                'scan_request' => 'on',
                'push_name' => '',
                'platform' => '',
                'phone' => '',
                'updated' => date('Y-m-d H:i:s')
            );
            $this->data->update("client_device", $dataUpdate, $clientDeviceId);
            $response = array(
                'status'  => 'OK',
                'message' => 'Device is disconnected'
            );

            $data_pusher = array(
                'client' => $client
            );
            // $this->fx->pusherSend('wetalk_whatsapp', 'config-disconnected', $data_pusher);
            $this->fx->pusherSendv2($clientDevicePusherChannel, 'config-disconnected', $data_pusher, $clientDeviceId);

        }else {
            $response = array(
                'status'  => 'FAIL',
                'message' => 'Config device not updated'
            );
        }
        echo json_encode($response);       
    }

    // In Process Broadcast terdapat status 0 (pending), 1 (success), 2 (failed)
    public function processBroadcastSuccess(){
        $getTransactions = $this->messagingModel->loadTransactionsSuccess(0, date('Y-m-d'));
        $getTransactions = json_decode($getTransactions);
        $message = $getTransactions->success == false ? $getTransactions->message : "";

        $getTransactions = $getTransactions->data;

        if (count($getTransactions) != 0) {
            foreach($getTransactions as $gt) {
                if ($gt->client_device_status != 0) {
                    $param_send = [
                        "id"                => $gt->broadcast_id,
                        "access_key"        => $gt->client_device_access_key,
                        "receiver"          => $gt->broadcast_receiver,
                        "message_header"    => $gt->broadcast_message_header,
                        "message_body"      => $gt->broadcast_message_body,
                        "message_footer"    => $gt->broadcast_message_footer,
                        "media_url"         => $gt->broadcast_media_url,
                        "message_type"      => $gt->broadcast_message_type,
                        "device_name"       => $gt->device_name,
                    ];
                        
                    $response = $this->fx->sendApi($gt->broadcast_url . '/chat/sendBroadcast', $param_send);
                    $interval = rand(3, 8);
                    sleep($interval);
                } else {
                    $id = $gt->broadcast_id;
                    $param_send = [
                        "status" => 2
                    ];
                    $this->data->update('broadcast', $param_send, $id);
                }
            }
        }
        
    }

    // In Process Broadcast terdapat status 0 (pending), 1 (success), 2 (failed)
    public function processBroadcastFailed(){
        $getTransactions = $this->messagingModel->loadTransactionsFailed(0, date('Y-m-d'));
        $getTransactions = json_decode($getTransactions);
        $message = $getTransactions->success == false ? $getTransactions->message : "";

        $getTransactions = $getTransactions->data;

        if (count($getTransactions) != 0) {
            foreach($getTransactions as $gt) {
                $id = $gt->id;
                $param_send = [
                        "status" => 2,
                ];
                $this->data->update('broadcast', $param_send, $id);
            } 
        }
        
    }

    public function autoDeleteMessage(){
        $getMessage = $this->messagingModel->loadGetsMessageForDelete(date('Y-m-d'));
        $getMessage = json_decode($getMessage, false);

        $getMessage = $getMessage->data;

        foreach($getMessage as $gm) {
            if ($gm->outbound_key != null && $gm->inbound_key != null) {
                $param_send = [
                    'outbound_id' => $gm->message_outbound_id,
                    'inbound_id' => $gm->message_inbound_id,
                    'outbound_receiver' => $gm->outbound_receiver,
                    'message' => $gm->message,
                    'url_server' => $gm->url_server,
                    'device_name' => $gm->device_name,
                    'access_key' => $gm->access_key,
                    'key_outbound' => $gm->outbound_key,
                    'key_inbound' => $gm->inbound_key,
                    'timestamp_outbound' => $gm->message_outbound_timestamp,
                    'timestamp_inbound' => $gm->message_inbound_timestamp,
                ];
                $this->fx->sendApi($gm->url_server . '/chat/autoDeleteMessage', $param_send);
                $interval = rand(1, 4);
                sleep($interval);
            }
        }
    }

    public function deleteMessage(){
        $file = file_get_contents('php://input');
        $json = json_decode($file, true);

        $data =  isset($json['data']) ? $json['data'] : "";

        $outbound_id =  isset($data['id_outbound']) ? $data['id_outbound'] :  "";
        $inbound_id =  isset($data['id_inbound']) ? $data['id_inbound'] :  "";

        $dataOutbound = [
            'message_id' => null
        ];
        $dataInbound = [
            'message_id' => null
        ];
        $this->data->update('message_outbound', $dataOutbound, $outbound_id);
        $this->data->update('message_inbound', $dataInbound, $inbound_id);
    }



    public function saveLiveChat(){
        $file = file_get_contents('php://input');
        $json = json_decode($file, true);
        echo "--start save_message outbound--";
        print_r($json);
        // $data =  isset($json['data']) ? $json['data'] : "";

        // $id =  isset($data['id_broadcast']) ? $data['id_broadcast'] :  "";

            // $data_message = array(
            //     'status'    => 1,
            //     'updated'   => date("Y-m-d H:i:s"),
            // ); 
            // $this->data->update('broadcast', $data_message, $id);
            // $dataResponse = array(
            //     'success'  => true,
            //     'message' => 'save outbound ok',
            // ); 
            // echo json_encode($dataResponse); 
    }
    public function saveBroadcast(){
        $file = file_get_contents('php://input');
        $json = json_decode($file, true);
        
        $data =  isset($json['data']) ? $json['data'] : "";

        $id =  isset($data['id_broadcast']) ? $data['id_broadcast'] :  "";

       
            $data_message = array(
                'status'    => 1,
                'updated'   => date("Y-m-d H:i:s"),
            ); 
            $this->data->update('broadcast', $data_message, $id);
            $dataResponse = array(
                'success'  => true,
                'message' => 'save outbound ok',
            ); 
            echo json_encode($dataResponse);
        // }    
    }

    public function saveGroup()
    {
        $file = file_get_contents('php://input');
        $json = json_decode($file, true);
        // echo "--start save_message outbound--";
        // print_r($json);
        $data =  isset($json['data']) ? $json['data'] : "";

        $deviceName = $json['device_name'];

        $getDeviceId = $this->data->get("device", "WHERE name = '$deviceName'");
        $getDeviceId = $getDeviceId->id;

        $getClientId = $this->data->get('client_device', "WHERE device_id = $getDeviceId");
        $getClientId = $getClientId->id;

        $getAdminId = $this->data->get('admin_device', "WHERE client_device_id = $getClientId");
        $getAdminId = $getAdminId->client_id;

        $device_    = $this->adminDevice->loadDeviceAdmin($getAdminId); 
        $device = json_decode($device_);
        $message = $device->message == false ? $device->message : "";
        $deviceData = $device->data;

        $groupId =  isset($data['group_id']) ? $data['group_id'] :  "";
        $groupNo =  isset($data['group_no']) ? $data['group_no'] :  "";
        $groupName =  isset($data['group_name'][0]) ? $data['group_name'][0] :  "";
        $inviteFrom =  isset($data['invite_from']) ? $data['invite_from'] :  "";
        $messageTimestamp =  isset($data['message_timestamp']) ? $data['message_timestamp'] :  "";

        $deviceGroupExist = $this->data->get("device_on_group", "WHERE group_no = $groupNo AND status = 1");

        // if(isset($from_me)){
        if (!isset($deviceGroupExist)) {
            $data_message = array(
                'client_device_id'    => $deviceData->client_device_id,
                'group_id'    => $groupId,
                'group_no'    => $groupNo,
                'group_name'    => $groupName,
                'invite_from'    => $inviteFrom,
                'message_timestamp'    => $messageTimestamp,
                'status'    => 1,
                'created'   => date("Y-m-d H:i:s")
            ); 
            $this->data->set('device_on_group', $data_message);
        }
            // $dataResponse = array(
            //     'success'  => true,
            //     'message' => 'save outbound ok',
            // ); 
            // echo json_encode($dataResponse);
        // }
    }

    public function removeGroup()
    {
        $file = file_get_contents('php://input');
        $json = json_decode($file, true);  
          
        $data =  isset($json['data']) ? $json['data'] : "";

        $groupNo =  isset($data['group_no']) ? $data['group_no'] :  "";
        $inviteFrom =  isset($data['invite_from']) ? $data['invite_from'] :  "";
        $messageTimestamp =  isset($data['message_timestamp']) ? $data['message_timestamp'] :  "";
        $participantRemove =  isset($data['participant_remove']) ? $data['participant_remove'] :  "";

        $dataClientDevice = $this->data->get("client_device", "WHERE phone = '$participantRemove'");
        $deviceDataClientDeviceId = $dataClientDevice->id;

        
        $deviceGroupExist = $this->data->get("device_on_group", "WHERE group_no = $groupNo AND client_device_id = $deviceDataClientDeviceId AND status = 1");
        
        // if(isset($from_me)){
            if (isset($deviceGroupExist)) {
                $data_message = array(
                'remove_by'            => $inviteFrom,
                'message_timestamp'    => $messageTimestamp,
                'status'               => 2,
                'created'              => date("Y-m-d H:i:s")
            ); 
          
            $this->data->update('device_on_group', $data_message, $groupNo, 'group_no');
        }
            // $dataResponse = array(
            //     'success'  => true,
            //     'message' => 'save outbound ok',
            // ); 
            // echo json_encode($dataResponse);
        // }
    }

    
    public function saveDeviceMessageCustomer()
    {
        $file = file_get_contents('php://input');
        $json = json_decode($file, true);
        echo "-- saveDeviceMessageCustomer --";
        if ($json === "" || $json === null) return;
     
        $data =  isset($json['data']) ? $json['data'] : "";

        // Client_Device_Id
        $deviceName = $json['device_name'];

        $getDeviceId = $this->data->get("device", "WHERE name = '$deviceName'");
        $getDeviceId = $getDeviceId->id;

        $getClientId = $this->data->get('client_device', "WHERE device_id = $getDeviceId");
        $getClientId = $getClientId->id;

        $getAdminId = $this->data->get('admin_device', "WHERE client_device_id = $getClientId");
        $getAdminId = $getAdminId->client_id;

        $device_    = $this->adminDevice->loadDeviceAdmin($getAdminId); 
        $device = json_decode($device_);
        $message = $device->message == false ? $device->message : "";
        $deviceData = $device->data;
        $clientDeviceId = $deviceData->client_device_id;

        $messageId =  isset($data['message_id']) ? $data['message_id'] :  "";
        $type =  isset($data['type']) ? $data['type'] :  "";
        $messageIdGroup =  isset($data['message_id_group']) ? $data['message_id_group'] :  "";
        $customerName =  isset($data['customer_name']) ? $data['customer_name'] :  "";
        $sender =  isset($data['sender']) ? $data['sender'] :  "";
        $message =  isset($data['message']) ? $data['message'] :  "";
        $timestamp =  isset($data['timestamp']) ? $data['timestamp'] :  "";
        // Image
        $b64 =  isset($data['b64']) ? $data['b64'] :  "";
        $caption =  isset($data['caption']) ? $data['caption'] :  "";
        $fileType =  isset($data['filetype']) ? $data['filetype'] :  "";
        // Document
        $fileName   = isset($json['data']['media_origin_filename'])  ? $json['data']['media_origin_filename'] : ""; 
        // Location 
        $locLat   = isset($json['data']['latitude'])  ? $json['data']['latitude'] : ""; 
        $locLng   = isset($json['data']['longitude'])  ? $json['data']['longitude'] : ""; 
        $locName   = isset($json['data']['loc_name'])  ? $json['data']['loc_name'] : ""; 
        $locAddress   = isset($json['data']['loc_address'])  ? $json['data']['loc_address'] : ""; 

        $dataDeviceOnGroup = $this->data->get("device_on_group", "WHERE group_no = $messageIdGroup", "id, client_device_id");
        $idDeviceOnGroup = $dataDeviceOnGroup->id;
        $clientDeviceIdDeviceOnGroup = $dataDeviceOnGroup->client_device_id;

        // Jika chat bukan berasal dari chatbot yang pertama di invite group maka data jangan dimasukan
        if ($getClientId != $clientDeviceIdDeviceOnGroup) return;

        // group_no_message akan di return jika status
        if ($messageIdGroup == "status") return;

        // Menambahkan customer ke group customer_group_wa
        $this->customer->checkGroup($idDeviceOnGroup, $sender, $customerName, $idDeviceOnGroup);

        $media_name = $sender . "_" . time();
        
        if($b64 != ""){
            $saveMedia = $this->fx->saveMediaGroup($b64, $media_name); 
        }
        if ($type == 'text') { 
            $rawData = $this->messageInbound->prepareForTextGroup($idDeviceOnGroup, $messageIdGroup, $messageId, $sender, $customerName, $message, $timestamp);
            $data = json_decode($rawData);
            $data_message = $data->data_message;
            $chatWithAgent = $data->chat_with_agent;
            
        }

        if ($type == 'image') { 
            $data_message =  $this->messageInbound->prepareForImageGroup($idDeviceOnGroup, $messageIdGroup, $messageId, $sender, $customerName, $caption, $saveMedia, $fileType, $timestamp);
        }  

        if ($type == 'video') {
           $data_message =  $this->messageInbound->prepareForVideoGroup($idDeviceOnGroup, $messageIdGroup, $messageId, $sender, $customerName, $caption, $saveMedia, $fileType, $timestamp);
        }
        if ($type == 'document') {
            $data_message =  $this->messageInbound->prepareForDocumentGroup($idDeviceOnGroup, $messageIdGroup, $messageId, $sender, $customerName, $fileName, $saveMedia, $fileType, $timestamp);
        }
        if ($type == 'current_location') { 
            $data_message =  $this->messageInbound->prepareForCurrentLocationGroup($idDeviceOnGroup, $messageIdGroup, $messageId, $sender, $customerName, $locLat, $locLng, $locName, $locAddress, $timestamp);
        }
        if ($type == 'live_location') { 
            $data_message =  $this->messageInbound->prepareForLiveLocationGroup($idDeviceOnGroup, $messageIdGroup, $messageId, $sender, $customerName, $locLat, $locLng, $locName, $caption, $timestamp);
        }

        echo "-- data_message --";
        print_r($data_message);
        $result = $this->data->set('message_inbound_group', $data_message);
        print_r($result);

        // $dataResponse = array(
        //     'success'  => true,
        //     'message' => 'save outbound ok',
        // ); 
        // echo json_encode($dataResponse);

    }

    public function bulkSendMessagesCustomer(){
        // Load data customer yang sudah teregistrasi
        $clientId = 7; //id unique di table client_device
        $getCustomers = $this->clientDevice->loadGetCustomerByClientId($clientId);
        $getCustomers = json_decode($getCustomers);
        $getCustomersData = $getCustomers->data;

        // Foreach data customer 
        foreach ($getCustomersData as $gc) {
            $loadNotif = $this->fx->loadAutoreplySystem(1);
            $provinceId = $gc->customer_province_id;

            $getProvinceCustomer = $this->data->get("provinces", "WHERE id = $provinceId");

            $replace_message = [
                'nama' => $gc->customer_name,
                'province' => $getProvinceCustomer->name
            ];

            $message = $loadNotif->message_body;
            if(isset($replace_message))
            $message = preg_replace_callback('/{{(\w+)}}/', function($match) use($replace_message) {
                return $replace_message[$match[1]];
            }, $message );

            $buttons = array(
                "button_1_id" => $loadNotif->button_1_id,
                "button_1_label" => $loadNotif->button_1_label,
                "button_2_id" => $loadNotif->button_2_id,
                "button_2_label" => $loadNotif->button_2_label,
                "button_3_id" => $loadNotif->button_3_id,
                "button_3_label" => $loadNotif->button_3_label
            );

            $paramSend = [
                "access_key"        => $gc->client_device_access_key,
                'sender'            => $gc->client_device_phone,
                "receiver"          => $gc->customer_phone,
                "message_body"      => $message,
                'buttons'           => $buttons,
                'button_1_id'       => $loadNotif->button_1_id,
                'button_1_label'    => $loadNotif->button_1_label,
                "message_type"      => $loadNotif->message_type,
                "device_name"       => $gc->device_name,
            ];
                
            $response = $this->fx->sendApi($gc->device_url_server . '/chat/sendv2', $paramSend);
            // Buat interval untuk setiap message
            $interval = rand(3, 5);
            sleep($interval);
        }

    }

}