<?php

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

$hook = array(
    'hook' => 'AfterModuleCreate',
    'function' => 'suiten_NewProductActivation'
);

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

if (!function_exists('suiten_NewProductActivation')) {

	function suiten_NewProductActivation($SuitenObject) {

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

		$global_module_name = 'SUITEN Whatsapp API';

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

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

		$service_id = $SuitenObject['params']['model']['id'];
		$client_id = $SuitenObject['params']['model']['userid'];
		$product_id = $SuitenObject['params']['model']['packageid'];
		$service_domain = $SuitenObject['params']['model']['domain'];
		$NamaLayanan = $SuitenObject['params']['model']['product']['name'];
		$iplayanan = $SuitenObject['params']['model']['dedicatedIp'];


		//$tglregister = $SuitenObject['params']['model']['regDate'];
		//$tglskrg = time();
		//$regudahberapalama = $tglskrg - $tglregister;
		//if ($regudahberapalama > 864000) {
			// Register lebih dari 10 hari lalu (10 x 24 x 60 x 60)
			// Gak usah kirim activation
		//	logactivity( 'SUITEN_WAMLog: NewProductActivation Skipped (more than 10days)', $client_id);
		//	return $hook;
		//}
			
		// Data Client
        $firstname = $SuitenObject['params']['model']['client']['firstname'];
        $lastname = $SuitenObject['params']['model']['client']['lastname'];
        $email = $SuitenObject['params']['model']['client']['email'];
        $phonenumber = $SuitenObject['params']['model']['client']['phonenumber'];
        $alamat1 = $SuitenObject['params']['model']['client']['address1'];
        $alamat2 = $SuitenObject['params']['model']['client']['address2'];
        $kota = $SuitenObject['params']['model']['client']['city'];
        $provinsi = $SuitenObject['params']['model']['client']['state'];
        $kodepos = $SuitenObject['params']['model']['client']['postcode'];
        $negara = $SuitenObject['params']['model']['client']['country'];
		$client_info = $firstname . ' ' . $lastname . ' (' . $email . ')';

		$suiten_nomorwhatsapp = '';
        if($whatsapp_metode_kirim == 'Custom') {
			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', 'New Product Activation')->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 != "")) {

			$sLogo = "";
			if (strpos(strtolower($body_message),"{logo}") !== false) {
				$body_message = str_ireplace(
					"{logo}", 
					"", 
					$body_message
				);
				$sLogo = "logo";
			}

			if (strpos($body_message,"{S10WA_DomainLayanan}") !== false AND $service_domain == "") {
				if ($iplayanan <> "") {
					$service_domain = $iplayanan;
				} else {
					// Cari di tblcustofieldvalues
					foreach (Capsule::table('tblcustomfieldsvalues')->where([['relid','=',$client_id],['value','LIKE','.']])->get() as $datarecord) {
						$service_domain = $datarecord->value;
					}					
				}
			}

			// Handles the strings for the message template
			$s10tag_key = array(
				"{S10WA_NamaClient}",
				"{S10WA_FirstName}",
				"{S10WA_LastName}",
				"{suiten_signature}",
				"{S10WA_DomainWHMCS}",
				"{S10WA_ServiceID}",
				"{S10WA_NamaLayanan}",
				"{S10WA_DomainLayanan}",
				"{S10WA_TimeStamp}"
			);

			$s10tag_value = array(
				trim($firstname) . ' ' . trim($lastname),
				$firstname,
				$lastname,
				$whatsapp_Signature_message,
				$suiten_url_whmcs,
				$service_id,
				$NamaLayanan,
				$service_domain,
				timeStampWhatsapp()
			);

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

			// Call  API
			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 . ' NewProductActivation WA#'.$KoreksiNomor. ( $sLogo == "" ? "" : " with ". $sLogo ), $client_id);
						if (function_exists('suiten_SyncDB')) 
							suiten_SyncDB($SuitenObject);

                    }
                );

               
            } catch (\Exception $e) {

                $result = 'MySQL Error: ' . $e;

                exit();

            }
			
		}

	}

}

return $hook;