<?php

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

$hook = array(
    'hook' => 'EmailPreSend',
    'function' => 'suiten_EmailPreSend'
);

global $suiten_nomorwhatsapp;
global $suiten_Whatsapp_Message;
global $KoreksiNomor, $SubKontak, $remote_file;
global $client_id, $client_info;

if (!function_exists('suiten_EmailPreSend')) {

	function suiten_EmailPreSend($SuitenObject) {

		global $suiten_nomorwhatsapp;
		global $suiten_Whatsapp_Message;
		global $KoreksiNomor, $SubKontak, $remote_file;
		global $client_id, $client_info;
		
		global $NamaTemplate;
	
		$global_module_name = 'SUITEN Whatsapp API';

		$merge_fields = [];
//		logactivity( 'SUITEN_WAMLog: EmailPreSEND ' . $SuitenObject['messagename'] );
//foreach ($SuitenObject as $dkey => $dvalue) {
//    logactivity( 'SUITEN_WAMLog: EmailPreSEND '. $dkey . ' >>> '. $dvalue);
//}
//foreach ($SuitenObject['mergefields'] as $dkey => $dvalue) {
//    logactivity( 'SUITEN_WAMLog: EmailPreSEND MF '. $dkey . ' >>> '. $dvalue);
//}

//		logactivity( 'SUITEN_WAMLog: RelID ' . $idproduk );

		$result = WHMCS\Database\Capsule::table('tblconfiguration')->select('value')->where('setting', 'LogErrors')->first();
		$logerror = ($result->value == "on" ? TRUE : FALSE);
		
		$result = WHMCS\Database\Capsule::table('tblconfiguration')->select('value')->where('setting', 'LogErrors')->first();
		
		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_metode_kirim = $modulwa_config->suiten_sending_method;
		    $whatsapp_Signature_message = $modulwa_config->suiten_signature;
			$licensekey = explode(";",$modulwa_config->suiten_lisensi)[0];
			$sendingdelay = $modulwa_config->suiten_sending_delay;
			$pdfserver = $modulwa_config->suiten_pdfserver;
		}

		if ($sendingdelay == 8) {
			$cancelinvoiceemail = TRUE;
			// cuma 1x skip			
			WHMCS\Database\Capsule::table('s10wa_config')->WHERE('suiten_Nama_Modul', $global_module_name)->update(array('suiten_sending_delay' => 1));
		} elseif ($sendingdelay == 9) {
			$cancelinvoiceemail = TRUE;
		} else {
			$cancelinvoiceemail = FALSE;
		}

		if (is_numeric(substr($pdfserver, 0, 1))) {
			$pdfpassive = TRUE;
		} elseif ($pdfserver[0]=='A') { 
			$pdfpassive = FALSE;
			$pdfserver = substr($pdfserver,1);
		} elseif ($pdfserver[0]=='P') { 
			$pdfpassive = TRUE;
			$pdfserver = substr($pdfserver,1);
		} else {
			$pdfserver = "";
		}
		$pdfkey = $modulwa_config->suiten_pdfkey;
		$pdfprefix = $modulwa_config->suiten_pdfprefix;

		// UPDATE NAMA TEMPLATE
		switch ($SuitenObject['messagename']) {
			case 'Invoice Payment Confirmation':
			case 'Credit Card Payment Confirmation':
				$NamaTemplate = 'Payment Confirmation';

		// Debug Payment Confirmation
		$output = var_export($SuitenObject, true);
		file_put_contents('paymentconfirmation.txt', $output);
		$output = var_export($SuitenObject['mergefields'], true);
		file_put_contents('paymentconfirmation1.txt', $output);

				break;
			case 'Service Suspension Notification':
				$NamaTemplate = 'Service Suspension';
				break;
			case 'Service Unsuspension Notification':
				$NamaTemplate = 'Service Reactivation';
				break;
			default:
				$NamaTemplate = $SuitenObject['messagename'];
		}

		// AMBIL DATA CLIENT ID
		switch ($SuitenObject['messagename']) {
			case 'Invoice Created':
			case 'Invoice Modified':
			case 'Invoice Payment Reminder':
			case 'First Invoice Overdue Notice':
			case 'Second Invoice Overdue Notice':
			case 'Third Invoice Overdue Notice':
			case 'Invoice Payment Confirmation':
			case 'Credit Card Payment Confirmation':
				if ($cancelinvoiceemail) $merge_fields['abortsend'] = true;

				$nomorinvoice = $SuitenObject['relid'];
				foreach (Capsule::table('tblinvoices')->where([['id','=',$nomorinvoice],])->get() as $invoice) {
					$client_id = $invoice->userid;
					$datepaid = $invoice->datepaid;
					$invoicenum = $invoice->invoicenum;
					$invoiceissuedate = explode('-',$invoice->date);
					$invoiceduedate = explode('-',$invoice->duedate);
					$berapalamaoverdue = time() - strtotime($invoiceduedate[0] . '-' . $invoiceduedate[1] . '-' . $invoiceduedate[2]. '00:00:00');
					$invoicetotal = $invoice->total;
					$creditapplied = $invoice->credit;
					$invoiceamount = $invoicetotal+$creditapplied;
				}

				// link Gerencianet
				//$linkgerencianet = WHMCS\Database\Capsule::table('gofasgerencianetboleto')->select('link')->where('invoice_id', $nomorinvoice)->first();	

				break;
			case 'Service Suspension Notification':
			case 'Service Unsuspension Notification':
			    $product_id = $SuitenObject['relid'];

				foreach (Capsule::table('tblhosting')->where([['id','=',$product_id],])->get() as $client) {
					$client_id = $client->userid;
					$package_id = $client->packageid;
					$namaDomain = $client->domain;
				}
				foreach (Capsule::table('tblproducts')->where([['id','=',$package_id],])->get() as $client2) {
					$namaLayanan = $client2->name;
				}
				break;		
			case 'Upcoming Domain Renewal Notice';
			case 'Expired Domain Notice';
			    $product_id = $SuitenObject['relid'];

				foreach (Capsule::table('tbldomains')->where([['id','=',$product_id],])->get() as $client) {
					$client_id = $client->userid;
					$namaDomain = $client->domain;
					$regperiod = $client->registrationperiod;
					$recuramount = $client->recurringamount;
				}
			default:
				// do nothing return immediately
				// logactivity( 'SUITEN_WAMLog: Skip ' . $SuitenObject['messagename'], $client_id );
				if ($logerror) logactivity( 'SUITEN_WAMLog: Skip EmailPreSEND ' . $SuitenObject['messagename'] );
				$merge_fields = [];
				return $merge_fields;			
		}

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

		// Ambil Data Client
		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;
            $MataUang	=	$CustomerInfo->currency;
        }
		$client_info = $firstname . ' ' . $lastname . ' (' . $email . ')';

		// ambil data subkontak 1
		$SubKontak = array(array('phonenumber'=>'','client_name'=>'','client_info'=>'','remotefile'=>''));
		foreach (Capsule::table('tblcontacts')->where([['userid',$client_id],['invoiceemails',1],])->get() as $ContactData) {
			//SubKontak NomorTelp,Nama+Email, (later added: RemoteFile)
			if ($ContactData->phonenumber <> "") {
				$sk_phone = suiten_koreksinomor($negara,$ContactData->phonenumber);
				$sk_name = $ContactData->firstname . ' ' . $ContactData->lastname;
				$sk_info = $sk_name . ' (' . $ContactData->email . ')';				
				$SubKontak[] = array('phonenumber'=>$sk_phone,'client_name'=>$sk_name,'client_info'=>$sk_info,'remotefile'=>'');
			}
        }	

        foreach (Capsule::table('tblcurrencies')->where([['id','=',$MataUang],])->get() as $result) {
            $suiten_Currency = $result->prefix;
			$suiten_ccycode = $result->code;
            $suiten_ccyprefix = $result->prefix;
            $suiten_ccysuffix = $result->suffix;
			$suiten_ccyformat = $result->format;
        }	

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

		// AMBIL DETAIL LAIN
		switch ($SuitenObject['messagename']) {
			case 'Invoice Created':
			case 'Invoice Modified':
			case 'Invoice Payment Reminder':
			case 'First Invoice Overdue Notice':
			case 'Second Invoice Overdue Notice':
			case 'Third Invoice Overdue Notice':
			case 'Invoice Payment Confirmation':
			case 'Credit Card Payment Confirmation':

				// Reformat invoice amount
				if ($suiten_ccyformat  == 1) {
					$invoicetotaltidy =  number_format($invoicetotal, 2, '.', '');
					$invoiceamounttidy = number_format($invoiceamount, 2, '.', '');
					$creditused = $suiten_ccyprefix. number_format($creditapplied, 2, '.', '').$suiten_ccysuffix;
				} elseif ($suiten_ccyformat  == 2) {
					$invoicetotaltidy = number_format($invoicetotal, 2, '.', ',');
					$invoiceamounttidy = number_format($invoiceamount, 2, '.', ',');
					$creditused = $suiten_ccyprefix. number_format($creditapplied, 2, '.', ',').$suiten_ccysuffix;
				} elseif ($suiten_ccyformat  == 3) {
					$invoicetotaltidy = number_format($invoicetotal, 2, ',', '.');
					$invoiceamounttidy = number_format($invoiceamount, 2, ',', '.');
					$creditused = $suiten_ccyprefix. number_format($creditapplied, 2, ',', '.').$suiten_ccysuffix;
				} elseif ($suiten_ccyformat  == 4) {
					$invoicetotaltidy = number_format($invoicetotal, 0, '', ',');
					$invoiceamounttidy = number_format($invoiceamount, 0, '', ',');
					$creditused = $suiten_ccyprefix. number_format($creditapplied, 0, '', ',').$suiten_ccysuffix;
				} elseif ($suiten_ccycode  == "IDR") {
					$invoicetotaltidy = number_format($invoicetotal, 0, '', '.');
					$invoiceamounttidy = number_format($invoiceamount, 0, '', '.');
					$creditused = $suiten_ccyprefix. number_format($creditapplied, 0, '', '.').$suiten_ccysuffix;
				} else {
					$invoicetotaltidy = strval($invoicetotal);
					$invoiceamounttidy = strval($invoiceamount);
					$creditappliedstr = $suiten_ccyprefix. $creditapplied . $suiten_ccysuffix;
				}

				// Check mergefields exists?
				if ( array_key_exists( 'mergefields' , $SuitenObject ) ) {

					$rincianraw = $SuitenObject['mergefields']['invoice_html_contents'];
					//logactivity('RincianRaw: ' . $rincianraw, $client_id);
					$rincianinvoice = substr($rincianraw,0,strpos($rincianraw,"------------------------------------------------------"));
					$arrayinvoice = explode("<br>", $rincianinvoice);
					$invoiceitemstring = "";
					$invoiceitemcut = "";
				
					//$pakaicredit = $SuitenObject['mergefields']['invoice_credit'];
					$pakaicredit = "";
					//logactivity('RincianRaw: ' . $rincianraw, $client_id);
					$pakaicredit = substr($rincianraw, strpos($rincianraw, "Credit: "));
					$pakaicredit = substr($pakaicredit, 8);
					$pakaicredit = substr($pakaicredit, 0, strpos($pakaicredit,"<br>"));
					$pakaicreditnumonly = intval(preg_replace("/[^0-9]/", "", $pakaicredit ));

					foreach($arrayinvoice as $iteminvoice){
						if(trim($iteminvoice) <> "") {
							//logactivity('Item=' . $iteminvoice, $client_id);
							$invoiceitemstring = $invoiceitemstring . trim($iteminvoice) . "\r\n";
							// $baris_satu = strtok(trim($iteminvoice), "\n");
							if (strpos($iteminvoice,": 0 x ") == false) {
								$invoiceitemcut = $invoiceitemcut . trim($iteminvoice) . "\r\n";
							}
						}
					}
					
					$invoiceitemstring = trim($invoiceitemstring);
					$invoiceitemcut = trim($invoiceitemcut);
					//logactivity('ItemInvoice: ' . $invoiceitemstring, $client_id);
					
				} else {
					$pakaicreditnumonly = $creditapplied;
					$pakaicredit = $creditappliedstr;
					// AMBIL RINCIAN INVOICE
					$invoiceitemstring = "";
					$invoiceitemcut = "";
					foreach (Capsule::table('tblinvoiceitems')->where([['invoiceid',$nomorinvoice],])->get() as $rincian) {
						$invoiceline = $rincian->description.'   ';
						if ($suiten_ccyformat  == 1) {
							$invoiceline .= $suiten_ccyprefix. number_format($rincian->amount, 2, '.', '').$suiten_ccysuffix;
						} elseif ($suiten_ccyformat  == 2) {
								$invoiceline .= $suiten_ccyprefix. number_format($rincian->amount, 2, '.', ',').$suiten_ccysuffix;
						} elseif ($suiten_ccyformat  == 3) {
								$invoiceline .= $suiten_ccyprefix. number_format($rincian->amount, 2, ',', '.').$suiten_ccysuffix;
						} elseif ($suiten_ccyformat  == 4) {
								$invoiceline .= $suiten_ccyprefix. number_format($rincian->amount, 0, '', ',').$suiten_ccysuffix;
						} elseif ($suiten_ccycode  == "IDR") {
								$invoiceline .= $suiten_ccyprefix. number_format($rincian->amount, 0, '', '.').$suiten_ccysuffix;
						} else {
								$invoiceline .= $suiten_ccyprefix. $rincian->amount.$suiten_ccysuffix;
						}
						$invoiceitemstring .= $invoiceline."\r\n";
						if ($rincian->amount <> 0) {
							$invoiceitemcut .= $invoiceline."\r\n";
						}
					}
					
				}
		
				$invoiceitemstring = trim($invoiceitemstring);
				$invoiceitemcut = trim($invoiceitemcut);
		
				// NilaiBayar
				if ($SuitenObject['messagename'] == 'Invoice Payment Confirmation' || $SuitenObject['messagename'] == 'Credit Card Payment Confirmation'){
					$nilaibayar = $SuitenObject['mergefields']['invoice_last_payment_amount'];

					if (trim($nilaibayar) == "") {
						$nilaibayar = $SuitenObject['mergefields']['invoice_amount_paid'];					
					}
					$concatok = "";
					$tok = strtok($SuitenObject['mergefields']['invoice_last_payment_transid'],"\n");
					if ($tok !== false) {
						$concatok = trim($tok);
						$tok = strtok("\n");
						if ($tok !== false) {
							$concatok = ($concatok == "" ? "" : $concatok . ".");
							$concatok = $concatok . trim($tok);
						}
					}
					$transidbayar = $concatok;
					
					if (trim($nilaibayar) == "") {
						$result = Capsule::table('tblaccounts')->where([['userid','=',$client_id],['invoiceid','=',$nomorinvoice]])->orderBy('date','desc')->first();
						$nilaibayar = $result->amountin;
						$transidbayar = $result->transid;
						$paymethod = $result->gateway;
					}

					if (trim($transidbayar) == "" && $pakaicreditnumonly > 0) {
						if ($negara == "ID") {
							$paymethod = "Deposit";
							$transidbayar = "Debet Saldo";
						} else {
							$paymethod = "Auto";
							$transidbayar = "Credit Balance";
						}
						$amtpaidnumonly = preg_replace("/[^0-9]/", "", $SuitenObject['mergefields']['invoice_amount_paid'] );
						if ($amtpaidnumonly > 0) {
							$nilaibayar = $SuitenObject['mergefields']['invoice_amount_paid'];
						} else {
							$nilaibayar = $pakaicredit;
						}
					} else {
						$paymethod = $SuitenObject['mergefields']['invoice_payment_method'];
					}
				} else {
					$nilaibayar = "";
					$transidbayar = "";
					$paymethod = "";
				}

				// Nominal Unik
				$nominalunik = "";
				try {
					foreach (Capsule::table('bilo_gateway_unik')->where([['invoice','=',$nomorinvoice],])->get() as $bilounik) {
						$nominalunik = number_format($bilounik->jumlah, 0, ',', '.');
						if ($bilounik->process == 1) {
							$paymethod = "Transfer Bank";
						}
					}
				} catch (\Exception $e) {

				}		
				if($suiten_ccycode == 'IDR') {
					// Hapus decimal
					//$invoiceamounttitik = substr($invoiceamounttitik, 0, strlen($invoiceamounttitik)-3);
					//$invoiceamountkoma = substr($invoiceamountkoma, 0, strlen($invoiceamountkoma)-3);
					if($nominalunik <> "") {
						$nominalunik = "sejumlah *Rp ".$nominalunik."*";
					}
				}
				else
				{
					$nominalunik = "";
					
				}

				$wamsg_tag_key = array(
					"{S10WA_NamaClient}", 
					"{S10WA_FirstName}",
					"{S10WA_LastName}",
					"{S10WA_ClientID}", 
					"{S10WA_ClientEmail}", 
					"{S10WA_NomorInvoice}", 
					"{S10WA_NomorInvFinal}", 
					"{S10WA_NilaiInvoice}", 
					"{S10WA_CreditUsed}", 
					"{S10WA_TotalInvoice}", 
					"{S10WA_NilaiBayar}", 
					"{S10WA_TransID}",
					"{S10WA_PayMethod}",					
					"{S10WA_TglCetakInvoice}",
					"{S10WA_JatuhTempoInvoice}",
					"{suiten_signature}",
					"{S10WA_DomainWHMCS}",
					"{S10WA_NominalUnik}",
					"{S10WA_InvoiceItems}",
					"{S10WA_InvoiceItemCut}"

				);

				$wamsg_tag_value = array(
					trim($firstname) . ' ' . trim($lastname),
					$firstname,
					$lastname,
					$client_id, 
					$email, 
					$nomorinvoice, 
					$invoicenum, 
					$suiten_ccyprefix . $invoiceamounttidy . $suiten_ccysuffix, 
					$creditused,
					$suiten_ccyprefix . $invoicetotaltidy . $suiten_ccysuffix, 
					$nilaibayar, 
					$transidbayar,
					$paymethod,
					$invoiceissuedate[2] . '/' . $invoiceissuedate[1] . '/' . $invoiceissuedate[0],
					$invoiceduedate[2] . '/' . $invoiceduedate[1] . '/' . $invoiceduedate[0],
					$whatsapp_Signature_message,
					$suiten_url_whmcs,
					$nominalunik,
					$invoiceitemstring,
					$invoiceitemcut
				);
				break;
			case 'Service Suspension Notification':
			case 'Service Unsuspension Notification':
			case 'Upcoming Domain Renewal Notice';
			case 'Expired Domain Notice';
			
				$wamsg_tag_key = array(
				"{S10WA_NamaClient}",
				"{S10WA_FirstName}",
				"{S10WA_LastName}",
				"{S10WA_DomainLayanan}",
				"{S10WA_NamaLayanan}",
				"{suiten_signature}",
				"{S10WA_DomainWHMCS}"
				);
		
				$wamsg_tag_value = array(
					trim($firstname) . ' ' . trim($lastname),
					$firstname,
					$lastname,
					$namaDomain,
					$namaLayanan,
					$whatsapp_Signature_message,
					$suiten_url_whmcs
				);
				break;

			default:
				// do nothing return immediately
				$merge_fields = [];
				return $merge_fields;			
		}

		// Set PESAN
		switch ($SuitenObject['messagename']) {
    case 'Invoice Created':
    case 'Invoice Modified':
    case 'Invoice Payment Reminder':
    case 'First Invoice Overdue Notice':
    case 'Second Invoice Overdue Notice':
    case 'Third Invoice Overdue Notice':
    case 'Invoice Payment Confirmation':
    case 'Credit Card Payment Confirmation':

        if ((($SuitenObject['messagename'] == 'Invoice Payment Reminder') || (strpos($SuitenObject['messagename'], "Invoice Overdue Notice"))) && ($berapalamaoverdue > 0)) {
            foreach (WHMCS\Database\Capsule::table('s10wa_templates')->WHERE('s10wa_templatetitle', 'Invoice Overdue Reminder')->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;
            }
        } else {
            foreach (WHMCS\Database\Capsule::table('s10wa_templates')->WHERE('s10wa_templatetitle', $NamaTemplate)->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;
            }
        }

        // logactivity($body_message, $client_id);
       // logactivity($body_message, $client_id); 

if (($status_message >= "1") && ($suiten_nomorwhatsapp != "") && ($suiten_nomorwhatsapp != "0") && (strlen($suiten_nomorwhatsapp) > 8) && ($client_id != 0) && ($client_id != "")) {

    // Set the directory where the PDF will be stored locally
    $pdf_directory = $_SERVER['DOCUMENT_ROOT'] . '/pdf/';
    if (!is_dir($pdf_directory)) {
        mkdir($pdf_directory, 0755, true);
    }

    // Generate the filename for the PDF
    $remote_file = $KoreksiNomor . '_' . time() . '__' . $pdfprefix . $nomorinvoice . '.pdf';

    // Create temporary file
    $local_file = fopen($pdf_directory . $remote_file, 'w+');

    // Check for Paghiper Tag for PagHiper 2.1 clients
    if (str_contains($body_message, '{S10WA_Paghiper}')) {
        $body_message = str_ireplace("{S10WA_Paghiper}", "", $body_message);

        // Use cURL to fetch the Paghiper PDF
        $cpdf = curl_init();
        curl_setopt($cpdf, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($cpdf, CURLOPT_URL, $suiten_url_whmcs . "/modules/gateways/paghiper.php?invoiceid=" . $nomorinvoice . "&uuid=" . $client_id . "&mail=" . $email);
        $generatepagehiper = curl_exec($cpdf);

        // Extract the PDF URL from the HTML response
        $ini = strpos($generatepagehiper, "<span class=\"fa fa-file-pdf-o\"></span><a href='");
        if ($ini == 0) {
            $urlpdf = "";
        } else {
            $ini += strlen("<span class=\"fa fa-file-pdf-o\"></span><a href='");
            $len = strpos($generatepagehiper, "'> SALVAR EM PDF</a>", $ini) - $ini;
            $urlpdf = substr($generatepagehiper, $ini, $len);
        }
        logactivity('SUITEN_WAMLog: Getting Paghiper ' . $urlpdf, $client_id);

        if ($urlpdf == "") {
            curl_close($cpdf);
            fwrite($local_file, \pdfInvoice($nomorinvoice));
        } else {
            curl_setopt($cpdf, CURLOPT_URL, $urlpdf);
            $pdfstring = curl_exec($cpdf);
            curl_close($cpdf);
            fwrite($local_file, $pdfstring);
        }
    } else {
        // Generate the PDF using WHMCS invoice function
        fwrite($local_file, \pdfInvoice($nomorinvoice));
    }

    // Close the file after writing
    fclose($local_file);

    // Log that the file was generated locally
    logactivity('S10WA File ' . $remote_file . ' generated locally for Invoice ID: ' . $nomorinvoice, $client_id);

    // Handle sending WhatsApp message and media
    $suiten_Whatsapp_Message = str_ireplace($wamsg_tag_key, $wamsg_tag_value, $body_message);

    try {
        global $msgtemplatename;
        $msgtemplatename = $SuitenObject['messagename'];

        Capsule::connection()->transaction(function ($connectionManager) use ($suiten_Whatsapp_Message, $KoreksiNomor, $remote_file, $client_id, $client_info, $SubKontak) {
            $waktukirim = timeStampWhatsapp();

            // Insert the main message
            $connectionManager->table('s10wa_sendmsg')->insert([
                's10wa_date' => $waktukirim,
                's10wa_wanumber' => $KoreksiNomor,
                's10wa_interval' => (int)4,
                's10wa_priority' => (int)3,
                's10wa_message' => $suiten_Whatsapp_Message,
                's10wa_msgtype' => (int)2,
                's10wa_attachment' => $remote_file,  // Attach the local PDF file
                's10wa_clientid' => $client_id,
                's10wa_clientinfo' => $client_info,
                's10wa_status' => (int)0
            ]);

            // Handle additional contacts (SubKontak) if they exist
            if (count($SubKontak) > 1) {
                foreach ($SubKontak as $key => $value) {
                    if ($SubKontak[$key]['phonenumber'] != "") {
                        $SubKontak[$key]['remotefile'] = $SubKontak[$key]['phonenumber'] . '_' . time() . '__' . $pdfprefix . $nomorinvoice . '.pdf';

                        // Insert message for sub-contact
                        $connectionManager->table('s10wa_sendmsg')->insert([
                            's10wa_date' => $waktukirim,
                            's10wa_wanumber' => $SubKontak[$key]['phonenumber'],
                            's10wa_interval' => (int)4,
                            's10wa_priority' => (int)3,
                            's10wa_message' => "CC: " . $SubKontak[$key]['client_name'] . "\r\n" . $suiten_Whatsapp_Message,
                            's10wa_msgtype' => (int)2,
                            's10wa_attachment' => $SubKontak[$key]['remotefile'],  // Attach the sub-contact file
                            's10wa_clientid' => $client_id,
                            's10wa_clientinfo' => $SubKontak[$key]['client_info'],
                            's10wa_status' => (int)0
                        ]);

                        logactivity('SUITEN_WAMLog: InvSub (' . $msgtemplatename . ') CC #' . $SubKontak[$key]['phonenumber'], $client_id);
                    }
                }
            }
        });

        logactivity('SUITEN_WAMLog: InvMsg (' . $SuitenObject['messagename'] . ') #' . $KoreksiNomor, $client_id);

        if (function_exists('suiten_SyncDB')) {
            suiten_SyncDB($SuitenObject);
        }
    } catch (\Exception $e) {
        LogActivity('S10WAM MySQL Error: ' . $e);
        exit();
    }
}

        break;


			case 'Service Suspension Notification':
			case 'Service Unsuspension Notification':
			case 'Upcoming Domain Renewal Notice';
			case 'Expired Domain Notice';

				$status_message = 0;
				foreach (WHMCS\Database\Capsule::table('s10wa_templates')->WHERE('s10wa_templatetitle', $NamaTemplate)->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;
				}

				if(($status_message >= "1") && ($suiten_nomorwhatsapp != "") && ($suiten_nomorwhatsapp != "0") && (strlen($suiten_nomorwhatsapp) > 8) && ($client_id != 0) && ($client_id != "")) {

					$suiten_Whatsapp_Message = str_ireplace(
						$wamsg_tag_key, 
						$wamsg_tag_value, 
						$body_message
					);

					try {

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

								global $suiten_Whatsapp_Message;
								global $KoreksiNomor, $SubKontak, $remote_file;
								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_clientid' => $client_id,
										's10wa_clientinfo' => $client_info,
										's10wa_status' => (int)0
									]

								);
							}
						);
						logactivity( 'SUITEN_WAMLog: '. $NamaTemplate .' (' . $SuitenObject['messagename'] . ') #'.$KoreksiNomor, $client_id);
						if (function_exists('suiten_SyncDB')) 
							suiten_SyncDB($SuitenObject);
               
					} catch (\Exception $e) {

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

					}

				}
				break;

	
			default:
				// do nothing
		}

		// logactivity( 'SUITEN_WAMLog: EmailPreSEND FINISH ' . $SuitenObject['messagename'] , $client_id);

		return $merge_fields;

	}
}

return $hook;