<?php
/*+*******************************************************************************
 * The content of this file is subject to the CRMTiger Pro license.
 * ("License"); You may not use this file except in compliance with the License
 * The Initial Developer of the Original Code is vTiger
 * The Modified Code of the Original Code owned by https://crmtiger.com/
 * Portions created by CRMTiger.com are Copyright(C) CRMTiger.com
 * All Rights Reserved.
  ***************************************************************************** */
require_once 'modules/CTWhatsApp/CTWhatsApp.php';

class CTMobile_WS_SendWhatsAppMessage extends CTMobile_WS_Controller {
	
	function process(CTMobile_API_Request $request) {
		$default_charset = VTWS_PreserveGlobal::getGlobal('default_charset');
		global $current_user, $adb, $site_URL,$root_directory; // Few core API assumes this variable availability
		$current_user = $this->getActiveUser();
        $currenUserID = $current_user->id;
        $configurationData = Settings_CTWhatsApp_Record_Model::getUserConfigurationAllDataWithId($currenUserID);
        $api_url = $configurationData['api_url'];
        $auth_token = $configurationData['authtoken'];
        $customfield1 = $configurationData['customfield1'];
        $whatsappScanNo = $configurationData['whatsappno'];
        $whatsappStatus = $configurationData['whatsappstatus'];
        $configureUserid = $configurationData['configureUserid'];
        if(!$whatsappStatus){
            $response = new CTMobile_API_Response();
            $response->setError(345,"WhatsApp number is disconnected");
            return $response;
            exit;
        }
		$message = $request->get('message');
        if(is_numeric($message)){
            $message = $message.' ';
        }
		$tonumber = $request->get('tonumber');
        $moduleRecordid = $request->get('recordid');
        $recordModule = $request->get('recordModule');
        $replyMessageId = $request->get('replyMessageId');
        $replymessageText = $request->get('replymessageText');
		$sendMessagewpnumber = $request->get('sendMessagewpnumber');
        $wptemplateid = $request->get('wptemplateid');
		if($_FILES['filename']['name'] != ''){
			$whatsappFolderPath = "/modules/CTWhatsApp/CTWhatsAppStorage/";
			$msgbody = $filename = $_FILES['filename']['name'];
			$filetype = $_FILES['filename']['type'];
			
			/*if($filetype == 'm4a'){
                $pathinfo = pathinfo($filename);
                $filename = $pathinfo['filename'].'.mp3';
            }*/

            if($filename != ''){
                $documentpath = 'storage';
                $filepath = 'storage/';
                $year  = date('Y');
                $month = date('F');
                $day   = date('j');
                $week  = '';

                if (!is_dir($root_directory.$filepath . $year)) {
                    //create new folder
                    mkdir($root_directory.$filepath . $year);
                    chmod($root_directory.$filepath . $year, 0777);
                }

                if (!is_dir($root_directory.$filepath . $year . "/" . $month)) {
                    //create new folder
                    mkdir($root_directory.$filepath . "$year/$month");
                    chmod($root_directory.$filepath . "$year/$month", 0777);
                }

                if ($day > 0 && $day <= 7)
                    $week = 'week1';
                elseif ($day > 7 && $day <= 14)
                    $week = 'week2';
                elseif ($day > 14 && $day <= 21)
                    $week = 'week3';
                elseif ($day > 21 && $day <= 28)
                    $week = 'week4';
                else
                    $week = 'week5';

                if (!is_dir($root_directory.$filepath . $year . "/" . $month . "/" . $week)) {
                    //create new folder
                    mkdir($root_directory.$filepath . "$year/$month/$week");
                    chmod($root_directory.$filepath . "$year/$month/$week", 0777);
                }

                $target_file = $root_directory.$filepath.$year.'/'.$month.'/'.$week.'/';

                /*list($type, $base64imagedata) = explode(';', $base64imagedata);
                list(, $base64imagedata)      = explode(',', $base64imagedata);
                $base64imagedata = base64_decode($base64imagedata);*/

                $filemove = copy($_FILES['filename']['tmp_name'],$target_file.$filename);
                if($filemove){
                    $Document = Vtiger_Record_Model::getCleanInstance('Documents');
                    $Document->set('mode', '');
                    $Document->set('assigned_user_id',$current_user->id);
                    $Document->set('folderid', 1);
                    $Document->set('filelocationtype', 'I');
                    $Document->set('filestatus',1);
                    $Document->set('filename',$filename);
                    $Document->save();
                    $documentid = $Document->getId();
                    $current_id = $adb->getUniqueID("vtiger_crmentity");

                    $sql1 = "insert into vtiger_crmentity (crmid,smcreatorid,smownerid,setype,description,createdtime,modifiedtime) values(?, ?, ?, ?, ?, ?, ?)";
                    $params1 = array($current_id, $current_user->id, 1, "Documents Attachment", '', $adb->formatDate($date_var, true), $adb->formatDate($date_var, true));
                    $adb->pquery($sql1, $params1);
                    rename($target_file.$filename,$target_file.$current_id.'_'.$filename);
                    chmod($target_file, 0777);

                    $sql2 = "insert into vtiger_attachments(attachmentsid, name, description, type, path) values(?, ?, ?, ?, ?)";
                    $params2 = array($current_id, $filename, '', '', $target_file);
                    $result = $adb->pquery($sql2, $params2);

                    $sql3 = 'insert into vtiger_seattachmentsrel values(?,?)';
                    $adb->pquery($sql3, array($documentid, $current_id));

                    $sql4 = 'insert into vtiger_senotesrel values(?,?)';
                    $adb->pquery($sql4, array($moduleRecordid, $documentid));
                }
                $fileURL = $site_URL.$filepath.$year.'/'.$month.'/'.$week.'/'.$current_id.'_'.$filename;
                $oldfile = $root_directory.$filepath.$year.'/'.$month.'/'.$week.'/'.$current_id.'_'.$filename;

                $filename = str_replace(' ', '', $filename);
                $newfile = $root_directory.$whatsappFolderPath . "$year/$month/$week/".$filename;

                copy($oldfile, $newfile);
                $newFilename = urlencode($filename);
                $newFilename = str_replace('+','%20',$newFilename);
                $newFilename = str_replace('_','%5F',$newFilename);
                $newFilename = str_replace('.','%2E',$newFilename);
                $newFilename = str_replace('-','%2D',$newFilename); 
                $newfileURL = $site_URL.$whatsappFolderPath . "$year/$month/$week/".$newFilename;
                $newBodyfileURL = $site_URL.$whatsappFolderPath . "$year/$month/$week/".$filename;
            }
            //$newfileURL = "https://4.img-dpreview.com/files/p/E~C667x0S5333x4000T1200x900~articles/3925134721/0266554465.jpeg";
            $url = $api_url.'/sendfileurl';

            if($filetype == 'image/jpeg' || $filetype == 'image/jpg' || $filetype == 'image/png'){
	            $postfields = array(
	                'number' => $tonumber,
	                'url' => $newfileURL,
	                'filetype' => 'imageMessage',
	                'caption' => ''
	            );
            }else if($filetype == 'image/gif'){
                $url = $api_url.'/sendfileurl';

                $postfields = array(
                    'number' => $tonumber,
                    'url' => $newfileURL,
                    'filetype' => 'gifMessage',
                    'caption' => ''
                );
            }else if($filetype == 'application/pdf'){
                $url = $api_url.'/sendfileurl';
                $postfields = array(
                    'number' => $tonumber,
                    'url' => $newfileURL,
                    'mimetype' => 'application/pdf',
                    'filetype' => 'documentMessage',
                    'caption' => urlencode($filename)
                );
            }else if($filetype == 'audio/mpeg'){
                $url = $api_url.'/sendfileurl';
                $postfields = array(
                    'number' => $tonumber,
                    'url' => $newfileURL,
                    'mimetype' => 'audio/mp4',
                    'filetype' => 'audioMessage',
                    'caption' => urlencode($filename)
                );
            }else if($filetype == 'm4a'){
                $url = $api_url.'/sendfileurl';
                $postfields = array(
                    'number' => $tonumber,
                    'url' => $newfileURL,
                    //'mimetype' => 'audio/ogg; codecs=opus',
                    'mimetype' => 'audio/mp4',
                    'filetype' => 'audioMessage',
                    'caption' => urlencode($filename)
                );
            }else{
                $url = $api_url.'/sendfileurl';
                $postfields = array(
                    'number' => $tonumber,
                    'url' => $newfileURL,
                    'mimetype' => $filetype,
                    'filetype' => 'documentMessage',
                    'caption' => urlencode($filename) 
                );
            }

            if($moduleRecordid){
                $setype = VtigerCRMObject::getSEType($moduleRecordid);
                $recordModel = Vtiger_Record_Model::getInstanceById($moduleRecordid, $setype);
                $displayname = $recordModel->get('label');
            }else{
                $displayname = $tonumber;
            }

            if($tonumber){
                $getnumberImportant = CTWhatsApp_Record_Model::getWhatsappNumberImportant($tonumber);
            }
            $date_var = date("Y-m-d H:i:s");

            $getLicenseDetail = CTWhatsApp_Record_Model::getWhatsAppLicenseDetail();
            $licenseKey = $getLicenseDetail['licenseKey'];
            $getWhatsappAccount = CTWhatsApp_Record_Model::getWhatsappAccountDetail($licenseKey);
            $oneDayMessages = CTWhatsApp_Record_Model::getOneDaysMessages();

            $currentusername = $current_user->first_name.' '.$current_user->last_name;

            $whatsappLogQuery = CTWhatsApp_Record_Model::getWhatsAppLogData($tonumber, $moduleRecordid, $whatsappScanNo);
            $whatsapplogRows = $whatsappLogQuery['rows'];
            if($whatsapplogRows == 0){
                $recordModel = Vtiger_Record_Model::getCleanInstance('WhatsAppLog');
                $recordModel->set('whatsapplog_sendername', $currentusername);
                
                if($whatsappModule == "Groups"){
                    $recordModel->set('whatsapplog_msgid', $displayname);
                    $recordModel->set('whatsapplog_withccode', 'Groups');
                }else{
                    $recordModel->set('whatsapplog_msgid', $val['key']['id']);
                    $recordModel->set('whatsapplog_withccode', $mobileno);
                }
                $recordModel->set('messagelog_type', 'Send');

                if($fileURL){
                    $recordModel->set('messagelog_body', $newBodyfileURL);
                }else{
                    $recordModel->set('messagelog_body', $msgbody);
                }
                $recordModel->set('whatsapplog_displayname', $displayname);
                $recordModel->set('whatsapplog_contactid', $moduleRecordid);
                $recordModel->set('whatsapplog_unreadread', 'Unread');
                $recordModel->set('whatsapplog_important', $getnumberImportant);
                $recordModel->set('whatsapplog_your_number', $whatsappScanNo);
                $recordModel->set('whatsapplog_datetime', $adb->formatDate($date_var, true));
                $recordModel->set('assigned_user_id', $currenUserID);
                $recordModel->set('whatsapplog_quotemessage', $replymessageText);
                $requestParam = $whatsappactiveURL.' ';
                $requestParam .= json_encode($postfieldWhatsAppnumber);    
                $recordModel->set('whatsapplog_request', $requestParam);
                if($numberactive == 1){
                    $recordModel->set('whatsapp_numberactive', 1);   
                }else{
                    $recordModel->set('whatsapp_numberactive', 0);
                }
                $recordModel->set('whatsapplog_response', json_encode($whatsAppActiveInActive));

                if($msgbody != ''){
                    if($getWhatsappAccount->type == 'free' && $oneDayMessages < '100'){
                        $recordModel->save();
                    }else if($getWhatsappAccount->type == 'premium'){
                        $recordModel->save();
                    }
                }
                $whatsAppLogId = $recordModel->getId();
            }else{
                $whatsapplogid = $whatsappLogQuery['whatsapplogid'];
                $recordModel = Vtiger_Record_Model::getInstanceById($whatsapplogid, 'WhatsAppLog');
                $recordModel->set('mode', 'edit');
                $recordModel->set('id', $whatsapplogid);
                $recordModel->set('whatsapplog_datetime', $adb->formatDate($date_var, true));
                if($fileURL){
                    $recordModel->set('messagelog_body', $newBodyfileURL);
                }else{
                    $recordModel->set('messagelog_body', $msgbody);
                }
                if($numberactive == 1){
                    $recordModel->set('whatsapp_numberactive', 1);
                }else{
                    $recordModel->set('whatsapp_numberactive', 0);
                }
                $recordModel->set('whatsapplog_response', json_encode($whatsAppActiveInActive));
                $recordModel->save();
                $whatsAppLogId = $recordModel->getId();
            }



            $recordModel = Vtiger_Record_Model::getCleanInstance('CTWhatsApp');
            $recordModel->set('whatsapp_sendername', $currentusername);
            
            if($whatsappModule == "Groups"){
                $recordModel->set('whatsapp_withccode', 'Groups');
            }else{
                $recordModel->set('whatsapp_withccode', $tonumber);
            }
            $recordModel->set('message_type', 'Send');

            /*if($i == 0){
                $recordModel->set('message_body', $msgbody);
            }else{
                $recordModel->set('message_body', $newBodyfileURL);
            }*/
            
            if($fileURL){
                $recordModel->set('message_body', $newBodyfileURL);
            }else{
                $recordModel->set('message_body', $msgbody);
            }

            $recordModel->set('whatsapp_displayname', $displayname);
            $recordModel->set('whatsapp_contactid', $moduleRecordid);
            $recordModel->set('whatsapp_unreadread', 'Unread');
            $recordModel->set('whatsapp_fromno', $whatsappScanNo);
            $recordModel->set('whatsapp_important', $getnumberImportant);
            $recordModel->set('your_number', $whatsappScanNo);
            $recordModel->set('whatsapp_datetime', $adb->formatDate($date_var, true));
            $recordModel->set('assigned_user_id', $currenUserID);
            $recordModel->set('whatsapp_quotemessage', $replymessageText);
            $requestParam = $url.' ';
            $requestParam .= json_encode($postfields);
            $configurationData = Settings_CTWhatsApp_Record_Model::getUserConfigurationDataWithId();
            $whatsapplog = $configurationData['whatsapplog'];
            if($whatsapplog == 1){
                $recordModel->set('whatsapp_request', $requestParam);
            }
            if($msgbody != ''){
                if($getWhatsappAccount->type == 'free' && $oneDayMessages < '100'){
                    $recordModel->save();
                }else if($getWhatsappAccount->type == 'premium'){
                    $recordModel->save();
                }
            }
            $whatsAppModuleId = $recordModel->getId();
            
            $val = CTWhatsApp_WhatsappChat_View::callCURL($url, $postfields, $auth_token);

            $updateWhatsAppLogMessageId = self::updateWhatsAppMessageId('WhatsAppLog', $whatsAppLogId, $val, $whatsapplog, $tonumbersValue, $whatsappModule);

            $updateWhatsAppMessageId = self::updateWhatsAppMessageId('CTWhatsApp', $whatsAppModuleId, $val, $whatsapplog, $tonumber, $whatsappModule);

            if($val['status'] = ""){
            	$response = new CTMobile_API_Response();
				$response->setResult(array("message"=>"Something Went Wrong"));
				return $response;
            }
		}else{
			//$tonumbers = array($tonumber);
            $newRequest = new Vtiger_Request($_REQUEST);
            $newRequest->set('module','CTWhatsApp');
            if (strpos($tonumber, '@g.us') !== false) {
                $newRequest->set('whatsappModule','Groups');
            }else{
                $newRequest->set('whatsappModule','AllMessages');
            }
            if($wptemplateid){
                if(filter_var($message, FILTER_VALIDATE_URL)){
                    $message = "";
                }else{
                    if($moduleRecordid){
                        $setype = VtigerCRMObject::getSEType($moduleRecordid);
                        $message = getMergedDescription($message,$moduleRecordid,$setype);
                    }
                }
            }
        
            $newRequest->set('moduleRecordid',$moduleRecordid);
            $newRequest->set('mobileno',$tonumber);
            $newRequest->set('msgbody',$message);
            $newRequest->set('replyMessageId',$replyMessageId);
            $newRequest->set('replymessageText',$replymessageText);
            $newRequest->set('whatsappNumber',$sendMessagewpnumber);
            //$newRequest->set('wptemplateid',$wptemplateid);
            $sendIndividulMessageDate = CTWhatsApp_Record_Model::sendIndividulMessage($newRequest);
			//CTWhatsApp::sendsms($message, $tonumbers, $current_user->id,'', $sendMessagewpnumber);
		}
		
		
		$response = new CTMobile_API_Response();
		$response->setResult(array("message"=>"Message Sent successfully"));
		return $response;
	}

    public function updateWhatsAppMessageId($modulename, $whatsAppModuleId, $val, $whatsapplog, $mobileno, $whatsappModule){
        if($whatsAppModuleId){
            if($modulename == 'CTWhatsApp'){
                $whatsappRecordModel = Vtiger_Record_Model::getInstanceById($whatsAppModuleId, $modulename);
                $whatsappRecordModel->set('mode', 'edit');
                $whatsappRecordModel->set('id', $whatsAppModuleId);
                if($whatsappModule == "Groups"){
                    $whatsappRecordModel->set('msgid', $mobileno);
                }else{
                    $whatsappRecordModel->set('msgid', $val['key']['id']);
                }
                if($whatsapplog == 1){
                    $whatsappRecordModel->set('whatsapp_response', json_encode($val));
                }
                $whatsappRecordModel->save();   
            }else{
                $whatsappRecordModel = Vtiger_Record_Model::getInstanceById($whatsAppModuleId, $modulename);
                $whatsappRecordModel->set('mode', 'edit');
                $whatsappRecordModel->set('id', $whatsAppModuleId);
                if($whatsappModule == "Groups"){
                    //$whatsappRecordModel->set('whatsapplog_msgid', $mobileno);
                }else{
                    $whatsappRecordModel->set('whatsapplog_msgid', $val['key']['id']);
                }
                if($whatsapplog == 1){
                    $whatsappRecordModel->set('whatsapplog_response', json_encode($val));
                }
                $whatsappRecordModel->save();   
            }
        }
    }

}
