<?php
namespace App\Controllers;
use App\Models\Employee;
use App\Models\Order;
use App\Models\Branch;
use DateTime;

class Customer extends BaseController
{
	// private $xxx = [];

	function __construct()
	{
		parent::__construct('customer');

		// $XXX = new XXX();
		// $this->xxx = $XXX->get_xxx();
	}

	function index()
	{
		
	}

	function mobile() {
		$is_mobile = request()->getPost('is_mobile');
		session()->set('is_mobile', $is_mobile);
		echo 'success';
	}
		
	function get_register()
	{
		$branchModel 	= new Branch();
		$branchRecords 	= $branchModel->select('site_name')
									  ->orderBy('site_name', 'asc')
									  ->findAll();
		$all_branches 	= array_map(static function ($branch) {
			return $branch['site_name'] ?? null;
		}, $branchRecords);

		// Get reCAPTCHA site key from epos_app_config
		$db = \Config\Database::connect();
		$result = $db->table('epos_app_config')->where('key', 'recaptcha_site_key')->get()->getRow();
		$recaptcha_site_key = (!empty($result) && !empty($result->value)) ? $result->value : env('RECAPTCHA_SITE_KEY', '6LeIxAcTAAAAAJcZVRqyHh71UMIEGNQ_MXjiZKhI');

		echo view('v2/pages/customer_register', [
			'all_branches' => array_filter($all_branches),
			'recaptcha_site_key' => $recaptcha_site_key,
		]);
	}

	function post_register()
	{
		// Verify reCAPTCHA
		$recaptchaResponse = request()->getPost('g-recaptcha-response');
		if (empty($recaptchaResponse)) {
			return $this->response->setJSON([
				'success' => 0,
				'msg' => 'Please complete the reCAPTCHA verification.'
			]);
		}

		// Get reCAPTCHA secret key from epos_app_config
		$db = \Config\Database::connect();
		$result = $db->table('epos_app_config')->where('key', 'recaptcha_secret_key')->get()->getRow();
		$secretKey = (!empty($result) && !empty($result->value)) ? $result->value : env('RECAPTCHA_SECRET_KEY', '6LeIxAcTAAAAAGG-vFI1TnRWxMZNFuojJ4WifJWe');

		$verifyUrl = 'https://www.google.com/recaptcha/api/siteverify';

		// On local XAMPP whose curl.cainfo is missing or stale, the verify URL's
		// TLS handshake fails with "unable to get local issuer certificate".
		// Toggle verify off via .env on dev only — leave it on in production.
		$verifyEnv = env('recaptcha.ssl_verify', true);
		if (is_bool($verifyEnv)) {
			$verify = $verifyEnv;
		} else {
			$str = strtolower(trim((string) $verifyEnv));
			$verify = !in_array($str, ['0', 'false', 'no', 'off', ''], true);
		}

		$client = \Config\Services::curlrequest();
		$response = $client->post($verifyUrl, [
			'form_params' => [
				'secret' => $secretKey,
				'response' => $recaptchaResponse,
				'remoteip' => request()->getIPAddress()
			],
			'verify' => $verify,
		]);
		
		$recaptchaResult = json_decode($response->getBody(), true);
		
		if (!$recaptchaResult['success']) {
			return $this->response->setJSON([
				'success' => 0,
				'msg' => 'reCAPTCHA verification failed. Please try again.'
			]);
		}

		$busi_legal_nm 					= request()->getPost("busi_legal_nm");	
		$busi_start_dt  				= request()->getPost("busi_start_dt");	
		$busi_trad_nm  					= request()->getPost("busi_trad_nm");	
		$addr_line1  					= request()->getPost("addr_line1");	
		$addr_line2   					= request()->getPost("addr_line2");	
		$county  						= request()->getPost("county");	
		$city  							= request()->getPost("city");	
		$country  						= request()->getPost("country");	
		$post_code  					= request()->getPost("post_code");	
		$contact_nm  					= request()->getPost("contact_nm");	
		$contact_phone_ll   			= request()->getPost("contact_phone_ll");	
		$contact_phone_mb   			= request()->getPost("contact_phone_mb");	
		$contact_email   				= request()->getPost("contact_email");	
		$company_no   					= request()->getPost("company_no");	
		$vat_number  	 				= request()->getPost("vat_number");	
		$busi_trad_years   				= request()->getPost("busi_trad_years");	
		$store_sz   					= request()->getPost("store_sz");	
		$store_avg    					= request()->getPost("store_avg");	
		$pref_payment_method    		= request()->getPost("pref_payment_method");	
		$credit_acc_facility    		= request()->getPost("credit_acc_facility");	
		$offers_and_info    			= request()->getPost("offers_and_info");	
		$marketing_options    			= request()->getPost("marketing_options");	
		$self_service    				= request()->getPost("self_service");	
		$click_and_collect    			= request()->getPost("click_and_collect");	
		$delivered    					= request()->getPost("delivered");	
		$confirm_legal_owner_director 	= request()->getPost("confirm_legal_owner_director");
		$prefered_branch 				= request()->getPost("prefered_branch");
		$sell_alcohol 					= request()->getPost("sell_alcohol");
		$sell_tobacco 					= request()->getPost("sell_tobacco");
		$sell_vapes 					= request()->getPost("sell_vapes");
		$premises_licence 				= request()->getPost("premises_licence");
		$eoid 							= request()->getPost("eoid");
		$fid 							= request()->getPost("fid");
		$owner_house_no 				= request()->getPost("owner_house_no");
		$owner_house_name 				= request()->getPost("owner_house_name");
		$owner_street 					= request()->getPost("owner_street");
		$owner_village 					= request()->getPost("owner_village");
		$owner_city 					= request()->getPost("owner_city");
		$owner_country 					= request()->getPost("owner_country");
		$owner_post_code 				= request()->getPost("owner_post_code");
		$credit_limit_raw 				= request()->getPost("credit_limit");
		// The requested_credit_limit column is NOT NULL on the DB side. Use 0
		// when the credit-facility toggle is off or the input is empty.
		$credit_limit 					= ($credit_acc_facility && $credit_limit_raw !== '' && $credit_limit_raw !== null)
											? (int) $credit_limit_raw
											: 0;

		// Convert business start date from dd/mm/yyyy to yyyy-mm-dd
		if (!empty($busi_start_dt)) {
			$date_obj = DateTime::createFromFormat('d/m/Y', $busi_start_dt);
			if ($date_obj) {
				$busi_start_dt = $date_obj->format('Y-m-d');
			}
		}
		
		$dt = new DateTime(); // current date/time
		$date_created  = $dt->format('Y-m-d H:i:s'); // 2025-11-05 12:34:56
		$customer_data_to_save = array(
			'business_legal_name'     		=> $busi_legal_nm,
			'business_start_date'     		=> $busi_start_dt,
			'business_trading_name'     	=> $busi_trad_nm,
			'address_line1'     			=> $addr_line1,
			'address_line2'     			=> $addr_line2,
			'county'     					=> $county,
			'city'     						=> $city,
			'country'     					=> $country,
			'post_code'     				=> $post_code,
			'contact_name'     				=> $contact_nm,
			'contact_telephone_landline'	=> $contact_phone_ll,
			'contact_telephone_mobile'  	=> $contact_phone_mb,
			'contact_email'     			=> $contact_email,
			'company_number'     			=> $company_no,
			'vat_number'     				=> $vat_number,
			'business_trading_years'    	=> $busi_trad_years,
			'store_size'     				=> $store_sz,
			'store_average'     			=> $store_avg,
			'prefered_payment_method'   	=> $pref_payment_method,
			'credit_account_facility' 		=> $credit_acc_facility,
			'offers_and_info' 				=> $offers_and_info,
			'marketing_options' 			=> $marketing_options,
			'self_service' 					=> $self_service,
			'click_and_collect' 			=> $click_and_collect,
			'delivered' 					=> $delivered,
			'confirm_legal_owner_director'	=> $confirm_legal_owner_director,
			'date_created' 					=> $date_created,
			'prefered_branch' 				=> $prefered_branch,
			'sell_alcohol' 					=> $sell_alcohol,
			'sell_tobacco' 					=> $sell_tobacco,
			'sell_vapes' 					=> $sell_vapes,
			'premises_licence' 				=> $premises_licence,
			'eoid' 							=> $eoid,
			'fid' 							=> $fid,
			'contact_addr_house_number' 	=> $owner_house_no,
			'contact_addr_house_name_flat' 	=> $owner_house_name,
			'contact_addr_street' 			=> $owner_street,
			'contact_addr_vill_town' 		=> $owner_village,
			'contact_addr_city' 			=> $owner_city,
			'contact_addr_country' 			=> $owner_country,
			'contact_addr_postcode' 		=> $owner_post_code,
			'requested_credit_limit' 		=> $credit_limit,
		);		

    	$db->transStart();
		// Append New Customer Registration to epos_customer_registration table
		$db->table('epos_customer_registration')->insert($customer_data_to_save);
		$registration_id = $db->insertID();

		// ### Generate his email verification code ###
		// generate 8-digit random number
		$min = 10000000;
		$max = 99999999;
		$rand8 = mt_rand($min, $max);
		// Store the expiry as a Unix timestamp (int) — the column is INT, so
		// formatted datetime strings get silently truncated to "2026" and break
		// every verification. 10-minute window to match the modal text.
		$now = new DateTime();
		$now->add(new \DateInterval('PT10M'));
		$expired_datetime = $now->getTimestamp();
		// Append new email verification info to epos_customer_confirm table
		$db->table('epos_customer_confirm')->insert([
			'registration_id' => $registration_id,
			'email' => $contact_email,
			'pin_verify_number' => $rand8,
			'pin_expired_datetime' => $expired_datetime
		]);
		// generate base64 encoded token to identify registration info
		$payload = [
			'registration_id' => $registration_id,
			'email' => $contact_email,
		];
		$json = json_encode($payload);
		$base64_token = base64_encode($json);

		$db->transComplete();
		if ($db->transStatus() === FALSE) {
			$db->transRollback();
			return response()->setJSON([
				'success' => 0,
				'error' => 'An error has occurred in registering customer. Code 2001'
			]);
		} 

		if ($pref_payment_method == "cash") {
			$pref_payment_method = "Cash";
		} else if ($pref_payment_method == "bank_transfer") {
			$pref_payment_method = "Bank Transfer";
		} else if ($pref_payment_method == "echo_pay") {
			$pref_payment_method = "EchoPay";
		} else if ($pref_payment_method == "card") {
			$pref_payment_method = "Card";
		} else if ($pref_payment_method == "credit_facility") {
			$pref_payment_method = "Credit Facility";
		}
		// Send email to customer
		// send email

		// Get branch id from epos_branches table where site_name matches prefered_branch
		$prefered_branch_id = null;
		if (!empty($prefered_branch)) {
			$branch_result = $db->table('epos_branches')
				->where('site_name', $prefered_branch)
				->get()
				->getRow();
			if ($branch_result) {
				$prefered_branch_id = $branch_result->id;
			}
		}

		// Branch config via key-value table. (object) cast keeps the property-access
		// shape the original block used; missing keys fall through to null via ??.
		$from_email = null;
		$cc_email = null;
		$sendRegFormTo = null;
		if (!empty($prefered_branch_id)) {
			$config_result = (object) \App\Models\BranchConfig::getAll($prefered_branch_id);
			$from_email    = $config_result->from_email    ?? null;
			$cc_email      = $config_result->cc_email      ?? null;
			$sendRegFormTo = $config_result->sendRegFormTo ?? null;
			$smtp_used     = $config_result->smtp_used     ?? null;
			$smtp_host     = $config_result->smtp_host     ?? null;
			$smtp_user     = $config_result->smtp_user     ?? null;
			$smtp_password = $config_result->smtp_password ?? null;
			$smtp_port     = $config_result->smtp_port     ?? null;
		}

		$db = \Config\Database::connect();

		$result = $db->table('epos_app_config')->where('key' , 'development_cc_email')->get()->getRow();
		$mail_addr_development_cc = $result->value;

		$result = $db->table('epos_app_config')->where('key' , 'company')->get()->getRow();
		$company_name = $result->value;

		$mail_subject = "Please validate your email address";

		$message = "<html><body>";
		
		$message .= "<div style='font-family:Arial; font-size:13px;'>";
		$message .= "Dear Customer.";
		$message .= "</div>";
		$message .= "<br>";
		$message .= "<div style='font-family:Arial; font-size:13px;'>";
		$message .= "Please enter this code <b>" . $rand8 . "</b> in order to verify your email address and submit your application form. The code is valid for 10 minutes.";
		$message .= '</div>';
		$message .= "<br>";
		$message .= "<div style='font-family:Arial; font-size:13px;'>";
		$message .= "This is a system generated email, please do not reply to it.";
		$message .= '</div>';

		$message .= "</body></html>";

		// $email = "test_ac_1234@ecso.co.uk";
		$res = false;
		if ($from_email && $contact_email) {
			$res = $this->do_send_email_phpmailer($from_email, $contact_email, $cc_email, $mail_addr_development_cc, $company_name, $mail_subject, $message, $smtp_used, $smtp_host, $smtp_user, $smtp_password, $smtp_port, \App\Models\BranchConfig::get($prefered_branch_id, 'reply_to_email'));
		}

		return response()->setJSON([
			'success' => 1,
			'base64_token' => $base64_token,
		]);
	}

	function send_unsent_emails()
	{
		$db = \Config\Database::connect();
		
		// Get all unsent customer registrations
		$builder = $db->table('epos_customer_registration');
		$builder->groupStart()
			->where('email_sended !=', 1)
			->orWhere('email_sended', null)
			->groupEnd();
		$unsent_registrations = $builder->get()->getResult();
		
		if (empty($unsent_registrations)) {
			return response()->setJSON([
				'success' => 1,
				'msg' => 'No unsent emails found.'
			]);
		}
		
		$success_count = 0;
		$fail_count = 0;
		
		foreach ($unsent_registrations as $registration) {
			// Get branch id
			$prefered_branch_id = null;
			if (!empty($registration->prefered_branch)) {
				$branch_result = $db->table('epos_branches')
					->where('site_name', $registration->prefered_branch)
					->get()
					->getRow();
				if ($branch_result) {
					$prefered_branch_id = $branch_result->id;
				}
			}
			
			// Get email config from branch
			$from_email = null;
			$cc_email = null;
			$sendRegFormTo = null;
			if (!empty($prefered_branch_id)) {
				$config_result = (object) \App\Models\BranchConfig::getAll($prefered_branch_id);
				$from_email    = $config_result->from_email    ?? null;
				$cc_email      = $config_result->cc_email      ?? null;
				$sendRegFormTo = $config_result->sendRegFormTo ?? null;
				$smtp_used     = $config_result->smtp_used     ?? null;
				$smtp_host     = $config_result->smtp_host     ?? null;
				$smtp_user     = $config_result->smtp_user     ?? null;
				$smtp_password = $config_result->smtp_password ?? null;
				$smtp_port     = $config_result->smtp_port     ?? null;
			}

			// If no branch config, skip this registration
			if (empty($from_email) || empty($sendRegFormTo)) {
				$fail_count++;
				continue;
			}
			
			// Get app config
			$result = $db->table('epos_app_config')->where('key', 'development_cc_email')->get()->getRow();
			$mail_addr_development_cc = $result->value ?? null;
			
			$result = $db->table('epos_app_config')->where('key', 'company')->get()->getRow();
			$company_name = $result->value ?? '';
			
			$mail_subject = "A copy of your Application Form";
			
			// Format payment method
			$pref_payment_method = $registration->prefered_payment_method ?? '';
			if ($pref_payment_method == "cash") {
				$pref_payment_method = "Cash";
			} else if ($pref_payment_method == "bank_transfer") {
				$pref_payment_method = "Bank Transfer";
			} else if ($pref_payment_method == "echo_pay") {
				$pref_payment_method = "EchoPay";
			} else if ($pref_payment_method == "card") {
				$pref_payment_method = "Card";
			} else if ($pref_payment_method == "credit_facility") {
				$pref_payment_method = "Credit Facility";
			}
			
			// Build email message (reuse the same template from post_register)
			$message = $this->build_registration_email_message($registration, $pref_payment_method);
			
			// Send email
			$res = $this->do_send_email_phpmailer($from_email, $sendRegFormTo, $cc_email, $mail_addr_development_cc, $company_name, $mail_subject, $message, $smtp_used, $smtp_host, $smtp_user, $smtp_password, $smtp_port, \App\Models\BranchConfig::get($prefered_branch_id, 'reply_to_email'));
			
			if ($res) {
				// Update email_sended to 1
				$db->table('epos_customer_registration')
					->where('id', $registration->id)
					->update(['email_sended' => 1]);
				$success_count++;
			} else {
				$fail_count++;
			}
		}
		
		$msg = "Successfully sent {$success_count} email(s)";
		if ($fail_count > 0) {
			$msg .= ". {$fail_count} email(s) failed to send.";
		}
		
		return response()->setJSON([
			'success' => $success_count > 0 ? 1 : 0,
			'msg' => $msg
		]);
	}

	function resend_email($registrationId = null)
	{
		$db = \Config\Database::connect();
		
		if (!$registrationId) {
			return response()->setJSON([
				'success' => 0,
				'msg' => 'Registration ID is required'
			]);
		}

		// Get registration
		$registration = $db->table('epos_customer_registration')
			->where('id', $registrationId)
			->get()
			->getRow();

		if (!$registration) {
			return response()->setJSON([
				'success' => 0,
				'msg' => 'Registration not found'
			]);
		}

		// Get branch id
		$prefered_branch_id = null;
		if (!empty($registration->prefered_branch)) {
			$branch_result = $db->table('epos_branches')
				->where('site_name', $registration->prefered_branch)
				->get()
				->getRow();
			if ($branch_result) {
				$prefered_branch_id = $branch_result->id;
			}
		}
		
		// Get email config from branch
		$from_email = null;
		$cc_email = null;
		$sendRegFormTo = null;
		if (!empty($prefered_branch_id)) {
			$config_result = (object) \App\Models\BranchConfig::getAll($prefered_branch_id);
			$from_email    = $config_result->from_email    ?? null;
			$cc_email      = $config_result->cc_email      ?? null;
			$sendRegFormTo = $config_result->sendRegFormTo ?? null;
			$smtp_used     = $config_result->smtp_used     ?? null;
			$smtp_host     = $config_result->smtp_host     ?? null;
			$smtp_user     = $config_result->smtp_user     ?? null;
			$smtp_password = $config_result->smtp_password ?? null;
			$smtp_port     = $config_result->smtp_port     ?? null;
		}

		// If no branch config, return error
		if (empty($from_email) || empty($sendRegFormTo)) {
			return response()->setJSON([
				'success' => 0,
				'msg' => 'Email configuration not found for this branch'
			]);
		}
		
		// Get app config
		$result = $db->table('epos_app_config')->where('key', 'development_cc_email')->get()->getRow();
		$mail_addr_development_cc = $result->value ?? null;
		
		$result = $db->table('epos_app_config')->where('key', 'company')->get()->getRow();
		$company_name = $result->value ?? '';
		
		$mail_subject = "A copy of your Application Form";
		
		// Format payment method
		$pref_payment_method = $registration->prefered_payment_method ?? '';
		if ($pref_payment_method == "cash") {
			$pref_payment_method = "Cash";
		} else if ($pref_payment_method == "bank_transfer") {
			$pref_payment_method = "Bank Transfer";
		} else if ($pref_payment_method == "echo_pay") {
			$pref_payment_method = "EchoPay";
		} else if ($pref_payment_method == "card") {
			$pref_payment_method = "Card";
		} else if ($pref_payment_method == "credit_facility") {
			$pref_payment_method = "Credit Facility";
		}
		
		// Build email message
		$message = $this->build_registration_email_message($registration, $pref_payment_method);
		
		// Send email
		$res = $this->do_send_email_phpmailer($from_email, $sendRegFormTo, $cc_email, $mail_addr_development_cc, $company_name, $mail_subject, $message, $smtp_used, $smtp_host, $smtp_user, $smtp_password, $smtp_port, \App\Models\BranchConfig::get($prefered_branch_id, 'reply_to_email'));
		
		if ($res) {
			// Update email_sended to 1
			$db->table('epos_customer_registration')
				->where('id', $registrationId)
				->update(['email_sended' => 1]);
			
			return response()->setJSON([
				'success' => 1,
				'msg' => 'Email sent successfully'
			]);
		} else {
			return response()->setJSON([
				'success' => 0,
				'msg' => 'Failed to send email'
			]);
		}
	}
	
	private function build_registration_email_message($registration, $pref_payment_method)
	{
		$message = "<html><head><style>
			.customer-register-panel-for-email {
				width: 1000px;
			}
			.customer-register-panel-for-email table {
				border-collapse: collapse;
				width: 100%;
				font-family: Arial, sans-serif;
				font-size: 12px;
				color: #545454;
			}
			.customer-register-panel-for-email th.section-title {
				text-align: left;
				background: #e5e5e5;
				font-size: 14px;
				padding: 6px 8px;
				border: 1px solid #ccc;
			}
			.customer-register-panel-for-email td {
				border: 1px solid #ccc;
				padding: 4px 6px;
				vertical-align: top;
			}
			.customer-register-panel-for-email td.label {
				width: 22%;
				white-space: nowrap;
				font-weight: bold;
			}
			.customer-register-panel-for-email td.value input,
			.customer-register-panel-for-email td.value select {
				width: 100%;
				box-sizing: border-box;
			}
			.customer-register-panel-for-email .checkbox-row label,
			.customer-register-panel-for-email .checkbox-column label {
				display: inline-block;
				margin-right: 14px;
			}
			.customer-register-panel-for-email .checkbox-column label {
				display: block;
			}
			.customer-register-panel-for-email .required::after {
				content: '(*)';
				color: #c00;
				padding-left: 2px;
			}
		</style></head><body>";
		
		$message .= '<div class="customer-register-panel-for-email">';
		$message .= "<div style='font-family:Arial; font-size:13px;'>";
		$message .= "Dear Customer.";
		$message .= "</div>";
		$message .= "<br>";
		$message .= "<div style='font-family:Arial; font-size:13px;'>";
		$message .= "Please find below a copy of the information you have submitted as part of your request to open a trade account.";
		$message .= '</div>';
		$message .= "<br>";
		$message .= "<div style='font-family:Arial; font-size:13px;'>";
		$message .= "This is a system generated email, please do not reply to it.";
		$message .= '</div>';
		$message .= '<br>';
		$message .= '<table class="email-table" cellpadding="4" cellspacing="0" width="100%">
				<tr>
					<th colspan="4" class="section-title">Business</th>
				</tr>
				<tr>
					<td class="label required">Business Legal Name:</td>
					<td class="value"><input id="busi_legal_nm_for_email" type="text" value="'.htmlspecialchars($registration->business_legal_name ?? '').'" /></td>
					<td class="label required">Address Line 1:</td>
					<td class="value"><input id="addr_line1_for_email" type="text" value="'.htmlspecialchars($registration->address_line1 ?? '').'" /></td>
				</tr>
				<tr>
					<td class="label required">Business Trading Name:</td>
					<td class="value"><input id="busi_trad_nm_for_email" type="text" value="'.htmlspecialchars($registration->business_trading_name ?? '').'" /></td>
					<td class="label">Address Line 2:</td>
					<td class="value"><input id="addr_line2_for_email" type="text" value="'.htmlspecialchars($registration->address_line2 ?? '').'" /></td>
				</tr>
				<tr>
					<td class="label required">Business Start Date:</td>
					<td class="value"><input id="busi_start_dt_for_email" type="text" value="'.htmlspecialchars($registration->business_start_date ?? '').'" /></td>
					<td class="label required">County:</td>
					<td class="value"><input id="county_for_email" type="text" value="'.htmlspecialchars($registration->county ?? '').'" /></td>
				</tr>
				<tr>
					<td class="label">Preferred Branch:</td>
					<td class="value">
						<select id="prefered_branch_for_email" value="'.htmlspecialchars($registration->prefered_branch ?? '').'">
						<option value="'.htmlspecialchars($registration->prefered_branch ?? '').'">'.htmlspecialchars($registration->prefered_branch ?? '').'</option>
						</select>
					</td>
					<td class="label required">City:</td>
					<td class="value"><input id="city_for_email" type="text" value="'.htmlspecialchars($registration->city ?? '').'" /></td>
				</tr>
				<tr>
					<td colspan="2" class="checkbox-cell">
						<label>
						<input type="checkbox" id="confirm_legal_owner_director_for_email" '.($registration->confirm_legal_owner_director==1?'checked="checked"':'').' />
						I confirm I am the Legal Owner or Director
						</label>
					</td>
					<td class="label required">Country:</td>
					<td class="value">
						<select id="country_for_email" value="'.htmlspecialchars($registration->country ?? '').'">
						<option value="'.htmlspecialchars($registration->country ?? '').'">'.htmlspecialchars($registration->country ?? '').'</option>
						</select>
					</td>
				</tr>
				<tr>
					<td colspan="2"></td>
					<td class="label required">Post Code:</td>
					<td class="value"><input id="post_code_for_email" type="text" value="'.htmlspecialchars($registration->post_code ?? '').'" /></td>
				</tr>

				<tr>
					<th colspan="4" class="section-title">Contact</th>
				</tr>
				<tr>
					<td class="label required">Contact Name:</td>
					<td class="value"><input id="contact_nm_for_email" type="text" value="'.htmlspecialchars($registration->contact_name ?? '').'" /></td>
					<td class="label">Contact Telephone Landline:</td>
					<td class="value"><input id="contact_phone_ll_for_email" type="text" value="'.htmlspecialchars($registration->contact_telephone_landline ?? '').'" /></td>
				</tr>
				<tr>
					<td class="label required">Contact Telephone Mobile:</td>
					<td class="value"><input id="contact_phone_mb_for_email" type="text" value="'.htmlspecialchars($registration->contact_telephone_mobile ?? '').'" /></td>
					<td class="label required">Contact email address:</td>
					<td class="value"><input id="contact_email_for_email" type="text" value="'.htmlspecialchars($registration->contact_email ?? '').'" /></td>
				</tr>

				<tr>
					<th colspan="4" class="section-title">Owner/Director Address</th>
				</tr>
				<tr>
					<td class="label required">House Number:</td>
					<td class="value"><input id="owner_house_no_for_email" type="text" value="'.htmlspecialchars($registration->contact_addr_house_number ?? '').'" /></td>
					<td class="label">House Name/Flat:</td>
					<td class="value"><input id="owner_house_name_for_email" type="text" value="'.htmlspecialchars($registration->contact_addr_house_name_flat ?? '').'" /></td>
				</tr>
				<tr>
					<td class="label required">Street:</td>
					<td class="value"><input id="owner_street_for_email" type="text" value="'.htmlspecialchars($registration->contact_addr_street ?? '').'" /></td>
					<td class="label required">Village/Town:</td>
					<td class="value"><input id="owner_village_for_email" type="text" value="'.htmlspecialchars($registration->contact_addr_vill_town ?? '').'" /></td>
				</tr>
				<tr>
					<td class="label required">City:</td>
					<td class="value"><input id="owner_city_for_email" type="text" value="'.htmlspecialchars($registration->contact_addr_city ?? '').'" /></td>
					<td class="label required">Country:</td>
					<td class="value"><input id="owner_country_for_email" type="text" value="'.htmlspecialchars($registration->contact_addr_country ?? '').'" /></td>
				</tr>
				<tr>
					<td class="label required">Post Code:</td>
					<td class="value"><input id="owner_post_code_for_email" type="text" value="'.htmlspecialchars($registration->contact_addr_postcode ?? '').'" /></td>
					<td colspan="2">&nbsp;</td>
				</tr>

				<tr>
					<th colspan="4" class="section-title">Company</th>
				</tr>
				<tr>
					<td class="label">Company Number:</td>
					<td class="value"><input id="company_no_for_email" type="text" value="'.htmlspecialchars($registration->company_number ?? '').'" /></td>
					<td class="label">VAT Number:</td>
					<td class="value"><input id="vat_number_for_email" type="text" value="'.htmlspecialchars($registration->vat_number ?? '').'" /></td>
				</tr>
				<tr>
					<td class="label required">For how many years has the business been trading?</td>
					<td class="value"><input id="busi_trad_years_for_email" type="text" value="'.htmlspecialchars($registration->business_trading_years ?? '').'" /></td>
					<td class="label">&nbsp;</td>
					<td class="value">&nbsp;</td>
				</tr>

				<tr>
					<th colspan="4" class="section-title">Sell</th>
				</tr>
				<tr>
					<td colspan="4" class="checkbox-column">
						<label><input type="checkbox" id="sell_alcohol_for_email" '.($registration->sell_alcohol==1?'checked="checked"':'').'/> Do you sell Alcohol?</label>
					</td>
				</tr>';
				if ($registration->premises_licence) {
					$message .= '<tr>
						<td class="label">Premises Licence:</td>
						<td colspan="3" class="value"><input id="premises_licence_for_email" type="text" value="'.htmlspecialchars($registration->premises_licence ?? '').'" /></td>
					</tr>';
				}
				$message .= '<tr>
					<td colspan="4" class="checkbox-column">
						<label><input type="checkbox" id="sell_tobacco_for_email" '.($registration->sell_tobacco==1?'checked="checked"':'').'/> Do you sell Tobacco?</label>
					</td>
				</tr>';
				if ($registration->eoid) {
					$message .= '<tr>
						<td class="label">EOID:</td>
						<td colspan="3" class="value"><input id="eoid_for_email" type="text" value="'.htmlspecialchars($registration->eoid ?? '').'" /></td>
					</tr>';
				}
				if ($registration->fid) {
					$message .= '<tr>
						<td class="label">FID:</td>
						<td colspan="3" class="value"><input id="fid_for_email" type="text" value="'.htmlspecialchars($registration->fid ?? '').'" /></td>
					</tr>';
				}
				$message .= '
				<tr>
					<td colspan="4" class="checkbox-column">
						<label><input type="checkbox" id="sell_vapes_for_email" '.($registration->sell_vapes==1?'checked="checked"':'').'/> Do you sell Vapes?</label>
					</td>
				</tr>

				<tr>
					<th colspan="4" class="section-title">Store</th>
				</tr>
				<tr>
					<td class="label required">Store size in square feet?</td>
					<td class="value"><input id="store_sz_for_email" type="text" value="'.htmlspecialchars($registration->store_size ?? '').'" /></td>
					<td class="label required">Store average turnover weekly?</td>
					<td class="value"><input id="store_avg_for_email" type="text" value="'.htmlspecialchars($registration->store_average ?? '').'" /></td>
				</tr>
				<tr>
					<td colspan="4" class="checkbox-column">
						<div><label><input type="checkbox" id="self_service_for_email" '.($registration->self_service==1?'checked="checked"':'').'/> I will visit the depot to purchase goods</label></div>
						<div><label><input type="checkbox" id="click_and_collect_for_email" '.($registration->click_and_collect==1?'checked="checked"':'').'/> I will order online then come in to collect goods</label></div>
						<div><label><input type="checkbox" id="delivered_for_email" '.($registration->delivered==1?'checked="checked"':'').'/> I will order online and require a delivery of goods</label></div>
						<div><label><input type="checkbox" id="offers_and_info_for_email" '.($registration->offers_and_info==1?'checked="checked"':'').'/> Do you wish to receive marketing offers and info?</label></div>';
						if ($registration->offers_and_info==1 && $registration->marketing_options) {
							$available_marketing_options = explode(',', 'post,email,sms,messaging,telephone');
							$array_marketing_options = explode(',', $registration->marketing_options);
							$message1 = '';
							foreach ($available_marketing_options as $available_marketing_options_item) {
								if (in_array($available_marketing_options_item, $array_marketing_options)) {
									$message1 .= '<label style="padding-left:0px"><input type="checkbox" id="marketing_option_for_email" checked="checked" /> '.$available_marketing_options_item.'</label>';
								} else {
									$message1 .= '<label style="padding-left:0px"><input type="checkbox" id="marketing_option_for_email" /> '.$available_marketing_options_item.'</label>';
								}
							}
							if ($message1) {
								$message .= '<div style="display: flex"><span style="padding: 0px 4px 0px 17px">by: </span>'.$message1.'</div>';
							}
						}
		$message .= '</td>
				</tr>

				<tr>
					<th colspan="4" class="section-title">Payment &amp; Offer</th>
				</tr>
				<tr>
					<td class="label">What is your preferred payment method?</td>
					<td class="value">
						<select id="pref_payment_method_for_email" value="'.htmlspecialchars($pref_payment_method).'">
						<option value="'.htmlspecialchars($pref_payment_method).'">'.htmlspecialchars($pref_payment_method).'</option>
						</select>
					</td>
					<td class="label">Do you require a credit account facility?</td>
					<td class="">
						<label>
						<input type="checkbox" id="credit_acc_facility_for_email" '.($registration->credit_account_facility==1?'checked="checked"':'').'/>
						Yes
						</label>
					</td>
				</tr>';

		if (!empty($registration->requested_credit_limit)) {
			$message .= '
				<tr>
					<td class="label">&nbsp;</td>
					<td class="value">&nbsp;</td>
					<td class="label required">Required Credit Limit &pound;\'s:</td>
					<td class="value"><input id="credit_limit_for_email" type="text" value="'.htmlspecialchars($registration->requested_credit_limit).'" /></td>
				</tr>';
		}

		$message .= '
			</table>
		</div>';

		$message .= "</body></html>";
		return $message;
	}

	function do_send_email($from, $to, $cc, $mail_addr_development_cc, $senderCompany, $subject, $message, $reply_to = null)
	{
		$email = \Config\Services::email();
        $email->setFrom($from, $senderCompany);
		if (!empty($cc)) {
			$email->setCC($cc);
		}
		$email->setReplyTo($reply_to ?: $from);
		
		$to_email = $to . ($mail_addr_development_cc ? "," . $mail_addr_development_cc : "");
        $email->setTo($to_email);
		
        $email->setSubject($subject);
        $email->setMessage($message);

        $email->setProtocol('mail');
		$email->setMailType('html');
        if ($email->send()) {
            // echo 'Email sent'; 
			return true;
        } else {
            // echo $email->printDebugger(); 
			return false;
        }
	}

	/**
	 * Send email using PHPMailer with SMTP.
	 * SMTP settings from epos_app_config: phpmailer_smtp_used, phpmailer_smtp_host, phpmailer_smtp_user,
	 * phpmailer_smtp_password, phpmailer_smtp_port, phpmailer_smtp_crypto. Falls back to .env/Config\Email if missing.
	 */
	private function do_send_email_phpmailer($from, $to, $cc, $mail_addr_development_cc, $senderCompany, $subject, $message, $smtp_used, $smtp_host, $smtp_user, $smtp_password, $smtp_port, $reply_to = null)
	{
		if (!$smtp_used || empty($smtp_host) || empty($to)) {
			if (!$smtp_used) {
				return $this->do_send_email($from, $to, $cc, $mail_addr_development_cc, $senderCompany, $subject, $message, $reply_to);
			}
			return false;
		}

		$config = config(\Config\Email::class);
		$mail = new \PHPMailer\PHPMailer\PHPMailer(true);
		try {
			$mail->isSMTP();
			$mail->Host       = $smtp_host;
			$mail->SMTPAuth   = !empty($smtp_user);
			$mail->Username   = $smtp_user;
			$mail->Password   = $smtp_password;
			// Port 465 uses implicit SSL (SMTPS); 587 and others use STARTTLS.
			// Gmail on 465 fails with STARTTLS, so pick encryption by port.
			$mail->SMTPSecure = ((int) $smtp_port === 465)
				? \PHPMailer\PHPMailer\PHPMailer::ENCRYPTION_SMTPS
				: \PHPMailer\PHPMailer\PHPMailer::ENCRYPTION_STARTTLS;
			$mail->Port       = $smtp_port;
			$mail->CharSet    = $config->charset;
			$mail->isHTML(true);

			$mail->setFrom($from, $senderCompany);
			$mail->addReplyTo($reply_to ?: $from);
			$mail->addAddress($to);
			if (!empty($mail_addr_development_cc)) {
				$mail->addCC($mail_addr_development_cc);
			}
			if (!empty($cc)) {
				$mail->addCC($cc);
			}
			$mail->Subject = $subject;
			$mail->Body    = $message;

			$mail->send();
			return true;
		} catch (\PHPMailer\PHPMailer\Exception $e) {
			log_message('error', 'PHPMailer: ' . $mail->ErrorInfo);
			// SMTP unreachable (firewall, credentials, DNS). Fall back to PHP's
			// local mail() via CI4's email library so the registration email
			// still gets out instead of hard-failing.
			return $this->do_send_email($from, $to, $cc, $mail_addr_development_cc, $senderCompany, $subject, $message, $reply_to);
		}
	}

	function register_list()
	{
		$db = \Config\Database::connect();
		$request = \Config\Services::request();
		
		// Get query parameters
		$fromDate = $request->getGet('from_date');
		$toDate = $request->getGet('to_date');
		$searchText = $request->getGet('search_text');
		$count = (int)($request->getGet('count') ?: 10);
		$startPosition = (int)($request->getGet('start_position') ?: 0);
		
		// Build query with filters
		$builder = $db->table('epos_customer_registration');
		
		// Apply filters
		if ($fromDate) {
			$builder->where('date_created >=', $fromDate . ' 00:00:00');
		}
		if ($toDate) {
			$builder->where('date_created <=', $toDate . ' 23:59:59');
		}
        if ($searchText) {
            $builder->groupStart()
                ->like('business_legal_name', $searchText)
                ->orLike('business_trading_name', $searchText)
                ->orLike('contact_email', $searchText)
                ->orLike('contact_name', $searchText)
                ->orLike('contact_telephone_landline', $searchText)
                ->orLike('contact_telephone_mobile', $searchText)
                ->orLike('address_line1', $searchText)
                ->orLike('address_line2', $searchText)
                ->orLike('city', $searchText)
                ->orLike('country', $searchText)
                ->orLike('county', $searchText)
                ->orLike('post_code', $searchText)
                ->groupEnd();
        }
		
		// Get total count before pagination
		$totalCount = $builder->countAllResults(false);
		
		// Apply pagination
		$builder->orderBy('date_created', 'DESC')
			->limit($count, $startPosition);
		
		$result = $builder->get()->getResult();
		
		// Get envelope status for each registration
		$docusign_api = new DocusignApi();
		$status = $request->getGet('status');
		$filteredResults = [];
		
		// Get employee model for fetching creator info
		$employeeModel = new Employee();
		
		foreach ($result as $registration) {
			$envelope_id = $registration->envelope_id;
			if ($envelope_id) {
				$envelope_status = $docusign_api->envelopeDetails($envelope_id, true);
				if ($envelope_status) {
					// Apply status filter if specified
					if ($status && strtolower($envelope_status['status'] ?? '') !== strtolower($status)) {
						continue; // Skip if status doesn't match
					}
					$registration->envelope_status = $envelope_status;
				}
			} else if ($status) {
				// If status filter is set but no envelope_id, skip
				continue;
			}
			
			// Get creator info if mms_creator_id exists
			if (!empty($registration->mms_creator_id)) {
				$creatorInfo = $employeeModel->get_info($registration->mms_creator_id);
				if ($creatorInfo && isset($creatorInfo->username)) {
					$registration->mms_creator_username = $creatorInfo->username;
					$registration->mms_creator_email = $creatorInfo->email ?? '';
				}
			}
			
			$filteredResults[] = $registration;
		}
		
		$endPosition = min($startPosition + count($filteredResults), $totalCount);
		
		return response()->setJSON([
			'success' => 1,
			'registrations' => $filteredResults,
			'total_count' => $totalCount,
			'start_position' => $startPosition,
			'end_position' => $endPosition
		]);
	}

	function confirm_ui($base64_token)
	{
		$payload = json_decode(base64_decode($base64_token), true);
		$registration_id = $payload['registration_id'];
		$email = $payload['email'];

		echo view('v2/pages/customer_confirm', [
			'registration_id' => $registration_id,
			'email' => $email,
		]);
	}

	function resend_verification_code()
	{
		$email = request()->getPost('email');
		$registration_id = request()->getPost('registration_id');

		if (empty($email) || empty($registration_id)) {
			return $this->response->setJSON([
				'success' => 0,
				'error' => 'Email and registration ID are required.'
			]);
		}

		$db = \Config\Database::connect();

		// Verify registration exists and email matches
		$registration = $db->table('epos_customer_registration')
			->where('id', $registration_id)
			->where('contact_email', $email)
			->get()
			->getRow();
		if (!$registration) {
			return $this->response->setJSON([
				'success' => 0,
				'error' => 'Invalid registration or email.'
			]);
		}

		// Generate new 8-digit code and expiry — store as Unix timestamp (the
		// column is INT) and match the 10-minute window the modal advertises.
		$rand8 = mt_rand(10000000, 99999999);
		$now = new \DateTime();
		$now->add(new \DateInterval('PT10M'));
		$expired_datetime = $now->getTimestamp();

		// Update epos_customer_confirm with new code and expiry
		$updated = $db->table('epos_customer_confirm')
			->where('registration_id', $registration_id)
			->where('email', $email)
			->update([
				'pin_verify_number' => $rand8,
				'pin_expired_datetime' => $expired_datetime
			]);
		if (!$updated) {
			return $this->response->setJSON([
				'success' => 0,
				'message' => 'Could not update verification record. Please try again.'
			]);
		}

		// Get branch config for sending email
		$prefered_branch_id = null;
		if (!empty($registration->prefered_branch)) {
			$branch_result = $db->table('epos_branches')
				->where('site_name', $registration->prefered_branch)
				->get()
				->getRow();
			if ($branch_result) {
				$prefered_branch_id = $branch_result->id;
			}
		}
		$from_email = null;
		$cc_email = null;
		if (!empty($prefered_branch_id)) {
			$config_result = (object) \App\Models\BranchConfig::getAll($prefered_branch_id);
			$from_email    = $config_result->from_email    ?? null;
			$cc_email      = $config_result->cc_email      ?? null;
			$smtp_used     = $config_result->smtp_used     ?? null;
			$smtp_host     = $config_result->smtp_host     ?? null;
			$smtp_user     = $config_result->smtp_user     ?? null;
			$smtp_password = $config_result->smtp_password ?? null;
			$smtp_port     = $config_result->smtp_port     ?? null;
		}
		$result = $db->table('epos_app_config')->where('key', 'development_cc_email')->get()->getRow();
		$mail_addr_development_cc = $result->value ?? '';

		$result = $db->table('epos_app_config')->where('key', 'company')->get()->getRow();
		$company_name = $result->value ?? '';
		
		$mail_subject = 'Please validate your email address';

		$message = "<html><body>";
		
		$message .= "<div style='font-family:Arial; font-size:13px;'>";
		$message .= "Dear Customer.";
		$message .= "</div>";
		$message .= "<br>";
		$message .= "<div style='font-family:Arial; font-size:13px;'>";
		$message .= "Please enter this code <b>" . $rand8 . "</b> in order to verify your email address and submit your application form. The code is valid for 10 minutes.";
		$message .= '</div>';
		$message .= "<br>";
		$message .= "<div style='font-family:Arial; font-size:13px;'>";
		$message .= "This is a system generated email, please do not reply to it.";
		$message .= '</div>';

		$message .= "</body></html>";

		$res = false;
		if ($from_email && $email) {
			$res = $this->do_send_email_phpmailer($from_email, $email, $cc_email, $mail_addr_development_cc, $company_name, $mail_subject, $message, $smtp_used, $smtp_host, $smtp_user, $smtp_password, $smtp_port, \App\Models\BranchConfig::get($prefered_branch_id, 'reply_to_email'));
		}

		if (!$res) {
			return $this->response->setJSON([
				'success' => 0,
				'error' => 'Failed to send verification email. Please try again later.'
			]);
		}

		return $this->response->setJSON([
			'success' => 1,
			'message' => 'A new verification code has been sent to your email.'
		]);
	}

	function confirm_by_code()
	{
		/**
		 * ### MAIN LOGIC ###
		 * 0. Check the validation of the pin verify number
		 * 1. Get the registration data
		 * 2. Send application form to email
		 * 3. Create docusign envelope
		 * 4. Update the registration data
		 * 5. Return the success message
		 */
		$error_message = '';
		
		/**
		 * 0. Check the validation of the pin verify number
		 */ 
		$email = request()->getPost('email');
		$registration_id = request()->getPost('registration_id');
		$pin_verify_number = request()->getPost('pin_verify_number');

		if (empty($email) || empty($registration_id) || empty($pin_verify_number)) {
			return $this->response->setJSON([
				'success' => 0,
				'error' => 'Email, registration ID and pin verify number are required.'
			]);
		}

		$db = \Config\Database::connect();
		$registration = $db->table('epos_customer_registration')
			->where('id', $registration_id)
			->where('contact_email', $email)
			->get()
			->getRow();
		if (!$registration) {
			return $this->response->setJSON([
				'success' => 0,
				'error' => 'Invalid registration or email.'
			]);
		}

		$confirm = $db->table('epos_customer_confirm')
			->where('registration_id', $registration_id)
			->where('email', $email)
			->get()
			->getRow();
		if (!$confirm) {
			return $this->response->setJSON([
				'success' => 0,
				'error' => 'Invalid confirm record.'
			]);
		}

		// pin_expired_datetime is stored as a Unix timestamp (int column).
		if ((int) $confirm->pin_expired_datetime < time()) {
			return $this->response->setJSON([
				'success' => 0,
				'error' => 'The code has expired.'
			]);
		}

		if ($pin_verify_number != $confirm->pin_verify_number) {
			return $this->response->setJSON([
				'success' => 0,
				'error' => 'The code is incorrect.'
			]);
		}

		/**
		 * 1. Get the registration data
		 */
		$registration_data = $db->table('epos_customer_registration')
			->where('id', $registration_id)
			->get()
			->getRow();
		if (!$registration_data) {
			return $this->response->setJSON([
				'success' => 0,
				'error' => 'Invalid registration data.'
			]);
		}
		$busi_legal_nm = $data4docusign['busi_legal_nm'] = $registration_data->business_legal_name;
		$busi_start_dt = $data4docusign['busi_start_dt'] = $registration_data->business_start_date;
		$busi_trad_nm = $data4docusign['busi_trad_nm'] = $registration_data->business_trading_name;
		$addr_line1 = $data4docusign['addr_line1'] = $registration_data->address_line1;
		$addr_line2 = $data4docusign['addr_line2'] = $registration_data->address_line2;
		$county = $data4docusign['county'] = $registration_data->county;
		$city = $data4docusign['city'] = $registration_data->city;
		$country = $data4docusign['country'] = $registration_data->country;
		$post_code = $data4docusign['post_code'] = $registration_data->post_code;
		$contact_nm = $data4docusign['contact_nm'] = $registration_data->contact_name;
		$contact_phone_ll = $data4docusign['contact_phone_ll'] = $registration_data->contact_telephone_landline;
		$contact_phone_mb = $data4docusign['contact_phone_mb'] = $registration_data->contact_telephone_mobile;
		$contact_email = $data4docusign['contact_email'] = $registration_data->contact_email;
		$company_no = $data4docusign['company_no'] = $registration_data->company_number;
		$vat_number = $data4docusign['vat_number'] = $registration_data->vat_number;
		$busi_trad_years = $data4docusign['busi_trad_years'] = $registration_data->business_trading_years;
		$store_sz = $data4docusign['store_sz'] = $registration_data->store_size;
		$store_avg = $data4docusign['store_avg'] = $registration_data->store_average;
		$pref_payment_method = $data4docusign['pref_payment_method'] = $registration_data->prefered_payment_method;
		$credit_acc_facility = $data4docusign['credit_acc_facility'] = $registration_data->credit_account_facility;
		$offers_and_info = $data4docusign['offers_and_info'] = $registration_data->offers_and_info;
		$marketing_options = $data4docusign['marketing_options'] = $registration_data->marketing_options;
		$self_service = $data4docusign['self_service'] = $registration_data->self_service;
		$click_and_collect = $data4docusign['click_and_collect'] = $registration_data->click_and_collect;
		$delivered = $data4docusign['delivered'] = $registration_data->delivered;
		$confirm_legal_owner_director = $data4docusign['confirm_legal_owner_director'] = $registration_data->confirm_legal_owner_director;
		$prefered_branch = $data4docusign['prefered_branch'] = $registration_data->prefered_branch;
		$sell_alcohol = $data4docusign['sell_alcohol'] = $registration_data->sell_alcohol;
		$sell_tobacco = $data4docusign['sell_tobacco'] = $registration_data->sell_tobacco;
		$sell_vapes = $data4docusign['sell_vapes'] = $registration_data->sell_vapes;
		$premises_licence = $data4docusign['premises_licence'] = $registration_data->premises_licence;
		$eoid = $data4docusign['eoid'] = $registration_data->eoid;
		$fid = $data4docusign['fid'] = $registration_data->fid;
		$owner_house_no   = $data4docusign['owner_house_no']   = $registration_data->contact_addr_house_number    ?? '';
		$owner_house_name = $data4docusign['owner_house_name'] = $registration_data->contact_addr_house_name_flat ?? '';
		$owner_street     = $data4docusign['owner_street']     = $registration_data->contact_addr_street          ?? '';
		$owner_village    = $data4docusign['owner_village']    = $registration_data->contact_addr_vill_town       ?? '';
		$owner_city       = $data4docusign['owner_city']       = $registration_data->contact_addr_city            ?? '';
		$owner_country    = $data4docusign['owner_country']    = $registration_data->contact_addr_country         ?? '';
		$owner_post_code  = $data4docusign['owner_post_code']  = $registration_data->contact_addr_postcode        ?? '';
		$credit_limit     = $data4docusign['credit_limit']     = $registration_data->requested_credit_limit       ?? 0;

		/**
		 * 2. Send application form to email
		 */
		
		if ($pref_payment_method == "cash") {
			$pref_payment_method = "Cash";
		} else if ($pref_payment_method == "bank_transfer") {
			$pref_payment_method = "Bank Transfer";
		} else if ($pref_payment_method == "echo_pay") {
			$pref_payment_method = "EchoPay";
		} else if ($pref_payment_method == "card") {
			$pref_payment_method = "Card";
		} else if ($pref_payment_method == "credit_facility") {
			$pref_payment_method = "Credit Facility";
		}

		$prefered_branch_id = null;
		if (!empty($prefered_branch)) {
			$branch_result = $db->table('epos_branches')
				->where('site_name', $prefered_branch)
				->get()
				->getRow();
			if ($branch_result) {
				$prefered_branch_id = $branch_result->id;
			}
		}

		$from_email = null;
		$cc_email = null;
		$sendRegFormTo = null;
		if (!empty($prefered_branch_id)) {
			$config_result = (object) \App\Models\BranchConfig::getAll($prefered_branch_id);
			$from_email    = $config_result->from_email    ?? null;
			$cc_email      = $config_result->cc_email      ?? null;
			$sendRegFormTo = $config_result->sendRegFormTo ?? null;
			$smtp_used     = $config_result->smtp_used     ?? null;
			$smtp_host     = $config_result->smtp_host     ?? null;
			$smtp_user     = $config_result->smtp_user     ?? null;
			$smtp_password = $config_result->smtp_password ?? null;
			$smtp_port     = $config_result->smtp_port     ?? null;
		}

		$result = $db->table('epos_app_config')->where('key' , 'development_cc_email')->get()->getRow();
		$mail_addr_development_cc = $result->value;

		$result = $db->table('epos_app_config')->where('key' , 'company')->get()->getRow();
		$company_name = $result->value;

		$mail_subject = "A copy of your Application Form";

		$message = "<html><head><style>
			.customer-register-panel-for-email {
				width: 1000px;
			}
			.customer-register-panel-for-email table {
				border-collapse: collapse;
				width: 100%;
				font-family: Arial, sans-serif;
				font-size: 12px;
				color: #545454;
			}
			.customer-register-panel-for-email th.section-title {
				text-align: left;
				background: #e5e5e5;
				font-size: 14px;
				padding: 6px 8px;
				border: 1px solid #ccc;
			}
			.customer-register-panel-for-email td {
				border: 1px solid #ccc;
				padding: 4px 6px;
				vertical-align: top;
			}
			.customer-register-panel-for-email td.label {
				width: 22%;
				white-space: nowrap;
				font-weight: bold;
			}
			.customer-register-panel-for-email td.value input,
			.customer-register-panel-for-email td.value select {
				width: 100%;
				box-sizing: border-box;
			}
			.customer-register-panel-for-email .checkbox-row label,
			.customer-register-panel-for-email .checkbox-column label {
				display: inline-block;
				margin-right: 14px;
			}
			.customer-register-panel-for-email .checkbox-column label {
				display: block;
			}
			.customer-register-panel-for-email .required::after {
				content: '(*)';
				color: #c00;
				padding-left: 2px;
			}
		</style></head><body>";
		
		$message .= '<div class="customer-register-panel-for-email">';
		$message .= "<div style='font-family:Arial; font-size:13px;'>";
		$message .= "Dear Customer.";
		$message .= "</div>";
		$message .= "<br>";
		$message .= "<div style='font-family:Arial; font-size:13px;'>";
		$message .= "Please find below a copy of the information you have submitted as part of your request to open a trade account.";
		$message .= '</div>';
		$message .= "<br>";
		$message .= "<div style='font-family:Arial; font-size:13px;'>";
		$message .= "This is a system generated email, please do not reply to it.";
		$message .= '</div>';
		$message .= '<br>';
		$message .= '<table class="email-table" cellpadding="4" cellspacing="0" width="100%">
				<tr>
					<th colspan="4" class="section-title">Business</th>
				</tr>
				<tr>
					<td class="label required">Business Legal Name:</td>
					<td class="value"><input id="busi_legal_nm_for_email" type="text" value="'.$busi_legal_nm.'" /></td>
					<td class="label required">Address Line 1:</td>
					<td class="value"><input id="addr_line1_for_email" type="text" value="'.$addr_line1.'" /></td>
				</tr>
				<tr>
					<td class="label required">Business Trading Name:</td>
					<td class="value"><input id="busi_trad_nm_for_email" type="text" value="'.$busi_trad_nm.'" /></td>
					<td class="label">Address Line 2:</td>
					<td class="value"><input id="addr_line2_for_email" type="text" value="'.$addr_line2.'" /></td>
				</tr>
				<tr>
					<td class="label required">Business Start Date:</td>
					<td class="value"><input id="busi_start_dt_for_email" type="text" value="'.$busi_start_dt.'" /></td>
					<td class="label required">County:</td>
					<td class="value"><input id="county_for_email" type="text" value="'.$county.'" /></td>
				</tr>
				<tr>
					<td class="label">Preferred Branch:</td>
					<td class="value">
						<select id="prefered_branch_for_email" value="'.$prefered_branch.'">
						<option value="'.$prefered_branch.'">'.$prefered_branch.'</option>
						</select>
					</td>
					<td class="label required">City:</td>
					<td class="value"><input id="city_for_email" type="text" value="'.$city.'" /></td>
				</tr>
				<tr>
					<td colspan="2" class="checkbox-cell">
						<label>
						<input type="checkbox" id="confirm_legal_owner_director_for_email" checked="checked" />
						I confirm I am the Legal Owner or Director
						</label>
					</td>
					<td class="label required">Country:</td>
					<td class="value">
						<select id="country_for_email" value="'.$country.'">
						<option value="'.$country.'">'.$country.'</option>
						</select>
					</td>
				</tr>
				<tr>
					<td colspan="2"></td>
					<td class="label required">Post Code:</td>
					<td class="value"><input id="post_code_for_email" type="text" value="'.$post_code.'" /></td>
				</tr>

				<tr>
					<th colspan="4" class="section-title">Contact</th>
				</tr>
				<tr>
					<td class="label required">Contact Name:</td>
					<td class="value"><input id="contact_nm_for_email" type="text" value="'.$contact_nm.'" /></td>
					<td class="label">Contact Telephone Landline:</td>
					<td class="value"><input id="contact_phone_ll_for_email" type="text" value="'.$contact_phone_ll.'" /></td>
				</tr>
				<tr>
					<td class="label required">Contact Telephone Mobile:</td>
					<td class="value"><input id="contact_phone_mb_for_email" type="text" value="'.$contact_phone_mb.'" /></td>
					<td class="label required">Contact email address:</td>
					<td class="value"><input id="contact_email_for_email" type="text" value="'.$contact_email.'" /></td>
				</tr>

				<tr>
					<th colspan="4" class="section-title">Owner/Director Address</th>
				</tr>
				<tr>
					<td class="label required">House Number:</td>
					<td class="value"><input id="owner_house_no_for_email" type="text" value="'.htmlspecialchars($owner_house_no).'" /></td>
					<td class="label">House Name/Flat:</td>
					<td class="value"><input id="owner_house_name_for_email" type="text" value="'.htmlspecialchars($owner_house_name).'" /></td>
				</tr>
				<tr>
					<td class="label required">Street:</td>
					<td class="value"><input id="owner_street_for_email" type="text" value="'.htmlspecialchars($owner_street).'" /></td>
					<td class="label required">Village/Town:</td>
					<td class="value"><input id="owner_village_for_email" type="text" value="'.htmlspecialchars($owner_village).'" /></td>
				</tr>
				<tr>
					<td class="label required">City:</td>
					<td class="value"><input id="owner_city_for_email" type="text" value="'.htmlspecialchars($owner_city).'" /></td>
					<td class="label required">Country:</td>
					<td class="value"><input id="owner_country_for_email" type="text" value="'.htmlspecialchars($owner_country).'" /></td>
				</tr>
				<tr>
					<td class="label required">Post Code:</td>
					<td class="value"><input id="owner_post_code_for_email" type="text" value="'.htmlspecialchars($owner_post_code).'" /></td>
					<td colspan="2">&nbsp;</td>
				</tr>

				<tr>
					<th colspan="4" class="section-title">Company</th>
				</tr>
				<tr>
					<td class="label">Company Number:</td>
					<td class="value"><input id="company_no_for_email" type="text" value="'.$company_no.'" /></td>
					<td class="label">VAT Number:</td>
					<td class="value"><input id="vat_number_for_email" type="text" value="'.$vat_number.'" /></td>
				</tr>
				<tr>
					<td class="label required">For how many years has the business been trading?</td>
					<td class="value"><input id="busi_trad_years_for_email" type="text" value="'.$busi_trad_years.'" /></td>
					<td class="label">&nbsp;</td>
					<td class="value">&nbsp;</td>
				</tr>

				<tr>
					<th colspan="4" class="section-title">Sell</th>
				</tr>
				<tr>
					<td colspan="4" class="checkbox-column">
						<label><input type="checkbox" id="sell_alcohol_for_email" '.($sell_alcohol==1?'checked="checked"':'').'/> Do you sell Alcohol?</label>
					</td>
				</tr>';
				if ($premises_licence) {
					$message .= '<tr>
						<td class="label">Premises Licence:</td>
						<td colspan="3" class="value"><input id="premises_licence_for_email" type="text" value="'.htmlspecialchars($premises_licence ?? '').'" /></td>
					</tr>';
				}
				$message .= '<tr>
					<td colspan="4" class="checkbox-column">
						<label><input type="checkbox" id="sell_tobacco_for_email" '.($sell_tobacco==1?'checked="checked"':'').'/> Do you sell Tobacco?</label>
					</td>
				</tr>';
				if ($eoid) {
					$message .= '<tr>
						<td class="label">EOID:</td>
						<td colspan="3" class="value"><input id="eoid_for_email" type="text" value="'.htmlspecialchars($eoid ?? '').'" /></td>
					</tr>';
				}
				if ($fid) {
					$message .= '<tr>
						<td class="label">FID:</td>
						<td colspan="3" class="value"><input id="fid_for_email" type="text" value="'.htmlspecialchars($fid ?? '').'" /></td>
					</tr>';
				}
				$message .= '<tr>
					<td colspan="4" class="checkbox-column">
						<label><input type="checkbox" id="sell_vapes_for_email" '.($sell_vapes==1?'checked="checked"':'').'/> Do you sell Vapes?</label>
					</td>
				</tr>

				<tr>
					<th colspan="4" class="section-title">Store</th>
				</tr>
				<tr>
					<td class="label required">Store size in square feet?</td>
					<td class="value"><input id="store_sz_for_email" type="text" value="'.$store_sz.'" /></td>
					<td class="label required">Store average turnover weekly?</td>
					<td class="value"><input id="store_avg_for_email" type="text" value="'.$store_avg.'" /></td>
				</tr>
				<tr>
					<td colspan="4" class="checkbox-column">
						<div><label><input type="checkbox" id="self_service_for_email" '.($self_service==1?'checked="checked"':'').'/> I will visit the depot to purchase goods</label></div>
						<div><label><input type="checkbox" id="click_and_collect_for_email" '.($click_and_collect==1?'checked="checked"':'').'/> I will order online then come in to collect goods</label></div>
						<div><label><input type="checkbox" id="delivered_for_email" '.($delivered==1?'checked="checked"':'').'/> I will order online and require a delivery of goods</label></div>
						<div><label><input type="checkbox" id="offers_and_info_for_email" '.($offers_and_info==1?'checked="checked"':'').'/> Do you wish to receive marketing offers and info?</label></div>';
						if ($offers_and_info==1 && $marketing_options) {
							$available_marketing_options = explode(',', 'post,email,sms,messaging,telephone');
							$array_marketing_options = explode(',', $marketing_options);
							$message1 = '';
							foreach ($available_marketing_options as $available_marketing_options_item) {
								if (in_array($available_marketing_options_item, $array_marketing_options)) {
									$message1 .= '<label style="padding-left:0px"><input type="checkbox" id="marketing_option_for_email" checked="checked" /> '.$available_marketing_options_item.'</label>';
								} else {
									$message1 .= '<label style="padding-left:0px"><input type="checkbox" id="marketing_option_for_email" /> '.$available_marketing_options_item.'</label>';
								}
							}
							if ($message1) {
								$message .= '<div style="display: flex"><span style="padding: 0px 4px 0px 17px">by: </span>'.$message1.'</div>';
							}
						}
		$message .= '</td>
				</tr>

				<tr>
					<th colspan="4" class="section-title">Payment &amp; Offer</th>
				</tr>
				<tr>
					<td class="label">What is your preferred payment method?</td>
					<td class="value">
						<select id="pref_payment_method_for_email" value="'.$pref_payment_method.'">
						<option value="'.$pref_payment_method.'">'.$pref_payment_method.'</option>
						</select>
					</td>
					<td class="label">Do you require a credit account facility?</td>
					<td class="">
						<label>
						<input type="checkbox" id="credit_acc_facility_for_email" '.($credit_acc_facility==1?'checked="checked"':'').'/>
						Yes
						</label>
					</td>
				</tr>';

		if (!empty($credit_limit)) {
			$message .= '
				<tr>
					<td class="label">&nbsp;</td>
					<td class="value">&nbsp;</td>
					<td class="label required">Required Credit Limit &pound;\'s:</td>
					<td class="value"><input id="credit_limit_for_email" type="text" value="'.htmlspecialchars((string) $credit_limit).'" /></td>
				</tr>';
		}

		$message .= '
			</table>
		</div>';

		$message .= "</body></html>";


		$res_email = false;
		if ($from_email && $sendRegFormTo) {
			// $res_email = $this->do_send_email($from_email, $sendRegFormTo, $cc_email, $mail_addr_development_cc, $company_name, $mail_subject, $message);
			$res_email = $this->do_send_email_phpmailer($from_email, $sendRegFormTo, $cc_email, $mail_addr_development_cc, $company_name, $mail_subject, $message, $smtp_used, $smtp_host, $smtp_user, $smtp_password, $smtp_port, \App\Models\BranchConfig::get($prefered_branch_id, 'reply_to_email'));
		}
		
		if (!$res_email) {
			$error_message .= 'Failed to send application form to email. Code 2004';
		}

		/**
		 * 3. Create docusign envelope
		 */
		// Get docusign config info according to the prefered branch
		$branch_result = $db->table('epos_branches')->where('site_name', $prefered_branch)->get()->getRow();
		if (!$branch_result) {
			$error_message .= '\nBranch not found. Code 2006';
			return $this->response->setJSON([
				'success' => 0,
				'error' => $error_message
			]);
		}
		$prefered_branch_id = $branch_result->id;

		$result = (object) \App\Models\BranchConfig::getAll($prefered_branch_id);
		if (empty($result->docusign_user_id)) {
			$error_message .= '\nPrefered branch not found. Code 2007';
			return $this->response->setJSON([
				'success' => 0,
				'error' => $error_message
			]);
		}
		$docusign_company_signer_name  = $result->docusign_company_signer_name  ?? '';
		$docusign_company_signer_email = $result->docusign_company_signer_email ?? '';
		$integrationKey                = $result->docusign_integration_key      ?? '';
		$userId                        = $result->docusign_user_id              ?? '';
		$oauthBasePath                 = $result->docusign_oauth_base_path      ?? '';
		$basePath                      = ($result->docusign_account_base_uri    ?? '') . '/restapi';
		$docusign_account_id           = $result->docusign_account_id           ?? '';

		// Prepare data for docusign
		$data4docusign['signers'][] = [
			"email" => $contact_email,
			"name" => $busi_legal_nm,
			"full_name_anchor_string" => "/fn1/",
			"signed_anchor_string" => "/sn1/",
			"date_signed_anchor_string" => "/dt1/",
			"attachment_anchor_string1" => "/pat1/",
			"attachment_anchor_string2" => "/bat1/"
		];
		$newSigner = [
			"email" => $docusign_company_signer_email,
			"name" => $docusign_company_signer_name,
			"full_name_anchor_string" => "/fn2/",
			"signed_anchor_string" => "/sn2/",
			"date_signed_anchor_string" => "/dt2/"
		];
		$data4docusign['signers'][] = $newSigner;
		$data4docusign['email_subject'] = "New Account Application Form";
		$data4docusign['use_anchor_tags'] = true;
		
		$docusignApi = new DocusignApi();
		$html_content = $docusignApi->build_pdf_html_content($data4docusign);

		// Generate PDF
		// Note: This requires DomPDF library - install via: composer require dompdf/dompdf
		// For now, we'll create the PDF file directly using DomPDF if available

		// Check if DomPDF is available
		if (class_exists('\Dompdf\Dompdf')) {
			$dompdf = new \Dompdf\Dompdf();
			$dompdf->loadHtml($html_content);
			$dompdf->setPaper('A4', 'Portrait');
			// $dompdf->set_option('margin-left', '10mm');
			$dompdf->set_option('margin-right', '10mm');
			$dompdf->set_option('margin-top', '10mm');
			$dompdf->set_option('margin-bottom', '10mm');
			$dompdf->render();
			$pdf_content = $dompdf->output();
		} else {
			// Fallback: Return error if DomPDF is not installed
			$error_message .= '\nPDF library not installed. Please install DomPDF: composer require dompdf/dompdf. Code 2009';
			return $this->response->setJSON([
				'success' => 0,
				'error' => $error_message
			]);
		}
		// Read and encode PDF
		$documentBase64 = base64_encode($pdf_content);
		$documentName = basename('orderuk-contract.pdf');

		// Get access token
		$accessToken = $docusignApi->getJwtAccessToken($integrationKey, $userId, $oauthBasePath);
		
		if (!$accessToken) {
			$error_message .= '\nFailed to obtain access token. Code 2008';
			return $this->response->setJSON([
				'success' => 0,
				'error' => $error_message
			]);
		}

		// Determine if using anchor tags or absolute positioning
		$useAnchorTags = $data4docusign['use_anchor_tags'] ?? true;

		// Prepare signers with routing order
		$signers = [];
		foreach ($data4docusign['signers'] as $index => $signer) {
			$recipientId = (string)($index + 1);
			$routingOrder = (string)($index + 1);
			
			// Build tabs based on positioning method
			$tabs = [];
			
			if ($useAnchorTags && 
			!empty($signer['signed_anchor_string']) &&
			!empty($signer['date_signed_anchor_string'])) {
				// Use anchor string positioning (recommended for prepared PDFs)
				$tabs['fullNameTabs'] = [
					[
						"anchorString"=> $signer['full_name_anchor_string'],
						"anchorUnits"=> "pixels",
						"anchorXOffset"=> "0",
						"anchorYOffset"=> "0",
						"font"=> "Tahoma",
						"fontColor"=> "Purple",
						"tabLabel"=> "FullNameLabel"
					]
				];
				$tabs['signHereTabs'] = [
					[
						'anchorString' => $signer['signed_anchor_string'],
						'anchorUnits' => 'pixels',
						'anchorXOffset' => '0',
						'anchorYOffset' => '0',
					]
				];
				$tabs['dateSignedTabs'] = [
					[
						'anchorString' => $signer['date_signed_anchor_string'],
						'anchorUnits' => 'pixels',
						'anchorXOffset' => '0',
						'anchorYOffset' => '0',
						'tabLabel' => 'Date Signed',
					]
				];
				if ($index == 0) {
					$tabs['signerAttachmentTabs'] = [
						[
							'anchorString' => $signer['attachment_anchor_string1'],
							'anchorUnits' => 'pixels',
							'anchorXOffset' => '0',
							'anchorYOffset' => '0',
							'tabLabel' => 'Upload supporting document1',
							'required' => 'true',
						],
						[
							'anchorString' => $signer['attachment_anchor_string2'],
							'anchorUnits' => 'pixels',
							'anchorXOffset' => '0',
							'anchorYOffset' => '0',
							'tabLabel' => 'Upload supporting document2',
							'required' => 'true',
						]
					];
				}
			} else {
				// Use absolute positioning (fallback)
				$pageNumber = $signer['page_number'] ?? '1';
				$xPosition = $signer['x_position'] ?? '100';
				$yPosition = $signer['y_position'] ?? (string)(100 + ($index * 100));
				
				$tabs['signHereTabs'] = [
					[
						'documentId' => '1',
						'pageNumber' => $pageNumber,
						'xPosition' => $xPosition,
						'yPosition' => $yPosition
					]
				];
				$tabs['dateSignedTabs'] = [
					[
						'documentId' => '1',
						'pageNumber' => $pageNumber,
						'xPosition' => (string)((int)$xPosition + 200),
						'yPosition' => $yPosition
					]
				];
			}
			
			$signers[] = [
				'email' => $signer['email'],
				'name' => $signer['name'],
				'recipientId' => $recipientId,
				'routingOrder' => $routingOrder,
				'tabs' => $tabs
			];
		}

		// Prepare envelope data
		$envelopeData = [
			'emailSubject' => $data4docusign['email_subject'] ?? 'Please sign this document',
			'documents' => [
				[
					'documentBase64' => $documentBase64,
					'name' => $documentName,
					'fileExtension' => 'pdf',
					'documentId' => '1'
				]
			],
			'recipients' => [
				'signers' => $signers
			],
			'status' => 'sent'
		];

		// Send envelope via DocuSign API
		$result = $docusignApi->createEnvelope($accessToken, $envelopeData, $basePath, $docusign_account_id);
		
		$res_docusign = false;
		if ($result['envelopeId']) {
			$res_docusign = true;
		} else {
			$res_docusign = false;
		}
		
		if ($res_email) {
			$db->table('epos_customer_registration')->where('id', $registration_id)->update(['email_sended' => 1]);
		} else {
			$error_message .= 'Failed to send application form to email. Code 2004 \n';
		}
		if ($res_docusign) {
			$db->table('epos_customer_registration')->where('id', $registration_id)->update(['envelope_id' => $result['envelopeId']]);
		} else {
			$error_message .= 'Failed to create docusign envelope. Code 2005 \n';
		}

		if ($error_message) {
			return $this->response->setJSON([
				'success' => 0,
				'error' => $error_message
			]);
		} else {
			return $this->response->setJSON([
				'success' => 1,
				'message' => 'Application received ✔\nWe\'ve emailed you a secure link to complete the final step.\nPlease review and sign our Terms and Conditions and upload the documents needed to open your account.'
			]);
		}
	}

}

?>