| Server IP : 72.60.21.38 / Your IP : 216.73.216.25 Web Server : LiteSpeed System : Linux uk-fast-web1372.main-hosting.eu 4.18.0-553.121.1.lve.el8.x86_64 #1 SMP Thu Apr 30 16:40:41 UTC 2026 x86_64 User : u390967363 ( 390967363) PHP Version : 8.2.30 Disable Function : system, exec, shell_exec, passthru, mysql_list_dbs, ini_alter, dl, symlink, link, chgrp, leak, popen, apache_child_terminate, virtual, mb_send_mail MySQL : OFF | cURL : ON | WGET : ON | Perl : OFF | Python : OFF | Sudo : OFF | Pkexec : OFF Directory : /home/u390967363/domains/aibenproperties.com/public_html/app/ |
Upload File : |
<?php
session_start();
require_once 'includes/db.php';
require_once 'includes/functions.php';
$role = $_SESSION['user_role'] ?? 'guest';
if (!in_array($role, ['super_admin','admin','operations','customer_rep','contact_rep','finance','finance_manager','finance_officer'])) {
echo "<div class='container py-4'><div class='alert alert-danger'>Access Denied</div></div>";
require 'includes/footer.php';
exit;
}
$companyId = function_exists('getCurrentCompanyId') ? getCurrentCompanyId() : null;
$isFinance = in_array($role, ['finance','finance_manager','super_admin']);
$isCustCare = in_array($role, ['admin','operations','customer_rep','contact_rep','super_admin']);
$toast = '';
$toastType = 'success';
if (isset($_GET['ajax']) && $_GET['ajax'] === 'form_data') {
header('Content-Type: application/json; charset=UTF-8');
$id = isset($_GET['id']) ? (int)$_GET['id'] : 0;
$qEmail = isset($_GET['email']) ? trim($_GET['email']) : '';
$qName = isset($_GET['name']) ? trim($_GET['name']) : '';
$res = [];
try {
$st = $pdo->prepare("SELECT cf.*, u.name AS u_name, u.email AS u_email, u.phone AS u_phone FROM client_forms cf LEFT JOIN users u ON cf.client_id = u.id WHERE cf.id = ? LIMIT 1");
$st->execute([$id]);
$row = $st->fetch(PDO::FETCH_ASSOC) ?: [];
$data = [];
if (!empty($row['form_data'])) {
$raw = $row['form_data'];
$tmp = json_decode($raw, true);
if (!is_array($tmp)) {
$b = base64_decode($raw, true);
if ($b !== false) {
$tmp = json_decode($b, true);
}
}
if (!is_array($tmp) && is_string($tmp)) {
$tmp2 = json_decode($tmp, true);
if (is_array($tmp2)) { $tmp = $tmp2; }
}
if (is_array($tmp) && count($tmp) === 1) {
$only = reset($tmp);
if (is_string($only)) {
$tmp3 = json_decode($only, true);
if (is_array($tmp3)) { $tmp = $tmp3; }
} elseif (is_array($only)) {
$tmp = $only;
}
}
if (is_array($tmp)) $data = $tmp;
}
$uid = (int)($row['client_id'] ?? 0);
if (!$data && $uid > 0) {
try {
$q1 = $pdo->prepare("SELECT form_data FROM client_forms WHERE client_id = ? AND form_data IS NOT NULL AND form_data <> '' ORDER BY created_at DESC LIMIT 1");
$q1->execute([$uid]);
$fj = (string)($q1->fetchColumn() ?: '');
if ($fj !== '') {
$tmp = json_decode($fj, true);
if (!is_array($tmp)) {
$b = base64_decode($fj, true);
if ($b !== false) { $tmp = json_decode($b, true); }
}
if (!is_array($tmp) && is_string($tmp)) {
$t2 = json_decode($fj, true);
if (is_array($t2)) { $tmp = $t2; }
}
if (is_array($tmp) && count($tmp) > 0) { $data = $tmp; }
}
} catch (Throwable $e1) {}
if (!$data) {
try {
$qa = $pdo->prepare("SELECT form_data FROM client_forms WHERE client_id = ? ORDER BY created_at DESC");
$qa->execute([$uid]);
while ($rowA = $qa->fetch(PDO::FETCH_ASSOC)) {
$fj = (string)($rowA['form_data'] ?? '');
if ($fj === '') continue;
$tmp = json_decode($fj, true);
if (!is_array($tmp)) {
$b = base64_decode($fj, true);
if ($b !== false) { $tmp = json_decode($b, true); }
}
if (!is_array($tmp) && is_string($tmp)) {
$t2 = json_decode($fj, true);
if (is_array($t2)) { $tmp = $t2; }
}
if (is_array($tmp) && count($tmp) > 0) { $data = $tmp; break; }
}
} catch (Throwable $e1a) {}
}
if (!$data) {
try {
$qc = $pdo->prepare("SELECT * FROM clients WHERE id = ? LIMIT 1");
$qc->execute([$uid]);
$crow = $qc->fetch(PDO::FETCH_ASSOC) ?: [];
if ($crow) {
$data = [
'Full Name' => $crow['name'] ?? ($crow['client_name'] ?? ''),
'Email' => $crow['email'] ?? '',
'Phone' => $crow['phone'] ?? '',
'Address' => $crow['address'] ?? ($crow['residential_address'] ?? ($crow['home_address'] ?? ''))
];
}
} catch (Throwable $e1b) {}
}
if (!$data) {
try {
$qp = $pdo->prepare("SELECT meta_json FROM payments WHERE user_id = ? ORDER BY id DESC LIMIT 1");
$qp->execute([$uid]);
$mj = (string)($qp->fetchColumn() ?: '');
if ($mj !== '') {
$tmp = json_decode($mj, true);
if (is_array($tmp)) { $data = $tmp; }
}
} catch (Throwable $e1c) {}
}
if (!$data) {
try {
$em = ''; $nm = '';
$qeu = $pdo->prepare("SELECT email, name FROM users WHERE id = ? LIMIT 1");
$qeu->execute([$uid]);
$ur = $qeu->fetch(PDO::FETCH_ASSOC) ?: [];
if (!empty($ur['email'])) $em = $ur['email'];
if (!empty($ur['name'])) $nm = $ur['name'];
if (!$em || !$nm) {
$qec = $pdo->prepare("SELECT email, name FROM clients WHERE id = ? LIMIT 1");
$qec->execute([$uid]);
$cr = $qec->fetch(PDO::FETCH_ASSOC) ?: [];
if (!$em && !empty($cr['email'])) $em = $cr['email'];
if (!$nm && !empty($cr['name'])) $nm = $cr['name'];
}
if ($em) {
$qe2 = $pdo->prepare("SELECT form_data FROM client_forms WHERE form_data IS NOT NULL AND form_data <> '' AND form_data LIKE ? ORDER BY updated_at DESC, id DESC LIMIT 1");
$qe2->execute(['%'.$em.'%']);
$fj = (string)($qe2->fetchColumn() ?: '');
if ($fj !== '') {
$tmp = json_decode($fj, true);
if (!is_array($tmp)) {
$b = base64_decode($fj, true);
if ($b !== false) { $tmp = json_decode($b, true); }
}
if (!is_array($tmp) && is_string($tmp)) {
$t2 = json_decode($fj, true);
if (is_array($t2)) { $tmp = $t2; }
}
if (is_array($tmp)) { $data = $tmp; }
}
}
if (!$data && $nm) {
$qn2 = $pdo->prepare("SELECT form_data FROM client_forms WHERE form_data IS NOT NULL AND form_data <> '' AND form_data LIKE ? ORDER BY updated_at DESC, id DESC LIMIT 1");
$qn2->execute(['%'.$nm.'%']);
$fj = (string)($qn2->fetchColumn() ?: '');
if ($fj !== '') {
$tmp = json_decode($fj, true);
if (!is_array($tmp)) {
$b = base64_decode($fj, true);
if ($b !== false) { $tmp = json_decode($b, true); }
}
if (!is_array($tmp) && is_string($tmp)) {
$t2 = json_decode($fj, true);
if (is_array($t2)) { $tmp = $t2; }
}
if (is_array($tmp)) { $data = $tmp; }
}
}
} catch (Throwable $e1d) {}
}
}
if (!$data && $uid === 0 && $qEmail !== '') {
try {
$qe = $pdo->prepare("SELECT cf.form_data FROM client_forms cf JOIN users u ON cf.client_id = u.id WHERE u.email = ? AND cf.form_data IS NOT NULL AND cf.form_data <> '' ORDER BY cf.updated_at DESC, cf.id DESC LIMIT 1");
$qe->execute([$qEmail]);
$fj = (string)($qe->fetchColumn() ?: '');
if ($fj !== '') {
$tmp = json_decode($fj, true);
if (!is_array($tmp)) {
$b = base64_decode($fj, true);
if ($b !== false) { $tmp = json_decode($b, true); }
}
if (!is_array($tmp) && is_string($tmp)) {
$t2 = json_decode($fj, true);
if (is_array($t2)) { $tmp = $t2; }
}
if (is_array($tmp)) { $data = $tmp; }
}
} catch (Throwable $e2) {}
if (!$data) {
try {
$qc = $pdo->prepare("SELECT id FROM clients WHERE email = ? LIMIT 1");
$qc->execute([$qEmail]);
$cid = (int)($qc->fetchColumn() ?: 0);
if ($cid > 0) {
$q1 = $pdo->prepare("SELECT form_data FROM client_forms WHERE client_id = ? AND form_data IS NOT NULL AND form_data <> '' ORDER BY created_at DESC LIMIT 1");
$q1->execute([$cid]);
$fj = (string)($q1->fetchColumn() ?: '');
if ($fj !== '') {
$tmp = json_decode($fj, true);
if (!is_array($tmp)) {
$b = base64_decode($fj, true);
if ($b !== false) { $tmp = json_decode($b, true); }
}
if (!is_array($tmp) && is_string($tmp)) {
$t2 = json_decode($fj, true);
if (is_array($t2)) { $tmp = $t2; }
}
if (is_array($tmp)) { $data = $tmp; }
}
if (!$data) {
$qa = $pdo->prepare("SELECT form_data FROM client_forms WHERE client_id = ? ORDER BY created_at DESC");
$qa->execute([$cid]);
while ($rowA = $qa->fetch(PDO::FETCH_ASSOC)) {
$fj = (string)($rowA['form_data'] ?? '');
if ($fj === '') continue;
$tmp = json_decode($fj, true);
if (!is_array($tmp)) {
$b = base64_decode($fj, true);
if ($b !== false) { $tmp = json_decode($b, true); }
}
if (!is_array($tmp) && is_string($tmp)) {
$t2 = json_decode($fj, true);
if (is_array($t2)) { $tmp = $t2; }
}
if (is_array($tmp) && count($tmp) > 0) { $data = $tmp; break; }
}
}
}
} catch (Throwable $e2c) {}
}
if (!$data) {
try {
$qe2 = $pdo->prepare("SELECT form_data FROM client_forms WHERE form_data IS NOT NULL AND form_data <> '' AND form_data LIKE ? ORDER BY updated_at DESC, id DESC LIMIT 1");
$qe2->execute(['%'.$qEmail.'%']);
$fj = (string)($qe2->fetchColumn() ?: '');
if ($fj !== '') {
$tmp = json_decode($fj, true);
if (!is_array($tmp)) {
$b = base64_decode($fj, true);
if ($b !== false) { $tmp = json_decode($b, true); }
}
if (!is_array($tmp) && is_string($tmp)) {
$t2 = json_decode($fj, true);
if (is_array($t2)) { $tmp = $t2; }
}
if (is_array($tmp)) { $data = $tmp; }
}
} catch (Throwable $e2b) {}
}
}
if (!$data && $uid === 0 && $qName !== '') {
try {
$qn = $pdo->prepare("SELECT cf.form_data FROM client_forms cf JOIN users u ON cf.client_id = u.id WHERE u.name = ? AND cf.form_data IS NOT NULL AND cf.form_data <> '' ORDER BY cf.updated_at DESC, cf.id DESC LIMIT 1");
$qn->execute([$qName]);
$fj = (string)($qn->fetchColumn() ?: '');
if ($fj !== '') {
$tmp = json_decode($fj, true);
if (!is_array($tmp)) {
$b = base64_decode($fj, true);
if ($b !== false) { $tmp = json_decode($b, true); }
}
if (!is_array($tmp) && is_string($tmp)) {
$t2 = json_decode($fj, true);
if (is_array($t2)) { $tmp = $t2; }
}
if (is_array($tmp)) { $data = $tmp; }
}
} catch (Throwable $e3) {}
if (!$data) {
try {
$qc = $pdo->prepare("SELECT id FROM clients WHERE name = ? LIMIT 1");
$qc->execute([$qName]);
$cid = (int)($qc->fetchColumn() ?: 0);
if ($cid > 0) {
$q1 = $pdo->prepare("SELECT form_data FROM client_forms WHERE client_id = ? AND form_data IS NOT NULL AND form_data <> '' ORDER BY created_at DESC LIMIT 1");
$q1->execute([$cid]);
$fj = (string)($q1->fetchColumn() ?: '');
if ($fj !== '') {
$tmp = json_decode($fj, true);
if (!is_array($tmp)) {
$b = base64_decode($fj, true);
if ($b !== false) { $tmp = json_decode($b, true); }
}
if (!is_array($tmp) && is_string($tmp)) {
$t2 = json_decode($fj, true);
if (is_array($t2)) { $tmp = $t2; }
}
if (is_array($tmp)) { $data = $tmp; }
}
if (!$data) {
$qa = $pdo->prepare("SELECT form_data FROM client_forms WHERE client_id = ? ORDER BY created_at DESC");
$qa->execute([$cid]);
while ($rowA = $qa->fetch(PDO::FETCH_ASSOC)) {
$fj = (string)($rowA['form_data'] ?? '');
if ($fj === '') continue;
$tmp = json_decode($fj, true);
if (!is_array($tmp)) {
$b = base64_decode($fj, true);
if ($b !== false) { $tmp = json_decode($b, true); }
}
if (!is_array($tmp) && is_string($tmp)) {
$t2 = json_decode($fj, true);
if (is_array($t2)) { $tmp = $t2; }
}
if (is_array($tmp) && count($tmp) > 0) { $data = $tmp; break; }
}
}
}
} catch (Throwable $e3c) {}
}
if (!$data) {
try {
$qn2 = $pdo->prepare("SELECT form_data FROM client_forms WHERE form_data IS NOT NULL AND form_data <> '' AND form_data LIKE ? ORDER BY updated_at DESC, id DESC LIMIT 1");
$qn2->execute(['%'.$qName.'%']);
$fj = (string)($qn2->fetchColumn() ?: '');
if ($fj !== '') {
$tmp = json_decode($fj, true);
if (!is_array($tmp)) {
$b = base64_decode($fj, true);
if ($b !== false) { $tmp = json_decode($b, true); }
}
if (!is_array($tmp) && is_string($tmp)) {
$t2 = json_decode($fj, true);
if (is_array($t2)) { $tmp = $t2; }
}
if (is_array($tmp)) { $data = $tmp; }
}
} catch (Throwable $e3b) {}
}
}
$flat = [];
$stack = [];
if ($data && is_array($data)) { $stack[] = ['', $data]; }
while (!empty($stack)) {
list($prefix, $arr) = array_pop($stack);
foreach ($arr as $k=>$v) {
$key = is_string($k) ? $k : (string)$k;
$label = $prefix ? $prefix . ' ' . $key : $key;
if (is_array($v)) {
$stack[] = [$label, $v];
} else {
$flat[$label] = $v;
}
}
}
if (empty($flat)) {
if (!empty($row['u_name'])) $res['full_name'] = $row['u_name'];
if (!empty($row['u_email'])) $res['email'] = $row['u_email'];
if (!empty($row['u_phone'])) $res['phone'] = $row['u_phone'];
if ($uid > 0) {
try {
$uCols = [];
if (function_exists('tableHasColumn')) {
$cand = ['name','email','phone','address','residential_address','home_address','gender','date_of_birth','marital_status','nationality','state_of_origin','occupation','employer','office_address','whatsapp_phone','office_phone','referral_source','referral_other'];
foreach ($cand as $c) { if (tableHasColumn('users',$c)) { $uCols[] = $c; } }
} else {
$uCols = ['name','email','phone'];
}
if ($uCols) {
$sqlU = "SELECT " . implode(',', $uCols) . " FROM users WHERE id = ? LIMIT 1";
$su = $pdo->prepare($sqlU);
$su->execute([$uid]);
$urow = $su->fetch(PDO::FETCH_ASSOC) ?: [];
foreach ($urow as $k=>$v) { if ($v !== null && $v !== '') { $res[$k] = $v; } }
}
} catch (Throwable $eU) {}
}
} else {
$res = $flat;
}
if (empty($res['full_name']) && (isset($res['first_name']) || isset($res['last_name']))) {
$fn = trim((string)($res['first_name'] ?? ''));
$ln = trim((string)($res['last_name'] ?? ''));
$mn = trim((string)($res['middle_name'] ?? ''));
$nm = trim(($fn.' '.($mn !== '' ? $mn.' ' : '').$ln));
if ($nm !== '') { $res['full_name'] = $nm; }
}
$nameKeys = ['full_name','fullname','full name','company_name','company name','client_name','client name','name','first_name'];
foreach ($nameKeys as $nk) { if (isset($res[$nk]) && $res[$nk]) { $res['full_name'] = $res['full_name'] ?? $res[$nk]; } }
$emailKeys = ['email','email_address','email address','client_email','emailAddress'];
foreach ($emailKeys as $ek) { if (isset($res[$ek]) && $res[$ek]) { $res['email'] = $res[$ek]; break; } }
$phoneKeys = ['phone','phone_number','phone number','whatsapp_phone','office_phone','mobile','mobile_number','telephone','tel','contact_phone','contact phone','client_phone'];
foreach ($phoneKeys as $pk) { if (isset($res[$pk]) && $res[$pk]) { $res['phone'] = $res[$pk]; break; } }
$addrKeys = ['residential_address','residential address','address','home_address','home address','company_address','company address','office_address','contact_address','contact address','residentialAddress'];
foreach ($addrKeys as $ak) { if (isset($res[$ak]) && $res[$ak]) { $res['residential_address'] = $res[$ak]; break; } }
$passKeys = ['passport_photo_path','passport_photo','passportPhotoPath','passportPhoto','passport','passport_url'];
foreach ($passKeys as $pk) { if (isset($res[$pk]) && $res[$pk]) { $res['passport_photo_path'] = $res[$pk]; break; } }
$idKeys = ['id_document_path','id_document','id_card','idCard','national_id','nin_card'];
foreach ($idKeys as $ik) { if (isset($res[$ik]) && $res[$ik]) { $res['id_document_path'] = $res[$ik]; break; } }
if (!isset($res['dob'])) {
$dobKeys = ['dob','date_of_birth','birthdate','birth_date','dateOfBirth'];
foreach ($dobKeys as $dk) { if (isset($res[$dk]) && $res[$dk]) { $res['dob'] = $res[$dk]; break; } }
}
if (!isset($res['gender'])) {
$gKeys = ['gender','sex'];
foreach ($gKeys as $gk) { if (isset($res[$gk]) && $res[$gk]) { $res['gender'] = $res[$gk]; break; } }
}
if (!isset($res['marital_status'])) {
$msKeys = ['marital_status','maritalStatus','married'];
foreach ($msKeys as $mk) { if (isset($res[$mk]) && $res[$mk]) { $res['marital_status'] = $res[$mk]; break; } }
}
if (!isset($res['nationality'])) {
$nKeys = ['nationality','country','citizenship'];
foreach ($nKeys as $nk) { if (isset($res[$nk]) && $res[$nk]) { $res['nationality'] = $res[$nk]; break; } }
}
} catch (Throwable $e) {}
echo json_encode($res ?: new stdClass());
exit;
}
try {
$pdo->exec("
CREATE TABLE IF NOT EXISTS client_forms (
id INT AUTO_INCREMENT PRIMARY KEY,
company_id INT NULL,
client_id INT NOT NULL,
form_data TEXT NULL,
amount_due DECIMAL(12,2) NULL,
receipt_path VARCHAR(255) NULL,
status VARCHAR(50) NOT NULL DEFAULT 'draft',
created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
)
");
} catch (Exception $e) {}
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$action = $_POST['action'] ?? '';
$id = (int)($_POST['id'] ?? 0);
try {
if ($action === 'verify_payment' && $isFinance) {
$stmt = $pdo->prepare("UPDATE client_forms SET status = 'payment_verified', updated_at = CURRENT_TIMESTAMP WHERE id = ?");
$stmt->execute([$id]);
$toast = "Payment Verified";
} elseif ($action === 'approve_client' && $isCustCare) {
$stmt = $pdo->prepare("UPDATE client_forms SET status = 'payment_verified', updated_at = CURRENT_TIMESTAMP WHERE id = ?");
$stmt->execute([$id]);
$q = $pdo->prepare("SELECT * FROM client_forms WHERE id = ? LIMIT 1");
$q->execute([$id]);
$row = $q->fetch(PDO::FETCH_ASSOC);
$data = [];
if ($row && !empty($row['form_data'])) {
$tmp = json_decode($row['form_data'], true);
if (is_array($tmp)) { $data = $tmp; }
}
$name = $data['full_name'] ?? ($data['company_name'] ?? '');
$email = $data['email'] ?? '';
$phone = $data['phone'] ?? ($data['company_contact'] ?? '');
if ($email !== '' && $name !== '') {
$exists = $pdo->prepare("SELECT id FROM users WHERE email = ? LIMIT 1");
$exists->execute([$email]);
$userId = (int)($exists->fetchColumn() ?: 0);
if ($userId > 0) {
if (function_exists('tableHasColumn') && tableHasColumn('users','status')) {
$pdo->prepare("UPDATE users SET status = 'active' WHERE id = ?")->execute([$userId]);
}
} else {
$pwd = bin2hex(random_bytes(4));
$hash = password_hash($pwd, PASSWORD_DEFAULT);
$cols = ["name","email","password","role"];
$vals = [$name, $email, $hash, 'client'];
if (function_exists('tableHasColumn') && tableHasColumn('users','company_id') && $companyId) {
array_unshift($cols, "company_id");
array_unshift($vals, $companyId);
}
if (function_exists('tableHasColumn') && tableHasColumn('users','status')) {
$cols[] = "status";
$vals[] = "active";
}
if (function_exists('tableHasColumn') && tableHasColumn('users','phone') && $phone) {
$cols[] = "phone";
$vals[] = $phone;
}
$sql = "INSERT INTO users (" . implode(',', $cols) . ") VALUES (" . implode(',', array_fill(0, count($cols), '?')) . ")";
$ins = $pdo->prepare($sql);
$ins->execute($vals);
$userId = (int)$pdo->lastInsertId();
try {
$to = $email;
$companyName = getSetting('company_name', 'Aiben Properties');
$subject = getSetting('welcome_email_subject', "Welcome to $companyName");
$loginUrl = getSetting('app_url', 'http://localhost/Aibenproperties/index.php');
$defaultBody = "Dear {name},\n\nYour account has been created on {company}.\n\nLogin: {login_url}\nEmail: {email}\nTemporary Password: {password}\n\nPlease change your password after login.\n\nThank you,\n{company}";
$chairmanName = function_exists('ap_get_chairman_name') ? ap_get_chairman_name($companyId) : getSetting('chairman_name', 'Chairman / CEO');
$message = function_exists('ap_apply_placeholders')
? ap_apply_placeholders($defaultBody, [
'{name}' => $name,
'{company}' => $companyName,
'{chairman}' => (string)$chairmanName,
'{login_url}' => $loginUrl,
'{email}' => $email,
'{password}' => $pwd ?? '',
])
: str_replace(
['{name}','{company}','{chairman}','{login_url}','{email}','{password}'],
[$name,$companyName,(string)$chairmanName,$loginUrl,$email,$pwd ?? ''],
$defaultBody
);
if (function_exists('sendEmail')) { sendEmail($to, $subject, $message); }
} catch (Exception $e2) {}
}
if (!empty($userId)) {
$pdo->prepare("UPDATE client_forms SET client_id = ? WHERE id = ?")->execute([$userId, $id]);
}
}
$toast = "Payment verified and client profile created";
} elseif ($action === 'reject_client' && $isCustCare) {
$stmt = $pdo->prepare("UPDATE client_forms SET status = 'rejected', updated_at = CURRENT_TIMESTAMP WHERE id = ?");
$stmt->execute([$id]);
$toast = "Account Not verified";
$toastType = 'danger';
header("Location: customer-care-forms.php?view=error&msg=" . urlencode("Dear Client, your request was not approved. Please contact us for more details"));
exit;
} elseif ($action === 'create_client_account' && $isCustCare) {
$q = $pdo->prepare("SELECT * FROM client_forms WHERE id = ? LIMIT 1");
$q->execute([$id]);
$row = $q->fetch(PDO::FETCH_ASSOC);
if (!$row) { throw new Exception('Form not found'); }
if (($row['status'] ?? '') !== 'approved') { throw new Exception('Form must be approved'); }
$data = [];
if (!empty($row['form_data'])) {
$tmp = json_decode($row['form_data'], true);
if (is_array($tmp)) { $data = $tmp; }
}
$name = $data['full_name'] ?? ($data['company_name'] ?? '');
$email = $data['email'] ?? '';
$phone = $data['phone'] ?? ($data['company_contact'] ?? '');
if ($email === '' || $name === '') { throw new Exception('Missing name or email'); }
$exists = $pdo->prepare("SELECT id FROM users WHERE email = ? LIMIT 1");
$exists->execute([$email]);
$userId = (int)($exists->fetchColumn() ?: 0);
if ($userId > 0) {
if (function_exists('tableHasColumn') && tableHasColumn('users','status')) {
$pdo->prepare("UPDATE users SET status = 'active' WHERE id = ?")->execute([$userId]);
}
} else {
$pwd = bin2hex(random_bytes(4));
$hash = password_hash($pwd, PASSWORD_DEFAULT);
$cols = ["name","email","password","role"];
$vals = [$name, $email, $hash, 'client'];
if (function_exists('tableHasColumn') && tableHasColumn('users','company_id') && $companyId) {
array_unshift($cols, "company_id");
array_unshift($vals, $companyId);
}
if (function_exists('tableHasColumn') && tableHasColumn('users','status')) {
$cols[] = "status";
$vals[] = "active";
}
if (function_exists('tableHasColumn') && tableHasColumn('users','phone') && $phone) {
$cols[] = "phone";
$vals[] = $phone;
}
$sql = "INSERT INTO users (" . implode(',', $cols) . ") VALUES (" . implode(',', array_fill(0, count($cols), '?')) . ")";
$ins = $pdo->prepare($sql);
$ins->execute($vals);
$userId = (int)$pdo->lastInsertId();
}
if ($userId > 0) {
$pdo->prepare("UPDATE client_forms SET client_id = ? WHERE id = ?")->execute([$userId, $id]);
}
$toast = "Client account created";
try {
$to = $email;
$companyName = getSetting('company_name', 'Aiben Properties');
$subject = getSetting('welcome_email_subject', "Welcome to $companyName");
$loginUrl = getSetting('app_url', 'http://localhost/Aibenproperties/index.php');
$defaultBody = "Dear {name},\n\nYour account has been {status} on {company}.\n\nLogin: {login_url}\nEmail: {email}\n{password_line}\n\nFor security, please change your password after login.\n\nThank you,\n{company}";
$bodyTemplate = getSetting('welcome_email_body', $defaultBody);
$newlyCreated = ($row && empty($row['client_id'])) || (isset($pwd) && $pwd);
$passwordLine = $newlyCreated && isset($pwd) ? "Temporary Password: {password}" : '';
$chairmanName = function_exists('ap_get_chairman_name') ? ap_get_chairman_name($companyId) : getSetting('chairman_name', 'Chairman / CEO');
$repls = [
'{name}' => $name,
'{company}' => $companyName,
'{chairman}' => (string)$chairmanName,
'{login_url}' => $loginUrl,
'{email}' => $email,
'{password_line}' => $passwordLine,
'{password}' => $pwd ?? '',
'{status}' => ($newlyCreated ? 'created' : 'activated'),
];
$message = function_exists('ap_apply_placeholders')
? ap_apply_placeholders($bodyTemplate, $repls)
: str_replace(array_keys($repls), array_values($repls), $bodyTemplate);
if (function_exists('sendEmail')) { sendEmail($to, $subject, $message); }
} catch (Exception $e3) {}
}
} catch (Exception $e) {
$toast = $e->getMessage();
$toastType = 'danger';
}
header("Location: customer-care-forms.php?toast=" . urlencode($toast) . "&type=" . urlencode($toastType));
exit;
}
$filter = $_GET['filter'] ?? 'all';
$params = [];
$sql = "SELECT cf.*, u.name as client_name, u.email as client_email FROM client_forms cf LEFT JOIN users u ON cf.client_id = u.id WHERE 1=1";
if ($companyId) { $sql .= " AND cf.company_id = ?"; $params[] = $companyId; }
if ($filter === 'awaiting') {
$sql .= " AND cf.status IN ('receipt_uploaded','sent_to_accounts')";
} elseif ($filter === 'verified') {
$sql .= " AND cf.status = 'payment_verified'";
} elseif ($filter === 'approved') {
$sql .= " AND cf.status = 'approved'";
}
$sql .= " ORDER BY cf.created_at DESC";
$stmt = $pdo->prepare($sql);
$stmt->execute($params);
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
require 'includes/header.php';
if (isset($_GET['view']) && $_GET['view'] === 'error') {
$msg = $_GET['msg'] ?? 'An error occurred';
$supportUrl = 'customer-care.php';
echo "<div class='container py-4'><div class='card shadow-sm'><div class='card-body'>";
echo "<div class='alert alert-danger mb-3'>".htmlspecialchars($msg)."</div>";
echo "<a class='btn btn-outline-primary' href='".htmlspecialchars($supportUrl)."'>Contact Us</a>";
echo "</div></div></div>";
require 'includes/footer.php';
exit;
}
if (isset($_GET['toast'])) {
$cls = ($_GET['type'] ?? 'success') === 'danger' ? 'alert-danger' : 'alert-success';
echo "<div class='container py-2'><div class='alert {$cls}'>" . htmlspecialchars($_GET['toast']) . "</div></div>";
}
?>
<div class="container-fluid px-4">
<style>
.ccfq-table-scroll{display:block;width:100%;max-width:100%;overflow:auto !important;overflow-x:auto !important;overflow-y:hidden;-webkit-overflow-scrolling:touch;touch-action:pan-x pan-y;cursor:grab}
.ccfq-table-scroll.ccfq-grabbing{cursor:grabbing}
.table-responsive.ccfq-table-scroll{overflow:auto !important;overflow-x:auto !important;overflow-y:hidden}
.ccfq-table{width:max-content;min-width:860px}
.ccfq-table th,.ccfq-table td{white-space:nowrap !important}
.ccfq-table td.ccfq-primary{white-space:normal;min-width:240px}
.ccfq-actions{display:inline-flex;flex-wrap:wrap;gap:.35rem;align-items:center;justify-content:flex-end}
.ccfq-actions form{display:inline-block;margin:0}
@media (max-width:576px){
.ccfq-actions{justify-content:flex-start}
.ccfq-actions .btn{padding:.25rem .45rem}
}
</style>
<div class="d-flex justify-content-between align-items-center mt-4 mb-4">
<h1 class="h3 mb-0">Client Forms Queue</h1>
<div class="btn-group btn-group-sm">
<a href="?filter=all" class="btn <?= $filter==='all'?'btn-primary':'btn-outline-primary' ?>">All</a>
<a href="?filter=awaiting" class="btn <?= $filter==='awaiting'?'btn-primary':'btn-outline-primary' ?>">Awaiting</a>
<a href="?filter=verified" class="btn <?= $filter==='verified'?'btn-primary':'btn-outline-primary' ?>">Verified</a>
<a href="?filter=approved" class="btn <?= $filter==='approved'?'btn-primary':'btn-outline-primary' ?>">Approved</a>
</div>
</div>
<div class="card shadow-sm">
<div class="card-body">
<div class="d-sm-none text-muted small border-bottom pb-2 mb-2">Swipe left/right to see all columns.</div>
<div class="table-responsive ccfq-table-scroll">
<table class="table table-hover align-middle ccfq-table">
<thead class="table-light">
<tr>
<th class="d-none d-md-table-cell">Date</th>
<th>Client</th>
<th>Amount</th>
<th>Status</th>
<th>Receipt</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
<?php if (empty($rows)): ?>
<tr><td colspan="6" class="text-center text-muted py-4">No forms found</td></tr>
<?php else: foreach ($rows as $r): ?>
<tr>
<?php $createdLabel = !empty($r['created_at']) ? date('M d, Y', strtotime($r['created_at'])) : '-'; ?>
<td class="d-none d-md-table-cell"><?= htmlspecialchars($createdLabel) ?></td>
<td class="ccfq-primary">
<?php
$derived = ['name'=>'','email'=>''];
$rawFd = $r['form_data'] ?? '';
$decodedFd = null;
if ($rawFd) {
$tmp = json_decode($rawFd, true);
if (!is_array($tmp)) {
$b = base64_decode($rawFd, true);
if ($b !== false) { $tmp = json_decode($b, true); }
}
if (!is_array($tmp) && is_string($tmp)) {
$t2 = json_decode($tmp, true);
if (is_array($t2)) { $tmp = $t2; }
}
if (is_array($tmp) && count($tmp) === 1) {
$only = reset($tmp);
if (is_string($only)) {
$t3 = json_decode($only, true);
if (is_array($t3)) { $tmp = $t3; }
} elseif (is_array($only)) {
$tmp = $only;
}
}
if (is_array($tmp)) { $decodedFd = $tmp; }
}
if (is_array($decodedFd)) {
$nameKeys = ['full_name','fullname','full name','company_name','company name','client_name','client name','name'];
foreach ($nameKeys as $nk) { if (!empty($decodedFd[$nk])) { $derived['name'] = $decodedFd[$nk]; break; } }
$emailKeys = ['email','email_address','email address'];
foreach ($emailKeys as $ek) { if (!empty($decodedFd[$ek])) { $derived['email'] = $decodedFd[$ek]; break; } }
}
$dispName = $r['client_name'] ?: $derived['name'];
$dispEmail = $r['client_email'] ?: $derived['email'];
if (empty($dispName) && !empty($r['client_id'])) {
try {
$qcList = $pdo->prepare("SELECT name, email FROM clients WHERE id = ? LIMIT 1");
$qcList->execute([(int)$r['client_id']]);
$cl = $qcList->fetch(PDO::FETCH_ASSOC) ?: [];
if (!empty($cl['name'])) $dispName = $cl['name'];
if (!empty($cl['email'])) $dispEmail = $cl['email'];
} catch (Throwable $eL) {}
}
?>
<div class="fw-bold"><?= htmlspecialchars($dispName ?? '') ?></div>
<div class="small text-muted"><?= htmlspecialchars($dispEmail ?? '') ?></div>
<div class="small text-muted d-md-none"><?= htmlspecialchars($createdLabel) ?></div>
</td>
<td class="fw-bold text-success"><?= formatCurrency($r['amount_due'] ?? 0) ?></td>
<td><span class="badge bg-info"><?= htmlspecialchars($r['status']) ?></span></td>
<td>
<?php if (!empty($r['receipt_path'])): ?>
<a class="btn btn-sm btn-outline-secondary" target="_blank" href="<?= htmlspecialchars($r['receipt_path']) ?>">View</a>
<?php else: ?>
<span class="text-muted">-</span>
<?php endif; ?>
</td>
<td>
<div class="ccfq-actions">
<?php
$formDataB64 = base64_encode($r['form_data'] ?? '{}');
if (empty($r['form_data']) && !empty($r['client_id'])) {
try {
$stx = $pdo->prepare("SELECT form_data FROM client_forms WHERE client_id = ? AND form_data IS NOT NULL AND form_data <> '' ORDER BY created_at DESC LIMIT 1");
$stx->execute([(int)$r['client_id']]);
$fj = (string)($stx->fetchColumn() ?: '');
if ($fj !== '') {
$formDataB64 = base64_encode($fj);
$tmp2 = json_decode($fj, true);
if (!is_array($tmp2)) {
$b2 = base64_decode($fj, true);
if ($b2 !== false) { $tmp2 = json_decode($b2, true); }
}
if (!is_array($tmp2) && is_string($tmp2)) {
$t22 = json_decode($fj, true);
if (is_array($t22)) { $tmp2 = $t22; }
}
if (is_array($tmp2) && count($tmp2) > 0) { $decodedFd = $tmp2; }
}
} catch (Throwable $e) {}
if (!is_array($decodedFd)) {
try {
$stxa = $pdo->prepare("SELECT form_data FROM client_forms WHERE client_id = ? ORDER BY created_at DESC");
$stxa->execute([(int)$r['client_id']]);
while ($ra = $stxa->fetch(PDO::FETCH_ASSOC)) {
$fj = (string)($ra['form_data'] ?? '');
if ($fj === '') continue;
$tmp2 = json_decode($fj, true);
if (!is_array($tmp2)) {
$b2 = base64_decode($fj, true);
if ($b2 !== false) { $tmp2 = json_decode($b2, true); }
}
if (!is_array($tmp2) && is_string($tmp2)) {
$t22 = json_decode($fj, true);
if (is_array($t22)) { $tmp2 = $t22; }
}
if (is_array($tmp2) && count($tmp2) > 0) {
$decodedFd = $tmp2;
$formDataB64 = base64_encode($fj);
break;
}
}
} catch (Throwable $eA) {}
}
if (!is_array($decodedFd)) {
try {
$qc2 = $pdo->prepare("SELECT * FROM clients WHERE id = ? LIMIT 1");
$qc2->execute([(int)$r['client_id']]);
$crow = $qc2->fetch(PDO::FETCH_ASSOC) ?: [];
if ($crow) {
$tmp2 = [
'Full Name' => $crow['name'] ?? ($crow['client_name'] ?? ''),
'Email' => $crow['email'] ?? '',
'Phone' => $crow['phone'] ?? '',
'Address' => $crow['address'] ?? ($crow['residential_address'] ?? ($crow['home_address'] ?? ''))
];
$decodedFd = $tmp2;
$formDataB64 = base64_encode(json_encode($tmp2));
}
} catch (Throwable $eC) {}
}
if (!is_array($decodedFd)) {
try {
$qp2 = $pdo->prepare("SELECT meta_json FROM payments WHERE user_id = ? ORDER BY id DESC LIMIT 1");
$qp2->execute([(int)$r['client_id']]);
$mj = (string)($qp2->fetchColumn() ?: '');
if ($mj !== '') {
$tmp2 = json_decode($mj, true);
if (is_array($tmp2)) {
$decodedFd = $tmp2;
$formDataB64 = base64_encode(json_encode($tmp2));
}
}
} catch (Throwable $eP) {}
}
} elseif (empty($r['form_data'])) {
try {
$emailFind = $dispEmail ?? '';
if ($emailFind !== '') {
$qc3 = $pdo->prepare("SELECT id FROM clients WHERE email = ? LIMIT 1");
$qc3->execute([$emailFind]);
$cid = (int)($qc3->fetchColumn() ?: 0);
if ($cid > 0) {
$stx = $pdo->prepare("SELECT form_data FROM client_forms WHERE client_id = ? AND form_data IS NOT NULL AND form_data <> '' ORDER BY created_at DESC LIMIT 1");
$stx->execute([$cid]);
$fj = (string)($stx->fetchColumn() ?: '');
if ($fj !== '') {
$formDataB64 = base64_encode($fj);
$tmp2 = json_decode($fj, true);
if (!is_array($tmp2)) {
$b2 = base64_decode($fj, true);
if ($b2 !== false) { $tmp2 = json_decode($b2, true); }
}
if (!is_array($tmp2) && is_string($tmp2)) {
$t22 = json_decode($fj, true);
if (is_array($t22)) { $tmp2 = $t22; }
}
if (is_array($tmp2) && count($tmp2) > 0) { $decodedFd = $tmp2; }
}
if (!is_array($decodedFd)) {
$stxa = $pdo->prepare("SELECT form_data FROM client_forms WHERE client_id = ? ORDER BY created_at DESC");
$stxa->execute([$cid]);
while ($ra = $stxa->fetch(PDO::FETCH_ASSOC)) {
$fj = (string)($ra['form_data'] ?? '');
if ($fj === '') continue;
$tmp2 = json_decode($fj, true);
if (!is_array($tmp2)) {
$b2 = base64_decode($fj, true);
if ($b2 !== false) { $tmp2 = json_decode($b2, true); }
}
if (!is_array($tmp2) && is_string($tmp2)) {
$t22 = json_decode($fj, true);
if (is_array($t22)) { $tmp2 = $t22; }
}
if (is_array($tmp2) && count($tmp2) > 0) {
$decodedFd = $tmp2;
$formDataB64 = base64_encode($fj);
break;
}
}
}
}
}
} catch (Throwable $eE) {}
if (!is_array($decodedFd) && !empty($dispEmail)) {
try {
$qe2 = $pdo->prepare("SELECT form_data FROM client_forms WHERE form_data IS NOT NULL AND form_data <> '' AND form_data LIKE ? ORDER BY updated_at DESC, id DESC LIMIT 1");
$qe2->execute(['%'.$dispEmail.'%']);
$fj = (string)($qe2->fetchColumn() ?: '');
if ($fj !== '') {
$formDataB64 = base64_encode($fj);
$tmp2 = json_decode($fj, true);
if (!is_array($tmp2)) {
$b2 = base64_decode($fj, true);
if ($b2 !== false) { $tmp2 = json_decode($b2, true); }
}
if (!is_array($tmp2) && is_string($tmp2)) {
$t22 = json_decode($fj, true);
if (is_array($t22)) { $tmp2 = $t22; }
}
if (is_array($tmp2) && count($tmp2) > 0) { $decodedFd = $tmp2; }
}
} catch (Throwable $eE2) {}
}
}
?>
<?php if (!empty($_GET['debug']) && ($_GET['debug']==='1' || $_GET['debug']==='on')): ?>
<div class="small text-muted"><pre style="white-space:pre-wrap;max-height:120px;overflow:auto;"><?= htmlspecialchars($r['form_data'] ?? '') ?></pre></div>
<?php endif; ?>
<?php
$attrName = htmlspecialchars($dispName ?? '');
$attrEmail = htmlspecialchars($dispEmail ?? '');
?>
<button type="button"
class="btn btn-sm btn-outline-secondary"
data-bs-toggle="modal"
data-bs-target="#formDetailsModal"
data-id="<?= (int)$r['id'] ?>"
data-client="<?= $attrName ?>"
data-email="<?= $attrEmail ?>"
data-amount="<?= htmlspecialchars((string)($r['amount_due'] ?? '0')) ?>"
data-receipt="<?= htmlspecialchars($r['receipt_path'] ?? '') ?>"
data-form="<?= htmlspecialchars($formDataB64) ?>"
data-status="<?= htmlspecialchars($r['status'] ?? '') ?>">
Details
</button>
<?php if ($isFinance && in_array($r['status'], ['sent_to_accounts','payment_verification'])): ?>
<form method="POST">
<input type="hidden" name="id" value="<?= (int)$r['id'] ?>">
<button class="btn btn-sm btn-primary" name="action" value="verify_payment">Verify Payment</button>
</form>
<?php endif; ?>
<?php if ($isCustCare && ($r['status'] ?? '') === 'approved'): ?>
<form method="POST">
<input type="hidden" name="id" value="<?= (int)$r['id'] ?>">
<button class="btn btn-sm btn-dark" name="action" value="create_client_account">Create Client Account</button>
</form>
<?php endif; ?>
</div>
</td>
</tr>
<?php endforeach; endif; ?>
</tbody>
</table>
</div>
</div>
</div>
</div>
<!-- DETAILS MODAL -->
<div class="modal fade" id="formDetailsModal" tabindex="-1" aria-labelledby="formDetailsLabel" aria-hidden="true">
<div class="modal-dialog modal-xl modal-dialog-centered modal-dialog-scrollable">
<div class="modal-content modal-premium">
<div class="modal-header">
<img id="ccAvatarImg" src="" alt="" style="width:56px;height:56px;border-radius:50%;object-fit:cover;display:none;">
<h5 class="modal-title" id="formDetailsLabel"><i class="fa-solid fa-id-card me-2"></i>Client Submission Details</h5>
<button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<div class="modal-body">
<div class="row g-3">
<div class="col-md-6">
<div class="card shadow-sm">
<div class="card-header bg-white">
<strong>Profile & Contact</strong>
</div>
<div class="card-body" id="detailsProfile">
<div class="text-muted">Loading…</div>
</div>
</div>
</div>
<div class="col-md-6">
<div class="card shadow-sm">
<div class="card-header bg-white">
<strong>Attachments</strong>
</div>
<div class="card-body" id="detailsAttachments">
<div class="text-muted">Loading…</div>
</div>
</div>
</div>
</div>
<div class="mt-3">
<div class="card shadow-sm">
<div class="card-header bg-white">
<strong>Application Data</strong>
</div>
<div class="card-body" id="detailsData">
<div class="text-muted">Loading…</div>
</div>
</div>
</div>
</div>
<div class="modal-footer">
<div class="me-auto d-flex gap-2">
<?php if ($isCustCare): ?>
<form method="POST" id="approveForm">
<input type="hidden" name="id" id="approveId" value="">
<button type="submit" name="action" value="approve_client" class="btn btn-success">
<i class="fa-solid fa-check me-1"></i> Approve
</button>
</form>
<form method="POST" id="rejectForm">
<input type="hidden" name="id" id="rejectId" value="">
<button type="submit" name="action" value="reject_client" class="btn btn-danger">
<i class="fa-solid fa-xmark me-1"></i> Reject
</button>
</form>
<?php endif; ?>
</div>
<form method="POST" id="createClientForm">
<input type="hidden" name="id" id="createClientId" value="">
<button type="submit" name="action" value="create_client_account" class="btn btn-dark" id="createClientBtn" style="display:none;">
<i class="fa-solid fa-user-check me-1"></i> Create Client Account
</button>
</form>
<button type="button" class="btn btn-outline-secondary" data-bs-dismiss="modal">Close</button>
</div>
</div>
</div>
<script>
document.getElementById('formDetailsModal').addEventListener('show.bs.modal', function (ev) {
var btn = ev.relatedTarget;
var id = btn.getAttribute('data-id');
var client = btn.getAttribute('data-client') || '';
var email = btn.getAttribute('data-email') || '';
var amount = btn.getAttribute('data-amount') || '';
var receipt = btn.getAttribute('data-receipt') || '';
var formB64 = btn.getAttribute('data-form') || '';
var status = btn.getAttribute('data-status') || '';
function tryParse(s) {
if (!s) return {};
try { return JSON.parse(s); } catch(e) {}
try { return JSON.parse(atob(s)); } catch(e2) {}
try { var b = atob(s); return JSON.parse(b); } catch(e3) {}
return {};
}
function normalizeObj(d) {
if (!d) return {};
if (typeof d === 'string') {
try { d = JSON.parse(d); } catch(e) { d = {}; }
}
if (d && typeof d === 'object') {
var ks = Object.keys(d);
if (ks.length === 1) {
var only = d[ks[0]];
if (typeof only === 'string') {
try { var t = JSON.parse(only); if (t && typeof t === 'object') d = t; } catch(e) {}
} else if (only && typeof only === 'object') {
d = only;
}
}
}
return d && typeof d === 'object' ? d : {};
}
var data = normalizeObj(tryParse(formB64));
var ap = document.getElementById('approveId');
if (ap) ap.value = id;
var rj = document.getElementById('rejectId');
if (rj) rj.value = id;
document.getElementById('createClientId').value = id;
function findBySubstr(d, subs){
var out = '';
try {
var keys = Object.keys(d||{});
for (var i=0;i<keys.length;i++){
var k = keys[i];
for (var j=0;j<subs.length;j++){
if (k.toLowerCase().indexOf(subs[j]) !== -1) {
var v = d[k];
if (v) { return v; }
}
}
}
} catch(e){}
return out;
}
function render(d){
d = d || {};
var fullName = d.full_name || d.fullname || (function(){
var fn = d.first_name || d.firstname || '';
var mn = d.middle_name || d.middlename || '';
var ln = d.last_name || d.lastname || '';
var nm = (fn?fn+' ':'') + (mn?mn+' ':'') + ln;
return nm.trim();
})() || client || '-';
var emailV = d.email || d.email_address || d['email address'] || email || '-';
var phoneV = d.phone || d.phone_number || d['phone number'] || d.whatsapp_phone || d.office_phone || d.mobile || d.mobile_number || d.telephone || d.tel || d.contact_phone || findBySubstr(d, ['phone','mobile','whatsapp']) || '-';
var addrV = d.residential_address || d.address || d.home_address || d.company_address || d.office_address || d.contact_address || findBySubstr(d, ['address']) || '-';
var purposeV = d.purpose || findBySubstr(d, ['purpose']) || '-';
var applStat = d.applicant_status || d.applicantStatus || '-';
var genderV = d.gender || d.sex || findBySubstr(d, ['gender','sex']) || '-';
var dobV = d.dob || d.date_of_birth || d.birthdate || d.birth_date || findBySubstr(d, ['birth','dob']) || '-';
var maritalV = d.marital_status || d.maritalStatus || findBySubstr(d, ['marital']) || '-';
var nationV = d.nationality || d.country || d.citizenship || findBySubstr(d, ['national','country']) || '-';
var passPath = d.passport_photo_path || d.passport_photo || d.passportPhotoPath || d.passportPhoto || d.passport || d.passport_url || '';
var imgEl = document.getElementById('ccAvatarImg');
if (passPath && imgEl) { imgEl.src = passPath; imgEl.style.display = 'block'; }
var profHtml = '<div class="row g-2">';
profHtml += '<div class="col-12"><div class="fw-bold">'+ fullName +'</div><div class="text-muted small">'+ emailV +'</div></div>';
profHtml += '<div class="col-6"><span class="text-muted small">Phone</span><div>'+ phoneV +'</div></div>';
profHtml += '<div class="col-6"><span class="text-muted small">Residential Address</span><div>'+ addrV +'</div></div>';
profHtml += '<div class="col-6"><span class="text-muted small">Purpose</span><div>'+ purposeV +'</div></div>';
profHtml += '<div class="col-6"><span class="text-muted small">Applicant Status</span><div>'+ applStat +'</div></div>';
profHtml += '<div class="col-6"><span class="text-muted small">Gender</span><div>'+ genderV +'</div></div>';
profHtml += '<div class="col-6"><span class="text-muted small">DOB</span><div>'+ dobV +'</div></div>';
profHtml += '<div class="col-6"><span class="text-muted small">Marital Status</span><div>'+ maritalV +'</div></div>';
profHtml += '<div class="col-6"><span class="text-muted small">Nationality</span><div>'+ nationV +'</div></div>';
profHtml += '</div>';
document.getElementById('detailsProfile').innerHTML = profHtml;
var attHtml = '<div class="d-flex flex-wrap gap-2">';
if (receipt) {
attHtml += '<a class="btn btn-sm btn-outline-secondary" target="_blank" href="'+receipt+'"><i class="fa-solid fa-receipt me-1"></i>Receipt</a>';
}
if (d.passport_photo_path) {
attHtml += '<a class="btn btn-sm btn-outline-primary" target="_blank" href="'+d.passport_photo_path+'"><i class="fa-regular fa-id-badge me-1"></i>Passport Photo</a>';
}
if (d.id_document_path) {
attHtml += '<a class="btn btn-sm btn-outline-dark" target="_blank" href="'+d.id_document_path+'"><i class="fa-solid fa-id-card me-1"></i>ID Document</a>';
}
attHtml += '</div>';
document.getElementById('detailsAttachments').innerHTML = attHtml;
var keys = Object.keys(d || {}).sort();
var table = '<div class="table-responsive"><table class="table table-sm"><tbody>';
if (keys.length === 0) {
table += '<tr><td class="text-muted">No valid onboarding data found</td></tr>';
} else {
keys.forEach(function(k){
var v = d[k];
if (v && typeof v === 'object') { try { v = JSON.stringify(v); } catch(e) { v = String(v); } }
var label = k.replace(/_/g,' ').replace(/\b\w/g,function(m){return m.toUpperCase();});
table += '<tr><th class="w-25">'+label+'</th><td>'+ (v || '-') +'</td></tr>';
});
}
table += '</tbody></table></div>';
var amtLine = '<div class="alert alert-info mb-3"><i class="fa-solid fa-sack-dollar me-1"></i> Amount Due: <strong>'+ (amount || '0') +'</strong></div>';
document.getElementById('detailsData').innerHTML = amtLine + table;
var createBtn = document.getElementById('createClientBtn');
if (status === 'approved') { createBtn.style.display = 'inline-block'; } else { createBtn.style.display = 'none'; }
}
var qs = 'customer-care-forms.php?ajax=form_data&id=' + encodeURIComponent(id);
if (email) { qs += '&email=' + encodeURIComponent(email); }
if (client) { qs += '&name=' + encodeURIComponent(client); }
var base = data && typeof data === 'object' ? data : {};
fetch(qs)
.then(function(r){return r.json();})
.then(function(j){
var jn = normalizeObj(j);
var merged = {};
Object.keys(base).forEach(function(k){ merged[k]=base[k]; });
if (jn && typeof jn === 'object') { Object.keys(jn).forEach(function(k){ if (merged[k] == null || merged[k] === '') { merged[k]=jn[k]; } }); }
render(merged);
})
.catch(function(){ render(base); });
});
</script>
<script>
(function(){
var el = document.querySelector('.ccfq-table-scroll');
if (!el) return;
var isDown = false;
var startX = 0;
var scrollLeft = 0;
el.addEventListener('mousedown', function(e){
if (e.button !== 0) return;
if (e.target && e.target.closest('a,button,input,select,textarea,label,.modal,.dropdown-menu')) return;
isDown = true;
el.classList.add('ccfq-grabbing');
startX = e.pageX;
scrollLeft = el.scrollLeft;
});
document.addEventListener('mouseup', function(){
if (!isDown) return;
isDown = false;
el.classList.remove('ccfq-grabbing');
});
document.addEventListener('mousemove', function(e){
if (!isDown) return;
var walk = (e.pageX - startX);
el.scrollLeft = scrollLeft - walk;
});
})();
</script>
</div>
<?php require 'includes/footer.php'; ?>