<?php

use WHMCS\Session;
use Carbon\Carbon;
use WHMCS\Database\Capsule;

$hook = array(
    'hook' => 'TicketOpen',
    'function' => 'suiten_TicketOpen'
);

global $suiten_nomorwhatsapp;
global $whatsapp_admin;
global $suiten_Whatsapp_Message, $sLogo;
global $suiten_Whatsapp_AdminMsg;
global $KoreksiNomor;
global $client_id, $client_info;

if (!function_exists('suiten_TicketOpen')) {

	function suiten_TicketOpen($SuitenObject) {

		global $suiten_nomorwhatsapp;
		global $suiten_Whatsapp_Message, $sLogo;
		global $KoreksiNomor;
		global $client_id, $client_info;
		
		global $suiten_Whatsapp_AdminMsg;
		global $whatsapp_admin;
		global $status_adminmsg;
				
		$global_module_name = 'SUITEN Whatsapp API';
	
		$ticketuid = $SuitenObject['ticketid'];
		$departamentodoticket = $SuitenObject['deptname'];
		$prioridadedoticket = $SuitenObject['priority'];

		foreach (WHMCS\Database\Capsule::table('s10wa_config')->WHERE('suiten_Nama_Modul', $global_module_name)->get() as $modulwa_config) {
		    $gwhost = $modulwa_config->gwhost;
		    $whatsapp_source = $modulwa_config->suiten_field_nomorwa;
			$whatsapp_admin = $modulwa_config->suiten_adminwa;
		    $whatsapp_metode_kirim = $modulwa_config->suiten_sending_method;
		    $whatsapp_Signature_message = $modulwa_config->suiten_signature;
			$cfgnegara = $modulwa_config->suiten_countrycode;
		}

		// Ambil Data Client
		foreach (Capsule::table('tbltickets')->where([['id','=',$ticketuid],])->get() as $client) {
	    	$client_id = $client->userid;
			$clientcallid = $client->tid;
			$clientcallkey = $client->c;
			$ticket_title = $client->title;
			$ticket_msg = $client->message;
		}

		// datarecord do Cliente tblclients
		foreach (Capsule::table('tblclients')->where([['id','=',$client_id],])->get() as $CustomerInfo) {
            $firstname = rtrim($CustomerInfo->firstname);
            $lastname = rtrim($CustomerInfo->lastname);
            $email = $CustomerInfo->email;
            $phonenumber = $CustomerInfo->phonenumber;
            $alamat1 = $CustomerInfo->address1;
            $alamat2 = $CustomerInfo->address2;
            $kota = $CustomerInfo->city;
            $provinsi = $CustomerInfo->state;
            $kodepos = $CustomerInfo->postcode;
            $negara = $CustomerInfo->country;
        }
		$client_info = $firstname . ' ' . $lastname . ' (' . $email . ')';

		$suiten_nomorwhatsapp = '';
        if($whatsapp_metode_kirim == 'Custom') {
			$suiten_nomorwhatsapp =  "";
			foreach (Capsule::table('tblcustomfieldsvalues')->where([['fieldid','=',$whatsapp_source],['relid','=',$client_id],])->get() as $datarecord) {
				$suiten_nomorwhatsapp = $datarecord->value;
			}
        } else {
            $suiten_nomorwhatsapp = $phonenumber;
        }
		$KoreksiNomor = suiten_koreksinomor($negara,$suiten_nomorwhatsapp);	

		foreach (WHMCS\Database\Capsule::table('s10wa_templates')->WHERE('s10wa_templatetitle', 'Ticket Opened')->get() as $wamodule_msg_record) {
			$body_message = suiten_pilihbahasatemplate($negara, $KoreksiNomor, $wamodule_msg_record->s10wa_templatecontent, $wamodule_msg_record->s10wa_templateenglish);
			$status_message = $wamodule_msg_record->s10wa_templatestatus;
		}

		foreach (WHMCS\Database\Capsule::table('s10wa_templates')->WHERE('s10wa_templatetitle', 'Admin Ticket Opened')->get() as $wamodule_msg_record) {
	        $body_adminmsg = $wamodule_msg_record->s10wa_templatecontent;
	        $status_adminmsg = $wamodule_msg_record->s10wa_templatestatus;
	    }

		$query = "SELECT tk.date, rp.date, tk.id FROM tbltickets as tk, tblticketreplies as rp WHERE tk.id=rp.tid AND tk.admin='' GROUP BY tk.id ORDER BY tk.date DESC LIMIT 0,10";
		$result = full_query($query);	
		while ($data = @mysql_fetch_array ($result)) {
			$tempo = abs(strtotime($data['0']) - strtotime($data['1']));
			$minutos  = floor(($tempo)/ 60);
			$tempos[] = $minutos;
		}
		
		$media = round(array_sum($tempos)/10);
		$nJam = (int)($media / 60);
		$h = ($nJam > 0) ? $nJam." jam " : "";	
		$nMenit = $media - ($nJam * 60);
		$m = $nMenit." menit";
		$durasirespon = suiten_pilihbahasatemplate($negara, $KoreksiNomor, $h.$m, $nJam.":".$nMenit);

		$suiten_url_whmcs = rtrim(\App::getSystemUrl(),"/");

		if(($client_id != 0) && ($client_id != "")) {
			$sLogo = "";
			if (strpos(strtolower($body_message),"{logo}") !== false) {
				$body_message = str_ireplace(
					"{logo}", 
					"", 
					$body_message
				);
				$sLogo = "logo";
			}
						
			// Handles the strings for the message template
			$s10tag_key = array(
				"{S10WA_NamaClient}",
				"{S10WA_FirstName}",
				"{S10WA_LastName}",
				"{S10WA_DurasiRespon}",
				"{S10WA_AvgHour}",
				"{S10WA_AvgMin}",
				"{S10WA_AvgMins}",
				"{S10WA_TiketPerihal}",
				"{S10WA_TiketSysID}",
				"{S10WA_TiketNomor}",
				"{S10WA_TiketMsg}",
				"{S10WA_DeptStaf}",
				"{S10WA_SessionKey}",
				"{S10WA_TiketPrioritas}",
				"{suiten_signature}",
				"{S10WA_DomainWHMCS}",
				"{S10WA_OpenTicketPage}",
				"{S10WA_TimeStamp}"
			);

			$s10tag_value = array(
				trim($firstname) . ' ' . trim($lastname),
				$firstname,
				$lastname,
				$durasirespon,
				$nJam,
				$nMenit,
				$media,
				$ticket_title,
				$SuitenObject['ticketid'],
				$clientcallid,
				$ticket_msg,
				$departamentodoticket,
				$clientcallkey,
				$prioridadedoticket,
				$whatsapp_Signature_message,
				$suiten_url_whmcs,
				$suiten_url_whmcs . '/viewticket.php?tid=' . $clientcallid . '&c=' . $clientcallkey,
				timeStampWhatsapp()
			);

			$suiten_Whatsapp_Message = str_ireplace(
				$s10tag_key, 
				$s10tag_value, 
				$body_message
			);

			$suiten_Whatsapp_AdminMsg = str_ireplace(
				$s10tag_key, 
				$s10tag_value, 
				$body_adminmsg
			);
		}

		// Akses API for User 
		if(($status_message >= "1") && ($suiten_nomorwhatsapp != "") && ($suiten_nomorwhatsapp != "0") && (strlen($suiten_nomorwhatsapp) > 8) && ($client_id != 0) && ($client_id != "")) {

			try {

                Capsule::connection()->transaction(
                    function ($connectionManager)
                        {

                    	global $suiten_nomorwhatsapp;
                    	global $suiten_Whatsapp_Message, $sLogo;
						global $KoreksiNomor;
						global $client_id, $client_info;

                        $connectionManager->table('s10wa_sendmsg')->insert(

                            [
                                's10wa_date' => timeStampWhatsapp(),
                                's10wa_wanumber' => $KoreksiNomor,
                                's10wa_interval' => (int)4,
                                's10wa_message' => $suiten_Whatsapp_Message,
                                's10wa_msgtype' => (int)1,
								's10wa_attachment' => $sLogo,
								's10wa_clientid' => $client_id,
								's10wa_clientinfo' => $client_info,							
                                's10wa_status' => (int)0
                            ]

                        );

						logactivity( 'SUITEN_WAMLog: ' . $result . ' TicketOpen WA#'.$KoreksiNomor, $client_id);

                    }
                );

               

            } catch (\Exception $e) {

                $result = 'MySQL Error: ' . $e;
                exit();

            }
		}


		// Akses API for Admin 
		if( $status_adminmsg >= "1" && $whatsapp_admin != "" && $client_id != 0 && $client_id != "") {

			try {

				$daftarnomeradmin = explode(";",$whatsapp_admin);
				foreach ( $daftarnomeradmin as $eachwaadmin ) {
					$KoreksiNomor = suiten_koreksinomor($cfgnegara, $eachwaadmin);
					Capsule::connection()->transaction(
						function ($connectionManager)
							{

							global $KoreksiNomor;
							global $whatsapp_admin;
							global $suiten_Whatsapp_AdminMsg;
							global $client_id, $client_info;

							$connectionManager->table('s10wa_sendmsg')->insert(

								[
									's10wa_date' => timeStampWhatsapp(),
									's10wa_wanumber' => $KoreksiNomor,
									's10wa_interval' => (int)4,
									's10wa_message' => $suiten_Whatsapp_AdminMsg,
									's10wa_msgtype' => (int)1,
									's10wa_clientid' => $client_id,
									's10wa_status' => (int)0
								]

							);

							logactivity( 'SUITEN_WAMLog: ' . $result . ' TicketOpen Admin WA#'.$KoreksiNomor. ( $sLogo == "" ? "" : " with ". $sLogo ), $client_id);

						}
					);
				}
              
			} catch (\Exception $e) {

				$result = 'S10WAM Error: ' . $e;
				exit();

			}

			
			if (function_exists('suiten_SyncDB')) 
				suiten_SyncDB($SuitenObject);
	
		}

	}

}

return $hook;
