<?php

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

$hook = array(
    'hook' => 'ClientChangePassword',
    'function' => 'suiten_ClientChangePassword'
);

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

if (!function_exists('suiten_ClientChangePassword')) {

	function suiten_ClientChangePassword($SuitenObject) {

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

		$global_module_name = 'SUITEN Whatsapp API';
		$client_id = $SuitenObject['userid'];

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

		// 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', 'Password Changed')->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";
			}

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

			$s10tag_value = array(
				trim($firstname) . ' ' . trim($lastname),
				$firstname,
				$lastname,
				$whatsapp_Signature_message,
				$suiten_url_whmcs,
				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 . ' ClientChangePassword 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;

add_hook($hook['hook'], 1, $hook['function']);



add_hook('AfterPasswordReset', 1, function($vars) {
    logActivity('SUITEN_DEBUG: Password reset process triggered.');

    // You can add your logic here similar to the previous logic in suiten_ForwardEmail
});