<?php


if (!defined('WHMCS')) {
    exit('Access Restricted');
}

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

global $global_module_name;

$module_name = suiten_whatsapp_config();
$global_module_name = $module_name['name'];

function suiten_whatsapp_config() {

    $S10WAConfigArray = array(
        'name' => 'Hostinoz Whatsapp API',
        'description' => 'Whatsapp API WHMCS Integration Module, customized by Hostinoz',
        'version' => '2.0',
        'language' => 'english-en',
        'author' => "<a href='https://www.buana.net/' target='_blank'><img width='100px' src='data:image/png;base64, '></a>",
        'premium' => true,
		'fields' => [
            'ClientList' => [
                'FriendlyName' => 'Client List',
                'Type' => 'yesno',
                'Description' => 'Tick to enable',
            ],
		]
    );

    return $S10WAConfigArray;

}



// Set the content type to UTF-8
header('Content-Type: text/html; charset=utf-8');




function suiten_whatsapp_activate() {

    global $CONFIG;
    $default_collation = 'utf8mb4_unicode_ci';
    $default_charset = 'utf8mb4';

    ////////////////////////////////////////////////////////////////////////
    // Pembuatan Tabel - Configuration /////////////////////////////////////
    ////////////////////////////////////////////////////////////////////////

	if (!Capsule::schema()->hasTable('s10wa_config')){
		try {
			Capsule::schema()->create(
				's10wa_config',
				function ($table) {
					/** @var \Illuminate\Database\Schema\Blueprint $table */
					$table->increments('suiten_rid');
					$table->string('suiten_Nama_Modul');
					$table->string('suiten_lisensi',(int)250);
                    $table->string('suiten_lisensi_url',(int)200);
					$table->string('suiten_email',(int)40);
					$table->string('suiten_apikey',(int)200);
					$table->string('suiten_countrycode',(int)2);
					$table->string('suiten_countryprefix',(int)5);
					$table->string('suiten_mobileprefix',(int)50);
					$table->string('suiten_pdfserver',(int)20);
					$table->string('suiten_pdfkey',(int)20);
					$table->string('suiten_pdfprefix',(int)20);
					$table->integer('suiten_logretention');
					$table->string('suiten_adminwa');
					$table->string('suiten_field_nomorwa');
					$table->integer('suiten_sending_delay');
					$table->string('suiten_sending_method');
					$table->string('suiten_signature', (int)3000);
					$table->string('suiten_client_validation');
					$table->string('gwhost');
					$table->string('gwdb');
					$table->string('gwuser');
					$table->string('gwpass');				
				}
			);
		} catch (\Exception $e) {
			echo "Unable to create my_table: {$e->getMessage()}";
		}
	}
    
    // Adds default record into s10wa_config table
	$cekrecord = Capsule::table('s10wa_config')->select('suiten_lisensi')->count();
	if ($cekrecord=0){
		try {
			
			foreach (WHMCS\Database\Capsule::table('tblconfiguration')->get() as $rec) {
				$admcountry = $rec->RegistrarAdminCountry;
			}

			switch ($admcountry) {
				case 'BR':	// Brazil
					$admprefix = '55';
					$admmobile = '';
					break;
				case 'IR':	// Iran
					$admprefix = '98';
					$admmobile = '21;021';
					break;
				case 'BD':	// Bangladesh
					$admprefix = '880';
					$admmobile = '1;01';
					break;
				case 'ES':	// Spain
					$admprefix = '34';
					$admmobile = '7;6';
					break;
				default:
					$admprefix = '62';
					$admmobile = '8;08';
			}		

			$panjang = 10;
			$characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
			$charactersLength = strlen($characters);
			$randomString = '';
			for ($i = 0; $i < $panjang; $i++) {
				$randomString .= $characters[rand(0, $charactersLength - 1)];
			}
			
			Capsule::connection()->transaction(
				function ($connectionManager)
				{
					$connectionManager->table('s10wa_config')->insert(
						[
							'suiten_Nama_Modul' => 'Hostinoz Whatsapp API',
							'suiten_lisensi' => '',
							'suiten_email' => '',
							'suiten_apikey' => $randomString,
							'suiten_countrycode' => $admcountry,
							'suiten_countryprefix' => $admprefix,
							'suiten_mobileprefix' => $admmobile,
							'suiten_pdfserver' => '',
							'suiten_pdfkey' => '',
							'suiten_pdfprefix' => 'Invoice-',
							'suiten_adminwa' => '',
							'suiten_sending_delay' => 5,
							'suiten_signature' => 'Terima kasih,
	
Sukses Selalu!',
						'suiten_logretention' => 14,
						]
					);
				}
			);
		} catch (\Exception $e) {
			echo "Uh oh! Inserting didn't work, but I was able to rollback. {$e->getMessage()}";
		}
	} 

    ////////////////////////////////////////////////////////////////////////
    // Pembuatan Tabel - Sending Message ///////////////////////////////////
    ////////////////////////////////////////////////////////////////////////

	if (!Capsule::Schema()->hasTable('s10wa_sendmsg')){
		try {
			Capsule::schema()->create(
				's10wa_sendmsg',
				function ($table) {
					/** @var \Illuminate\Database\Schema\Blueprint $table */
					$table->increments('s10wa_sendid');
					$table->datetime('s10wa_date');
					$table->string('s10wa_wanumber');
					$table->integer('s10wa_groupid');
					$table->integer('s10wa_interval');
					$table->integer('s10wa_priority');
					$table->text('s10wa_message')
                        ->charset('utf8mb4')
                        ->collation('utf8mb4_unicode_ci');
                        
					$table->integer('s10wa_msgtype');
					$table->string('s10wa_attachment', (int)100)->nullable();
					$table->integer('s10wa_clientid')->default(0);
					$table->string('s10wa_clientinfo', (int)250)->nullable();
					$table->string('s10wa_errormsg', (int)250)->nullable();
					$table->integer('s10wa_status');
					$table->datetime('s10wa_statusdate');
				}
			);
		} catch (\Exception $e) {
			echo "Unable to create my_table: {$e->getMessage()}";
		}
	}

    ////////////////////////////////////////////////////////////////////////
    // Pembuatan Tabel - Verify WA Number //////////////////////////////////
    ////////////////////////////////////////////////////////////////////////
	// status 0 = not set (default), 1 = dont send, 2 = send, 3 = notvalid, 4 = wait-verify
	if (!Capsule::Schema()->hasTable('s10wa_verify')){
		try {
			Capsule::schema()->create(
				's10wa_verify',
				function ($table) {
					$table->increments('id');
					$table->integer('clientid');
					$table->string('wanumber');
					$table->integer('status');
					$table->string('note', (int)250)->nullable();
					$table->string('otp');
					$table->datetime('timestamp');
				}
			);
		} catch (\Exception $e) {
			echo "Unable to create my_table: {$e->getMessage()}";
		}
	}

    ////////////////////////////////////////////////////////////////////////
    // Pembuatan Tabel - Template Message ////////////////////////////////
    ////////////////////////////////////////////////////////////////////////

	if (!Capsule::Schema()->hasTable('s10wa_templates')){
		try {
			Capsule::schema()->create(
            's10wa_templates',
            function ($table) {
                /** @var \Illuminate\Database\Schema\Blueprint $table */
                $table->increments('s10wa_msgid');
                $table->string('s10wa_templatetitle', (int)500);
                $table->text('s10wa_templatecontent')
                ->charset('utf8mb4')
                ->collation('utf8mb4_unicode_ci');
                $table->string('s10wa_templateenglish', (int)3000)->nullable();
                $table->integer('s10wa_templatestatus');
            }
        );
		} catch (\Exception $e) {
			echo "Unable to create my_table: {$e->getMessage()}";
		}
	}

    //$tabelas = array('s10wa_config', 's10wa_sendmsg', 's10wa_templates', 's10wa_loginlist');
    //foreach($tabelas as $tabela) {
    //    $changeCollationQuery = "ALTER TABLE $tabela CONVERT TO CHARACTER SET utf8 COLLATE utf8_general_ci;";
        //echo $changeCollationQuery;
    //    mysqli_query($changeCollationQuery);
    //}

    // Adds the msgs in the s10wa_templates table
	$aMsgTemplates = "";
	foreach (WHMCS\Database\Capsule::table('s10wa_templates')->get() as $tabelrec) {
		$aMsgTemplates = $aMsgTemplates . ">" . $tabelrec->s10wa_templatetitle . "<";
    }

	try {

		if (strpos($aMsgTemplates, ">" . "Login Alert" . "<") === false) {
    Capsule::connection()->transaction(function ($connectionManager) {
        $connectionManager->table('s10wa_templates')->insert([
            's10wa_templatetitle' => 'Login Alert',
            's10wa_templatecontent' => '🔔 প্রিয় {S10WA_NamaClient},

🤖 এটি সিস্টেম থেকে একটি স্বয়ংক্রিয় বার্তা, যা আপনাকে জানাচ্ছে যে:

📅 তারিখ: {s10wa_date}
⏰ সময়: {S10WA_Jam}
🌐 আইপি: {S10WA_ClientIP}
🖥️ ডোমেইন: {S10WA_DomainWHMCS}
📧 অ্যাকাউন্ট: {S10WA_ClientEmail}

একটি লগইন সম্পন্ন হয়েছে।

⚠️ যদি এই অ্যাক্সেসটি আপনি না করে থাকেন, তাহলে অনুগ্রহ করে অবিলম্বে আমাদের টিমের সাথে যোগাযোগ করুন। 🚨

{suiten_signature}',
            's10wa_templateenglish' => 'Hi {S10WA_NamaClient},
This is an automated login notification to {S10WA_DomainWHMCS} on {s10wa_date} {S10WA_Jam} from IP {S10WA_ClientIP}, using {S10WA_ClientEmail}.
If you do not recognize the access, contact our team immediately.',
            's10wa_templatestatus' => 1,
        ]);
    });
}


		if(strpos($aMsgTemplates,">"."Password Changed"."<") === false){
			Capsule::connection()->transaction(
				function ($connectionManager)
				{
					$connectionManager->table('s10wa_templates')->insert(
						[
							's10wa_templatetitle' => 'Password Changed',
							's10wa_templatecontent' => '🔐 প্রিয় {S10WA_NamaClient},

🚨 আপনার পাসওয়ার্ড পরিবর্তন করা হয়েছে! 

❓ যদি আপনি নিজে এই পরিবর্তন না করে থাকেন, তাহলে অনুগ্রহ করে অবিলম্বে আমাদের টিমের সাথে যোগাযোগ করুন! 📞

{suiten_signature}',
							's10wa_templateenglish' => 'Hi {S10WA_NamaClient},

Your password has been changed! If you did not change it, please contact our team immediately!

{suiten_signature}						
',
                        's10wa_templatestatus' => 1,
						]
					);
				}
			);
		}

		if(strpos($aMsgTemplates,">"."Invoice Created"."<") === false){
			Capsule::connection()->transaction(
				function ($connectionManager)
				{
					$connectionManager->table('s10wa_templates')->insert(
						[
							's10wa_templatetitle' => 'Invoice Created',
							's10wa_templatecontent' => '🌟 প্রিয় {S10WA_NamaClient},

📅 আপনার ইনভয়েসটি {S10WA_TglCetakInvoice} তারিখে তৈরি করা হয়েছে।
⚠️ নিরবিচ্ছিন্ন সেবা নিশ্চিত করতে, অনুগ্রহ করে নির্ধারিত তারিখের আগে ইনভয়েস পরিশোধ করুন।

📊 ইনভয়েস বিবরণ:
🧾 প্রফর্মা ইনভয়েস: *{S10WA_NomorInvoice}*
💰 ইনভয়েস পরিমাণ: *{S10WA_NilaiInvoice}*
⏰ শেষ তারিখ: *{S10WA_JatuhTempoInvoice}* 

📝 *ইনভয়েস আইটেম সমূহ*
{S10WA_InvoiceItems}

🔍 ইনভয়েসটি দেখতে, আপনি এখানে ক্লিক করুন: 
🔗 {S10WA_DomainWHMCS}/viewinvoice.php?id={S10WA_NomorInvoice}

🙏 আপনার সহযোগিতার জন্য ধন্যবাদ!

{suiten_signature}',
							's10wa_templateenglish' => 'Hi {S10WA_NamaClient},

Your invoice has been generated on {S10WA_TglCetakInvoice}
To ensure uninterrupted service, kindly settle invoice before due date.

Proforma Invoice: *{S10WA_NomorInvoice}*
Invoice Amount: *{S10WA_NilaiInvoice}*
Due Date: *{S10WA_JatuhTempoInvoice}* 

*Invoice Detail*
{S10WA_InvoiceItems}

To view the invoice, you can access it on {S10WA_DomainWHMCS}/viewinvoice.php?id={S10WA_NomorInvoice}

{suiten_signature}',
							's10wa_templatestatus' => 1,
						]
					);
				}
			);
		}

		// Rename template lama
		if(strpos($aMsgTemplates,">"."Invoice Reminder"."<") >= 0){
			try {
				$updatedUserCount = Capsule::table('s10wa_templates')
					->where('s10wa_templatetitle', 'Invoice Reminder')
					->update(
						[
							's10wa_templatetitle' => 'Invoice Payment Reminder',
						]
					);

			} catch (\Exception $e) {
				echo "I couldn't update template name. {$e->getMessage()}";
			}			
			$aMsgTemplates = $aMsgTemplates . ">Invoice Payment Reminder<";
		}
				
		if(!(strpos($aMsgTemplates,">"."Invoice Payment Reminder"."<"))){
			Capsule::connection()->transaction(
				function ($connectionManager)
				{
					$connectionManager->table('s10wa_templates')->insert(
						[
							's10wa_templatetitle' => 'Invoice Payment Reminder',
							's10wa_templatecontent' => '🌟 প্রিয় {S10WA_NamaClient},

💌 আশা করি আপনি ভালো আছেন। আপনার একটি অপরিশোধিত বিল রয়েছে, তাই একটু মনে করিয়ে দিচ্ছি।

⏰ নিরবিচ্ছিন্ন সেবা পেতে, অনুগ্রহ করে নির্ধারিত তারিখের আগে পরিশোধ করুন।

📝 বিল নম্বর: *{S10WA_NomorInvoice}*
💰 মোট পরিমাণ: *{S10WA_NilaiInvoice}*
📅 শেষ তারিখ: *{S10WA_JatuhTempoInvoice}* 

📊 *বিলের বিবরণ*
{S10WA_InvoiceItems}

🔗 বিল দেখতে, এই লিংকে যান: {S10WA_DomainWHMCS}/viewinvoice.php?id={S10WA_NomorInvoice}

🙏 আপনার সহযোগিতার জন্য ধন্যবাদ!

{suiten_signature}',
							's10wa_templateenglish' => 'Hi {S10WA_NamaClient},

This is a reminder for your unpaid invoice.
To ensure uninterrupted service, kindly settle invoice before due date.

Proforma Invoice: *{S10WA_NomorInvoice}*
Invoice Amount: *{S10WA_NilaiInvoice}*
Due Date: *{S10WA_JatuhTempoInvoice}* 

*Invoice Detail*
{S10WA_InvoiceItems}

To view the invoice, you can access it on {S10WA_DomainWHMCS}/viewinvoice.php?id={S10WA_NomorInvoice}

{suiten_signature}',
							's10wa_templatestatus' => 1,
						]
					);
				}
			);
		}

		if(!(strpos($aMsgTemplates,">"."Invoice Overdue Reminder"."<"))){
			Capsule::connection()->transaction(
				function ($connectionManager)
				{
					$connectionManager->table('s10wa_templates')->insert(
						[
							's10wa_templatetitle' => 'Invoice Overdue Reminder',
							's10wa_templatecontent' => '🔔 প্রিয় {S10WA_NamaClient},

🤖 আমরা আপনার জন্য একটি গুরুত্বপূর্ণ বিষয় নিয়ে আপনার সাথে যোগাযোগ করতে চাই। আপনার প্রফরমা ইনভয়েস {S10WA_NomorInvoice} {S10WA_TglCetakInvoice} তারিখে তৈরি করা হয়েছে এবং এটি অতিরিক্ত সময় পর্যন্ত পরিশোধ করা হয়নি।

📅 আমাদের সেবা চালিয়ে যেতে, আমরা আপনাকে অনুরোধ করছি যে আপনি যত তাড়াতাড়ি সম্ভব ইনভয়েসটি পরিশোধ করুন। নিম্নে ইনভয়েসের বিবরণ দেওয়া হলো:

📝 প্রফরমা ইনভয়েস: *{S10WA_NomorInvoice}*
💰 ইনভয়েস পরিমাণ: *{S10WA_NilaiInvoice}*
📅 শেষ তারিখ: *{S10WA_JatuhTempoInvoice}*

📊 *ইনভয়েস বিবরণ*
{S10WA_InvoiceItems}

🙏 আমাদের সেবা চালিয়ে যেতে, আমরা আপনার সহযোগিতার জন্য কৃতজ্ঞ। আমাদের সাথে যোগাযোগ করতে দ্বিধা করবেন না।

{suiten_signature}',
							's10wa_templateenglish' => 'Hi {S10WA_NamaClient},
						
Your proforma invoice {S10WA_NomorInvoice} generated on {S10WA_TglCetakInvoice} IS OVERDUE.

Proforma Invoice: *{S10WA_NomorInvoice}*
Invoice Amount: *{S10WA_NilaiInvoice}*
Due Date: *{S10WA_JatuhTempoInvoice}*

*Invoice Detail*
{S10WA_InvoiceItems}

Please settle the invoice as soon as possible.

{suiten_signature}',
							's10wa_templatestatus' => 1,
						]
					);
				}
			);
		}
				
		if(!(strpos($aMsgTemplates,">"."Payment Confirmation"."<"))){
			Capsule::connection()->transaction(
				function ($connectionManager)
				{
					$connectionManager->table('s10wa_templates')->insert(
						[
							's10wa_templatetitle' => 'Payment Confirmation',
							's10wa_templatecontent' => 'সালাম {S10WA_NamaClient} 🌟,

আপনার পেমেন্টের জন্য অনেক ধন্যবাদ! 🎉 আমরা প্রফর্মা ইনভয়েস *{S10WA_NomorInvoice}* এর জন্য *{S10WA_NilaiBayar}* পেয়েছি। 🙌

📜 *ইনভয়েসের বিস্তারিত*:
{S10WA_InvoiceItems}

আপনার সহযোগিতার জন্য আবারও ধন্যবাদ। ❤️ যদি কিছু দরকার হয়, আমাদের সাথে যোগাযোগ করুন! 🤗

শুভেচ্ছা সহ, {suiten_signature}',
							's10wa_templateenglish' => 'Hi {S10WA_NamaClient},
*Thank you* for your payment for invoice *{S10WA_NomorInvoice}* with amount *{S10WA_NilaiBayar}*

*Invoice Detail*
{S10WA_InvoiceItemCut}

Payment via {S10WA_PayMethod} with reference code {S10WA_TransID}',
							's10wa_templatestatus' => 1,
						]
					);
				}
			);
		}

		if(!(strpos($aMsgTemplates,">"."Invoice Cancellation"."<"))){
			Capsule::connection()->transaction(
				function ($connectionManager)
				{
					$connectionManager->table('s10wa_templates')->insert(
						[
							's10wa_templatetitle' => 'Invoice Cancellation',
							's10wa_templatecontent' => 'সালাম {S10WA_NamaClient} 🌟,

দুঃখিত 😔, কিন্তু আমাদের জানাতে হচ্ছে যে আপনার প্রফর্মা ইনভয়েস *{S10WA_NomorInvoice}* পরিমাণ *{S10WA_NilaiInvoice}* বাতিল করা হয়েছে। ❌🔔

*ইনভয়েসের বিস্তারিত* 📜:
{S10WA_InvoiceItems}

যদি আপনার কোনো প্রশ্ন থাকে বা আরও কোনো সাহায্যের প্রয়োজন হয়, দয়া করে আমাদের সাথে যোগাযোগ করুন! 😊📞💬

ধন্যবাদ ও শুভেচ্ছা, {suiten_signature} 🙏💖🌟',
							's10wa_templateenglish' => 'Hi {S10WA_NamaClient},

Your Proforma Invoice {S10WA_NomorInvoice} with amount {S10WA_NilaiInvoice} has been cancelled.

*Invoice Detail*
{S10WA_InvoiceItemCut}

{suiten_signature}',
							's10wa_templatestatus' => 1,
						]
					);
				}
			);
		}

		if(!(strpos($aMsgTemplates,">"."Service Suspension"."<"))){
			Capsule::connection()->transaction(
				function ($connectionManager)
				{
					$connectionManager->table('s10wa_templates')->insert(
						[
							's10wa_templatetitle' => 'Service Suspension',
							's10wa_templatecontent' => 'সালাম {S10WA_NamaClient} 🌟,

*আপনার সেবা সাময়িকভাবে স্থগিত (সাসপেন্ড) করা হয়েছে।* ⏳❗
আরও তথ্যের জন্য দয়া করে আমাদের সাথে যোগাযোগ করুন। 📞

সেবা: *{S10WA_NamaLayanan}* 🛠️
ডোমেইন: *{S10WA_DomainLayanan}* 🌐

ধন্যবাদ, {suiten_signature} 🙏',
							's10wa_templateenglish' => 'Hi {S10WA_NamaClient},

*Your service has been suspended*
Please contact us for further info.

Service: {S10WA_NamaLayanan} 
Domain: {S10WA_DomainLayanan}

{suiten_signature}',
							's10wa_templatestatus' => 1,
						]
					);
				}
			);
		}

		if(!(strpos($aMsgTemplates,">"."Service Reactivation"."<"))){
			Capsule::connection()->transaction(
				function ($connectionManager)
				{
					$connectionManager->table('s10wa_templates')->insert(
						[
							's10wa_templatetitle' => 'Service Reactivation',
							's10wa_templatecontent' => 'সালাম {S10WA_NamaClient} 🌟,

আপনার সেবা আবার *সক্রিয়* হয়েছে! 🎉✨

সেবা: *{S10WA_NamaLayanan}* 🛠️
ডোমেইন: *{S10WA_DomainLayanan}* 🌐

{suiten_signature}',
							's10wa_templateenglish' => 'Hi {S10WA_NamaClient},

Your service has been reactivated.

Service: {S10WA_NamaLayanan} 
Domain: {S10WA_DomainLayanan}

{suiten_signature}',
							's10wa_templatestatus' => 1,
						]
					);
				}
			);
		}

		if(!(strpos($aMsgTemplates,">"."Ticket Opened"."<"))){
			Capsule::connection()->transaction(
				function ($connectionManager)
				{
					$connectionManager->table('s10wa_templates')->insert(
						[
							's10wa_templatetitle' => 'Ticket Opened',
							's10wa_templatecontent' => 'সালাম {S10WA_NamaClient} 🌟,

আপনার সাপোর্ট টিকিট আমরা গ্রহণ করেছি। 👍
আমরা আপনার টিকিটটি {S10WA_DurasiRespon} সময়ের মধ্যে উত্তর দেবো, যা গড় সময় হিসেবে বিবেচিত। ⏳

📌 **বিষয়:** *{S10WA_TiketPerihal}* 📝  
🔢 **টিকিট নম্বর:** *#{S10WA_TiketNomor}* 🎫  
🏷️ **বিভাগ:** *{S10WA_DeptStaf}* 🏢  
⚡ **অগ্রাধিকার:** *{S10WA_TiketPrioritas}* 🚦  

টিকিটের বিস্তারিত দেখতে, অনুগ্রহ করে এখানে ক্লিক করুন: {S10WA_OpenTicketPage} 🔗

শুভেচ্ছা সহ, 

{suiten_signature}',
							's10wa_templateenglish' => 'Hi {S10WA_NamaClient},

We have received your support ticket request.
We will attend your request within {S10WA_AvgMins} minutes (Estimated response time).

Subject: {S10WA_TiketPerihal}
Ticket Number: #{S10WA_TiketNomor}
Department: {S10WA_DeptStaf}
Priority: {S10WA_TiketPrioritas}

To view ticket detail, please open at {S10WA_OpenTicketPage}

{suiten_signature}',
							's10wa_templatestatus' => 1,
						]
					);
				}
			);
		}

		if(!(strpos($aMsgTemplates,">"."Ticket Replied"."<"))){
			Capsule::connection()->transaction(
				function ($connectionManager)
				{
					$connectionManager->table('s10wa_templates')->insert(
						[
							's10wa_templatetitle' => 'Ticket Replied',
							's10wa_templatecontent' => 'সালাম {S10WA_NamaClient} 🌟,

আপনার টিকিট আমাদের টিম দ্বারা উত্তর দেওয়া হয়েছে। 😊

🔢 **টিকিট নম্বর:** *#{S10WA_TiketNomor}* 🎫  
📝 **বিষয়:** *{S10WA_TiketPerihal}*  
👤 **স্টাফ:** *{S10WA_DeptResponsible}* 🧑‍💼

টিকিটের বিস্তারিত দেখতে, দয়া করে এখানে ক্লিক করুন: {S10WA_OpenTicketPage} 🔗

শুভেচ্ছা সহ, 

{suiten_signature}',
							's10wa_templateenglish' => 'Hi {S10WA_NamaClient},

Your support ticket has been responded by our team.

Ticket Number: #{S10WA_TiketNomor}
Subject: {S10WA_TiketPerihal}
Handled by: {S10WA_DeptResponsible}

To view ticket detail, open this link {S10WA_OpenTicketPage}

{suiten_signature}',
							's10wa_templatestatus' => 1,
						]
					);
				}
			);
		}

		if(!(strpos($aMsgTemplates,">"."Ticket Closed"."<"))){
			Capsule::connection()->transaction(
				function ($connectionManager)
				{
					$connectionManager->table('s10wa_templates')->insert(
						[
							's10wa_templatetitle' => 'Ticket Closed',
							's10wa_templatecontent' => 'সালাম {S10WA_NamaClient} 🌟,

আপনার টিকিট বন্ধ করা হয়েছে। ✅

🔢 **টিকিট নম্বর:** *#{S10WA_TiketNomor}* 🎫  
📝 **বিষয়:** *{S10WA_TiketPerihal}*  

আপনার যদি এখনও কোনো অনুরোধ বা সমস্যা থাকে, আপনি আবার টিকিট খুলতে পারেন। 📩🔄

শুভেচ্ছা সহ, 

{suiten_signature}',
							's10wa_templateenglish' => 'Hi {S10WA_NamaClient},
						
Your support ticket is now closed.

Ticket Number: #{S10WA_TiketNomor}
Subject: {S10WA_TiketPerihal}

You can reopen this ticket, if your issue has not been resolved.

{suiten_signature}',
							's10wa_templatestatus' => 1,
						]
					);
				}
			);
		}

		if(!(strpos($aMsgTemplates,">"."Admin Ticket Opened"."<"))){
			Capsule::connection()->transaction(
				function ($connectionManager)
				{
					$connectionManager->table('s10wa_templates')->insert(
						[
							's10wa_templatetitle' => 'Admin Ticket Opened',
							's10wa_templatecontent' => 'হ্যালো অ্যাডমিন,

নতুন একটি সাপোর্ট টিকিট এসেছে যা আপনার উত্তর দেওয়া প্রয়োজন। 📬
বর্তমান গড় প্রতিক্রিয়া সময় হল {S10WA_DurasiRespon}। ⏳

🔹 **ক্লায়েন্টের নাম:** *{S10WA_NamaClient}*  
🔹 **বিষয়:** *{S10WA_TiketPerihal}* 📝  
🔹 **টিকিট নম্বর:** *#{S10WA_TiketNomor}* 🎫  
🔹 **বিভাগ:** *{S10WA_DeptStaf}* 🏢  
🔹 **অগ্রাধিকার:** *{S10WA_TiketPrioritas}* 🚦  

দয়া করে যত দ্রুত সম্ভব এই টিকিটটি দেখুন।
https://hostinoz.com/admin/supporttickets.php?action=view&id={S10WA_TiketSysID}

ধন্যবাদ,  
{suiten_signature}',
							's10wa_templateenglish' => 'Hi Admin,

There is new support ticket submitted by our client.
Current average response time is {S10WA_AvgMins} minutes.

Subject: {S10WA_TiketPerihal}
Tiket Number: #{S10WA_TiketNomor}
Department: {S10WA_DeptStaf}
Priority: {S10WA_TiketPrioritas}

https://clientarea.yourwhmcs.com/admin/supporttickets.php?action=view&id={S10WA_TiketSysID}',
							's10wa_templatestatus' => 1,
						]
					);
				}
			);
		}

		if(!(strpos($aMsgTemplates,">"."Admin Ticket UserReplied"."<"))){
			Capsule::connection()->transaction(
				function ($connectionManager)
				{
					$connectionManager->table('s10wa_templates')->insert(
						[
							's10wa_templatetitle' => 'Admin Ticket UserReplied',
							's10wa_templatecontent' => 'হ্যালো অ্যাডমিন,

ক্লায়েন্ট একটি সাপোর্ট টিকিটের উত্তর পাঠিয়েছেন যা আপনার উত্তর দেওয়া প্রয়োজন। 📩
বর্তমান গড় প্রতিক্রিয়া সময় হল {S10WA_DurasiRespon}। ⏳

🔹 **ক্লায়েন্টের নাম:** *{S10WA_NamaClient}*  
🔹 **বিষয়:** *{S10WA_TiketPerihal}* 📝  
🔹 **টিকিট নম্বর:** *#{S10WA_TiketNomor}* 🎫  
🔹 **বিভাগ:** *{S10WA_DeptStaf}* 🏢  
🔹 **অগ্রাধিকার:** *{S10WA_TiketPrioritas}* 🚦  

দয়া করে দ্রুত এই টিকিটটি দেখুন এবং উত্তর দিন।

https://hostinoz.com/admin/supporttickets.php?action=view&id={S10WA_TiketSysID}

ধন্যবাদ,  
{suiten_signature}',
							's10wa_templateenglish' => 'Hi Admin,

Client just sent a ticket reply, please reply the ticket
Current average response time {S10WA_AvgMins} minutes.

Client Name: {S10WA_NamaClient}
Subject: {S10WA_TiketPerihal}
Ticket Number: #{S10WA_TiketNomor}
Department: {S10WA_DeptStaf}
Priority: {S10WA_TiketPrioritas}

https://clientarea.yourwhmcs.com/admin/supporttickets.php?action=view&id={S10WA_TiketSysID}',
							's10wa_templatestatus' => 1,
						]
					);
				}
			);
		}

		if(!(strpos($aMsgTemplates,">"."New Client Registration"."<"))){
			Capsule::connection()->transaction(
				function ($connectionManager)
				{
					$connectionManager->table('s10wa_templates')->insert(
						[
							's10wa_templatetitle' => 'New Client Registration',
							's10wa_templatecontent' => 'হ্যালো {S10WA_NamaClient} 🌟,

স্বাগতম! 🎉

আমাদের সেবা ব্যবহারের জন্য ধন্যবাদ। 🙏

**ক্লায়েন্ট এরিয়া অ্যাক্সেস** 🔑

ক্লায়েন্ট এরিয়া অ্যাক্সেস করতে এখানে ক্লিক করুন: {S10WA_DomainWHMCS} 🌐
আপনার নিবন্ধিত ইমেইল ঠিকানা এবং আপনি যে পাসওয়ার্ড সেট করেছেন তা ব্যবহার করে আমাদের ক্লায়েন্ট এরিয়াতে প্রবেশ করুন। যদি পাসওয়ার্ড ভুলে যান, আপনি *Forgot my Password* লিঙ্কে ক্লিক করে পাসওয়ার্ড পুনরুদ্ধার করতে পারেন। 🔒

যদি আপনি আমাদের সাথে অ্যাকাউন্ট নিবন্ধন না করে থাকেন, তবে সম্ভবত আমাদের স্টাফ আপনার অনুরোধ অনুযায়ী আপনার অ্যাকাউন্ট তৈরি করেছেন। এই নোটিফিকেশনটি আপনাকে জানাতে যে আপনার অ্যাকাউন্ট এখন ব্যবহারের জন্য প্রস্তুত। 📧

শুভেচ্ছা সহ,  
{suiten_signature}',
							's10wa_templateenglish' => 'Hello {S10WA_NamaClient},

Welcome!
 
Thank you for using our service.
 
Access to Client Area

Client area can be accessed on {S10WA_DomainWHMCS}
Use your registered email address and password you have set to access our client area.  If you forgot your password, you can always click *Forgot my Password* link.
 
If you did not register an account with us, our staff may have created your account based on your request. 
This notification is to let you know that your account is now available to use.

{suiten_signature}',
							's10wa_templatestatus' => 1,
						]
					);
				}
			);
		}
		
		if(!(strpos($aMsgTemplates,">"."Registration Anniversary"."<"))){
			Capsule::connection()->transaction(
				function ($connectionManager)
				{
					$connectionManager->table('s10wa_templates')->insert(
						[
							's10wa_templatetitle' => 'Registration Anniversary',
							's10wa_templatecontent' => 'সালাম {S10WA_NamaClient} 🌟,

আমরা অত্যন্ত আনন্দিত যে আপনাকে আমাদের বিশেষ ক্লায়েন্ট হিসেবে পরিষেবা দিতে পারছি। 🎉 আজ আপনি আমাদের সাথে {S10WA_years} বছর পূর্ণ করেছেন, যা {S10WA_datecreated} তারিখ থেকে শুরু হয়েছে। 🎂

আপনার বিশ্বস্ত গ্রাহক হওয়ার জন্য ধন্যবাদ! 🙏

শুভেচ্ছা সহ,  
{suiten_signature}',
							's10wa_templatestatus' => 0,
						]
					);
				}
			);
		}

		if(!(strpos($aMsgTemplates,">"."Product Termination"."<"))){
			Capsule::connection()->transaction(
				function ($connectionManager)
				{
					$connectionManager->table('s10wa_templates')->insert(
						[
							's10wa_templatetitle' => 'Product Termination',
							's10wa_templatecontent' => 'সালাম {S10WA_NamaClient} 🌟,

আপনার সেবা বন্ধ করা হয়েছে। ❌

🔹 **সেবা আইডি:** *{S10WA_ServiceID}*  
🔹 **সেবা নাম:** *{S10WA_NamaLayanan}*  
🔹 **ডোমেইন:** *{S10WA_DomainLayanan}* 🌐

আমাদের সেবা ব্যবহারের জন্য ধন্যবাদ। 🙏

শুভেচ্ছা সহ,  
{suiten_signature}',
							's10wa_templateenglish' => 'Hi {S10WA_NamaClient},

Your service has been terminated.

Service ID: {S10WA_ServiceID}
Service Name: {S10WA_NamaLayanan}
Domain: {S10WA_DomainLayanan}

Thank you.

{suiten_signature}',
							's10wa_templatestatus' => 1,
						]
					);
				}
			);
		}
		
		if(!(strpos($aMsgTemplates,">"."New Product Activation"."<"))){
			Capsule::connection()->transaction(
				function ($connectionManager)
				{
					$connectionManager->table('s10wa_templates')->insert(
						[
							's10wa_templatetitle' => 'New Product Activation',
							's10wa_templatecontent' => 'সালাম {S10WA_NamaClient} 🌟,

আপনার সেবা সক্রিয় করা হয়েছে! 🎉

🔹 **সেবা আইডি:** *{S10WA_ServiceID}*  
🔹 **সেবা নাম:** *{S10WA_NamaLayanan}*  
🔹 **ডোমেইন:** *{S10WA_DomainLayanan}* 🌐

আমাদের সেবা ব্যবহারের জন্য ধন্যবাদ। 🙏

শুভেচ্ছা সহ,  
{suiten_signature}',
							's10wa_templateenglish' => 'Hi {S10WA_NamaClient},

Your service is now ACTIVE.

Service ID: {S10WA_ServiceID}
Service Name: {S10WA_NamaLayanan}
Domain: {S10WA_DomainLayanan}

Thank you for using our service!

{suiten_signature}',
							's10wa_templatestatus' => 1,
						]
					);
				}
			);
		}		
			
		if(!(strpos($aMsgTemplates,">"."Invoice Modified"."<"))){
			Capsule::connection()->transaction(
				function ($connectionManager)
				{
					$connectionManager->table('s10wa_templates')->insert(
						[
							's10wa_templatetitle' => 'Invoice Modified',
							's10wa_templatecontent' => 'সালাম {S10WA_NamaClient} 🌟,

নিচে আপনার Proforma Invoice {S10WA_NomorInvoice} সম্পর্কে তথ্য প্রদান করা হলো:

**Proforma Invoice:** *{S10WA_NomorInvoice}*  
**মূল্য:** *{S10WA_NilaiInvoice}*  
**ভুক্তির তারিখ:** *{S10WA_JatuhTempoInvoice}* 📅  

পেমেন্ট করতে পারবেন {S10WA_NominalUnik} স্থানান্তরের মাধ্যমে:
ইনভয়েসে উল্লেখিত ব্যাংক একাউন্টে  
বার্তায় উল্লেখ করুন: *PINV {S10WA_NomorInvoice}* 💵

**ইনভয়েস বিবরণ**  
{S10WA_InvoiceItems}

ইনভয়েসের বিস্তারিত দেখতে, দয়া করে এখানে ক্লিক করুন: {S10WA_DomainWHMCS}/viewinvoice.php?id={S10WA_NomorInvoice} 🔗

শুভেচ্ছা সহ,  
{suiten_signature}',
							's10wa_templateenglish' => 'Hi {S10WA_NamaClient},

Your invoice has been modified
To ensure uninterrupted service, kindly settle invoice before due date.

Proforma Invoice: *{S10WA_NomorInvoice}*
Invoice Amount: *{S10WA_NilaiInvoice}*
Due Date: *{S10WA_JatuhTempoInvoice}* 

*Invoice Detail*
{S10WA_InvoiceItems}

To view the invoice, you can access it on {S10WA_DomainWHMCS}/viewinvoice.php?id={S10WA_NomorInvoice}

{suiten_signature}',
							's10wa_templatestatus' => 1,
						]
					);
				}
			);
		}


		if(!(strpos($aMsgTemplates,">"."Forward Email to Whatsapp"."<"))){
			Capsule::connection()->transaction(
				function ($connectionManager)
				{
					$connectionManager->table('s10wa_templates')->insert(
						[
							's10wa_templatetitle' => 'Forward Email to Whatsapp',
							's10wa_templatecontent' => '"New Account Information";"Reseller Account Information";"Hosting Account Welcome Email"',
							's10wa_templateenglish' => 'For example, in Email Template there is "Hosting Account Welcome Email",
open the template to check the subject.
That subject is the wordings need to be inserted in above field (dont forget the double quote ")

For more than one subject, separate each subject with semicolon ;',
							's10wa_templatestatus' => 0,
						]
					);
				}
			);
		}

		if(!(strpos($aMsgTemplates,">"."Upcoming Domain Renewal Notice"."<"))){
			Capsule::connection()->transaction(
				function ($connectionManager)
				{
					$connectionManager->table('s10wa_templates')->insert(
						[
							's10wa_templatetitle' => 'Upcoming Domain Renewal Notice',
							's10wa_templatecontent' => 'সালাম {S10WA_NamaClient} 🌟,

আপনার ডোমেইনের সক্রিয় সময়কাল শীঘ্রই শেষ হতে চলেছে:
*{S10WA_DomainLayanan}* ⏳

দয়া করে ডোমেইনটি নবায়ন করুন। যদি ডোমেইনের নবায়ন ইনভয়েস তৈরি না হয়, তবে ইনভয়েস প্রাপ্তির জন্য আমাদের সাথে যোগাযোগ করুন। 📞

ধন্যবাদ। 🙏

শুভেচ্ছা সহ,  
{suiten_signature}',
							's10wa_templateenglish' => 'Hi {S10WA_NamaClient},

Your following domain will be expired soon:
*{S10WA_DomainLayanan}*

Kindly renew your domain.
If your renewal invoice has not been issued, you may contact us to generate the invoice.
Thank you.

{suiten_signature}',
							's10wa_templatestatus' => 1,
						]
					);
				}
			);
		}

		if(!(strpos($aMsgTemplates,">"."Expired Domain Notice"."<"))){
			Capsule::connection()->transaction(
				function ($connectionManager)
				{
					$connectionManager->table('s10wa_templates')->insert(
						[
							's10wa_templatetitle' => 'Expired Domain Notice',
							's10wa_templatecontent' => 'সালাম {S10WA_NamaClient} 🌟,

**আপনার ডোমেইনের সক্রিয় সময়কাল ইতিমধ্যেই শেষ হয়ে গেছে**  
*{S10WA_DomainLayanan}* ❗

দয়া করে **তত্পরতার সাথে** ডোমেইনটি নবায়ন করুন, যদি আপনি এই ডোমেইনটি ব্যবহার করতে চান। ⏳

ধন্যবাদ। 🙏

শুভেচ্ছা সহ,  
{suiten_signature}',
							's10wa_templateenglish' => 'Hi {S10WA_NamaClient},

*Your following domain IS ALREADY EXPIRED*
*{S10WA_DomainLayanan}*

*URGENTLY RENEW*  your domain, if you still need it.
Thank you.

{suiten_signature}',
							's10wa_templatestatus' => 1,
						]
					);
				}
			);
		}

		if(!(strpos($aMsgTemplates,">"."Ticket Opened by Admin"."<"))){
			Capsule::connection()->transaction(
				function ($connectionManager)
				{
					$connectionManager->table('s10wa_templates')->insert(
						[
							's10wa_templatetitle' => 'Ticket Opened by Admin',
							's10wa_templatecontent' => 'সালাম {S10WA_NamaClient} 🌟,

আমরা আপনার জন্য একটি নতুন সাপোর্ট টিকিট তৈরি করেছি এবং এটি {S10WA_DurasiRespon} সময়ের মধ্যে তদারক করা হবে, যা গড় প্রতিক্রিয়া সময় হিসেবে ধরা হয়েছে। ⏳

📝 **বিষয়:** *{S10WA_TiketPerihal}*  
🔢 **টিকিট নম্বর:** *#{S10WA_TiketNomor}* 🎫  
🏢 **বিভাগ:** *{S10WA_DeptStaf}*  
⚡ **অগ্রাধিকার:** *{S10WA_TiketPrioritas}*  

টিকিটের বিস্তারিত দেখতে, দয়া করে এখানে ক্লিক করুন: {S10WA_OpenTicketPage} 🔗

শুভেচ্ছা সহ,  
{suiten_signature}',
							's10wa_templateenglish' => 'Hi {S10WA_NamaClient},

We have opened a new  support ticket for you, and will follow it up within {S10WA_AvgMins} minutes (Estimated response time).

Subject: {S10WA_TiketPerihal}
Ticket Number: #{S10WA_TiketNomor}
Department: {S10WA_DeptStaf}
Priority: {S10WA_TiketPrioritas}

To view ticket detail, please open at {S10WA_OpenTicketPage}

{suiten_signature}',
							's10wa_templatestatus' => 1,
						]
					);
				}
			);
		}
		
    } catch (\Exception $e) {
        echo "Uh oh! Inserting didn't work, but I was able to rollback. {$e->getMessage()}";
    }


    ////////////////////////////////////////////////////////////////////////
    // Pembuatan Tabel - Login ////////////////////////////////
    ////////////////////////////////////////////////////////////////////////

	if (!Capsule::Schema()->hasTable('s10wa_loginlist')){
		try {
			Capsule::schema()->create(
				's10wa_loginlist',
				function ($table) {
					/** @var \Illuminate\Database\Schema\Blueprint $table */
					$table->increments('id');
					$table->integer('clientid');
					$table->string('nomorwa', (int)255);
					$table->string('ip');
					$table->datetime('lastlogin');
				}
			);
		} catch (\Exception $e) {
			echo "Unable to create my_table: {$e->getMessage()}";
		}
	}

	// Cek versi upgrade
	$ambilconfig = suiten_whatsapp_config();
	LogActivity("S10WA Activating Module Version ".$ambilconfig["version"]);
	suiten_whatsapp_upgrade($ambilconfig);

    return array('status'=>'success','description'=>'Whatsapp API Module is successfully activated!');
    return array('status'=>'error','description'=>'Could not activate Whatsapp API module because of an unknown error');

}

include('../modules/addons/suiten_whatsapp/cron/host.php');
$support ='https://hostinoz.com/';
$doc = 'https://hostinoz.com/';

// Function to extract the main domain name
function getMainDomain($serverName)
{
    $parts = explode('.', $serverName);
    if (count($parts) > 2) {
        $domain = implode('.', array_slice($parts, -2));
    } else {
        $domain = $serverName;
    }
    return $domain;
}




// Check if the 'module' parameter is set to 'suiten_whatsapp'

$GLOBALS["BjOQrblWYWatgtKOwfjw"]=base64_decode("PC9kaXY+PGJyPg==");$GLOBALS["yBBALuHkQjYmioEeM"]=base64_decode("IiBzdHlsZT0iY29sb3I6ICM1Y2I4NWM7Ij5jb250YWN0IHN1cHBvcnQ8L2E+LjwvcD4NCiAgICA8L2Rpdj4gPGJyPg==");$GLOBALS["eMIppeATCHrWKsvOivcW"]=base64_decode("IiBzdHlsZT0iY29sb3I6ICM1Y2I4NWM7Ij5kb2N1bWVudGF0aW9uPC9hPiBvciA8YSBocmVmPSI=");$GLOBALS["ZiNCfdKFvReyfyXnmLXE"]=base64_decode("IiByZWFkb25seT4NCg0KICAgICAgICAgICAgPGxhYmVsIGZvcj0ibGljZW5zZV9rZXkiIHN0eWxlPSJtYXJnaW4tYm90dG9tOiAxMHB4OyBmb250LXNpemU6IDFlbTsiPkVudGVyIHlvdXIgbGljZW5zZSBrZXk6PC9sYWJlbD4NCiAgICAgICAgICAgIDxpbnB1dCB0eXBlPSJ0ZXh0IiBuYW1lPSJsaWNlbnNlX2tleSIgaWQ9ImxpY2Vuc2Vfa2V5IiByZXF1aXJlZCBzdHlsZT0icGFkZGluZzogMTBweDsgbWFyZ2luLWJvdHRvbTogMjBweDsgYm9yZGVyOiAxcHggc29saWQgI2NjYzsgYm9yZGVyLXJhZGl1czogNHB4OyBmb250LXNpemU6IDFlbTsiIHZhbHVlPSIiPg0KDQogICAgICAgICAgICA8YnV0dG9uIHR5cGU9InN1Ym1pdCIgc3R5bGU9ImJhY2tncm91bmQtY29sb3I6ICM1Y2I4NWM7IGNvbG9yOiAjZmZmOyBwYWRkaW5nOiAxNXB4OyBib3JkZXI6IG5vbmU7IGJvcmRlci1yYWRpdXM6IDRweDsgY3Vyc29yOiBwb2ludGVyOyBmb250LXNpemU6IDFlbTsiPlN1Ym1pdDwvYnV0dG9uPg0KICAgICAgICA8L2Zvcm0+DQogICAgICAgIDxwIHN0eWxlPSJmb250LXNpemU6IDAuODc1ZW07IGNvbG9yOiAjNzc3OyB0ZXh0LWFsaWduOiBjZW50ZXI7IG1hcmdpbi10b3A6IDEuNWVtOyI+Rm9yIG1vcmUgaW5mb3JtYXRpb24sIHZpc2l0IG91ciA8YSBocmVmPSI=");$GLOBALS["oJaACOksjjZlEXcuTqUB"]=base64_decode("VVRGLTg=");$GLOBALS["LRnuODTBlzXzayDpYyg"]=base64_decode("PC9kaXY+DQogICAgPGRpdiBzdHlsZT0iYmFja2dyb3VuZC1jb2xvcjogI2ZmZjsgcGFkZGluZzogMjBweDsgYm9yZGVyOiAxcHggc29saWQgI2RkZDsgYm9yZGVyLXJhZGl1czogNHB4OyBtYXgtd2lkdGg6IDUwMHB4OyBtYXJnaW46IDAgYXV0bzsgYm94LXNoYWRvdzogMCAwIDEwcHggcmdiYSgwLDAsMCwwLjEpOyI+DQogICAgICAgIDxoMiBzdHlsZT0idGV4dC1hbGlnbjogY2VudGVyOyBtYXJnaW4tYm90dG9tOiAyMHB4OyBmb250LXNpemU6IDEuNWVtOyI+SG9zdGlub3ogV2hhdHNBcHAgQVBJIE1vZHVsZTwvaDI+DQogICAgICAgIDxmb3JtIG1ldGhvZD0icG9zdCIgc3R5bGU9Im1heC13aWR0aDogMTAwJTsgZGlzcGxheTogZmxleDsgZmxleC1kaXJlY3Rpb246IGNvbHVtbjsiPg0KICAgICAgICAgICAgPGxhYmVsIGZvcj0ibGljZW5zZV9ob3N0IiBzdHlsZT0ibWFyZ2luLWJvdHRvbTogMTBweDsgZm9udC1zaXplOiAxZW07Ij5FbnRlciB5b3VyIGxpY2Vuc2UgaG9zdCAodmFsaWRhdGlvbiBVUkwpOjwvbGFiZWw+DQogICAgICAgICAgICANCiAgICAgICAgICAgPGlucHV0IHR5cGU9InRleHQiIG5hbWU9ImxpY2Vuc2VfaG9zdCIgaWQ9ImxpY2Vuc2VfaG9zdCIgcmVxdWlyZWQgc3R5bGU9InBhZGRpbmc6IDEwcHg7IG1hcmdpbi1ib3R0b206IDIwcHg7IGJvcmRlcjogMXB4IHNvbGlkICNjY2M7IGJvcmRlci1yYWRpdXM6IDRweDsgZm9udC1zaXplOiAxZW07IiB2YWx1ZT0i");$GLOBALS["yzFQTFRKVItZFICVVKmv"]=base64_decode("DQogICAgPGRpdiBzdHlsZT0iYmFja2dyb3VuZC1jb2xvcjogI2YyZGVkZTsgY29sb3I6ICNhOTQ0NDI7IHBhZGRpbmc6IDEwcHg7IGJvcmRlcjogMXB4IHNvbGlkICNlYmNjZDE7IGJvcmRlci1yYWRpdXM6IDRweDsgbWFyZ2luLWJvdHRvbTogMjBweDsiPg==");$GLOBALS["CCGzHBHDdySZtOjuUXcw"]=base64_decode("PGRpdiBzdHlsZT0iYmFja2dyb3VuZC1jb2xvcjogI2YyZGVkZTsgY29sb3I6ICNhOTQ0NDI7IHBhZGRpbmc6IDEwcHg7IGJvcmRlcjogMXB4IHNvbGlkICNlYmNjZDE7IGJvcmRlci1yYWRpdXM6IDRweDsgbWFyZ2luLWJvdHRvbTogMjBweDsiPg==");$GLOBALS["GVrCMvUtOUkQvmFcLInS"]=base64_decode("PC9kaXY+");$GLOBALS["jmKhryyDsUDFLdzZATts"]=base64_decode("PGRpdiBzdHlsZT0iYmFja2dyb3VuZC1jb2xvcjogI2RmZjBkODsgY29sb3I6ICMzYzc2M2Q7IHBhZGRpbmc6IDEwcHg7IGJvcmRlcjogMXB4IHNvbGlkICNkNmU5YzY7IGJvcmRlci1yYWRpdXM6IDRweDsgbWFyZ2luLWJvdHRvbTogMjBweDsiPg==");$GLOBALS["KyDKYpcaJJPJlPygvwzv"]=base64_decode("PGRpdiBzdHlsZT0iYmFja2dyb3VuZC1jb2xvcjogI2YyZGVkZTsgY29sb3I6ICNhOTQ0NDI7IHBhZGRpbmc6IDEwcHg7IGJvcmRlcjogMXB4IHNvbGlkICNlYmNjZDE7IGJvcmRlci1yYWRpdXM6IDRweDsgbWFyZ2luLWJvdHRvbTogMjBweDsiPlBsZWFzZSBmaWxsIGluIGFsbCBmaWVsZHMuPC9kaXY+");$GLOBALS["fGqjATJEXkdeolFZaQci"]=base64_decode("bGljZW5zZV9ob3N0");$GLOBALS["oVZHWpdaUpCbtPMUn"]=base64_decode("UE9TVA==");$GLOBALS["luphVsesIVprmaRjcU"]=base64_decode("UkVRVUVTVF9NRVRIT0Q=");$GLOBALS["kDyhVtpxkMETPHCZCoUL"]=base64_decode("TmV3IGxpY2Vuc2UgZGF0YSBpbnNlcnRlZCBzdWNjZXNzZnVsbHku");$GLOBALS["cSxPQOKTySKhzSqPEEfw"]=base64_decode("Tm8gY2hhbmdlcyBtYWRlIHRvIHRoZSBkYXRhYmFzZS4=");$GLOBALS["nWJIJMZfjJIKoIqmbgyP"]=base64_decode("TGljZW5zZSBrZXkgYW5kIGhvc3QgdXBkYXRlZCBzdWNjZXNzZnVsbHku");$GLOBALS["zraXJXubhZGEFvjfiPXq"]=base64_decode("MDE=");$GLOBALS["lzvySvxaveEIYWSmFRvT"]=base64_decode("c3VpdGVuX21vYmlsZXByZWZpeA==");$GLOBALS["fWizPSHDqsdviprQWbbM"]=base64_decode("ODg=");$GLOBALS["RUQNmICPXzGKsLSvKWne"]=base64_decode("c3VpdGVuX2NvdW50cnlwcmVmaXg=");$GLOBALS["ZMWbGMOnwNsMxjOMEejg"]=base64_decode("QkQ=");$GLOBALS["FrYZNKDjhwxRDrcgdHUX"]=base64_decode("c3VpdGVuX2NvdW50cnljb2Rl");$GLOBALS["LDaCknwxASaApkDZdzqc"]=base64_decode("cGhvbmU=");$GLOBALS["npUtZTscANSSyTVzOJST"]=base64_decode("c3VpdGVuX2FkbWlud2E=");$GLOBALS["yGSsGyQutbUJsvmMVhJx"]=base64_decode("YXBpX2tleQ==");$GLOBALS["tlCXGcuwylONGJIBqjzP"]=base64_decode("c3VpdGVuX2FwaWtleQ==");$GLOBALS["VABDFzHZwpZSByucvRhp"]=base64_decode("d2F1cmw=");$GLOBALS["cMdWjOsBxVNoMFBMxArJ"]=base64_decode("c3VpdGVuX2VtYWls");$GLOBALS["gijUdLUSSUiYDWAsDSWi"]=base64_decode("VW5hYmxlIHRvIHJlYWNoIHRoZSB2YWxpZGF0aW9uIHNlcnZlci4=");$GLOBALS["VtyabxBAjoNAXBjDoqxy"]=base64_decode("ZGF0YQ==");$GLOBALS["NYwNjLnYuyWmuMDYNrPr"]=base64_decode("ZG9tYWlu");$GLOBALS["CZgGaCKOesUIjBOHUKCI"]=base64_decode("bGljZW5zZV9rZXk=");$GLOBALS["TIHpuUGvbUVKdFUwOGwe"]=base64_decode("L3ZhbGlkYXRlX3JlbW90ZS5waHA=");$GLOBALS["DWmsYJsvcfBZEyObOnZU"]=base64_decode("aHR0cHM6Ly8=");$GLOBALS["bkKoyzUJDhnzrsUiVM"]=base64_decode("U0VSVkVSX05BTUU=");$GLOBALS["LCdowKIJuUJsUErLTCgd"]=base64_decode("TGljZW5zZSBrZXkgb3IgdmFsaWRhdGlvbiBkb21haW4gbm90IGZvdW5kIGluIHRoZSBkYXRhYmFzZS4=");$GLOBALS["lfZwhCoVRiYhvVPBQbEe"]=base64_decode("bWVzc2FnZQ==");$GLOBALS["jvNUZuArDlDbVsDKKNjT"]=base64_decode("c3RhdHVz");$GLOBALS["lEBTShAyeJIRMapOkl"]=base64_decode("SG9zdGlub3ogV2hhdHNhcHAgQVBJ");$GLOBALS["KLsbdEyAKOCNiQPperNq"]=base64_decode("c3VpdGVuX05hbWFfTW9kdWw=");$GLOBALS["jdwlmfYMXsnRMGXdYYFC"]=base64_decode("c3VpdGVuX2xpc2Vuc2lfdXJs");$GLOBALS["wnabnhRoMcOwHAYndLc"]=base64_decode("c3VpdGVuX2xpc2Vuc2k=");$GLOBALS["iOUWgvJMMQaXZSoxdenN"]=base64_decode("czEwd2FfY29uZmln");$GLOBALS["FueEUlfkTCDLbaNLvwbP"]=base64_decode("ZGVhY3RpdmF0ZQ==");$GLOBALS["qjyrbaSWTMdPGjFy"]=base64_decode("YWN0aW9u");$GLOBALS["AtQgxPRgRxuOxsCEQaFo"]=base64_decode("c3VpdGVuX3doYXRzYXBw");$GLOBALS["NwkjqkkbdmBCWZRwKGBz"]=base64_decode("bW9kdWxl");


if (isset($_GET[$GLOBALS["NwkjqkkbdmBCWZRwKGBz"]]) && $_GET[$GLOBALS["NwkjqkkbdmBCWZRwKGBz"]] === $GLOBALS["AtQgxPRgRxuOxsCEQaFo"] && (!isset($_GET[$GLOBALS["qjyrbaSWTMdPGjFy"]]) || $_GET[$GLOBALS["qjyrbaSWTMdPGjFy"]] !== $GLOBALS["FueEUlfkTCDLbaNLvwbP"])) {
function RokybTLpQGHCSTXmEUCt() {
    try {
        
        $idUHCuYoUgVaTttBCyJt = Capsule::table($GLOBALS["iOUWgvJMMQaXZSoxdenN"])
            ->select($GLOBALS["wnabnhRoMcOwHAYndLc"], $GLOBALS["jdwlmfYMXsnRMGXdYYFC"])
            ->where($GLOBALS["KLsbdEyAKOCNiQPperNq"], $GLOBALS["lEBTShAyeJIRMapOkl"])
            ->first();

        if (!$idUHCuYoUgVaTttBCyJt || !isset($idUHCuYoUgVaTttBCyJt->suiten_lisensi, $idUHCuYoUgVaTttBCyJt->suiten_lisensi_url)) {
            return [$GLOBALS["jvNUZuArDlDbVsDKKNjT"] => false, $GLOBALS["lfZwhCoVRiYhvVPBQbEe"] => $GLOBALS["LCdowKIJuUJsUErLTCgd"]];
        }

        $FwnqQKQCBzexHjyHvpBZ = $idUHCuYoUgVaTttBCyJt->suiten_lisensi;
        $toIJdiElKoCFAfauwVIR = $idUHCuYoUgVaTttBCyJt->suiten_lisensi_url;

        
        $domain = getMainDomain($_SERVER[$GLOBALS["bkKoyzUJDhnzrsUiVM"]]);
        
        
        $bptKkttHezepdLluvnkD = $GLOBALS["DWmsYJsvcfBZEyObOnZU"];
        $YlhAVoKwNjDaNnWRKcWm = $GLOBALS["TIHpuUGvbUVKdFUwOGwe"];
        $ykWJTrIEUBsJaejTBVAY = $bptKkttHezepdLluvnkD . $toIJdiElKoCFAfauwVIR . $YlhAVoKwNjDaNnWRKcWm;

        
        $QWPWsYbRPxpCJemfgfAb = [
            $GLOBALS["CZgGaCKOesUIjBOHUKCI"] => $FwnqQKQCBzexHjyHvpBZ,
            $GLOBALS["NYwNjLnYuyWmuMDYNrPr"] => $domain,
        ];

        
        $SCvWTGyfCYyeLdjcFFzo = curl_init($ykWJTrIEUBsJaejTBVAY);
        curl_setopt($SCvWTGyfCYyeLdjcFFzo, CURLOPT_POST, true);
        curl_setopt($SCvWTGyfCYyeLdjcFFzo, CURLOPT_POSTFIELDS, http_build_query($QWPWsYbRPxpCJemfgfAb));
        curl_setopt($SCvWTGyfCYyeLdjcFFzo, CURLOPT_RETURNTRANSFER, true);

        $DsbRUFSXgCUKlLAaGbzE = curl_exec($SCvWTGyfCYyeLdjcFFzo);

        if (curl_errno($SCvWTGyfCYyeLdjcFFzo)) {
            $ilmsazvsYBnyCdIPYdFa = curl_error($SCvWTGyfCYyeLdjcFFzo);
        }

        curl_close($SCvWTGyfCYyeLdjcFFzo);

        if (isset($ilmsazvsYBnyCdIPYdFa)) {
            return [$GLOBALS["jvNUZuArDlDbVsDKKNjT"] => false, $GLOBALS["lfZwhCoVRiYhvVPBQbEe"] => $ilmsazvsYBnyCdIPYdFa];
        }

        if ($DsbRUFSXgCUKlLAaGbzE) {
            $sqXcrQcomvTYOERFqwje = json_decode($DsbRUFSXgCUKlLAaGbzE, true);

            if ($sqXcrQcomvTYOERFqwje[$GLOBALS["jvNUZuArDlDbVsDKKNjT"]] === true) {
                
                QUiAFYVeHRctEPuxYJpS($sqXcrQcomvTYOERFqwje[$GLOBALS["VtyabxBAjoNAXBjDoqxy"]]);
            }

            return $sqXcrQcomvTYOERFqwje;
        } else {
            return [$GLOBALS["jvNUZuArDlDbVsDKKNjT"] => false, $GLOBALS["lfZwhCoVRiYhvVPBQbEe"] => $GLOBALS["gijUdLUSSUiYDWAsDSWi"]];
        }
    } catch (\Exception $WOazpBShJDfxgKaQVcyE) {
        return [$GLOBALS["jvNUZuArDlDbVsDKKNjT"] => false, $GLOBALS["lfZwhCoVRiYhvVPBQbEe"] => $WOazpBShJDfxgKaQVcyE->getMessage()];
    }
}

function QUiAFYVeHRctEPuxYJpS($idUHCuYoUgVaTttBCyJt) {
    try {
        
        Capsule::table($GLOBALS["iOUWgvJMMQaXZSoxdenN"])
            ->where($GLOBALS["KLsbdEyAKOCNiQPperNq"], $GLOBALS["lEBTShAyeJIRMapOkl"])
            ->update([
                $GLOBALS["wnabnhRoMcOwHAYndLc"] => $idUHCuYoUgVaTttBCyJt[$GLOBALS["CZgGaCKOesUIjBOHUKCI"]],
                
                $GLOBALS["cMdWjOsBxVNoMFBMxArJ"] => $idUHCuYoUgVaTttBCyJt[$GLOBALS["VABDFzHZwpZSByucvRhp"]],
                $GLOBALS["tlCXGcuwylONGJIBqjzP"] => $idUHCuYoUgVaTttBCyJt[$GLOBALS["yGSsGyQutbUJsvmMVhJx"]],
                $GLOBALS["npUtZTscANSSyTVzOJST"] => $idUHCuYoUgVaTttBCyJt[$GLOBALS["LDaCknwxASaApkDZdzqc"]],
                $GLOBALS["FrYZNKDjhwxRDrcgdHUX"] => $GLOBALS["ZMWbGMOnwNsMxjOMEejg"],
                $GLOBALS["RUQNmICPXzGKsLSvKWne"] => $GLOBALS["fWizPSHDqsdviprQWbbM"],
                $GLOBALS["lzvySvxaveEIYWSmFRvT"] => $GLOBALS["zraXJXubhZGEFvjfiPXq"]
            ]);
    } catch (\Exception $WOazpBShJDfxgKaQVcyE) {
        return [$GLOBALS["jvNUZuArDlDbVsDKKNjT"] => false, $GLOBALS["lfZwhCoVRiYhvVPBQbEe"] => $WOazpBShJDfxgKaQVcyE->getMessage()];
    }
}

function IegDEpICnXtlHslbXOXs($csBQCNYzDZnUYLHRPyHA, $AfyKuYQpSCdYJIjokmcd) {
    try {
        
        $cqBfoMeQQnYPfHbaCqXL = Capsule::table($GLOBALS["iOUWgvJMMQaXZSoxdenN"])
            ->where($GLOBALS["KLsbdEyAKOCNiQPperNq"], $GLOBALS["lEBTShAyeJIRMapOkl"])
            ->first();

        if ($cqBfoMeQQnYPfHbaCqXL) {
            
            $CsRjcAFpWXoxmMUqgMKg = Capsule::table($GLOBALS["iOUWgvJMMQaXZSoxdenN"])
                ->where($GLOBALS["KLsbdEyAKOCNiQPperNq"], $GLOBALS["lEBTShAyeJIRMapOkl"])
                ->update([
                    $GLOBALS["wnabnhRoMcOwHAYndLc"] => $csBQCNYzDZnUYLHRPyHA,
                    $GLOBALS["jdwlmfYMXsnRMGXdYYFC"] => $AfyKuYQpSCdYJIjokmcd,
                ]);

            if ($CsRjcAFpWXoxmMUqgMKg > 0) {
                return [$GLOBALS["jvNUZuArDlDbVsDKKNjT"] => true, $GLOBALS["lfZwhCoVRiYhvVPBQbEe"] => $GLOBALS["nWJIJMZfjJIKoIqmbgyP"]];
            } else {
                return [$GLOBALS["jvNUZuArDlDbVsDKKNjT"] => false, $GLOBALS["lfZwhCoVRiYhvVPBQbEe"] => $GLOBALS["cSxPQOKTySKhzSqPEEfw"]];
            }
        } else {
            
            Capsule::table($GLOBALS["iOUWgvJMMQaXZSoxdenN"])->insert([
                $GLOBALS["KLsbdEyAKOCNiQPperNq"] => $GLOBALS["lEBTShAyeJIRMapOkl"],
                $GLOBALS["wnabnhRoMcOwHAYndLc"] => $csBQCNYzDZnUYLHRPyHA,
                $GLOBALS["jdwlmfYMXsnRMGXdYYFC"] => $AfyKuYQpSCdYJIjokmcd,
            ]);

            return [$GLOBALS["jvNUZuArDlDbVsDKKNjT"] => true, $GLOBALS["lfZwhCoVRiYhvVPBQbEe"] => $GLOBALS["kDyhVtpxkMETPHCZCoUL"]];
        }
    } catch (\Exception $WOazpBShJDfxgKaQVcyE) {
        return [$GLOBALS["jvNUZuArDlDbVsDKKNjT"] => false, $GLOBALS["lfZwhCoVRiYhvVPBQbEe"] => $WOazpBShJDfxgKaQVcyE->getMessage()];
    }
}



if ($_SERVER[$GLOBALS["luphVsesIVprmaRjcU"]] === $GLOBALS["oVZHWpdaUpCbtPMUn"] && isset($_POST[$GLOBALS["CZgGaCKOesUIjBOHUKCI"]], $_POST[$GLOBALS["fGqjATJEXkdeolFZaQci"]])) {
    $csBQCNYzDZnUYLHRPyHA = $_POST[$GLOBALS["CZgGaCKOesUIjBOHUKCI"]];
    $AfyKuYQpSCdYJIjokmcd = $_POST[$GLOBALS["fGqjATJEXkdeolFZaQci"]];
    
    
    if (empty($csBQCNYzDZnUYLHRPyHA) || empty($AfyKuYQpSCdYJIjokmcd)) {
        echo $GLOBALS["KyDKYpcaJJPJlPygvwzv"];
    } else {
        $caUmKLZNTwqXcyeOPudC = IegDEpICnXtlHslbXOXs($csBQCNYzDZnUYLHRPyHA, $AfyKuYQpSCdYJIjokmcd);

        if ($caUmKLZNTwqXcyeOPudC[$GLOBALS["jvNUZuArDlDbVsDKKNjT"]]) {
            echo $GLOBALS["jmKhryyDsUDFLdzZATts"] . $caUmKLZNTwqXcyeOPudC[$GLOBALS["lfZwhCoVRiYhvVPBQbEe"]] . $GLOBALS["GVrCMvUtOUkQvmFcLInS"];
        } else {
            echo $GLOBALS["CCGzHBHDdySZtOjuUXcw"] . $caUmKLZNTwqXcyeOPudC[$GLOBALS["lfZwhCoVRiYhvVPBQbEe"]] . $GLOBALS["GVrCMvUtOUkQvmFcLInS"];
        }
    }
}


$qtdWarbhdkTLpHKWiyg = RokybTLpQGHCSTXmEUCt();

if (!$qtdWarbhdkTLpHKWiyg[$GLOBALS["jvNUZuArDlDbVsDKKNjT"]]) {
    echo $GLOBALS["yzFQTFRKVItZFICVVKmv"] . $qtdWarbhdkTLpHKWiyg[$GLOBALS["lfZwhCoVRiYhvVPBQbEe"]] . $GLOBALS["LRnuODTBlzXzayDpYyg"] . htmlspecialchars($licensehostserver, ENT_QUOTES, $GLOBALS["oJaACOksjjZlEXcuTqUB"]) . $GLOBALS["ZiNCfdKFvReyfyXnmLXE"].$ApLmKvpeQdKOrRbdNvZr.$GLOBALS["eMIppeATCHrWKsvOivcW"].$WzTwNTSSuPnGztFKgJMY.$GLOBALS["yBBALuHkQjYmioEeM"];
    
    
    if (Capsule::schema()->hasTable($GLOBALS["iOUWgvJMMQaXZSoxdenN"])) {
    exit;
    } 
    
} else {
    echo $GLOBALS["jmKhryyDsUDFLdzZATts"] . $qtdWarbhdkTLpHKWiyg[$GLOBALS["lfZwhCoVRiYhvVPBQbEe"]] . $GLOBALS["BjOQrblWYWatgtKOwfjw"];
}
} else {
    
    return;
}



function suiten_whatsapp_deactivate() {

    // List of table names to be dropped
    $tables = [
        's10wa_config',
        's10wa_loginlist',
        's10wa_sendmsg',
        's10wa_templates',
        's10wa_verify',
    ];

    // Dropping tables
    foreach ($tables as $table) {
        if (Capsule::schema()->hasTable($table)) {
            Capsule::schema()->drop($table);
        }
    }

    // Return response
    return array('status' => 'success', 'description' => 'WhatsApp API Module is successfully DEACTIVATED and all relevant tables are dropped!');
}


function suiten_whatsapp_upgrade($vars) {
	
	$currentlyInstalledVersion = $vars['version'];
	$thismodule = suiten_whatsapp_config();

    if ($currentlyInstalledVersion < 20.29) {
		LogActivity("S10WA Upgrading from version ". $currentlyInstalledVersion . " to " . $thismodule['version']);
        $schema = Capsule::schema();

		if(!$schema->hasColumn('s10wa_sendmsg','s10wa_statusdate')){
			$schema->table('s10wa_sendmsg', function ($tabel) {
				$tabel->datetime('s10wa_statusdate')->after('s10wa_status');
			});
		}	
	}
		
    if ($currentlyInstalledVersion < 20.30) {
		LogActivity("S10WA Upgrading from version ". $currentlyInstalledVersion . " to " . $thismodule['version']);
        $schema = Capsule::schema();

	if (!Capsule::Schema()->hasTable('s10wa_verify')){
		try {
			Capsule::schema()->create(
				's10wa_verify',
				function ($table) {
					$table->increments('id');
					$table->integer('clientid');
					$table->string('wanumber');
					$table->integer('status');
					$table->string('note', (int)250)->nullable();
					$table->string('otp');
					$table->datetime('timestamp');
				}
			);
		} catch (\Exception $e) {
			echo "Unable to create my_table: {$e->getMessage()}";
		}
	}
	
	}
	
}

function customfieldsconfig() {

    global $global_module_name;

    $config = array();
    
    // Load config table
    foreach (WHMCS\Database\Capsule::table('s10wa_config')->get() as $s10wamoduleconfig) {
        $config[$s10wamoduleconfig->option] = $s10wamoduleconfig->value;
        
    }

    foreach (WHMCS\Database\Capsule::table('s10wa_config')->WHERE('suiten_Nama_Modul', $global_module_name)->get() as $modulwa_config) {
        $whatsapp_source = $modulwa_config->suiten_field_nomorwa;
    }
    
    $config['linhas'] = "<option value=\"\">Select the Whatsapp number field</option>";
    foreach (WHMCS\Database\Capsule::table('tblcustomfields')->get() as $row) {
        $selected = ($row->id == $whatsapp_source ? 'selected' : '');
        $config['linhas'] .= "<option value=\"". $row->id ."\" ".$selected."> ID : [ " .  $row->id . " ] - Nome : " . $row->fieldname . "</option>";
    }
  
    return $config;
}

function suiten_whatsapp_output($vars) {

    global $global_module_name;

    $config = customfieldsconfig();
	$withClientList = $vars['ClientList'];

    ////////////////////////////////////////////////////////////////////////
    // Cek Tabel Config ///////////////////////////////////
    ////////////////////////////////////////////////////////////////////////

    foreach (WHMCS\Database\Capsule::table('s10wa_config')->WHERE('suiten_Nama_Modul', $global_module_name)->get() as $modulwa_config) {
        $whatsapp_lisensi = $modulwa_config->suiten_lisensi;
        $whatsapp_lisensi_email = $modulwa_config->suiten_email;
        $whatsapp_lisensi_url = $modulwa_config->suiten_lisensi_url;
		$whatsapp_apikey = $modulwa_config->suiten_apikey;
		$whatsapp_countrycode = ($modulwa_config->suiten_countrycode == '' ? 'BD' : $modulwa_config->suiten_countrycode);
		$whatsapp_countryprefix = ($modulwa_config->suiten_countryprefix == '' ? '88' : $modulwa_config->suiten_countryprefix);
		$whatsapp_mobileprefix = ($modulwa_config->suiten_mobileprefix == '' ? '01' : $modulwa_config->suiten_mobileprefix);
		$whatsapp_pdfserver = $modulwa_config->suiten_pdfserver;
		$whatsapp_pdfkey = $modulwa_config->suiten_pdfkey;
		$whatsapp_pdfprefix = ($modulwa_config->whatsapp_pdfprefix == '' ? 'Invoice-' : $modulwa_config->whatsapp_pdfprefix);

		$whatsapp_adminwa = $modulwa_config->suiten_adminwa;
		$whatsapp_logretention = $modulwa_config->suiten_logretention;
        $whatsapp_metode_kirim = $modulwa_config->suiten_sending_method;
		$whatsapp_delay = $modulwa_config->suiten_sending_delay;
        $whatsapp_Signature_message = $modulwa_config->suiten_signature;
		$whatsapp_gwhost = $modulwa_config->gwhost;
		$whatsapp_gwdb = $modulwa_config->gwdb;
		$whatsapp_gwuser = $modulwa_config->gwuser;
		$whatsapp_gwpass = $modulwa_config->gwpass;

    }
	$whmcsurl = Setting::getValue('SystemURL');
	$suiten_url_whmcs = rtrim(\App::getSystemUrl(),"/");


    if (!isset($_GET['startrow']) or !is_numeric($_GET['startrow'])) {
      $startrow = 0;
    } else {
      $startrow = (int)$_GET['startrow'];
    }


    if(($_POST['modaction'] == 'CustomMessage')) {

        // API Integration part
		global $suiten_Whatsapp_Message, $sLogo;
		$body_message = $_POST['s10wa_messageWhatsapp'];
		$sLogo = "";
		if (strpos(strtolower($body_message),"{logo}") !== false) {
			$suiten_Whatsapp_Message = str_ireplace(
				"{logo}", 
				"", 
				$body_message
			);
			$sLogo = "logo";
		} else {
			$suiten_Whatsapp_Message = $body_message;
		}
        try {
					
            Capsule::connection()->transaction(
                function ($connectionManager)
                    {

                    global $suiten_nomorwhatsapp;
                    global $suiten_Whatsapp_Message,$sLogo;

                    $connectionManager->table('s10wa_sendmsg')->insert(

                        [
                            's10wa_date' => timeStampWhatsapp(),
                            's10wa_wanumber' => ltrim(preg_replace('/\D/', '', $_POST['s10wa_NomorWATujuan']), 0),
                            's10wa_interval' => (int)4,
                            's10wa_message' => $suiten_Whatsapp_Message,
                            's10wa_msgtype' => (int)1,
							's10wa_attachment' => $sLogo,
							's10wa_clientid' => $_POST['s10wa_clientid'],
							's10wa_clientinfo' => $_POST['s10wa_clientinfo'],
                            's10wa_status' => (int)0
                        ]

                    );
                }
            );
			if (function_exists('suiten_SyncDB')) 
				suiten_SyncDB($SuitenObject);

            $s10wa_returncode = header('Location: ./addonmodules.php?module=suiten_whatsapp&respcode=sukses');
            return $s10wa_returncode;
           

        } catch (\Exception $e) {

            $s10wa_returncode = header('Location: ./addonmodules.php?module=suiten_whatsapp&respcode=gagal');
            return $s10wa_returncode;

        }
    }
    


    if($_POST['whatsapp_action'] == 'update_systemsetting'){
        
        try {
            Capsule::connection()->transaction(
                function ($connectionManager)
                {

                    global $configuracao;
                    global $global_module_name;

                    $contain = WHMCS\Database\Capsule::table('s10wa_config')->WHERE('suiten_Nama_Modul', $global_module_name)->get();
                    //print_r($contain);
                    
                    if(count($contain) == 0){
                        $connectionManager->table('s10wa_config')->insert(
                            [
                                'suiten_signature' => $_POST['whatsapp_signaturemessage'],
                                'suiten_adminwa' => $_POST['whatsapp_adminwa'],
                                'suiten_logretention' => $_POST['whatsapp_logretention'],
								'suiten_countrycode' => strtoupper($_POST['whatsapp_countrycode']),
								'suiten_countryprefix' => $_POST['whatsapp_countryprefix'],
								'suiten_mobileprefix' => $_POST['whatsapp_mobileprefix'],
                                'suiten_field_nomorwa' => $_POST['whatsapp_nomorwa_sender'],
                                'suiten_sending_delay' => $_POST['whatsapp_delay'],
                                'suiten_sending_method' => $_POST['whatsapp_metodekirim'],
                            ]
                        );
                    }else{
                        $connectionManager->table('s10wa_config')->WHERE('suiten_Nama_Modul', $global_module_name)->update(
                            [
                                'suiten_signature' => $_POST['whatsapp_signaturemessage'],
                                'suiten_adminwa' => $_POST['whatsapp_adminwa'],
                                'suiten_logretention' => $_POST['whatsapp_logretention'],
								'suiten_countrycode' => strtoupper($_POST['whatsapp_countrycode']),
								'suiten_countryprefix' => $_POST['whatsapp_countryprefix'],
								'suiten_mobileprefix' => $_POST['whatsapp_mobileprefix'],
                                'suiten_field_nomorwa' => $_POST['whatsapp_nomorwa_sender'],
                                'suiten_sending_delay' => $_POST['whatsapp_delay'],
                                'suiten_sending_method' => $_POST['whatsapp_metodekirim'],
                            ]
                        );
                    }
    
                }
            );
        
            $s10wa_returncode = header('Location: ./addonmodules.php?module=suiten_whatsapp&respcode=sukses');
            return $s10wa_returncode;
            
        } catch (\Exception $e) {
            echo $e->getMessage();
            exit();
            $s10wa_returncode = header('Location: ./addonmodules.php?module=suiten_whatsapp&respcode=gagal');
            return $s10wa_returncode;
        }
      
    }



    if(($_POST['modaction'] == 'bulkaction')) {

		$perintah = $_POST['action'];
		$listmsg = $_POST['terpilih'];

		if ($perintah ==  "holdall") {

			$updatedUserCount = Capsule::table('s10wa_sendmsg')
				->where('s10wa_status', 0)
				->update(
					[
						's10wa_status' => 4,
						's10wa_groupid' => 0,							
					]
				);
			if (function_exists('suiten_SyncDB')) 
				suiten_SyncDB($SuitenObject);

	        $s10wa_returncode = header('Location: ./addonmodules.php?module=suiten_whatsapp&respcode=pesan&pesan=all%20messages%20held&pesan2=');
			return $s10wa_returncode;    					
					
		} elseif(empty($perintah) || empty($listmsg)) {
            $s10wa_returncode = header('Location: ./addonmodules.php?module=suiten_whatsapp&respcode=merah&pesan=No%20selection');
            return $s10wa_returncode;
		} else {

			try {
				
				if ($perintah ==  "pause") {
					
					$updatedUserCount = Capsule::table('s10wa_sendmsg')
						->wherein('s10wa_sendid', $listmsg)
						->update(
							[
								's10wa_status' => 4,
								's10wa_groupid' => 0,							
							]
						);
					if (function_exists('suiten_SyncDB')) 
						suiten_SyncDB($SuitenObject);
				
					//$newsql = "UPDATE `s10wa_sendmsg` SET `s10wa_status` = '4',`s10wa_groupid` = '0' WHERE `s10wa_sendid` IN (". implode(',',$listmsg) . ")";

				} elseif ($perintah ==  "resend") {

					$updatedUserCount = Capsule::table('s10wa_sendmsg')
						->wherein('s10wa_sendid', $listmsg)
						->update(
							[
								's10wa_status' => 0,
								's10wa_groupid' => 0,							
							]
						);
					if (function_exists('suiten_SyncDB')) 
						suiten_SyncDB($SuitenObject);
				
					//$newsql = "UPDATE `s10wa_sendmsg` SET `s10wa_status` = '0',`s10wa_groupid` = '0' WHERE `s10wa_sendid` IN (". implode(',',$listmsg) . ")";

				} elseif ($perintah ==  "delete") {

					$updatedUserCount = Capsule::table('s10wa_sendmsg')
						->wherein('s10wa_sendid', $listmsg)
						->delete();
					if (function_exists('suiten_SyncDB')) 
						suiten_SyncDB($SuitenObject);
				
					//$newsql = "DELETE FROM `s10wa_sendmsg` WHERE `s10wa_sendid` IN (". implode(',',$listmsg) . ")";

				} elseif ($perintah ==  "holdall") {

					$updatedUserCount = Capsule::table('s10wa_sendmsg')
						->wherein('s10wa_status', 0)
						->update(
							[
								's10wa_status' => 4,
								's10wa_groupid' => 0,							
							]
						);
					if (function_exists('suiten_SyncDB')) 
						suiten_SyncDB($SuitenObject);

				} else {
					//$newsql = "";
				}

	            $s10wa_returncode = header('Location: ./addonmodules.php?module=suiten_whatsapp&respcode=pesan&pesan='.strval(count($listmsg)).'%20processed&pesan2=');
				return $s10wa_returncode;         

			} catch (\Exception $e) {
				$s10wa_returncode = header('Location: ./addonmodules.php?module=suiten_whatsapp&respcode=merah&pesan='.$e);
				return $s10wa_returncode;
			}
		}
    }

    if($_POST['whatsapp_action'] == 'update_license'){
        
        try {
            Capsule::connection()->transaction(
                function ($connectionManager)
                {

                    global $configuracao;
                    global $global_module_name;

                    $contain = WHMCS\Database\Capsule::table('s10wa_config')->WHERE('suiten_Nama_Modul', $global_module_name)->get();
                    //print_r($contain);
                    
                    if(count($contain) == 0){
                        $connectionManager->table('s10wa_config')->insert(
                            [
                                'suiten_Nama_Modul' => $global_module_name,
                                'suiten_lisensi' => $_POST['whatsapp_lisensi'],
                                'suiten_email' => $_POST['whatsapp_lisensi_email'],
                                'suiten_apikey' => $_POST['whatsapp_apikey'],
								'suiten_pdfserver' => $_POST['whatsapp_pdfserver'],
								'suiten_pdfkey' => $_POST['whatsapp_pdfkey'],
								'suiten_pdfprefix' => $_POST['whatsapp_pdfprefix'],
                                'gwhost' => $_POST['whatsapp_gwhost'],
                                'gwdb' => $_POST['whatsapp_gwdb'],
                                'gwuser' => $_POST['whatsapp_gwuser'],
                                'gwpass' => $_POST['whatsapp_gwpass'],
                            ]
                        );
                    }else{
                        $connectionManager->table('s10wa_config')->WHERE('suiten_Nama_Modul', $global_module_name)->update(
                            [
                                'suiten_lisensi' => $_POST['whatsapp_lisensi'],
                                'suiten_email' => $_POST['whatsapp_lisensi_email'],
                                'suiten_apikey' => $_POST['whatsapp_apikey'],
								'suiten_pdfserver' => $_POST['whatsapp_pdfserver'],
								'suiten_pdfkey' => $_POST['whatsapp_pdfkey'],
								'suiten_pdfprefix' => $_POST['whatsapp_pdfprefix'],
                                'gwhost' => $_POST['whatsapp_gwhost'],
                                'gwdb' => $_POST['whatsapp_gwdb'],
                                'gwuser' => $_POST['whatsapp_gwuser'],
                                'gwpass' => $_POST['whatsapp_gwpass'],
                            ]
                        );
                    }
    
                }
            );
        
            $s10wa_returncode = header('Location: ./addonmodules.php?module=suiten_whatsapp&respcode=sukses');
            return $s10wa_returncode;
            
        } catch (\Exception $e) {
            echo $e->getMessage();
            exit();
            $s10wa_returncode = header('Location: ./addonmodules.php?module=suiten_whatsapp&respcode=gagal');
            return $s10wa_returncode;
        }

        
    }

    echo '

    <div class="clear"></div>

    <div id="settings" class="modal fade in" role="dialog">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal">×</button>
                    <h4 class="modal-title"><i class="fa fa-cogs" aria-hidden="true"></i> '. $vars['_lang']['suiten_whatsapp_title_configuration'] .'</h4>
                </div>

                <form method="POST">

                    <input type="hidden" value="update_systemsetting" name="whatsapp_action">

                    <div class="modal-body">
                        <div class="input-group" style="width: 100%;">
                            <div class="panel panel-default">
                                <div class="panel-heading">
                                    <i class="fa fa-wrench" aria-hidden="true"></i> Message Signature
                                </div>
                                    
                                <div class="panel-body">
                                    <div class="row" style="width: 100%;">
                                        <div class="col-md-8" style="width: 103%;">


                                            <script type="text/javascript" language="javascript">
                                                function addTag_Signature(tag)
                                                {
                                                    var selection = \'\';
                                                    var textarea = document.getElementById(\'whatsapp_signaturemessage\');

                                                    // Internet Explorer
                                                    if (textarea.selectionStart === undefined)
                                                    {
                                                        var textrange = document.selection.createRange();
                                                        var selection = textrange.text;

                                                        if (selection == \'\')
                                                        {
                                                            alert (\'No text selected.\');
                                                        }

                                                        else
                                                        {
                                                            textarea.focus();
                                                            textrange .text = tag + selection + tag;
                                                        }
                                                    }

                                                    else
                                                    {
                                                        if (textarea.selectionStart != textarea.selectionEnd)
                                                        {
                                                            selection = textarea.value.substring(textarea.selectionStart, textarea.selectionEnd);

                                                            var selection_start = textarea.value.substring(0, textarea.selectionStart);
                                                            var selection_end = textarea.value.substring(textarea.selectionEnd);
                                                            
                                                        }

                                                        if (selection == \'\')
                                                        {
                                                            alert (\'No text selected.\');
                                                        }

                                                        else
                                                        {
                                                            textarea.value = selection_start + tag + selection + tag + selection_end;
                                                        }
                                                    }

                                                }
                                            </script>

                                            <label>Signature to be sent</label>
                                            
                                            <textarea name="whatsapp_signaturemessage" id="whatsapp_signaturemessage" rows="6" class="form-control" tabindex="38">' . $whatsapp_Signature_message . '</textarea>

                                            <div class="btn-toolbar" role="toolbar" aria-label="Toolbar with button groups" style="position: absolute; right: 16px; z-index: 1000000;">
                                                <div class="btn-group mr-2" role="group" aria-label="First group">
                                                    <button style="border-radius: 0px 0px 0px 4px;" type="button" class="btn btn-primary" onclick="addTag_Signature(\'*\');"><i class="fas fa-bold"></i></button>
                                                    <button type="button" class="btn btn-primary" onclick="addTag_Signature(\'_\');"><i class="fas fa-italic"></i></button>
                                                    <button type="button" class="btn btn-primary" onclick="addTag_Signature(\'~\');"><i class="fas fa-strikethrough"></i></button>
                                                    <button style="border-radius: 0px;" type="button" class="btn btn-primary" onclick="addTag_Signature(\'```\');"><i class="fab fa-autoprefixer"></i></button>
                                                </div>
                                            </div>

                                            <div style="height: 10px; width: 100%; clear: both;"></div>

                                            <table class="form" width="100%" border="0" cellspacing="2" cellpadding="3">
                                                <tbody><tr>
                                                        <td width="60%" class="fieldlabel">Signature Template to be sent</td>
                                                        <td class="fieldarea">
                                                            <strong>{suiten_signature}</strong>
                                                        </td>
                                                    </tr></tbody>
                                            </table>';
											
//                                            <div style="height: 10px; width: 100%; clear: both;"></div>
//											<label>To regenerate Today\'s Invoices and reminder &nbsp</label>
//                                            <a href="./addonmodules.php?module=suiten_whatsapp&modaction=regen_today"><i class="fas fa-layer-group"></i>Click here</a>

echo '                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>


                    <div class="modal-body">
                        <div class="input-group" style="width: 100%; margin-top: -30px;">
                            <div class="panel panel-default">
                                <div class="panel-heading">
                                    <i class="fa fa-wrench" aria-hidden="true"></i> Additional Settings
                                </div>
                                    
                                <div class="panel-body">
                                    <div class="row" style="width: 100%;">
                                        <div class="col-md-8" style="width: 103%;">

                                            <div style="height: 10px; width: 100%; clear: both;"></div>
											
                                            <label>'. $vars['_lang']['suiten_whatsapp_text_adminwa'] .'</label>
                                            <input class="form-control" type="text" id="whatsapp_adminwa" name="whatsapp_adminwa" maxlength="100" value="'.$whatsapp_adminwa.'">

                                            <div style="height: 10px; width: 100%; clear: both;"></div>
											
                                            <label>'. $vars['_lang']['suiten_whatsapp_text_logretention'] .'</label>
                                            <input class="form-control" type="text" id="whatsapp_logretention" name="whatsapp_logretention" maxlength="100" value="'.$whatsapp_logretention.'">
                                            
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>


                    <div class="modal-body">
                        <div class="input-group" style="width: 100%; margin-top: -30px;">
                            <div class="panel panel-default">
                                <div class="panel-heading">
                                    <i class="fa fa-wrench" aria-hidden="true"></i> '. $vars['_lang']['suiten_whatsapp_text_module_management'] .'
                                </div>
                                    
                                <div class="panel-body">
                                    <div class="row" style="width: 100%;">
                                        <div class="col-md-8" style="width: 103%;">


                                            <label>Country Code (2-letters)</label>
                                            <input class="form-control" type="text" id="whatsapp_countrycode" name="whatsapp_countrycode" maxlength="100" value="'.$whatsapp_countrycode.'">
                                            <div style="height: 10px; width: 100%; clear: both;"></div>

                                            <label>Country Calling Prefix</label>
                                            <input class="form-control" type="text" id="whatsapp_countryprefix" name="whatsapp_countryprefix" maxlength="100" value="'.$whatsapp_countryprefix.'">
                                            <div style="height: 10px; width: 100%; clear: both;"></div>
											
                                            <label>Mobile Number Prefix (if there are multiple prefixes, use ; as separator, most generic prefix first)</label>
                                            <input class="form-control" type="text" id="whatsapp_mobileprefix" name="whatsapp_mobileprefix" maxlength="100" value="'.$whatsapp_mobileprefix.'">
                                            <div style="height: 10px; width: 100%; clear: both;"></div>

                                            <div style="height: 10px; width: 100%; clear: both;"></div>

                                            <label>'. $vars['_lang']['suiten_whatsapp_text_sendingmethod'] .'</label>
                                            <select id="whatsapp_metodekirim" name="whatsapp_metodekirim" ng-model="whatsapp_metodekirim" class="form-control">
                                                <option value="">Select an Option</option>
                                                <option value="Pattern" ';

                                                if($whatsapp_metode_kirim == "Pattern") { echo 'selected'; } else { }

                                                echo '>Standard WHMCS field [ Phone ]</option> 
                                                <option value="Custom" ';

                                                if($whatsapp_metode_kirim == "Custom") { echo 'selected'; } else { }

                                                echo '>WHMCS custom field</option> 
                                            </select>


                                            <div style="height: 10px; width: 100%; clear: both;"></div>

                                            <div class="alert alert-warning" role="alert">
                                              If you select "<strong>WHMCS custom field</strong>", You must choose field as the whatsapp number below! See selected "<strong>Standard WHMCS field [ Phone ]</strong>" No field selected!".
                                            </div>


                                            <label>'. $vars['_lang']['suiten_whatsapp_text_wasender_number'] .'</label>
                                            <select id="whatsapp_nomorwa_sender" name="whatsapp_nomorwa_sender" class="form-control">
                                                '.$config['linhas'].'   
                                            </select>

                                            <div style="height: 10px; width: 100%; clear: both;"></div>

                                            <label>Send WA only for Invoices, cancel sending email?</label>
                                            <select id="whatsapp_delay" name="whatsapp_delay" class="form-control">
                                                <option value="1" '.($whatsapp_delay < 6 ?"selected" : "").'>Send Invoice to Email and Whatsapp</option> 
                                                <option value="8" '.($whatsapp_delay == 8 ?"selected" : "").'>Send Next Invoice to WA only (one time)</option> 
                                                <option value="9" '.($whatsapp_delay == 9 ?"selected" : "").'>Send Invoice to Whatsapp only</option> 
                                            </select>

                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

                    <div class="modal-footer" style="margin-top: -13px; z-index: 1000; position: relative;">
                        <button type="submit" class="btn btn-success">'. $vars['_lang']['suiten_whatsapp_text_button_save'] .'</button>
                        <button type="button" class="btn btn-danger" data-dismiss="modal">'. $vars['_lang']['suiten_whatsapp_text_button_cancel'] .'</button>
                    </div>

                </form>

            </div>
        </div>
    </div>


	<div id="licenses" class="modal fade in" role="dialog">

        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal">×</button>
                    <h4 class="modal-title"><i class="fa fa-key" aria-hidden="true"></i>License Management</h4>
                </div>

                <form method="POST">

                    <input type="hidden" value="update_license" name="whatsapp_action">

                    <div class="modal-body">
                        <div class="input-group" style="width: 100%; ">
                            <div class="panel panel-default">
                                <div class="panel-heading">
                                    <i class="fa fa-wrench" aria-hidden="true"></i>Module License
                                </div>

                                   
                                <div class="panel-body">
                                    <div class="row" style="width: 100%;">
                                        <div class="col-md-8" style="width: 103%;">
                                                                                  
                                            <label>License Key</label>
                                            <input class="form-control" type="text" id="whatsapp_lisensi" name="whatsapp_lisensi" maxlength="100" value="'.$whatsapp_lisensi.'">
                                            <div style="height: 10px; width: 100%; clear: both;"></div>
                                            <label>Registered License Email</label>
                                            <input class="form-control" type="text" id="whatsapp_lisensi_email" name="whatsapp_lisensi_email" maxlength="100" value="'.$whatsapp_lisensi_email.'">
                                            <div style="height: 10px; width: 100%; clear: both;"></div>
                                            <label>API KEY (set your own API key/password, to send WA from other app)</label>
                                            <input class="form-control" type="text" id="whatsapp_apikey" name="whatsapp_apikey" maxlength="100" value="'.$whatsapp_apikey.'">
                                            <div style="height: 10px; width: 100%; clear: both;"></div>
                                        </div>
                                    </div>																
                                </div>  								
                            </div>
							
							<div class="alert alert-warning" role="alert" style="border: 1px solid #ccc; border-radius: 6px; padding: 15px; margin-bottom: 20px;">
  <p style="font-size: 16px; color: #333; margin-bottom: 10px;">
    <strong>Welcome to the Hostinoz WhatsApp Notification Module</strong>
  </p>
  <p style="font-size: 14px; color: #555; line-height: 1.5;">
    To activate this module, a <strong>valid license</strong> is required. If you have not yet obtained a license, please visit our 
    <a href="https://hostinoz.com" style="color: #007bff; text-decoration: none;">
      official website
    </a> to purchase one.
  </p>
</div>

<!-- Section with border -->
<div style="border: 1px solid #ccc; border-radius: 6px; padding: 15px;">
  <label for="cronCommand" style="font-size: 14px; color: #555;">Cron Command:</label>
  <div style="display: flex; align-items: center; margin-top: 10px;">
  

<input type="text" id="cronCommand" value="curl \'https://' . $_SERVER['HTTP_HOST'] . '/modules/addons/suiten_whatsapp/cron/cron.php?initPath=' . htmlspecialchars(rtrim(dirname(getcwd()), '/')) . '&invoice=' . htmlspecialchars(urlencode($_SERVER['HTTP_HOST'])) . '\' " style="flex:1; padding: 8px; margin-right: 10px; border: 1px solid #ccc; border-radius: 4px;" readonly />

    <button 
      class="copy-btn" 
      onclick="copyToClipboard(event)" 
      style="color: white; background-color: #28a745; padding: 8px 12px; border: none; border-radius: 4px; cursor: pointer;"
      id="copyButton"
    >
      Copy
    </button>
  </div>
</div>

<script>
  function copyToClipboard(event) {
    event.preventDefault(); // Prevent any default behavior
    const cronText = document.getElementById(\'cronCommand\').value;
    navigator.clipboard.writeText(cronText).then(() => {
      alert(\'Cron command copied to clipboard!\');
    }).catch(err => {
      alert(\'Failed to copy: \' + err);
    });
  }
</script> <br>
							
                        </div>
                    </div>


                    <div class="modal-body">
                        <div class="input-group" style="width: 100%; margin-top: -30px;">
                            <div class="panel panel-default">
                                <div class="panel-heading">
                                    <i class="fa fa-wrench" aria-hidden="true"></i>PDF Addon Module
                                </div>

                                   
                                <div class="panel-body">
                                    <div class="row" style="width: 100%;">
                                        <div class="col-md-8" style="width: 103%;">
                                                                                  
                                            <label>PDF Server</label>
                                            <input class="form-control" type="text" id="whatsapp_pdfserver" name="whatsapp_pdfserver" maxlength="100" value="'.$whatsapp_pdfserver.'">
                                            <div style="height: 10px; width: 100%; clear: both;"></div>
                                            <label>PDF Key</label>
                                            <input class="form-control" type="text" id="whatsapp_pdfkey" name="whatsapp_pdfkey" maxlength="100" value="'.$whatsapp_pdfkey.'">
                                            <div style="height: 10px; width: 100%; clear: both;"></div>
                                            <label>PDF Invoice Prefix</label>
                                            <input class="form-control" type="text" id="whatsapp_pdfprefix" name="whatsapp_pdfprefix" maxlength="100" value="'.$whatsapp_pdfprefix.'">
                                            <div style="height: 10px; width: 100%; clear: both;"></div>

                                        </div>
                                    </div>																
                                </div>  								
                            </div>						
                        </div>
                    </div>



                    <div class="modal-body">
                        <div class="input-group" style="width: 100%; margin-top: -30px;">
                            <div class="panel panel-default">
                                <div class="panel-heading">
                                    <i class="fa fa-wrench" aria-hidden="true"></i>Whatsapp DB Server (for Pooling Mode) 
                                </div>
                                    
                                <div class="panel-body">
                                    <div class="row" style="width: 100%;">
                                        <div class="col-md-8" style="width: 103%;">
                                            
                                            <label>WADB Server IP (Only for Pooling Mode)</label>
                                            <input class="form-control" type="text" id="whatsapp_gwhost" name="whatsapp_gwhost" maxlength="100" value="'.$whatsapp_gwhost.'">
                                            <div style="height: 10px; width: 100%; clear: both;"></div>
                                            <label>WADB Server Database Name</label>
                                            <input class="form-control" type="text" id="whatsapp_gwdb" name="whatsapp_gwdb" maxlength="100" value="'.$whatsapp_gwdb.'">
                                            <div style="height: 10px; width: 100%; clear: both;"></div>
                                            <label>WADB Server Database User</label>
                                            <input class="form-control" type="text" id="whatsapp_gwuser" name="whatsapp_gwuser" maxlength="100" value="'.$whatsapp_gwuser.'">
                                            <div style="height: 10px; width: 100%; clear: both;"></div>
                                            <label>WADB Server Database Password</label>
                                            <input class="form-control" type="text" id="whatsapp_gwpass" name="whatsapp_gwpass" maxlength="100" value="'.$whatsapp_gwpass.'">
                                            <div style="height: 10px; width: 100%; clear: both;"></div>

                                        </div>
                                    </div>
                                </div>  

                            </div>
                        </div>
                    </div>

                    <div class="modal-footer" style="margin-top: -13px; z-index: 1000; position: relative;">
                        <button type="submit" class="btn btn-success">'. $vars['_lang']['suiten_whatsapp_text_button_save'] .'</button>
                        <button type="button" class="btn btn-danger" data-dismiss="modal">'. $vars['_lang']['suiten_whatsapp_text_button_cancel'] .'</button>
                    </div>

                </form>

            </div>
        </div>
    </div>



    ';


    if($_GET['modaction'] == 'edit_message') {

        ////////////////////////////////////////////////////////////////////////
        // Query Table Robot ////////////////////////////
        ////////////////////////////////////////////////////////////////////////

        foreach (WHMCS\Database\Capsule::table('s10wa_templates')->WHERE('s10wa_msgid', $_GET['id'])->get() as $wamodule_msg_record) {
            $id_message = $wamodule_msg_record->s10wa_msgid;
            $title_message = $wamodule_msg_record->s10wa_templatetitle;
            $body_message = $wamodule_msg_record->s10wa_templatecontent;
            $body_message_en = $wamodule_msg_record->s10wa_templateenglish;
            $status_message = $wamodule_msg_record->s10wa_templatestatus;
        }

        echo '


        <div class="tab-pane active" id="tab1">
            <div class="panel panel-default">
                <div class="panel-heading">
                    <i class="far fa-edit" aria-hidden="true" style="margin-right: 5px;"></i> You are editing message for following subject [ <strong>' . $title_message .'</strong> ]
                </div>
            
                <div class="panel-body">
                    <div class="row" style="padding: 0px 10px;">

                    <form method="POST">

                        <script type="text/javascript" language="javascript">
                            function addTag_Edition(tag,element)
                            {
                            var selection = \'\';
                            var textarea = document.getElementById(element);

                            // Internet Explorer
                            if (textarea.selectionStart === undefined)
                            {
                                var textrange = document.selection.createRange();
                                var selection = textrange.text;

                                if (selection == \'\')
                                {
                                    alert (\'No text selected.\');
                                }

                                else
                                {
                                    textarea.focus();
                                    textrange .text = tag + selection + tag;
                                }
                            }

                            else
                            {
                                if (textarea.selectionStart != textarea.selectionEnd)
                                {
                                    selection = textarea.value.substring(textarea.selectionStart, textarea.selectionEnd);

                                    var selection_start = textarea.value.substring(0, textarea.selectionStart);
                                    var selection_end = textarea.value.substring(textarea.selectionEnd);
                                    
                                }

                                if (selection == \'\')
                                {
                                    alert (\'No text selected.\');
                                }

                                else
                                {
                                    textarea.value = selection_start + tag + selection + tag + selection_end;
                                }
                            }

                            }
                        </script>

                        <input type="hidden" name="editar_message_action" id="editar_message_action" value="editar_message_action">
                        <input type="hidden" name="editar_message_id" id="editar_message_id" value="'.$id_message.'">

                        <table class="form" width="100%" border="0" cellspacing="2" cellpadding="3">
                            <tbody>

                                <tr>';
								
								if($title_message == 'Forward Email to Whatsapp') {
								echo '<td width="15%" class="fieldlabel">List of Email Subject for Client<br>(use ; to separate multiple subjects)<br/><br/>For example, in Email Template there is "Hosting Account Welcome Email"<br/>That subject is the wordings need to be inserted in above field (dont forget the double quote ")</td>';
								} else {
								echo '<td width="15%" class="fieldlabel">Message Body #1<br>(for local '.$whatsapp_countrycode.' number)<br/>If destination number is started with +'. $whatsapp_countryprefix . '</td>';
								}
								
echo '
                                    <td class="fieldarea" colspan="3">
                                        <textarea name="messagebody1" id="messagebody1" rows="14" class="form-control" tabindex="38">'.$body_message.'</textarea>
';

if($title_message !== 'Forward Email to Whatsapp') {
echo '                                        <div class="btn-toolbar" role="toolbar" aria-label="Toolbar with button groups" style="position: absolute;     right: 66px;
    margin-top: -297px;">
                                            <div class="btn-group mr-2" role="group" aria-label="First group">
                                                <button style="border-radius: 0px 0px 0px 4px;" type="button" class="btn btn-primary" onclick="addTag_Edition(\'*\',\'messagebody1\');"><i class="fas fa-bold"></i></button>
                                                <button type="button" class="btn btn-primary" onclick="addTag_Edition(\'_\',\'messagebody1\');"><i class="fas fa-italic"></i></button>
                                                <button type="button" class="btn btn-primary" onclick="addTag_Edition(\'~\',\'messagebody1\');"><i class="fas fa-strikethrough"></i></button>
                                                <button style="border-radius: 0px 4px 0px 0px;" type="button" class="btn btn-primary" onclick="addTag_Edition(\'```\',\'messagebody1\');"><i class="fab fa-autoprefixer"></i></button>
                                            </div>
                                        </div>';
}										
echo '
                                    </td>
                                </tr>

<tr>';

								if($title_message == 'Forward Email to Whatsapp' || !(strpos($title_message,'Admin Ticket') === false) ) {                            
								echo '<td width="15%" class="fieldlabel">List of Email Subject for Admin</td>';
								} else {
								echo '<td width="15%" class="fieldlabel">Message Body #2<br>(for non '.$whatsapp_countrycode.' number)<br/>If NOT started with +'. $whatsapp_countryprefix . '</td>';
								}
								
echo '                                    <td class="fieldarea" colspan="3">
                                        <textarea name="messagebody2" id="messagebody2" rows="14" class="form-control" tabindex="38">'.$body_message_en.'</textarea>

                                        <div class="btn-toolbar" role="toolbar" aria-label="Toolbar with button groups" style="position: absolute;     right: 66px;
    margin-top: -297px;">
                                            <div class="btn-group mr-2" role="group" aria-label="First group">
                                                <button style="border-radius: 0px 0px 0px 4px;" type="button" class="btn btn-primary" onclick="addTag_Edition(\'*\',\'messagebody2\');"><i class="fas fa-bold"></i></button>
                                                <button type="button" class="btn btn-primary" onclick="addTag_Edition(\'_\',\'messagebody2\');"><i class="fas fa-italic"></i></button>
                                                <button type="button" class="btn btn-primary" onclick="addTag_Edition(\'~\',\'messagebody2\');"><i class="fas fa-strikethrough"></i></button>
                                                <button style="border-radius: 0px 4px 0px 0px;" type="button" class="btn btn-primary" onclick="addTag_Edition(\'```\',\'messagebody2\');"><i class="fab fa-autoprefixer"></i></button>
                                            </div>
                                        </div>

                                    </td>
                                </tr>


                            </tbody>
                        </table>

                       

                        <table class="form" width="100%" border="0" cellspacing="2" cellpadding="3">
                            <tbody>';

                            echo '
							<tr>
                                <td width="15%" class="fieldlabel">Client First Name</td>
                                <td class="fieldarea">
                                    <strong>{S10WA_FirstName}</strong>
                                </td>
                            </tr>

							<tr>
                                <td width="15%" class="fieldlabel">Client Last Name</td>
                                <td class="fieldarea">
                                    <strong>{S10WA_LastName}</strong>
                                </td>
                            </tr>

							<tr>
                                <td width="15%" class="fieldlabel">Client Full Name</td>
                                <td class="fieldarea">
                                    <strong>{S10WA_NamaClient}</strong>
                                </td>
                            </tr>


                            <tr>
                                <td width="15%" class="fieldlabel">Message Signature</td>
                                <td class="fieldarea">
                                    <strong>{suiten_signature}</strong>
                                </td>
                            </tr>';

                            if($title_message == 'Login Alert' || $title_message == 'Password Changed' || $title_message == 'Invoice Created' || $title_message == 'Invoice Modified' || $title_message == 'Invoice Payment Reminder' ||$title_message == 'Invoice Overdue Reminder' || $title_message == 'Payment Confirmation' || $title_message == 'Invoice Cancellation' || $title_message == 'Service Suspension' || $title_message == 'Service Reactivation' || $title_message == 'Ticket Opened' || $title_message == 'Ticket Opened by Admin' || $title_message == 'Ticket Replied' || $title_message == 'Ticket Replied' || $title_message == 'Ticket Closed' || $title_message == 'New Client Registration' || $title_message == 'New Product Activation' || $title_message == 'Product Termination' || $title_message == 'Payment Link') {
   
                                echo '<tr>
                                    <td width="15%" class="fieldlabel">WHMCS domain</td>
                                    <td class="fieldarea">
                                        <strong>{S10WA_DomainWHMCS}</strong><br>Result: '.$suiten_url_whmcs.'
                                    </td>
                                </tr>';

                            }

                            if($title_message == 'Login Alert') {

                                echo '<tr>
                                    <td width="15%" class="fieldlabel">Client Email</td>
                                    <td class="fieldarea">
                                        <strong>{S10WA_ClientEmail}</strong>
                                    </td>
                                </tr>';

                                echo '<tr>
                                    <td width="15%" class="fieldlabel">Event Date</td>
                                    <td class="fieldarea">
                                        <strong>{s10wa_date}</strong>
                                    </td>
                                </tr>';

                                echo '<tr>
                                    <td width="15%" class="fieldlabel">Event Time</td>
                                    <td class="fieldarea">
                                        <strong>{S10WA_Jam}</strong>
                                    </td>
                                </tr>';
                               
                                echo '<tr>
                                    <td width="15%" class="fieldlabel">IP Address</td>
                                    <td class="fieldarea">
                                        <strong>{S10WA_ClientIP}</strong>
                                    </td>
                                </tr>';

                            }

                            if($title_message == 'Invoice Created' || $title_message == 'Invoice Modified' || $title_message == 'Invoice Payment Reminder' || $title_message == 'Invoice Overdue Reminder' || $title_message == 'Payment Confirmation' || $title_message == 'Invoice Cancellation' || $title_message == 'Payment Link') {
                                
                                echo '<tr>
                                    <td width="15%" class="fieldlabel">Invoice Number</td>
                                    <td class="fieldarea">
                                        <strong>{S10WA_NomorInvoice}</strong>
                                    </td>
                                </tr>';

                                echo '<tr>
                                    <td width="15%" class="fieldlabel">Invoice Paid Number</td>
                                    <td class="fieldarea">
                                        <strong>{S10WA_NomorInvFinal}</strong>
                                    </td>
                                </tr>';


                            }

                            if($title_message == 'Invoice Created' || $title_message == 'Invoice Modified' || $title_message == 'Invoice Payment Reminder' || $title_message == 'Invoice Overdue Reminder' || $title_message == 'Payment Confirmation' || $title_message == 'Invoice Cancellation' || $title_message == 'Payment Link') {
                                
                                echo '<tr>
                                    <td width="15%" class="fieldlabel">Invoice Creation Date</td>
                                    <td class="fieldarea">
                                        <strong>{S10WA_TglCetakInvoice}</strong>
                                    </td>
                                </tr>';

                            }

                            if($title_message == 'Invoice Created' || $title_message == 'Invoice Modified' || $title_message == 'Invoice Payment Reminder' || $title_message == 'Invoice Overdue Reminder' || $title_message == 'Payment Confirmation' || $title_message == 'Invoice Cancellation' || $title_message == 'Payment Link') {
                                
                                echo '<tr>
                                    <td width="15%" class="fieldlabel">Invoice Amount</td>
                                    <td class="fieldarea">
                                        <strong>{S10WA_NilaiInvoice}</strong>
                                    </td>
                                </tr>';

                                echo '<tr>
                                    <td width="15%" class="fieldlabel">Credit Used</td>
                                    <td class="fieldarea">
                                        <strong>{S10WA_CreditUsed}</strong>
                                    </td>
                                </tr>';

                                echo '<tr>
                                    <td width="15%" class="fieldlabel">Invoice Total (after Credit)</td>
                                    <td class="fieldarea">
                                        <strong>{S10WA_TotalInvoice}</strong>
                                    </td>
                                </tr>';


                            }

                            if($title_message == 'Payment Confirmation') {
                                
                                echo '<tr>
                                    <td width="15%" class="fieldlabel">Payment Amount<br>Payment TransID<br>Payment Method</td>
                                    <td class="fieldarea">
                                        <strong>{S10WA_NilaiBayar}<br>
										{S10WA_TransID}<br>
										{S10WA_PayMethod}</strong>
										
                                    </td>
                                </tr>';

                            }

                            if($title_message == 'Invoice Created' || $title_message == 'Invoice Modified' || $title_message == 'Invoice Payment Reminder' || $title_message == 'Invoice Overdue Reminder' || $title_message == 'Payment Confirmation' ||$title_message == 'Invoice Cancellation' || $title_message == 'Payment Link') {
                                
                                echo '<tr>
                                    <td width="15%" class="fieldlabel">Invoice Due Date</td>
                                    <td class="fieldarea">
                                        <strong>{S10WA_JatuhTempoInvoice}</strong>
                                    </td>
                                </tr>';

                            }

                            if($title_message == 'Invoice Created' || $title_message == 'Invoice Modified' || $title_message == 'Invoice Payment Reminder' || $title_message == 'Invoice Overdue Reminder' || $title_message == 'Payment Confirmation' ||$title_message == 'Invoice Cancellation') {
                                
                                echo '<tr>
                                    <td width="15%" class="fieldlabel">Invoice Items</td>
                                    <td class="fieldarea">
                                        <strong>{S10WA_InvoiceItems}</strong>
                                    </td>
                                </tr>';

                                echo '<tr>
                                    <td width="15%" class="fieldlabel">Invoice Item (exclude zero qty addons)</td>
                                    <td class="fieldarea">
                                        <strong>{S10WA_InvoiceItemCut}</strong>
                                    </td>
                                </tr>';


                            }

                            if($title_message == 'Forward Email to Whatsapp') {                             
                                echo '<tr>
                                    <td width="15%" class="fieldlabel">Note</td>
                                    <td class="fieldarea">
                                        <strong>Enter Email Title to be forwarded to Whatsapp (for title with variable, just enter the static title without variable)</strong>
                                    </td>
                                </tr>';
                            }

                            if($title_message == 'Payment Link') {
                                echo '<tr>
                                    <td width="15%" class="fieldlabel">QR/Barcode</td>
                                    <td class="fieldarea">
                                        <strong>{S10WA_Barcode}</strong>
                                    </td>
                                </tr>';
                            }


                            if($title_message == 'Service Suspension' || $title_message == 'Service Reactivation' || $title_message == 'New Product Activation' || $title_message == 'Product Termination' ) {
                                
                                echo '<tr>
                                    <td width="15%" class="fieldlabel">Product Name</td>
                                    <td class="fieldarea">
                                        <strong>{S10WA_NamaLayanan}</strong>
                                    </td>
                                </tr>';

                            }

                            if($title_message == 'Service Suspension' || $title_message == 'Service Reactivation' || $title_message == 'New Product Activation' || $title_message == 'Product Termination' || $title_message == 'Upcoming Domain Renewal Notice' || $title_message == 'Expired Domain Notice' ) {
                                
                                echo '<tr>
                                    <td width="15%" class="fieldlabel">Product Domain</td>
                                    <td class="fieldarea">
                                        <strong>{S10WA_DomainLayanan}</strong>
                                    </td>
                                </tr>';

                            }

                            if($title_message == 'New Product Activation' || $title_message == 'Product Termination') {
                                
                                echo '<tr>
                                    <td width="15%" class="fieldlabel">Service ID</td>
                                    <td class="fieldarea">
                                        <strong>{S10WA_ServiceID}</strong>
                                    </td>
                                </tr>';

                            }
							
                            if($title_message == 'Ticket Opened' || $title_message == 'Ticket Opened by Admin' || $title_message == 'Admin Ticket Opened' || $title_message == 'Admin Ticket UserReplied' ) {
                                
                                echo '<tr>
                                    <td width="15%" class="fieldlabel">Ticket Reply Time (Bahasa)</td>
                                    <td class="fieldarea">
                                        <strong>{S10WA_DurasiRespon}</strong>
                                    </td>
                                </tr>									

								<tr>
                                    <td width="15%" class="fieldlabel">Reply Time (Hour part)</td>
                                    <td class="fieldarea">
                                        <strong>{S10WA_AvgHour}</strong>
                                    </td>
                                </tr>

								<tr>
                                    <td width="15%" class="fieldlabel">Reply Time (Minute part)</td>
                                    <td class="fieldarea">
                                        <strong>{S10WA_AvgMin}</strong>
                                    </td>
                                </tr>

								<tr>
                                    <td width="15%" class="fieldlabel">Reply Time (Total minutes)</td>
                                    <td class="fieldarea">
                                        <strong>{S10WA_AvgMins}</strong>
                                    </td>
                                </tr>
																
								<tr>
                                    <td width="15%" class="fieldlabel">Message Timestamp</td>
                                    <td class="fieldarea">
                                        <strong>{S10WA_TimeStamp}</strong>
                                    </td>
                                </tr>';
							

                            }

                            if($title_message == 'Ticket Opened' || $title_message == 'Ticket Opened by Admin' || $title_message == 'Ticket Replied' || $title_message == 'Admin Ticket Opened' || $title_message == 'Admin Ticket UserReplied' ) {
                                
                                echo '<tr>
                                    <td width="15%" class="fieldlabel">Ticket ID</td>
                                    <td class="fieldarea">
                                        <strong>{S10WA_TiketNomor}</strong>
                                    </td>
                                </tr>';

                                echo '<tr>
                                    <td width="15%" class="fieldlabel">Ticket Subject</td>
                                    <td class="fieldarea">
                                        <strong>{S10WA_TiketPerihal}</strong>
                                    </td>
                                </tr>';
                              
                                echo '<tr>
                                    <td width="15%" class="fieldlabel">Link to Ticket (for Client)</td>
                                    <td class="fieldarea">
                                        <strong>{S10WA_OpenTicketPage}</strong>
                                    </td>
                                </tr>';

                            }

                            if($title_message == 'Ticket Opened' || $title_message == 'Ticket Opened by Admin' || $title_message == 'Admin Ticket Opened' || $title_message == 'Admin Ticket UserReplied' ) {
                                
                                echo '<tr>
                                    <td width="15%" class="fieldlabel">Ticket Department</td>
                                    <td class="fieldarea">
                                        <strong>{S10WA_DeptStaf}</strong>
                                    </td>
                                </tr>';
                               
                                echo '<tr>
                                    <td width="15%" class="fieldlabel">Ticket Priority</td>
                                    <td class="fieldarea">
                                        <strong>{S10WA_TiketPrioritas}</strong>
                                    </td>
                                </tr>';

                            }

                            if($title_message == 'Ticket Replied' || $title_message == 'Admin Ticket UserReplied' ) {
                                
                                echo '<tr>
                                    <td width="15%" class="fieldlabel">Staff Responded The Ticket</td>
                                    <td class="fieldarea">
                                        <strong>{S10WA_DeptResponsible}</strong>
                                    </td>
                                </tr>';
                                echo '<tr>
                                    <td width="15%" class="fieldlabel">Reply Message Content</td>
                                    <td class="fieldarea">
                                        <strong>{S10WA_ReplyMsg}</strong>
                                    </td>
                                </tr>';
                            }

                            if($title_message == 'Admin Ticket Opened' || $title_message == 'Ticket Opened by Admin' || $title_message == 'Admin Ticket UserReplied' ) {

								$adminurl = substr($_SERVER['REQUEST_URI'],0,strpos($_SERVER['REQUEST_URI'],'/addonmodules.php'));
                                echo '<tr>
                                    <td width="15%" class="fieldlabel">Ticket System ID</td>
                                    <td class="fieldarea">
                                        For direct link to ticket, Enter full URL + <strong>{S10WA_TiketSysID}</strong> to use in template:<br/>https://'.$_SERVER['HTTP_HOST'].$adminurl.'/supporttickets.php?action=view&id={S10WA_TiketSysID}
                                    </td>
                                </tr>';

                            }

                            if($title_message == 'Registration Anniversary') {
                                
                                echo '<tr>
                                    <td width="15%" class="fieldlabel">Number of years</td>
                                    <td class="fieldarea">
                                        <strong>{S10WA_years}</strong>
                                    </td>
                                </tr>';

                                echo '<tr>
                                    <td width="15%" class="fieldlabel">Registration Date</td>
                                    <td class="fieldarea">
                                        <strong>{S10WA_datecreated}</strong>
                                    </td>
                                </tr>';
								
                            }

                            echo '</tbody>
                        </table>



                        <div class="btn-container">
                            <input type="submit" value="Save Changes" class="btn btn-primary" tabindex="39">
                        </div>
                    </form>


                    </div>
                </div>
            </div>
        </div>

        ';

    }


     if($_POST['editar_message_action'] == 'editar_message_action') {


        try {
            Capsule::connection()->transaction(
                function ($connectionManager)
                {
					$updatetemplate = $_POST['messagebody1'];
					$updatetemplate = str_ireplace("&amp;","&",$updatetemplate);
					
					$updatetemplateenglish = $_POST['messagebody2'];
					$updatetemplateenglish = str_ireplace("&amp;","&",$updatetemplateenglish);

					
                    $connectionManager->table('s10wa_templates')->WHERE('s10wa_msgid', $_POST['editar_message_id'])->update(
                        [
                            's10wa_templatecontent' => $updatetemplate,
                            's10wa_templateenglish' => $updatetemplateenglish,
                        ]
                    );
    
                }
            );
        
            $s10wa_returncode = header('Location: ./addonmodules.php?module=suiten_whatsapp&respcode=sukses');
            return $s10wa_returncode;
            
        } catch (\Exception $e) {
            echo $e->getMessage();
            exit();
            $s10wa_returncode = header('Location: ./addonmodules.php?module=suiten_whatsapp&respcode=gagal');
            return $s10wa_returncode;
        }


    }


    if($_GET['modaction'] == 'disable_message') {

        $id_message = $_GET['id'];

        try {

            //$query_message = "UPDATE `s10wa_templates` SET `s10wa_templatestatus` = '0' WHERE `s10wa_msgid` = ".$id_message;
            //mysqli_query($query_message);

			$updatedUserCount = Capsule::table('s10wa_templates')
				->where('s10wa_msgid', $id_message)
				->update(
					[
						's10wa_templatestatus' => 0,
					]
				);

            $s10wa_returncode = header('Location: ./addonmodules.php?module=suiten_whatsapp&respcode=sukses');
            return $s10wa_returncode;

        } catch (\Exception $e) {
            echo $e->getMessage();

            $s10wa_returncode = header('Location: ./addonmodules.php?module=suiten_whatsapp&respcode=gagal');
            return $s10wa_returncode;
        }

    }

    if($_GET['modaction'] == 'enable_message') {

        $id_message = $_GET['id'];

        try {

            //$query_message = "UPDATE `s10wa_templates` SET `s10wa_templatestatus` = '1' WHERE `s10wa_msgid` = ".$id_message."";
            //mysqli_query($query_message);

			$updatedUserCount = Capsule::table('s10wa_templates')
				->where('s10wa_msgid', $id_message)
				->update(
					[
						's10wa_templatestatus' => 1,
					]
				);

            $s10wa_returncode = header('Location: ./addonmodules.php?module=suiten_whatsapp&respcode=sukses');
            return $s10wa_returncode;

        } catch (\Exception $e) {
            echo $e->getMessage();

            $s10wa_returncode = header('Location: ./addonmodules.php?module=suiten_whatsapp&respcode=gagal');
            return $s10wa_returncode;
        }

    }

    if($_GET['modaction'] == 'updateverify') {

        $id_message = $_GET['id'];
		$tostatus = $_GET['to'];

        try {
			
			if ($tostatus == 6) {
				Capsule::table('s10wa_verify')
					->where('id', $id_message)
					->delete();
			} else {
				$updatedUserCount = Capsule::table('s10wa_verify')
					->where('id', $id_message)
					->update(
						[
							'status' => $tostatus,
							'timestamp' => timeStampWhatsapp(),
	
						]
					);
			}

            $s10wa_returncode = header('Location: ./addonmodules.php?module=suiten_whatsapp&respcode=sukses');
            return $s10wa_returncode;

        } catch (\Exception $e) {
            echo $e->getMessage();

            $s10wa_returncode = header('Location: ./addonmodules.php?module=suiten_whatsapp&respcode=gagal');
            return $s10wa_returncode;
        }

    }


    if($_GET['modaction'] == 'pause_sending') {

        $id_message = $_GET['id'];

        try {

			$updatedrows = Capsule::table('s10wa_sendmsg')
				->where('s10wa_status',0)
				->where('s10wa_sendid',$id_message)
				->update(
					[
						's10wa_status' => 4,
					]
				);
			if ($updatedrows > 0) {
				$s10wa_returncode = header('Location: ./addonmodules.php?module=suiten_whatsapp&respcode=sukses');
			} else {
				$s10wa_returncode = header('Location: ./addonmodules.php?module=suiten_whatsapp&respcode=udahproses');
			}
            return $s10wa_returncode;

        } catch (\Exception $e) {
            echo $e->getMessage();

            $s10wa_returncode = header('Location: ./addonmodules.php?module=suiten_whatsapp&respcode=gagal');
            return $s10wa_returncode;
        }

    }

    if($_GET['modaction'] == 'start_sending') {

        $id_message = $_GET['id'];
		$newnumber = $_GET['to'];

        try {

			if (empty($_GET['to'])) {
				$updatedrows = Capsule::table('s10wa_sendmsg')
					->where('s10wa_sendid',$id_message)
					->update(
						[
							's10wa_status' => 0,
						]
					);
			} else {
				$updatedrows = Capsule::table('s10wa_sendmsg')
					->where('s10wa_sendid',$id_message)
					->update(
						[
							's10wa_status' => 0,
							's10wa_wanumber' => $newnumber,
						]
					);
			}
			if ($updatedrows > 0) {
				$s10wa_returncode = header('Location: ./addonmodules.php?module=suiten_whatsapp&respcode=sukses');
			} else {
				$s10wa_returncode = header('Location: ./addonmodules.php?module=suiten_whatsapp&respcode=udahproses');
			}
            return $s10wa_returncode;

            $s10wa_returncode = header('Location: ./addonmodules.php?module=suiten_whatsapp&respcode=pesan&pesan=Message%20queued'.(empty($_GET) ? "" : "%20to%20".$newnumber));
            return $s10wa_returncode;

        } catch (\Exception $e) {
            echo $e->getMessage();

            $s10wa_returncode = header('Location: ./addonmodules.php?module=suiten_whatsapp&respcode=gagal');
            return $s10wa_returncode;
        }

    }

    if($_GET['modaction'] == 'delete_sending') {

        $id_message = $_GET['id'];
        try {

			Capsule::table('s10wa_sendmsg')
				->where('s10wa_sendid',$id_message)
				->delete();

            $s10wa_returncode = header('Location: ./addonmodules.php?module=suiten_whatsapp&respcode=sukses');
            return $s10wa_returncode;

        } catch (\Exception $e) {
            echo $e->getMessage();

            $s10wa_returncode = header('Location: ./addonmodules.php?module=suiten_whatsapp&respcode=gagal');
            return $s10wa_returncode;
        }

    }

    if($_GET['modaction'] == 'regenclient') {

        $newrec = 0;
        try {
			global $client_id, $phonenumber, $KoreksiNomor, $setstatus;
			foreach (Capsule::table('tblclients')->get() as $CustomerInfo) {
				$client_id = $CustomerInfo->id;
				$phonenumber = $CustomerInfo->phonenumber;
				$KoreksiNomor = suiten_koreksinomor($CustomerInfo->country,$phonenumber);
				if ($KoreksiNomor <> "") {
					$result = Capsule::table('s10wa_verify')->select('id')->where('clientid','=',$client_id)->first();
					if ($result) {
						// found it
						// check if whatsapp number changed
						if ($result->wanumber <> $KoreksiNomor) {

							$updatedUserCount = Capsule::table('s10wa_verify')
								->where('id', $result->id)
								->update(
									[
										'wanumber' => $KoreksiNomor,
										'status' => 0,
									]
								);

						}
					} else {
						// not found: create
						$newrec += 1;
						if (strlen($KoreksiNomor) < 10) {
							// notvalid
							$setstatus = 3;
						}else {
							$setstatus = 0;
						}
					
						Capsule::connection()->transaction(
							function ($connectionManager)
							{
								global $client_id, $phonenumber, $KoreksiNomor, $setstatus;
								/** @var \Illuminate\Database\Connection $connectionManager */
								$connectionManager->table('s10wa_verify')->insert(
									[
										'clientid' => $client_id,
										'wanumber' => $KoreksiNomor,
										'status' => $setstatus,
										'timestamp' => timeStampWhatsapp(),
									]
								);
							}
						);
					}
				}
			}


            $s10wa_returncode = header('Location: ./addonmodules.php?module=suiten_whatsapp&respcode=pesan&pesan='.strval($newrec).'%20processed&pesan2=');
			return $s10wa_returncode;         

        } catch (\Exception $e) {
            echo $e->getMessage();

			$s10wa_returncode = header('Location: ./addonmodules.php?module=suiten_whatsapp&respcode=merah&pesan='.$e);
			return $s10wa_returncode;
        }

    }


    if($_GET['modaction'] == 'regen_today') {

        try {

			// Invoice Generation  tblconfiguration CreateInvoiceDaysBefore xxx
			// Scan semua invoice yang keluar hari ini
			$result = WHMCS\Database\Capsule::table('tblconfiguration')->select('value')->where('setting', 'CreateInvoiceDaysBefore')->first();
			$CreateInvoiceDaysBefore = $result->value;


			// If SendReminder on
			$result = WHMCS\Database\Capsule::table('tblconfiguration')->select('value')->where('setting', 'SendReminder')->first();
			$sendreminder = ($result->value == "on" ? TRUE : FALSE);

			if ($sendreminder) {
			// 	SendInvoiceReminderDays = reminder (0 = disabled)
			//  Overdue SendFirstOverdueInvoiceReminder
			//  Overdue SendSecondOverdueInvoiceReminder
			//  Overdue SendThirdOverdueInvoiceReminder
			}
			
            $suiten_ModelMessage_Query            =   "SELECT * FROM s10wa_templates ORDER BY s10wa_msgid DESC";
            $query_message = "UPDATE `s10wa_templates` SET `s10wa_templatestatus` = '1' WHERE `s10wa_msgid` = ".$id_message."";

            $s10wa_returncode = header('Location: ./addonmodules.php?module=suiten_whatsapp&respcode=beres&line=20%20Invoices%20generated.');
            return $s10wa_returncode;

        } catch (\Exception $e) {
            echo $e->getMessage();

            $s10wa_returncode = header('Location: ./addonmodules.php?module=suiten_whatsapp&respcode=gagal');
            return $s10wa_returncode;
        }

    }


// Generate a random number once for consistency
$randomNumber = rand(); // or use mt_rand() for better randomness

// Output the CSS links
echo '<link href="../modules/addons/suiten_whatsapp/css/suiten_admins.css?' . $randomNumber . '" type="text/css" rel="stylesheet" />';
echo '<link href="../modules/addons/suiten_whatsapp/css/suiten_dataTables.css?' . $randomNumber . '" type="text/css" rel="stylesheet" />';

// Output the JavaScript link
echo '<script type="text/javascript" src="../modules/addons/suiten_whatsapp/suiten_javascript/suiten_search.js?' . $randomNumber . '"></script>


    <div class="body_Suiten">


    <div class="Header_Suiten_Template">
        <div class="basediv">

            <a href="'.substr($_SERVER['REQUEST_URI'],0,strpos($_SERVER['REQUEST_URI'],'?')).'?module=suiten_whatsapp"><div class="logowam"></div></a>
            <span><strong>Whatsapp Module</strong> for WHMCS.<br/>Version '.suiten_whatsapp_config()['version'].'</span>

            <div class="right" style="margin-top: 7px;">
                <a class="btn btn-default" data-target="#settings" data-toggle="modal" style="padding: 26px 38px;"><i class="fa fa-cogs" aria-hidden="true"></i> '. $vars['_lang']['suiten_whatsapp_button_configuration'] .'</a>
            </div>
            
            <div class="right" style="margin-top: 7px; margin-right: 5px">
                <a class="btn btn-default" data-target="#licenses" data-toggle="modal" style="padding: 26px 38px;"><i class="fa fa-cogs" aria-hidden="true"></i> License Management</a>
            </div>


            <div class="suiten_Clear"></div>
        </div>
    </div>

    <ul class="Menu_Suiten nav-tabs" role="tablist">
        <li class="active"><a class="tab-top" href="#tab3" role="tab" data-toggle="tab" id="tabLink1" data-tab-id="3" aria-expanded="false">'. $vars['_lang']['suiten_whatsapp_text_report_msg_sent'] .'</a></li>
        <li class=""><a class="tab-top" href="#tab4" role="tab" data-toggle="tab" id="tabLink2" data-tab-id="1" aria-expanded="false">Whatsapp Template</a></li>';
	if ($withClientList) 
        echo '<li class=""><a class="tab-top" href="#tab6" role="tab" data-toggle="tab" id="tabLink3" data-tab-id="1" aria-expanded="false">Client Status</a></li>
        <div class="suiten_Clear"></div>';
	echo '</ul>';

    // Respcodes screen
    if($_GET['respcode'] == 'beres') {
        echo '<div class="alert alert-primary alert-dismissable">
                    <a href="#" class="close" data-dismiss="alert" aria-label="close">×</a>
                    <strong>Command has been executed successfully</strong>';
		if ($_GET['line'] <> "") echo "<br/>".$_GET['line'];
        echo '</div>';
    }

    if($_GET['respcode'] == 'pesan') {
        echo '<div class="alert alert-warning alert-dismissable">
                    <a href="#" class="close" data-dismiss="alert" aria-label="close">×</a>
                    Result:';
		if ($_GET['pesan'] <> "") echo "<br/>".$_GET['pesan'];
		if ($_GET['pesan2'] <> "") echo "<br/>".$_GET['pesan2'];
		if ($_GET['pesan3'] <> "") echo "<br/>".$_GET['pesan3'];
        echo '</div>';
    }

    if($_GET['respcode'] == 'merah') {
        echo '<div class="alert alert-danger alert-dismissable">
                    <a href="#" class="close" data-dismiss="alert" aria-label="close">×</a>
                    Result:';
		if ($_GET['pesan'] <> "") echo "<br/>".$_GET['pesan'];
		if ($_GET['pesan2'] <> "") echo "<br/>".$_GET['pesan2'];
		if ($_GET['pesan3'] <> "") echo "<br/>".$_GET['pesan3'];
        echo '</div>';
    }
    
    if($_GET['respcode'] == 'sukses') {
        echo '<div class="alert alert-success alert-dismissable">
                    <a href="#" class="close" data-dismiss="alert" aria-label="close">×</a>
                    <strong>'. $vars['_lang']['suiten_whatsapp_alert_success'] .'</strong>  
                </div>';
    }
    
    if($_GET['respcode'] == 'gagal') {
        echo '<div class="alert alert-danger alert-dismissable">
                    <a href="#" class="close" data-dismiss="alert" aria-label="close">×</a>
                    <strong>'. $vars['_lang']['suiten_whatsapp_alert_error'] .'</strong>  
                </div>';
    }

    if($_GET['respcode'] == 'udahproses') {
        echo '<div class="alert alert-info alert-dismissable">
                    <a href="#" class="close" data-dismiss="alert" aria-label="close">×</a>
                    <strong>'. $vars['_lang']['suiten_whatsapp_alert_error'] .'<br/>Message was in process already</strong>  
                </div>';
    }

    echo '

    <div class="Content_Suiten">

        <div class="tab-content admin-tabs ng-scope">

        <div class="tab-content admin-tabs" ng-controller="controllerSUITEN">
            
        <div class="tab-pane fade" id="tab4">
            <div class="panel panel-default">
                <div class="panel-heading">
                    <i class="fa fa-user" aria-hidden="true" style="margin-right: 5px;"></i> Message Template Table
                </div>
            
                <div class="panel-body table-responsive">
                    <div class="row">
                        <div class="col-md-8" style="width: 100%;">';


							$startat = intval($_GET["startat"]);
							$limit = intval($_GET["limit"]) == 0 ? 100 : intval($_GET["limit"]);

							$suiten_templatelist = Capsule::table('s10wa_templates')
								->orderby('s10wa_msgid', 'DESC')
								->get();



                            echo '<table class="table table-hover">
                                <thead>
                                    <tr>
                                        <th style="text-align: center;">ID</th>
                                        <th style="text-align: center;">Message Template Title</th>
                                        <th style="text-align: center;">Status</th>
                                        <th style="text-align: center;">Edit</th>
                                        <th style="text-align: center;">Action</th>
                                    </tr>
                                </thead>

                                <tbody>';

                                foreach ($suiten_templatelist as $datarecord) {

                                    echo '<tr>

                                        <td style="text-align: center; padding-top: 15px;">
                                            ' . $datarecord->s10wa_msgid . '
                                        </td>

                                        <td style="text-align: center; padding-top: 15px;">' . $datarecord->s10wa_templatetitle . '</td>
                                        <td style="text-align: center; padding-top: 8px;">


                                        ' . ($datarecord->s10wa_templatestatus == '1' ? '<div class="btn btn-success"><i class="fa fa-check" aria-hidden="true"></i></div>':'<div class="btn btn-danger"><i class="fas fa-times"></i></div>') . '


                                        </td>

                                        <td style="text-align: center; padding-top: 15px;">

                                            <a style="margin-top: -7px;" href="./addonmodules.php?module=suiten_whatsapp&modaction=edit_message&id=' . $datarecord->s10wa_msgid . '" class="btn btn-default">
                                                <i class="far fa-edit"></i> Edit Message
                                            </a>

                                        </td>

                                        <td style="text-align: center; padding-top: 15px;">

                                            <a style="margin-top: -7px;" href="./addonmodules.php?module=suiten_whatsapp&modaction=disable_message&id=' . $datarecord->s10wa_msgid . '" class="btn btn-danger ' . ($datarecord->s10wa_templatestatus == '0' ? 'disabled':'') . '">
                                                <i class="far fa-bell-slash"></i> Disable
                                            </a>

                                            <a style="margin-top: -7px;" href="./addonmodules.php?module=suiten_whatsapp&modaction=enable_message&id=' . $datarecord->s10wa_msgid . '" class="btn btn-success ' . ($datarecord->s10wa_templatestatus == '1' ? 'disabled':'') . '">
                                                <i class="far fa-bell"></i> Enable
                                            </a>

                                        </td>

                                    </tr>';

                                }

                                echo '</tbody>
                            </table>
                            <div style="height: 10px; width: 100%; clear: both;"></div>

                        </div>
                    </div>
                </div>
            </div>
        </div>';

if ($withClientList) {
echo '
        <div class="tab-pane fade" id="tab6">
            <div class="panel panel-default">
                <div class="panel-heading">
                    <i class="fa fa-user" aria-hidden="true" style="margin-right: 5px;"></i> Client Whatsapp Number Status<br/><br/>';
echo '					Default: SEND Whatsapp &nbsp;&nbsp;';

echo '
						<a href="./addonmodules.php?module=suiten_whatsapp&modaction=regenclient" class="btn btn-info" data-toogle="tooltip" title="Regenerate Client">
                        <i class="fas fa-comment-slash" style="color: #fff;"></i><span style="color: #fff;"><b> &nbsp;REGENERATE UNLISTED</b></span></a>
                    ';
echo '                </div>
            
                <div class="panel-body table-responsive">
                    <div class="row">
                        <div class="col-md-8" style="width: 100%;">';


							$startat = intval($_GET["startat"]);
							$limit = intval($_GET["limit"]) == 0 ? 100 : intval($_GET["limit"]);

							$clientwa = Capsule::table('s10wa_verify')
								->select('s10wa_verify.id','s10wa_verify.clientid','s10wa_verify.wanumber','s10wa_verify.status','tblclients.firstname','tblclients.lastname')
								->join('tblclients','tblclients.id','=','s10wa_verify.clientid')
								->where("clientid",">",0)
								->get();

                            echo '<table class="table table-hover">
                                <thead>
                                    <tr>
                                        <th style="text-align: center;">ID</th>
                                        <th style="text-align: center;">Client ID</th>
                                        <th style="text-align: center;">WA Number</th>
                                        <th style="text-align: center;">Status</th>
                                        <th style="text-align: center;">Action</th>
                                    </tr>
                                </thead>

                                <tbody>';

                                foreach ($clientwa as $data) {

                                    echo '<tr>

                                        <td style="text-align: center; padding-top: 15px;">' . $data->id . '</td>
                                        <td style="text-align: center; padding-top: 15px;"><a href="clientssummary.php?userid='.$data->clientid.'" data-toggle="tooltip" title="Open Client Profile">[' . $data->clientid.'] '.$data->firstname.' '.$data->lastname.'</a></td>
                                        <td style="text-align: center; padding-top: 15px;">' . $data->wanumber . '</td>
                                        <td style="text-align: center; padding-top: 8px;">

                                        ';

if ($data->status == '0') {
	// default
	echo '<div class="btn btn-default"><i class="fa fa-circle-thin" aria-hidden="true"></i> Default</div>';
} elseif ($data->status == '1') {
	// send
	echo '<div class="btn btn-success"><i class="fa fa-check" aria-hidden="true"></i> Send WA</div>';
} elseif ($data->status == '2') {
	// dontsend
	echo '<div class="btn btn-danger"><i class="fa fa-check" aria-hidden="true"></i> Do NOT send</div>';
} elseif ($data->status == '3') {
	// notvalid
	echo '<div class="btn btn-warning"><i class="fa fa-check" aria-hidden="true"></i> Invalid</div>';
} elseif ($data->status == '4') {
	// waitverify
	echo '<div class="btn btn-info"><i class="fa fa-check" aria-hidden="true"></i> WaitVerify</div>';
}

									echo '
                                        </td>


                                        <td style="text-align: center; padding-top: 15px;">

                                            <a style="margin-top: -7px;" href="./addonmodules.php?module=suiten_whatsapp&modaction=updateverify&to=0&id=' . $data->id . '" class="btn btn-info ' . ($data->status == '0' ? 'disabled':'') . '">
                                                <i class="far chalkboard-teacher"></i> Default
                                            </a>

                                            <a style="margin-top: -7px;" href="./addonmodules.php?module=suiten_whatsapp&modaction=updateverify&to=1&id=' . $data->id . '" class="btn btn-success ' . ($data->status == '1' ? 'disabled':'') . '">
                                                <i class="far fa-comment-dots"></i> Send
                                            </a>

											<a style="margin-top: -7px;" href="./addonmodules.php?module=suiten_whatsapp&modaction=updateverify&to=2&id=' . $data->id . '" class="btn btn-danger ' . ($data->status == '2' ? 'disabled':'') . '">
                                                <i class="far fa-comment-slash"></i> No Send
                                            </a>

											<a style="margin-top: -7px;" href="./addonmodules.php?module=suiten_whatsapp&modaction=updateverify&to=6&id=' . $data->id . '" class="btn btn-basic"><i class="far fa-user-times"></i> Delete</a>

                                        </td>

                                    </tr>';

                                }

                                echo '</tbody>
                            </table>
                            <div style="height: 10px; width: 100%; clear: both;"></div>

                        </div>
                    </div>
                </div>
            </div>
        </div>';
}


		$jumlah_sent = Capsule::table('s10wa_sendmsg')
			->where('s10wa_status', 1)
			->count();

		$jumlah_pending = Capsule::table('s10wa_sendmsg')
			->where('s10wa_status', 0)
			->count();

		$jumlah_gagal = Capsule::table('s10wa_sendmsg')
			->where('s10wa_status', 2)
			->count();

		$jumlah_total  = Capsule::table('s10wa_sendmsg')
			->count();

		$rowtabel = Capsule::table('s10wa_sendmsg')
			->skip($startat)
			->take($limit)
			->orderby('s10wa_sendid', 'DESC')
			->get();
	
		$url = (isset($_SERVER['HTTPS']) ? "https" : "http" ) . "://" . $_SERVER['HTTP_HOST'] . strtok( $_SERVER['REQUEST_URI'] , '?');					

        echo '<div class="tab-pane fade active in" id="tab3">
        
            <div class="panel panel-default">
                <div class="panel-heading">
                    <i class="far fa-envelope-open" style="margin-right: 5px"></i> '. $vars['_lang']['suiten_whatsapp_text_title_sentmsg'] .'

                    <div class="btn btn-success" style="float: right; margin-top: -7px; margin-right: 8px; font-size: 12px; cursor: auto;">
                        <i class="far fa-check-circle"></i> Messages Sent <span class="badge badge-light" style="background-color: #fff; color: #000;">'.$jumlah_sent.'</span>
                    </div>

                    <div class="btn btn-danger" style="float: right; margin-top: -7px; margin-right: 8px; font-size: 12px; cursor: auto;">
                        <i class="far fa-times-circle"></i> Messages Failed <span class="badge badge-light" style="background-color: #fff; color: #000;">'.$jumlah_gagal.'</span>
                    </div>

                    <div class="btn btn-warning" style="float: right; margin-top: -7px; margin-right: 8px; font-size: 12px; cursor: auto;">
                        <i class="far fa-clock"></i> Messages in Queue <span class="badge badge-light" style="background-color: #fff; color: #000;">'.$jumlah_pending.'</span>
                    </div>';

		echo '
                    <div class="btn btn-info" style="float: right; margin-top: -7px; margin-right: 8px; font-size: 12px; cursor: auto;">';

		if ($startat>0) {
			echo '<a href="'.$url.'?module=suiten_whatsapp"><i class="far fa-caret-square-left"></i></a>&nbsp &nbsp';
		}

		if ($startat>99) {
			echo '<a href="'.$url.'?module=suiten_whatsapp&startat='.($startat-100).'"><i class="far fa-angle-double-left"></i></a>&nbsp';
		}
		echo '
                        <i class="far fa-bullhorn"></i> Loaded Message <span class="badge badge-light" style="background-color: #fff; color: #000;">'.($startat + 1).' - '.($startat + $limit).'</span>';

		if ($startat+100<$jumlah_total) {
			echo '&nbsp &nbsp<a href="'.$url.'?module=suiten_whatsapp&startat='.($startat+100).'"><i class="far fa-angle-double-right"></i></a>';
		}
		echo '
                    </div>


                </div>
            
                <div class="panel-body table-responsive">
                    <div class="row">
                        <div class="col-md-8" style="width: 100%;">

                            <script>
                                $(document).ready(function(){

                                    $(\'#s10wa_templates_sendmsg\').DataTable({
                                        "order": [[ 0, "desc" ]],
                                        "className": "mdl-data-table__cell--non-numeric",
                                        "language": {
                                            "lengthMenu": "Showing _MENU_ records per page",
                                            "zeroRecords": "No contact found!",
                                            "info": "Showing page _PAGE_ of _PAGES_",
                                            "infoEmpty": "No records available",
                                            "infoFiltered": "(filtering of _MAX_ records not all)",
                                        }
                                    });

                                });

								function checkAll(ele) {
									var checkboxes = document.getElementsByTagName(\'input\');
									if (ele.checked) {
							          for (var i = 0; i < checkboxes.length; i++) {
							              if (checkboxes[i].type == \'checkbox\' ) {
							                  checkboxes[i].checked = true;
							              }
							          }
									} else {
							          for (var i = 0; i < checkboxes.length; i++) {
									       if (checkboxes[i].type == \'checkbox\') {
									          checkboxes[i].checked = false;
									       }
									  }
									}
								}
								
								function editnomor(ele) {
									var val=ele.innerHTML;
									var sid=ele.id.substring(4);
									var awake="awake"+sid;
									var input=document.createElement("input");
									val=val.trim();
									if (val.indexOf(" ") > 0) {
										val=val.substr(0,val.indexOf(" "));
									}

									if (val != "<input>") {
										input.value=val;
										input.onblur=function(){
										var val=this.value;
										ele.innerHTML=val;
										document.getElementById(awake).href="./addonmodules.php?module=suiten_whatsapp&modaction=start_sending&id="+sid+"&to="+val; 
										}
										ele.innerHTML="";
										ele.appendChild(input);
									}
									input.focus();
								}

							
                            </script>


                            <table class="table table-hover table-responsive" id="s10wa_templates_sendmsg"">
                              <thead>
                                <tr>

                                    <th style="text-align: center; width: 2%;"><input type="checkbox" onchange="checkAll(this)" name="pil[]"></th>
                                    <th style="text-align: center; width: 5%;">ID</th>
                                    <th style="text-align: center; width: 10%;"><i class="fas fa-mobile-alt" style="margin-right: 5px"></i> '. $vars['_lang']['suiten_whatsapp_text_table_sentmsg_destination'] .'</th>
                                    <th style="text-align: center; width: 10%;"><i class="fas fa-user" style="margin-right: 5px"></i> Client ID</th>
                                    <th style="text-align: center; width: 10%;"><i class="fas fa-calendar-alt" style="margin-right: 5px"></i> '. $vars['_lang']['suiten_whatsapp_text_table_sentmsg_datetime'] .'</th>
                                    <th style="text-align: center; width: 35%;"><i class="far fa-comments" style="margin-right: 5px"></i> '. $vars['_lang']['suiten_whatsapp_text_table_sentmsg_message'] .'</th>
                                    <th style="text-align: center; width: 10%;"><i class="far fa-question-circle" style="margin-right: 5px"></i> '. $vars['_lang']['suiten_whatsapp_text_table_sentmsg_status'] .'</th>
                                    <th style="text-align: center; width: 20%;"><i class="fas fa-charging-station" style="margin-right: 5px"></i> Action</th>

                                  </tr>
                                </thead>

                                <tbody>';

                                foreach($rowtabel as $rowdata) {

									$withatt = $rowdata->s10wa_attachment == '' ? '<div class="btn btn-secondary" data-toggle="tooltip" title="message only"><i class="far fa-comment-dots"></i></div>' : '<div class="btn btn-secondary" data-toggle="tooltip" title="with attachment"><i class="far fa-paperclip"></i></div>';
                                    echo '<tr>

                                        <td style="text-align: center; padding-top: 44px;">
                                            <input type="checkbox" id="pilih'.$rowdata->s10wa_sendid.'" name="terpilih[]" form="bulkact" value="'.$rowdata->s10wa_sendid.'">
                                        </td>

                                        <td style="text-align: center; padding-top: 44px;">
                                            '.$rowdata->s10wa_sendid.'
                                        </td>

                                        <td style="text-align: center; padding-top: 44px;" id="wake'.$rowdata->s10wa_sendid.'" ondblclick="editnomor(this)">
                                            '.$rowdata->s10wa_wanumber.'

                                            '. ($rowdata->s10wa_status == '2' ? '<div class="btn btn-danger" style="color: #fff; padding: 5px; font-size: 9px; margin-left: 6px;"> Invalid</div> ':'') .'                                           

                                        </td>
										
										<td style="text-align: center; padding-top: 44px;">
';

										if ($rowdata->s10wa_clientid == 0 && !strpos($rowdata->s10wa_message,"Client ID:") == false) {											
											//Incoming Message
											$clientidslab = substr($rowdata->s10wa_message,strpos($rowdata->s10wa_message,"Client ID:"));
											$clientidslab = substr($clientidslab,0,strpos($clientidslab,")")+1);
											$clientidslab = trim($clientidslab);
											$clientdetail = substr($clientidslab,9);
											$clientspacepos = strpos($clientdetail," ");
											$clientid = substr($clientdetail,1,$clientspacepos);
											$clientinfo = substr($clientdetail,$clientspacepos);

											// Show Client ID link as is
											$clinfo = explode(" (",$clientinfo);
											$clinfo[1] = strpos($clinfo[1]," (") == false ? $clinfo[1] = substr($clinfo[1],0,-1) : "";
											echo '<a href="clientssummary.php?userid='.$clientid.'" data-toggle="tooltip" title="Open Client Profile">'.$clinfo[0].'</a><br/>'.$clinfo[1];
										} elseif ($rowdata->s10wa_clientid == 0) {
											//cari di database s10wa_sendmsg
											$cariid = Capsule::table('s10wa_sendmsg')
												->select('s10wa_clientid','s10wa_clientinfo')
												->where('s10wa_wanumber',$rowdata->s10wa_wanumber)
												->where('s10wa_clientid','>',0)
												->take(1)
												->get();

											//$query = "SELECT s10wa_clientid, s10wa_clientinfo FROM s10wa_sendmsg WHERE s10wa_wanumber='".$rowdata->s10wa_wanumber."' AND s10wa_clientid>0 LIMIT 1";
											//$result = mysql_query($query);
											if (count($cariid) > 0) {
				                                foreach ($cariid as $row) {
													$clinfo = explode(" (",$row->s10wa_clientinfo);		
													$clinfo[1] = strpos($clinfo[1]," (") == false ? $clinfo[1] = substr($clinfo[1],0,-1) : "";
													echo '<a href="clientssummary.php?userid='.$row->s10wa_clientid.'" data-toggle="tooltip" title="Open Client Profile">'.$clinfo[0].'</a><br/>'.$clinfo[1];
												}
											} else {
												//Incoming from nowhere, ignore
												echo '-';
											}
										} else {
											// Show Client ID link as is
											if ($rowdata->s10wa_clientinfo <> "") {
												$clinfo = explode(" (",$rowdata->s10wa_clientinfo);
												$clinfo[1] = strpos($clinfo[1]," (") == false ? $clinfo[1] = substr($clinfo[1],0,-1) : "";
												echo '<a href="clientssummary.php?userid='.$rowdata->s10wa_clientid.'" data-toggle="tooltip" title="Open Client Profile">'.$clinfo[0].'</a><br/>'.$clinfo[1];
											} else {
												echo '<a href="clientssummary.php?userid='.$rowdata->s10wa_clientid.'" data-toggle="tooltip" title="Open Client Profile">Client ID '.$rowdata->s10wa_clientid.'</a>';
											}
										}
echo '									                                            
                                        </td>


                                        <td style="text-align: center; padding-top: 44px;">'.date("d/m/Y H:i", strtotime($rowdata->s10wa_date)).'</td>
                                        <td style="text-align: center;">
                                            <textarea style="resize: vertical;" disabled="disabled" rows="4" class="form-control">'.$rowdata->s10wa_message.'</textarea>
                                        </td>
    
                                        <td style="text-align: center; padding-top: 37px;">

                                            '. ($rowdata->s10wa_status == '0' ? '<div class="btn btn-warning" data-toggle="tooltip" title="in Queue"><i class="far fa-clock"></i></div>'.$withatt:'') .'
                                            '. ($rowdata->s10wa_status == '1' ? '<div class="btn btn-success" data-toggle="tooltip" title="Sent"><i class="fa fa-check"></i></div>'.$withatt:'') .'
                                            '. ($rowdata->s10wa_status == '2' ? '<div class="btn btn-danger" data-toggle="tooltip" title="Failed"><i class="fas fa-times"> '.($rowdata->s10wa_errormsg).'</i></div>':'') .'
                                            '. ($rowdata->s10wa_status == '4' ? '<div class="btn btn-info" data-toggle="tooltip" title="Paused"><i class="far fa-pause-circle">'.($rowdata->s10wa_errormsg).'</i></div>'.$withatt:'') .'
                                            '. ($rowdata->s10wa_status == '5' ? '<div class="btn btn-primary" data-toggle="tooltip" title="Sending"><i class="far fa-rss"></i></div>'.$withatt:'') .'

                                        </td>

                                        <td style="text-align: center; padding-top: 37px;">

                                            <div class="btn-group" role="group" aria-label="Message Control">';

if ( $rowdata->s10wa_status == '0' ) {	
// Queue
echo '
                                                <a href="./addonmodules.php?module=suiten_whatsapp&modaction=start_sending&id='.$rowdata->s10wa_sendid.'" class="btn btn-primary disabled" data-toogle="tooltip" title="in Queue"><i class="far fa-play-circle"></i></a>

                                                <a href="./addonmodules.php?module=suiten_whatsapp&modaction=pause_sending&id='.$rowdata->s10wa_sendid.'" class="btn btn-info" data-toogle="tooltip" title="Hold"><i class="far fa-pause-circle"></i></a>

                                                <a href="./addonmodules.php?module=suiten_whatsapp&modaction=delete_sending&id='.$rowdata->s10wa_sendid.'" class="btn btn-danger" data-toogle="tooltip" title="Delete"><i class="far fa-trash-alt"></i></a>
';
} elseif ( $rowdata->s10wa_status == '1' ) {
// Sent
echo '
												<a href="./addonmodules.php?module=suiten_whatsapp&modaction=start_sending&id='.$rowdata->s10wa_sendid.'" class="btn btn-primary" data-toogle="tooltip" title="Resend (Message only)" id="awake'.$rowdata->s10wa_sendid.'"><i class="far fa-play-circle"></i></a>
												<a href="./addonmodules.php?module=suiten_whatsapp&modaction=delete_sending&id='.$rowdata->s10wa_sendid.'" class="btn btn-danger" data-toogle="tooltip" title="Delete"><i class="far fa-trash-alt"></i></a>';
} elseif ( $rowdata->s10wa_status == '2' ) {
// Failed
echo '
                                                <a href="./addonmodules.php?module=suiten_whatsapp&modaction=start_sending&id='.$rowdata->s10wa_sendid.'" class="btn btn-primary" data-toogle="tooltip" title="Retry Sending" id="awake'.$rowdata->s10wa_sendid.'"><i class="far fa-play-circle"></i></a>
                                                <a href="./addonmodules.php?module=suiten_whatsapp&modaction=delete_sending&id='.$rowdata->s10wa_sendid.'" class="btn btn-danger" data-toogle="tooltip" title="Delete"><i class="far fa-trash-alt"></i></a>
';
} elseif ( $rowdata->s10wa_status == '4' ) {
// Paused
echo '
                                                <a href="./addonmodules.php?module=suiten_whatsapp&modaction=start_sending&id='.$rowdata->s10wa_sendid.'" class="btn btn-primary" data-toogle="tooltip" title="Resend" id="awake'.$rowdata->s10wa_sendid.'"><i class="far fa-play-circle"></i></a>
                                                <a href="./addonmodules.php?module=suiten_whatsapp&modaction=pause_sending&id='.$rowdata->s10wa_sendid.'" class="btn btn-info disabled" data-toogle="tooltip" title="Message Held"><i class="far fa-pause-circle"></i></a>
                                                <a href="./addonmodules.php?module=suiten_whatsapp&modaction=delete_sending&id='.$rowdata->s10wa_sendid.'" class="btn btn-danger" data-toogle="tooltip" title="Delete"><i class="far fa-trash-alt"></i></a>
';
} elseif ( $rowdata->s10wa_status == '5' ) {
// Sending
echo '
                                                <a href="./addonmodules.php?module=suiten_whatsapp&modaction=start_sending&id='.$rowdata->s10wa_sendid.'" class="btn btn-primary" data-toogle="tooltip" title="Retry Sending" id="awake'.$rowdata->s10wa_sendid.'"><i class="far fa-play-circle"></i></a>
                                                <a href="./addonmodules.php?module=suiten_whatsapp&modaction=pause_sending&id='.$rowdata->s10wa_sendid.'" class="btn btn-info disabled" data-toogle="tooltip" title="Message Held"><i class="far fa-pause-circle"></i></a>
                                                <a href="./addonmodules.php?module=suiten_whatsapp&modaction=delete_sending&id='.$rowdata->s10wa_sendid.'" class="btn btn-danger" data-toogle="tooltip" title="Delete"><i class="far fa-trash-alt"></i></a>
';
} else {
echo '
                                                <a href="./addonmodules.php?module=suiten_whatsapp&modaction=start_sending&id='.$rowdata->s10wa_sendid.'" class="btn btn-primary '. ($rowdata->s10wa_status == '0' || $rowdata->s10wa_status == '1' ? 'disabled':'') .'" data-toogle="tooltip" title="Cannot Send"><i class="far fa-play-circle"></i></a>

                                                <a href="./addonmodules.php?module=suiten_whatsapp&modaction=pause_sending&id='.$rowdata->s10wa_sendid.'" class="btn btn-info '. ($rowdata->s10wa_status > '0' ? 'disabled':'') .'" data-toogle="tooltip" title="Cannot Pause"><i class="far fa-pause-circle"></i></a>

                                                <a href="./addonmodules.php?module=suiten_whatsapp&modaction=delete_sending&id='.$rowdata->s10wa_sendid.'" class="btn btn-danger '. ($rowdata->s10wa_status == '1' ? 'disabled':'') .'" data-toogle="tooltip" title="Cannot Delete"><i class="far fa-trash-alt"></i></a>
'; }
echo '
                                            </div>

                                        </td>
                                        
                                    </tr>';


                                }

                                echo '</tbody>

                            </table>

<form id="bulkact" action="addonmodules.php?module=suiten_whatsapp" method="POST">                               
  <input type="hidden" name="modaction" value="bulkaction">
  <label for="pilihaction">Bulk Action</label>
  <select id="pilihaction" name="action">
    <option value="pause">Hold Messages</option>
    <option value="delete">DELETE Messages</option>
    <option value="resend">Resend Messages</option>
    <option value="holdall">Hold ALL in queue</option>
  </select>
  <input type="submit" value="Apply Action">
</form>
                        </div>
                    </div>
                </div>

            </div>

        </div>

           
        </div>

        <div class="suiten_Clear"></div>
    </div>

</div>

<div class="Footer_Suiten">

        <li><strong>© 2020-2024 ALL RIGHTS RESERVED - WWW.HOSTINOZ.COM</strong><br>System time now: ';
echo timeStampWhatsapp();
echo '<br/>';
echo '
        </li>
        <div class="suiten_Clear"></div>
    </div>

</div>';

}

