<?php

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

$hook = array(
    'hook' => 'InvoiceCancelled',
    'function' => 'suiten_InvoiceCancelled'
);

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

if (!function_exists('suiten_InvoiceCancelled')) {

	function suiten_InvoiceCancelled($SuitenObject) {

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

		$global_module_name = 'SUITEN Whatsapp API';
		$nomorinvoice = $SuitenObject['invoiceid'];	

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

		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 ($cancelinvoiceemail) $merge_fields['abortsend'] = true;
		
		// Ambil Data Invoice
		foreach (Capsule::table('tblinvoices')->where([['id','=',$nomorinvoice],])->get() as $invoice) {			
			$invoicenum = ($invoice->invoicenum == "") ? $nomorinvoice : $invoice->invoicenum;
	    	$client_id = $invoice->userid;
	    	$datepaid = $invoice->datepaid;
			$invoicedate = date('d/m/Y', strtotime($invoice->date));
			$invoiceamount = $invoice->total+$invoice->credit;
	    	//$invoiceamounttitik = number_format($invoice->total+$invoice->credit, 2, '.', ',');
	    	//$invoiceamountkoma = number_format($invoice->total+$invoice->credit, 2, ',', '.');
			$invoiceissuedate = explode('-',$invoice->date);
			$invoiceduedate = explode('-',$invoice->duedate);
		}
				
		// 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;
            $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;
        }


		// Ambil Data Invoice Items
		$invoiceitemstring = "";
		$invoiceitemcut = "";		
		foreach (Capsule::table('tblinvoiceitems')->where([['invoiceid','=',$nomorinvoice],])->get() as $invitem) {
			$hargaitem = $invitem->amount;

			// Reformat hargaitem amount
			if ($suiten_ccyformat  == 1) {
				$hargaitemtidy = number_format($hargaitem, 2, '.', '');
			} elseif ($suiten_ccyformat  == 2) {
				$hargaitemtidy = number_format($hargaitem, 2, '.', ',');
			} elseif ($suiten_ccyformat  == 3) {
				$hargaitemtidy = number_format($hargaitem, 2, ',', '.');
			} elseif ($suiten_ccyformat  == 4) {
				$hargaitemtidy = number_format($hargaitem, 0, '', ',');
			} elseif ($suiten_ccycode  == "IDR") {
				$hargaitemtidy = number_format($hargaitem, 0, '', '.');
			} else {
				$hargaitemtidy = strval($hargaitem);
			}

			$hargaitem = number_format($hargaitem, 0, ',', '.');
			$invoiceitemstring = $invoiceitemstring . trim($invitem->description) . " " . $suiten_ccyprefix . $hargaitemtidy . $suiten_ccysuffix . "\r\n";

			if (strpos($invitem->description,": 0 x ") == false) {
					$invoiceitemcut = $invoiceitemcut . trim($invitem->description) . " " . $suiten_ccyprefix . $hargaitemtidy . $suiten_ccysuffix . "\r\n";
				}

		}
		$invoiceitemstring = trim($invoiceitemstring);
		$invoiceitemcut = trim($invoiceitemcut);

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

		$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', 'Invoice Cancellation')->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;
	    }

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

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

			if ($pdfkey <> "" && $pdfserver <> "" && $licensekey <> "") {

				$remote_file = $KoreksiNomor . '_' . time() . '__' . $pdfprefix . $nomorinvoice . '.pdf';

				// FTP login details
				$ftp_server=$pdfserver; 
				$ftp_user_name=$licensekey; 
				$ftp_user_pass=$pdfkey;

				if (!function_exists('pdfInvoice')) {
					require_once ROOTDIR . "/includes/invoicefunctions.php";
				}

				// Create temporary file
				$local_file=fopen('php://temp', 'r+');
				fwrite($local_file, \pdfInvoice($nomorinvoice));
				rewind($local_file);       

				// FTP connection
				$ftp_conn=ftp_connect($ftp_server); 

				// FTP login
				@$login_result=ftp_login($ftp_conn, $ftp_user_name, $ftp_user_pass); 

				// FTP upload
				if($login_result) {
					if($pdfpassive) ftp_pasv($ftp_conn, true);
					$upload_result=ftp_fput($ftp_conn, $remote_file, $local_file, FTP_BINARY );
				}

				// Error handling
				if(!$login_result or !$upload_result) {
					logactivity('S10WA File error FTP writing for Invoice ID: '.$nomorinvoice, $client_id);
				} else {
					logactivity('S10WA File '. $remote_file. ' generated for Invoice ID: '.$nomorinvoice, $client_id);
				}

				// Handle SubKontak 2 : Tambah remotefile
				if (count($SubKontak)>1) {
					foreach($SubKontak as $key => $value){
						if ($SubKontak[$key]['phonenumber'] <> "") {
							$SubKontak[$key]['remotefile'] = $SubKontak[$key]['phonenumber'] . '_' . time() . '__' . $pdfprefix . $nomorinvoice . '.pdf';
							rewind($local_file);
							$upload_result=ftp_fput($ftp_conn, $SubKontak[$key]['remotefile'], $local_file, FTP_BINARY );
							if(!$upload_result) {
								logactivity('S10WA File error FTP writing for Invoice ID: '.$nomorinvoice. ' to '.$SubKontak[$key]['phonenumber'], $client_id);
							} else {
								logactivity('S10WA File '. $SubKontak[$key]['remotefile'] . ' generated as CC Invoice ID: '.$nomorinvoice, $client_id);
							}
						}
					}
				}

				// Close FTP connection
				ftp_close($ftp_conn);

				// Close file handle
				fclose($local_file);					
					
			} else {
				// logactivity('S10WA NO PDF generated for Invoice ID: '.$nomorinvoice, $client_id);
			}


		    // Handles the strings for the message template
			$s10tag_key = array(
				"{S10WA_NamaClient}", 
				"{S10WA_FirstName}",
				"{S10WA_LastName}",
				"{S10WA_NomorInvoice}", 
				"{S10WA_NilaiInvoice}", 
				"{S10WA_TglCetakInvoice}",
				"{S10WA_JatuhTempoInvoice}",
				"{suiten_signature}",
				"{S10WA_DomainWHMCS}",
				"{S10WA_InvoiceItems}",
				"{S10WA_InvoiceItemCut}"
			);

			$s10tag_value = array(
				trim($firstname) . ' ' . trim($lastname),
				$firstname,
				$lastname,
				$invoicenum,
				$suiten_ccyprefix.$invoiceamounttidy.$suiten_ccysuffix, 
				$invoiceissuedate[2] . '/' . $invoiceissuedate[1] . '/' . $invoiceissuedate[0],
				$invoiceduedate[2] . '/' . $invoiceduedate[1] . '/' . $invoiceduedate[0],
				$whatsapp_Signature_message,
				$suiten_url_whmcs,
				$invoiceitemstring,
				$invoiceitemcut
			);

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

			try {

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

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

						$waktukirim = timeStampWhatsapp();
                        $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)1,
								's10wa_attachment' => $remote_file,
								's10wa_clientid' => $client_id,
								's10wa_clientinfo' => $client_info,
                                's10wa_status' => (int)0
                            ]

                        );

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

						// Handle SubKontak 3
						if (count($SubKontak)>1) {
							foreach($SubKontak as $key => $value){
								if ($SubKontak[$key]['phonenumber'] <> "") {
									$connectionManager->table('s10wa_sendmsg')->insert(
										[
											's10wa_date' => $waktukirim,
											's10wa_wanumber' => $SubKontak[$key]['phonenumber'],
											's10wa_interval' => (int)4,
											's10wa_message' => "CC: ".$SubKontak[$key]['client_name'] . "\r\n". $suiten_Whatsapp_Message,
											's10wa_msgtype' => (int)1,
											's10wa_attachment' => $SubKontak[$key]['remotefile'],
											's10wa_clientid' => $client_id,
											's10wa_clientinfo' => $SubKontak[$key]['client_info'],
											's10wa_status' => (int)0
										]
									);
									logactivity( 'SUITEN_WAMLog: ' . $result . ' InvoiceCancelled CC WA#'.$SubKontak[$key]['phonenumber'], $client_id);
								}
							}
						}
						
						if (function_exists('suiten_SyncDB')) 
							suiten_SyncDB($SuitenObject);

                    }
                );

               

            } catch (\Exception $e) {

                $result = 'MySQL Error: ' . $e;
				LogActivity("S10WAM InvoiceCancelled Error ".$e, $client_id);
                exit();

            }

		}

	}
}

return $hook;