<?php

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

$hook = array(
    'hook' => 'TicketPiping',
    'function' => 'suiten_TicketPiping'
);

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_TicketPiping')) {

	function suiten_TicketPiping($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';

		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;
		}

		$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);

		$firstname = $SuitenObject['name'];
		$lastname = '';
		$client_info = $firstname . ' ' . $lastname . ' (' . $SuitenObject['to'] . ')';


		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;
	    }


		// 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,
			$SuitenObject['subject'],
			"n/a",
			"n/a",
			$SuitenObject['body'],
			"n/a",
			"xxx",
			"Email",
			$whatsapp_Signature_message,
			$suiten_url_whmcs,
			$suiten_url_whmcs . '/viewticket.php',
			timeStampWhatsapp()
		);

		// Akses API for Admin
		if($status_adminmsg>=1 && $whatsapp_admin <> ''){
			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 . ' TicketOPipe 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;
