<?php
namespace App\Controllers\Client;
use App\Controllers\BaseController;
use App\Core\Service\Logger;
use App\Service\Messaging;
use App\Config\Main;
use App\Model\FxModel;
use App\Model\OrderModel;
use App\Model\MasterDataSetModel;
use App\Library\Utilities;
use App\Library\Fx;
use App\Library\WhatsApp;
use App\Library\Sms;
use App\Core\Library\Crypto;
class MailerController extends BaseController
{
    private $fx;
    private $MasterDataSetModel;
    private $FxModel;
    private $OrderModel;
    private $Utilities;
    private $Messaging;
    public function __construct() {
        parent::__construct();
        $this->MasterDataSetModel = new MasterDataSetModel();
        $this->FxModel = new FxModel();
        $this->OrderModel = new OrderModel();
        $this->Utilities   = new Utilities();
        $this->Messaging = new Messaging();
        $this->fx = new Fx();
    }
    
    private function processAttachments() {
        try {
            $attachment_list = [];
            if(!empty($_FILES['attachments'])) {
                $uploadDir = Main::getUploadPath();
                $uploadFolder = Main::getUploadFolder();
                $uploadBasePath = $uploadDir . '/comp-' . $this->user_data->comp_id . '/';
                if (!is_dir($uploadBasePath)) {
                    mkdir($uploadBasePath, 0755, true);
                }
                if (!is_dir($uploadBasePath)) {
                    throw new \Exception("Upload path does not exist");
                }
                
                $max_file_size = Main::getUploadMaxSize();
                $allowed_file_types = Main::getAllowedLogoFileTypes();
                foreach($_FILES['attachments']['name'] as $i=>$name) {
                    if ($_FILES['attachments']['size'][$i] > Main::getUploadMaxSize()) {
                        throw new \Exception('File size should be less than ' . ($max_file_size/1024) . ' KB');
                    }
                    if (!in_array($_FILES['attachments']["type"][$i], $allowed_file_types)) {
                        throw new \Exception('Invalid file type found in attachment list. Valid file types are:'.implode(", ", $allowed_file_types));
                    }
                    $file_name = 'attachment' . '_' . time() . '.' . pathinfo($name, PATHINFO_EXTENSION);
                    if(!move_uploaded_file($_FILES['attachments']['tmp_name'][$i], $uploadBasePath . $file_name)) {
                        throw new \Exception("Error in uploading attachment file:".$name);
                    }
                    $file_path = $uploadFolder . '/comp-' . $this->user_data->comp_id . '/' . $file_name;
                    $attachment_list[] = [
                        "path"=>$file_path,
                        "name"=>$name,
                        "size"=>$_FILES['attachments']["size"][$i],
                        "type"=>$_FILES['attachments']["type"][$i]
                    ];
                }
            }
            return ["status"=>true, "attachment_list"=>$attachment_list];
        } catch(\Exception $e) {
            Logger::error($e->getMessage(), ['File' => $e->getFile(), 'Line'=>$e->getLine()]);
            return ["status"=>true, "error"=>$e->getMessage()];
        }
    }

    public function saveEmailSMSLog() {
        try {
            $rules = [
                'type'=> array('rules' => 'required|in_list[sms,email,whatsapp]', 'label' => "Type"),
                'ref_type'=> array('rules' => 'in_list[lead,order]', 'label' => "Reference Type"),
                'body'=> array('rules' => 'required|max_length[50000]', 'label' => "Message content"),
            ];
            if(!empty($this->input['type'])) {
                if($this->input['type'] == 'email') {
                    $rules['subject'] = array('rules' => 'required|max_length[150]', 'label' => "Email Subject");
                    $rules['to'] = array('rules' => 'required|max_length[5000]|valid_emails', 'label' => "Recipient's Email ID");
                    $rules['cc'] = array('rules' => 'max_length[5000]|valid_emails', 'label' => "Email ID in CC");
                    $rules['bcc'] = array('rules' => 'max_length[5000]|valid_emails', 'label' => "Email ID in BCC");
                } else {
                    $rules['to'] = array('rules' => 'required|max_length[5000]|valid_phones', 'label' => "Recipient's Phone No");
                    $rules['country_code'] = array('rules' => 'required|max_length[10]', 'label' => "Country_code");
                }
            }
            if(!empty($_FILES['attachments'])) {
                $rules['body'] = array('rules' => 'max_length[50000]', 'label' => "Message content");
            }
            if(!empty($this->input['ref_type']) && !empty($this->input['ref_id'])) {
                unset($rules['to']);
            }
            $validation = $this->validateReqData($rules, $this->input);            
            if(empty($validation['status'])) {
                throw new \Exception($validation['error']);
            }
            if(!$validation['valid']) {
                $this->sendResponse(array('code' => 400, 'message' => $this->getFirstValidationError(), 'data'=>$validation['validation_error']));
            }
            
            $attchrs = $this->processAttachments();
            if(empty($attchrs['status'])) {
                throw new \Exception($attchrs['error']);
            }
            
            $ref_arr = !empty($this->input['ref_id']) ? (is_array($this->input['ref_id']) ? $this->input['ref_id'] : explode(",",$this->input['ref_id'])) : [];
            $req_id = $this->Utilities->random_string('alnum');
            $tbl  = $this->FxModel->client_db_prefix.$this->user_data->comp_id . "." . $this->FxModel->tables['email_sms_log'];
            $conn = $this->FxModel->conn();   
            $conn->beginTransaction();
            if(!empty($ref_arr)) {
                foreach($ref_arr as $refid) {
                    $savers = $this->saveLog($this->user_data->comp_id, $this->user_data->id, $conn, $req_id, $refid, $this->input, $attchrs['attachment_list']);
                    if(empty($savers['status'])) {
                        throw new \Exception($savers['error']);
                    }
                } 
            } else {
                $savers = $this->saveLog($this->user_data->comp_id, $this->user_data->id, $conn, $req_id, 0, $this->input, $attchrs['attachment_list']);
                if(empty($savers['status'])) {
                    throw new \Exception($savers['error']);
                }
            }
            if($conn->inTransaction()) $conn->commit();
            $this->Kafkam->sendMessage("sanordo_client_email_sms_whatsapp", ['comp_id'=>$this->user_data->comp_id, 'user_id'=>$this->user_data->id, 'req_id'=>$req_id]);
            $this->sendResponse(array('code' => 200, 'message' => ucfirst($this->input['type']) . ' request sent successfully. Check logs for details.', 'data'=> null)); 
        } catch(\Exception $e) {
            if(!empty($conn)) {
                if($conn->inTransaction()) $conn->rollBack();
            }
            Logger::error($e->getMessage(), ['File' => $e->getFile(), 'Line'=>$e->getLine()]);
            $this->sendResponse(array('code' => 400, 'message' => $e->getMessage(), 'data'=> null));
        }
    }
    
    private function saveLog($comp_id, $user_id, $conn, $req_id, $ref_id, $input, $attachment_list) {
        try {
            $insarr = [
                "request_id" => $req_id,
                "type" => trim($input['type']),
                "template_id" => !empty($input['template_id']) ? trim($input['template_id']) : NULL,
                "country_code" => !empty($input['country_code']) ? trim($input['country_code']) : NULL,
                "to" => !empty($input['to']) ? trim($input['to']) : NULL,
                "cc" => !empty($input['cc']) ? trim($input['cc']) : NULL,
                "bcc" => !empty($input['bcc']) ? trim($input['bcc']) : NULL,
                "email_subject"  => (trim($input['type']) == 'email') ? trim($input['subject']) : NULL,
                "body"     => $input['body'],
                "cr_usr"   => $user_id,
                "attachment" => !empty($attachment_list) ? json_encode($attachment_list) : NULL
            ];
            if(!empty($ref_id)) {
                $insarr['ref_id'] = $ref_id;
                if(!empty($input['ref_type'])) {
                    $insarr['ref_type'] = trim($input['ref_type']);
                }
            }
            $tbl  = $this->FxModel->client_db_prefix.$comp_id . "." . $this->FxModel->tables['email_sms_log'];
            if(!empty($attachment_list) && trim($input['type']) == 'whatsapp') {
                //FOR WHATSAPP EACH ATTACHMENT IS GOING TO INDIVIDUAL CHAT MESSAGE
                unset($insarr['attachment']);
                if(!empty($insarr['body'])) {
                    $insrs = $this->FxModel->insert($tbl, $insarr, $conn);
                    if(empty($insrs['status'])) {
                        throw new \Exception($insrs['error']);
                    }    
                }
                foreach($attachment_list as $atchmnt) {
                    $msg = $insarr;
                    $msg['attachment'] = json_encode([$atchmnt]);
                    $insrs = $this->FxModel->insert($tbl, $msg, $conn);
                    if(empty($insrs['status'])) {
                        throw new \Exception($insrs['error']);
                    }
                }
            } else {
                $insrs = $this->FxModel->insert($tbl, $insarr, $conn);
                if(empty($insrs['status'])) {
                    throw new \Exception($insrs['error']);
                }
            }
            return ["status"=>true];
        } catch(\Exception $e) {
            Logger::error($e->getMessage(), ['File' => $e->getFile(), 'Line'=>$e->getLine()]);
            return ["status"=>false, "error"=>$e->getMessage()];
        }
    }

    public function processEmailSMSLog($comp_id, $user_id, $req_id) {
        try {
            if(empty($comp_id)) {
                throw new \Exception("Company ID is required to process email/sms logs");
            }
            if(empty($user_id)) {
                throw new \Exception("User ID is required to process email/sms logs");
            }
            if(empty($req_id)) {
                throw new \Exception("Request ID is required to process email/sms logs");
            }
            $comprs = $this->fx->getCompanyDetail($comp_id);
            if(empty($comprs['status'])) {
                throw new \Exception($comprs['error']);
            }
            if(empty($comprs['data'])) {
                throw new \Exception("Company details not found for Request ID:$req_id");
            }
            $lrsp = $this->FxModel->getEmailSmsWhatsAppLog($comp_id, $req_id);
            if(empty($lrsp['status'])) {
                throw new \Exception($lrsp['error']);
            }
            if(empty($lrsp['data'])) {
                throw new \Exception("No Pending logs found to process email/sms for Request ID:$req_id");
            }
            $brchrs = $this->FxModel->getBranchMasterForMailer($comp_id);
            if(!$brchrs['status']) {
                throw new \Exception($brchrs['error']);
            }
            if(empty($brchrs['data'])) {
                throw new \Exception("Branch settings data not found");
            }

            $ubtbl = $this->FxModel->client_db_prefix.$comp_id . "." . $this->FxModel->tables['branch_user_rights'];
            $usrbranch = $this->FxModel->fetchSingleData("SELECT * FROM $ubtbl WHERE user_id=:usrid ORDER BY make_default DESC", [":usrid"=>$user_id]);
            if(empty($usrbranch['status'])) {
                throw new \Exception($usrbranch['error']);
            }
            $tbl  = $this->FxModel->client_db_prefix.$comp_id . "." . $this->FxModel->tables['email_sms_log'];
            foreach($lrsp['data'] as $log) {
                // print_r($log);
                $resp = $this->sendEmailSMSWhatsApp($comprs['data'], $brchrs['data'], $usrbranch['data'], $log);
                $response  = '';
                $sent         = 0;
                $status       = 0;
                $sent_at      = NULL;
                $message_id   = NULL;
                if(empty($resp['status'])) {
                    Logger::error("Email/SMS/WhatsApp Failed, Log ID:".$log['id']." : ".$resp['error'], ['File' => __FILE__, 'Line' => __LINE__]);
                    $response = $resp['error'];
                } else {
                    $response = $resp['data'];
                    $sent        = 1;
                    $status      = 1;
                    $sent_at  = date("Y-m-d H:i:s");
                    Logger::debug("Email/SMS/WhatsApp Success, Log ID:".$log['id'], ['File' => __FILE__, 'Line' => __LINE__]);
                }
                if(!empty($resp['message_status'])) {
                    $status = $resp['message_status'];
                }
                if(!empty($resp['message_id'])) {
                    $message_id = $resp['message_id'];
                }
                
                $updrs = $this->FxModel->update($tbl, ["status"=>$status, "sent"=>$sent, "sent_at"=>$sent_at, "response"=>$response, "transaction_id"=>$message_id], ["id"=>$log['id']]);
                if(empty($updrs)) {
                    Logger::error($updrs['error'], ['File' => __FILE__, 'Line' => __LINE__]);
                }
            }
            return ["status"=>true, "message"=>"Email/sms logs processed successfully."];
        } catch(\Exception $e) {
            Logger::error($e->getMessage(), ['File' => $e->getFile(), 'Line'=>$e->getLine()]);
            return ["status"=>false, "error"=>$e->getMessage()];
        }
    }

    function sendEmailSMSWhatsApp($comp, $branch_list, $usrbranch, $log) {
        try {
            if(!in_array(strtolower($log['type']), ['email', 'sms', 'whatsapp'])) {
                throw new \Exception("Type must be email, sms or whatsapp");
            }
            if(strtolower($log['type']) == 'email' && empty($log['email_subject'])) {
                throw new \Exception("Email Subject is required");
            }
            if(empty($log['body']) && empty($log['attachment'])) {
                throw new \Exception("Content or Attachment required");
            }
            
            $settings = [];
            foreach($branch_list as $val) {
                $branch = NULL;
                if(!empty($usrbranch)) {
                    if($usrbranch['branch_id'] == $val['branch_id']) {
                      $branch = $val;
                      break;
                    }
                } else {
                    if(!empty($val['is_default']) && $val['is_default'] == 1) {
                        $branch = $val;
                        break;
                    }
                }
            }
            
            if(empty($branch)) {
                throw new \Exception("Branch detail not configured to process email/SMS/whatsapp");
            }
            
            $default = ($branch['is_default']) ? " default":"";
            if(strtolower($log['type']) == 'email') {
                if(!empty($branch['email_host']) && !empty($branch['email_username']) && !empty($branch['email_password']) && !empty($branch['email_port'])) {
                    $settings = $branch;
                } else {
                    throw new \Exception("SMTP Setting not configured/complete in$default branch detail");
                } 
            } else if(strtolower($log['type']) == 'sms') {
                if(!empty($branch['sms_url']) && !empty($branch['sms_api_method']) && !empty($branch['sms_api_data_type']) && !empty($branch['sms_api_response_type'])) {
                    $settings = [
                        "url" => !empty($branch['sms_url']) ? stripslashes($branch['sms_url']) : "",
                        "api_method" => $branch['sms_api_method'],
                        "api_response_type" => $branch['sms_api_response_type'],
                        "api_headers" => !empty($branch['sms_api_headers']) ? stripslashes($branch['sms_api_headers']) : "",
                        "api_data_type" => $branch['sms_api_data_type'],
                        "api_data"=> !empty($branch['sms_api_data']) ? stripslashes($branch['sms_api_data']) : "",
                        "sms_provider" => !empty($branch['sms_provider']) ? $branch['sms_provider'] : ""
                    ];
                    foreach($branch as $key=>$val) {
                        if(in_array($key, ['sms_url','sms_provider', 'sms_api_headers', 'sms_api_method', 'sms_api_response_type', 'sms_api_data_type'])) {
                            $settings[$key] = $val;
                        }
                    }
                } else {
                    throw new \Exception("SMS Setting not configured/complete in$default branch detail");
                } 
            } else if(strtolower($log['type']) == 'whatsapp') {
                if(!empty($branch['whatsapp_provider']) && !empty($branch['whatsapp_url'])) {
                    $settings = [
                        "url" => !empty($branch['whatsapp_url']) ? stripslashes($branch['whatsapp_url']) : "",
                        "whatsapp_provider" => $branch['whatsapp_provider'],
                        "api_headers" => !empty($branch['whatsapp_api_headers']) ? stripslashes($branch['whatsapp_api_headers']) : "",
                        "api_method" => $branch['whatsapp_api_method'],
                        "api_response_type" => $branch['whatsapp_response_type'],
                        "api_data_type" => $branch['whatsapp_api_data_type'],
                        "api_data"=> ""
                    ];
                    foreach($branch as $key=>$val) {
                        if(in_array($key, ['whatsapp_url','whatsapp_provider', 'whatsapp_api_headers', 'whatsapp_api_method', 'whatsapp_response_type', 'whatsapp_api_data_type', 'whatsapp_text_message', 'whatsapp_image_message', 'whatsapp_audio_message', 'whatsapp_video_message', 'whatsapp_attachment_message'])) {
                            $settings[$key] = $val;
                        }
                    }
                } else {
                    throw new \Exception("WhatsApp Setting not configured/complete in $default branch detail");
                } 
            }
            if(empty($settings)) {
                throw new \Exception("Mailer/SMS/WhatsApp Setting not configured/complete in branch detail");
            }
            if(in_array(strtolower($log['type']), ['sms', 'whatsapp'])) {
                if(!empty($settings['api_headers'])) {
                    $settings['api_headers'] = json_decode($settings['api_headers'], true);
                } else {
                    $settings['api_headers'] = [];
                }
                if(strtolower($log['type']) == 'sms' && strtolower($settings['api_method']) == 'post') {
                    if(!empty($settings['api_data'])) {
                        $settings['api_data'] = json_decode($settings['api_data'], true);
                    } else {
                        $settings['api_data'] = [];
                    }
                }
            }
            
            if(strtolower($log['type']) == 'email') {
                return $this->sendEmail($comp, $log, $settings);
            } else if(in_array(strtolower($log['type']), ['sms', 'whatsapp'])) {
                return $this->sendSMSWhatsApp($comp, $log, $settings);
            } else {
                throw new \Exception("Invalid Log Type. Please specify: email, sms or whatsapp");
            }
        } catch(\Exception $e) {
            Logger::error($e->getMessage(), ['File' => $e->getFile(), 'Line'=>$e->getLine()]);
            return ["status"=>false, "error"=>$e->getMessage()];
        }
    }

    function sendEmail($comp, $log, $settings) {
        try {
            $template_vars = [];
            if(!empty($log['ref_id']) && !empty($log['ref_type'])) {
                $tmprs = $this->getVariableReplacementData($comp['id'], $log['ref_type'], $log['ref_id']);
                if(empty($tmprs['status'])) {
                    throw new \Exception($tmprs['error']);
                } 
                if(!empty($tmprs['data'])) {
                    $template_vars = !empty($tmprs['data']['variable_val']) ? $tmprs['data']['variable_val'] : [];
                }
                if(empty($log['to'])) {
                    if(!empty($tmprs['data']['email_id'])) {
                        $log['to'] =   $tmprs['data']['email_id'];       
                    } else {
                        throw new \Exception("Email Id found empty for this lead");
                    }
                }
                if(empty($log['to'])) {
                    throw new \Exception("recipient detail is required");
                }
                if(!empty($template_vars)) {
                    $replrs = Utilities::replaceVariables($template_vars, ["email_subject"=>$log["email_subject"], "body"=>$log["body"]]);
                    if(empty($replrs['status'])) {
                        throw new \Exception($replrs['error']);
                    } 
                    $log['email_subject'] = $replrs['data']['email_subject'];
                    $log['body'] = $replrs['data']['body'];
                }
            }
            $data = [
                "to" => explode(",", $log['to']),
                "cc" => !empty($log['cc']) ? explode(",", $log['cc']) : [],
                "bcc" => !empty($log['bcc']) ? explode(",", $log['bcc']) : [],
                "subject" => $log['email_subject'],
                "body" => !empty($log['body']) ? $log['body'] : NULL,
                "attachments" => !empty($log['attachment'])?json_decode($log['attachment'], true) : []
            ];
            $rsp = $this->Messaging->sendClientEmail($comp['id'], $log['cr_usr'], $settings, $data, $log['id']);
            if(empty($rsp['status'])) {
                throw new \Exception($rsp['error']);
            }
            return ["status"=>true, "data"=>$rsp['data']];
        } catch(\Exception $e) {
            Logger::error($e->getMessage(), ['File' => $e->getFile(), 'Line'=>$e->getLine()]);
            return ["status"=>false, "error"=>$e->getMessage()];
        }
    }
    
    function sendSMSWhatsApp($comp, $log, $settings) {
        try {
            $vars = Main::$api_variables;
            $api_vars = [];
            $template_vars = [];
            if(!empty($log['ref_id']) && !empty($log['ref_type'])) {
                $tmprs = $this->getVariableReplacementData($comp['id'], $log['ref_type'], $log['ref_id']);
                if(empty($tmprs['status'])) {
                    throw new \Exception($tmprs['error']);
                } 
                if(!empty($tmprs['variable_val'])) {
                    $template_vars = !empty($tmprs['variable_val']) ? $tmprs['variable_val'] : [];
                }

                if(empty($log['to'])) {
                    $log['country_code'] = !empty($tmprs['data']['country_code']) ? $tmprs['data']['country_code'] : '';
                    $log['to'] = !empty($tmprs['data']['mobile_no']) ? $tmprs['data']['mobile_no'] : '';
                }
                if(empty($log['to'])) {
                    throw new \Exception("recipient detail is required");
                }
                
                if(!empty($template_vars)) {
                    $replrs = Utilities::replaceVariables($template_vars, ["body"=>$log["body"]]);
                    if(empty($replrs['status'])) {
                        throw new \Exception($replrs['error']);
                    } 
                    $log['body'] = $replrs['data']['body'];
                }

                foreach ($vars as $k => $v) {
                    switch($k) {
                        case 'agent_extention': $api_vars[$v] = !empty($tmprs['data']['agent_extention']) ? $tmprs['data']['agent_extention'] : $v; break;
                        case 'agent_mobile_no': $api_vars[$v] = !empty($tmprs['data']['agent_mobile_no']) ? $tmprs['data']['agent_mobile_no'] : $v; break;
                        case 'lead_id': $api_vars[$v]  = !empty($tmprs['data']['lead_id']) ? $tmprs['data']['lead_id'] : $v; break;
                        case 'order_id': $api_vars[$v] = !empty($tmprs['data']['order_id']) ? $tmprs['data']['order_id'] : $v; break;
                        case 'agent_id': $api_vars[$v] = !empty($tmprs['data']['agent_id']) ? $tmprs['data']['agent_id'] : $v; break;
                        case 'uui' : $api_vars[$v] = !empty($tmprs['data']['uui']) ? $tmprs['data']['uui'] : $v; break;
                        default: break;
                    }
                }
            }
            foreach ($vars as $k => $v) {
                switch($k) {
                    case 'customer_mobile_no': {
                            if(empty($api_vars[$v])) {
                                if(!empty($log['to'])) {
                                    $phone_no_arr = explode(",", $log['to']);
                                    if(!empty($log['country_code'])) {
                                        foreach($phone_no_arr as $index => $phone_no) {
                                            if(strtolower($log['country_code']) == '91') {
                                                $phone_no_arr[$index] = strlen($phone_no) <= 10 ? $log['country_code'].$phone_no : $phone_no; 
                                            } else {
                                                $phone_no_arr[$index] = $log['country_code'].$phone_no; 
                                            }
                                        }
                                    }
                                    $api_vars[$v] = implode(",",$phone_no_arr);
                                }
                            }
                        }
                        break;
                    case 'sms_sender_id' : $api_vars[$v] = !empty($log['sender_id']) ? $log['sender_id'] : $v; break;
                    case 'dlt_template_id' : $api_vars[$v] = !empty($log['dlt_template_id']) ? $log['dlt_template_id'] : $v; break;
                    case 'message': $api_vars[$v] = $log['body']; break;
                    default: break;
                }
            }
            if(strtolower($log['type']) == 'sms') {
                return $this->sendSMS($settings, $log, $api_vars);
            } else if(strtolower($log['type']) == 'whatsapp') {
                return $this->sendWhatsAppMessage($settings, $log, $api_vars);
            }
        } catch(\Exception $e) {
            Logger::error($e->getMessage(), ['File' => $e->getFile(), 'Line'=>$e->getLine()]);
            return ["status"=>false, "error"=>$e->getMessage()];
        }
    }

    function sendSMS($settings, $log, $api_vars) {
        try {
            $replrs = Utilities::replaceVariables($api_vars, ["url"=>$settings['url'], "api_headers"=>$settings["api_headers"], "api_data"=>$settings["api_data"]]);
                if(empty($replrs['status'])) {
                    throw new \Exception($replrs['error']);
                } 
                $settings['url'] = $replrs['data']['url'];
                $settings['api_headers'] = $replrs['data']['api_headers'];
                $settings['api_data'] = $replrs['data']['api_data'];
                $header = Sms::getAPIHeaders($settings, $replrs['data']['api_headers']);
                if(empty($header['status'])) {
                    throw new \Exception($header['error']);
                }
                $settings['api_headers'] = $header['data'];

                $rsp = $this->Messaging->sendClientMessage($settings, strtolower($log['type']));
                Logger::debug("api_status::".(string)$rsp['status'], ['File' => __FILE__, 'Line'=>__LINE__]);
                if(empty($rsp['status'])) {
                    throw new \Exception($rsp['error']);
                }
                $response = (strtolower($settings['api_response_type']) == 'json') ? json_decode($rsp['data'], true) : $rsp['data'];
                $resprs = Sms::checkApiResponse($settings, $response);
                if(!empty($resprs['status'])) {
                    return ["status"=>true, "data"=>$rsp['data'], "message_status"=>$resprs['message_status'], "message_id"=>$resprs['message_id']];
                } else {
                    Logger::error($resprs['error'], ['File' => __FILE__, 'Line'=>__LINE__]);
                }
                return ["status"=>true, "data"=>$response];
        } catch(\Exception $e) {
            Logger::error($e->getMessage(), ['File' => $e->getFile(), 'Line'=>$e->getLine()]);
            return ["status"=>false, "error"=>$e->getMessage()];    
        }
    }

    function sendWhatsAppMessage($settings, $log, $api_vars) {
        try {
            $replrs = Utilities::replaceVariables($api_vars, ["url"=>$settings['url'], "api_headers"=>$settings["api_headers"]]);
            if(empty($replrs['status'])) {
                throw new \Exception($replrs['error']);
            } 
            $settings['url'] = $replrs['data']['url'];
            $settings['api_headers'] = $replrs['data']['api_headers'];
            if(empty($log['whatsapp_provider'])) {
                foreach($settings as $key=>$val) {
                    if(in_array($key, ['whatsapp_url','whatsapp_provider', 'whatsapp_api_headers', 'whatsapp_api_method', 'whatsapp_response_type', 'whatsapp_api_data_type', 'whatsapp_text_message', 'whatsapp_image_message', 'whatsapp_audio_message', 'whatsapp_video_message', 'whatsapp_attachment_message'])) {
                        $log[$key] = $val;
                    }
                }
            }
            $header = WhatsApp::getAPIHeaders($log, $settings['api_headers']);
            if(empty($header['status'])) {
                throw new \Exception($header['error']);
            }
            $settings['api_headers'] = $header['data'];
            if(empty($log['is_whatsapp_business_template'])) {
                if(!empty($log['attachment'])) {
                    $attch = json_decode($log['attachment'], true);
                    $reprs = WhatsApp::getApiAttachmentMessage($log, $api_vars, $attch[0]);
                } else {
                    $reprs = WhatsApp::getApiTextMessage($log, $api_vars);
                }
                if(empty($reprs['status'])) {
                    throw new \Exception($reprs['error']);
                }
                $settings['api_data'] = $reprs['data'];
            } else {
                $settings['api_data'] = !empty($api_vars['message']) ? $api_vars['message'] : $log['body'];
            }
            $settings['api_method'] = $log['whatsapp_api_method'];
            $settings['api_response_type'] = $log['whatsapp_response_type'];
            $rsp = $this->Messaging->sendClientMessage($settings, strtolower($log['type']));
            Logger::debug("api_status::".(string)$rsp['status'], ['File' => __FILE__, 'Line'=>__LINE__]);
            if(empty($rsp['status'])) {
                throw new \Exception($rsp['error']);
            }
            $response = (strtolower($settings['api_response_type']) == 'json') ? json_decode($rsp['data'], true) : $rsp['data'];
            $resprs = WhatsApp::checkApiResponse($log, $response);
            if(!empty($resprs['status'])) {
                return ["status"=>true, "data"=>$rsp['data'], "message_status"=>$resprs['message_status'], "message_id"=>$resprs['message_id']];
            } else {
                Logger::error($resprs['error'], ['File' => __FILE__, 'Line'=>__LINE__]);
            }
            return ["status"=>true, "data"=>$response];
        } catch(\Exception $e) {
            Logger::error($e->getMessage(), ['File' => $e->getFile(), 'Line'=>$e->getLine()]);
            return ["status"=>false, "error"=>$e->getMessage()];    
        }
    }

    function getVariableReplacementData($comp_id, $ref_type, $ref_id) {
        try {
            if($ref_type == 'lead') {
                $rec = $this->getLeadVariableReplacementData($comp_id, $ref_id);
            } else if($ref_type == 'order') {
                $rec = $this->getOrderVariableReplacementData($comp_id, $ref_id);
            } else {
                return ["status"=>true, "data"=>null, 'variable_val'=>null];
            }
            if(empty($rec['status'])) {
                throw new \Exception($rec['error']);
            }
            $varrs = $this->FxModel->fetchAllData("SELECT * FROM ".$this->FxModel->tables['client_template_variables'], []);
            if(empty($varrs['status'])) {
                throw new \Exception($varrs['error']);
            }
            $reparr = [];
            if(!empty($varrs['data'])) {
                foreach($varrs['data'] as $row) {
                   switch($row['variable_value']) {
                        case '{{customer_name}}': $reparr[$row['variable_value']] = $rec['data']['customer_name']; break;
                        case '{{customer_email_id}}': $reparr[$row['variable_value']] = $rec['data']['customer_email_id']; break;
                        case '{{customer_mobile_no}}': $reparr[$row['variable_value']] = $rec['data']['customer_mobile_no']; break;
                        case '{{payment_link}}': $reparr[$row['variable_value']] = $rec['data']['payment_link']; break;
                        default: break;
                   }
                }
            }
           
            return ["status"=>true, "data"=>$rec['data'], 'variable_val'=>$reparr];
        } catch(\Exception $e) {
            Logger::error($e->getMessage(), ['File' => $e->getFile(), 'Line'=>$e->getLine()]);
            return ["status"=>false, "error"=>$e->getMessage()];   
        }
    }

    function getLeadVariableReplacementData($comp_id, $lead_id) {
        try {
            $cmprs = $this->fx->getCompanyDetail($comp_id);
            if(empty($cmprs['status'])) {
                throw new \Exception($cmprs['error']);
            }
            $table_name = $this->FxModel->client_db_prefix.$comp_id . "." . $this->FxModel->tables['leads'];
            $leadrs = $this->FxModel->getRowFromTable($table_name, "id=:lead_id", [":lead_id"=>$lead_id]);
            if(empty($leadrs['status'])) {
                throw new \Exception($leadrs['error']);
            }
            if(empty($leadrs['data'])) {
                throw new \Exception("Lead detail not found");
            }
            $branchrs = $this->fx->getBranchDetail($comp_id, $this->user_data, $leadrs['data']['branch']);
            if(empty($branchrs['status'])) {
                throw new \Exception($branchrs['error']);
            }
            if(empty($branchrs['data'])) {
                throw new \Exception("Branch detail not found");
            }
            $ldrs = $this->MasterDataSetModel->postDataByIdProcess('leads', $this->FxModel->client_db_prefix.$comp_id, $leadrs['data'], $lead_id);
            if(empty($ldrs['status'])) {
                throw new \Exception($ldrs['error']);
            }
            if(empty($ldrs['data'])) {
                throw new \Exception("Lead Item and tax detail not found");
            }
            $varrs = $this->FxModel->fetchAllData("SELECT * FROM ".$this->FxModel->tables['client_template_variables'], []);
            if(empty($varrs['status'])) {
                throw new \Exception($varrs['error']);
            }
            $ldrs['data']['lead_id'] = $ldrs['data']['id'];
            $ldrs['data']['customer_name'] = $ldrs['data']['client_name'];
            $ldrs['data']['customer_email_id'] = $ldrs['data']['email'];
            $ldrs['data']['country_code'] = $ldrs['data']['contact_code'];
            $ldrs['data']['mobile_no'] = $ldrs['data']['contact_no'];
            $ldrs['data']['customer_mobile_no'] = $ldrs['data']['contact_code'].$ldrs['data']['contact_no'];
            return ["status"=>true, "data"=>$ldrs['data']];
        } catch(\Exception $e) {
            Logger::error($e->getMessage(), ['File' => $e->getFile(), 'Line'=>$e->getLine()]);
            return ["status"=>false, "error"=>$e->getMessage()];   
        }
    }

    function getOrderVariableReplacementData($comp_id, $order_id) {
        try {
            $cmprs = $this->fx->getCompanyDetail($comp_id);
            if(empty($cmprs['status'])) {
                throw new \Exception($cmprs['error']);
            }
            $ordrs = $this->OrderModel->getOrderDetail($comp_id, "o.id IN(".$order_id.")", 1, 1);
            if(empty($ordrs['status'])) {
                throw new \Exception($ordrs['error']);
            }
            if(empty($ordrs['data'])) {
                throw new \Exception("Order detail not found");
            }
            
            $branchrs = $this->fx->getBranchDetail($comp_id, $this->user_data, $ordrs['data']['branch_id']);
            if(empty($branchrs['status'])) {
                throw new \Exception($branchrs['error']);
            }
            if(empty($branchrs['data'])) {
                throw new \Exception("Branch detail not found");
            }
            $ordItemrs = $this->OrderModel->getOrderItemList($comp_id, "order_id=".$order_id, 0, 0);
            if(empty($ordItemrs['status'])) {
                throw new \Exception($ordItemrs['error']);
            }
            if(empty($ordItemrs['data'])) {
                throw new \Exception("Order Item detail not found");
            }
            $ordrs['data']['item_list'] = $ordItemrs['data'];
            $ordTax = $this->OrderModel->getOrderItemTaxList($comp_id, "order_id=".$order_id);
            if(empty($ordTax['status'])) {
                throw new \Exception($ordTax['error']);
            }
            $tax_list = [];
            $tax_item_list = [];
            if(!empty($ordTax['data'])) {
                foreach ($ordTax['data'] as $tax) {
                    $tax_list[$tax['tax_id']] = $tax['tax_name'];
                    if(array_key_exists($tax['item_id'], $tax_item_list) == false) {
                        $tax_item_list[$tax['item_id']] = [];    
                    }
                    $tax_item_list[$tax['item_id']][$tax['tax_id']] = $tax;
                }
            }
            $ordrs['data']['tax_list'] = $tax_list;
            $ordrs['data']['tax_item_list'] = $tax_item_list;
            
            $custrs = $this->fx->getOrderCustomerDetail($comp_id, $ordrs['data']);
            if(empty($custrs['status'])) {
                throw new \Exception($custrs['error']);
            }
            if(empty($custrs['data'])) {
                throw new \Exception("Customer detail not found");
            }
            $ordrs['data']['customer_detail'] = $custrs['data'];
            $ordrs['data']['country_code'] = !empty($custrs['data']['country_code']) ? $custrs['data']['country_code'] : '91';
            $ordrs['data']['mobile_no'] = $custrs['data']['mobile_number'];
            $ordrs['data']['customer_name'] = $custrs['data']['customer_name'];
            $ordrs['data']['customer_email_id'] = $custrs['data']['email_id'];
            $ordrs['data']['customer_mobile_no'] = !empty($custrs['data']['country_code']) ? $custrs['data']['country_code'].$custrs['data']['mobile_number'] : $custrs['data']['mobile_number'];
            // PAYMENT LINK
            $order_detail = Crypto::getJwtToken(["comp_id"=>$comp_id, "order_id"=>$order_id]);
            $order_token  = Crypto::encryptData($order_detail);
            $link_url = urlencode(Main::getPublicURL().'/client/paynow?token='.urlencode($order_token));
            $ordrs['data']['payment_link'] = $link_url;

            return ["status"=>true, "data"=>$ordrs['data']];
        } catch(\Exception $e) {
            Logger::error($e->getMessage(), ['File' => $e->getFile(), 'Line'=>$e->getLine()]);
            return ["status"=>false, "error"=>$e->getMessage()];   
        }
    }
}
