<?php
session_start();

require_once __DIR__ . '/../includes/helpers.php';
require_once __DIR__ . '/../includes/layout.php';

if (!isset($_SESSION['authenticated'])) {
    redirect(page_url('signin'));
}

function settings_money(float $amount): string
{
    return '&#8377;' . number_format($amount, 2);
}

function settings_normalize_tab(string $value): string
{
    $value = strtolower(trim($value));

    return match ($value) {
        'preferences', 'userpreferences', 'user_preferences' => 'preferences',
        'travel', 'traveldetails', 'travel_details' => 'travel',
        'budgets', 'budget' => 'budgets',
        default => 'basic',
    };
}

function settings_normalize_travel_tab(string $value): string
{
    $value = strtolower(trim($value));

    return match ($value) {
        'loyalty', 'loyaltyprograms', 'loyalty_programs' => 'loyalty',
        'documents', 'traveldocuments', 'travel_documents' => 'documents',
        default => 'profile',
    };
}

function settings_format_date_display(?string $value): string
{
    $value = trim((string) $value);
    if ($value === '') {
        return '';
    }

    $date = DateTime::createFromFormat('Y-m-d', $value);
    if ($date instanceof DateTime) {
        return $date->format('d/m/Y');
    }

    return $value;
}

function settings_mask_account_number(string $value): string
{
    $digits = preg_replace('/\D+/', '', $value);
    if ($digits === '') {
        return '';
    }

    $visible = substr($digits, -4);
    return str_repeat('*', max(0, strlen($digits) - 4)) . $visible;
}

function settings_delegate_access_label(array $delegate): string
{
    if (!empty($delegate['can_approve'])) {
        return !empty($delegate['can_create']) && !empty($delegate['can_submit']) ? 'Submit and approve access' : 'Approve access';
    }

    return 'Submit access';
}

function settings_labelize(string $value): string
{
    $value = trim($value);
    if ($value === '') {
        return '-';
    }

    $value = str_replace(['_', '-'], ' ', $value);
    return ucwords($value);
}

function settings_parse_date_input(string $value): ?string
{
    $value = trim($value);
    if ($value === '') {
        return null;
    }

    $formats = ['d/m/Y', 'd-m-Y', 'Y-m-d'];
    foreach ($formats as $format) {
        $date = DateTime::createFromFormat($format, $value);
        if ($date instanceof DateTime && $date->format($format) === $value) {
            return $date->format('Y-m-d');
        }
    }

    return null;
}

function settings_store_uploaded_file(array $file, string $relativeDir, string $prefix, array $allowedExtensions = ['pdf', 'jpg', 'jpeg', 'png', 'webp']): string
{
    if (($file['error'] ?? UPLOAD_ERR_NO_FILE) !== UPLOAD_ERR_OK || empty($file['tmp_name'])) {
        return '';
    }

    $originalName = trim((string) ($file['name'] ?? ''));
    $extension = strtolower(pathinfo($originalName, PATHINFO_EXTENSION));
    if ($extension === '' || !in_array($extension, $allowedExtensions, true)) {
        return '';
    }

    $relativeDir = trim($relativeDir, '/');
    $absoluteDir = __DIR__ . '/../' . $relativeDir;
    if (!is_dir($absoluteDir)) {
        mkdir($absoluteDir, 0777, true);
    }

    $fileName = $prefix . '_' . time() . '_' . bin2hex(random_bytes(4)) . '.' . $extension;
    $absolutePath = $absoluteDir . '/' . $fileName;

    if (!move_uploaded_file((string) $file['tmp_name'], $absolutePath)) {
        return '';
    }

    return $relativeDir . '/' . $fileName;
}

function settings_ensure_travel_document_columns(): void
{
    $columns = [
        'document_country' => 'VARCHAR(100) NOT NULL DEFAULT ""',
        'document_number' => 'VARCHAR(120) NOT NULL DEFAULT ""',
        'issued_on' => 'DATE NULL DEFAULT NULL',
        'valid_from' => 'DATE NULL DEFAULT NULL',
        'expires_on' => 'DATE NULL DEFAULT NULL',
        'consent_given' => 'TINYINT(1) NOT NULL DEFAULT 0',
    ];

    foreach ($columns as $columnName => $definition) {
        $exists = fetch_one(
            'SELECT 1
             FROM information_schema.columns
             WHERE table_schema = DATABASE()
               AND table_name = ?
               AND column_name = ?
             LIMIT 1',
            'ss',
            ['user_travel_documents', $columnName]
        );

        if (!$exists) {
            db()->query('ALTER TABLE user_travel_documents ADD COLUMN ' . $columnName . ' ' . $definition);
        }
    }
}

function settings_ensure_loyalty_program_columns(): void
{
    $columns = [
        'program_type' => 'VARCHAR(120) NOT NULL DEFAULT ""',
        'program_number' => 'VARCHAR(100) NOT NULL DEFAULT ""',
    ];

    foreach ($columns as $columnName => $definition) {
        $exists = fetch_one(
            'SELECT 1
             FROM information_schema.columns
             WHERE table_schema = DATABASE()
               AND table_name = ?
               AND column_name = ?
             LIMIT 1',
            'ss',
            ['user_loyalty_programs', $columnName]
        );

        if (!$exists) {
            db()->query('ALTER TABLE user_loyalty_programs ADD COLUMN ' . $columnName . ' ' . $definition);
        }
    }
}

$userId = (int) ($_SESSION['user_id'] ?? 0);
$displayName = trim((string) ($_SESSION['user_company'] ?? 'Expense user'));
$workspace = trim((string) ($_SESSION['workspace_name'] ?? 'demo'));
$email = trim((string) ($_SESSION['user_email'] ?? ''));

if ($displayName === '') {
    $displayName = 'Expense user';
}

if ($workspace === '') {
    $workspace = 'demo';
}

$settingsSuccess = flash('settings_success');
$settingsError = flash('settings_error');

$organization = null;
if ($userId > 0) {
    $organization = fetch_one(
        'SELECT id, organization_name
         FROM organizations
         WHERE user_id = ?
         ORDER BY id DESC
         LIMIT 1',
        'i',
        [$userId]
    );
    settings_ensure_travel_document_columns();
    settings_ensure_loyalty_program_columns();
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['settings_action'])) {
    $action = trim((string) ($_POST['settings_action'] ?? ''));
    $failureRedirect = page_url('my_settings', 'navType=basic');
    $fail = static function (string $message) use (&$failureRedirect): void {
        flash('settings_error', $message);
        redirect($failureRedirect);
    };

    if ($userId <= 0) {
        $fail('Your account is not ready yet.');
    }

    if ($action === 'save_bank_account') {
        $accountHolderName = trim((string) ($_POST['account_holder_name'] ?? ''));
        $bankName = trim((string) ($_POST['bank_name'] ?? ''));
        $accountNumber = trim((string) ($_POST['account_number'] ?? ''));
        $retypeAccountNumber = trim((string) ($_POST['retype_account_number'] ?? ''));
        $accountType = strtolower(trim((string) ($_POST['account_type'] ?? 'savings')));
        $ifscCode = strtoupper(trim((string) ($_POST['ifsc_code'] ?? '')));
        $allowedAccountTypes = ['savings', 'current', 'salary', 'other'];

        if ($accountHolderName === '') {
            $fail('Please enter the account holder name.');
        } elseif ($bankName === '') {
            $fail('Please enter the bank name.');
        } elseif ($accountNumber === '') {
            $fail('Please enter the account number.');
        } elseif ($retypeAccountNumber === '') {
            $fail('Please retype the account number.');
        } elseif ($accountNumber !== $retypeAccountNumber) {
            $fail('The account numbers do not match.');
        } elseif (!in_array($accountType, $allowedAccountTypes, true)) {
            $fail('Please select a valid account type.');
        } elseif ($ifscCode === '') {
            $fail('Please enter the IFSC code.');
        } else {
            $conn = db();
            $conn->begin_transaction();

            $deactivated = execute_query(
                'UPDATE user_bank_accounts
                 SET status = "inactive", is_primary = 0
                 WHERE user_id = ? AND status = "active"',
                'i',
                [$userId]
            );

            $insertId = $deactivated >= 0 ? execute_query(
                'INSERT INTO user_bank_accounts
                    (user_id, bank_name, account_holder_name, account_number, ifsc_code, account_type, is_primary, status)
                 VALUES (?, ?, ?, ?, ?, ?, 1, "active")',
                'isssss',
                [
                    $userId,
                    $bankName,
                    $accountHolderName,
                    $accountNumber,
                    $ifscCode,
                    $accountType,
                ]
            ) : -1;

            if ($deactivated >= 0 && $insertId > 0) {
                $conn->commit();
                flash('settings_success', 'Saved successfully.');
                redirect(page_url('my_settings', 'navType=basic'));
            }

            $conn->rollback();
            $fail('Unable to save the bank account.');
        }
    }

    if ($action === 'save_ooa') {
        $approverUserId = (int) ($_POST['approver_user_id'] ?? 0);
        $startDate = settings_parse_date_input((string) ($_POST['start_date'] ?? ''));
        $endDate = settings_parse_date_input((string) ($_POST['end_date'] ?? ''));

        if ($approverUserId <= 0) {
            $fail('Please select an out of office approver.');
        } elseif ($startDate === null) {
            $fail('Please enter a valid start date.');
        } elseif ($endDate === null) {
            $fail('Please enter a valid end date.');
        } elseif ($endDate < $startDate) {
            $fail('End date cannot be earlier than start date.');
        } else {
            $approver = fetch_one(
                'SELECT id, business_name, email
                 FROM users
                 WHERE id = ?
                 LIMIT 1',
                'i',
                [$approverUserId]
            );

            if (!$approver) {
                $fail('Selected approver could not be found.');
            } else {
                $conn = db();
                $conn->begin_transaction();

                $deactivated = execute_query(
                    'UPDATE user_out_of_office_approvers
                     SET status = "inactive", is_primary = 0
                     WHERE user_id = ? AND status = "active"',
                    'i',
                    [$userId]
                );

                $insertId = $deactivated >= 0 ? execute_query(
                    'INSERT INTO user_out_of_office_approvers
                        (user_id, approver_name, approver_email, can_approve, start_date, end_date, is_primary, status)
                     VALUES (?, ?, ?, 1, ?, ?, 1, "active")',
                    'issss',
                    [
                        $userId,
                        trim((string) $approver['business_name']),
                        trim((string) $approver['email']),
                        $startDate,
                        $endDate,
                    ]
                ) : -1;

                if ($deactivated >= 0 && $insertId > 0) {
                    $conn->commit();
                    flash('settings_success', 'Saved successfully.');
                    redirect(page_url('my_settings', 'navType=basic'));
                }

                $conn->rollback();
                $fail('Unable to save the out of office approver.');
            }
        }
    } elseif ($action === 'delete_ooa') {
        $conn = db();
        $conn->begin_transaction();

        $updated = execute_query(
            'UPDATE user_out_of_office_approvers
             SET status = "inactive", is_primary = 0
             WHERE user_id = ? AND status = "active"',
            'i',
            [$userId]
        );

        if ($updated >= 0) {
            $conn->commit();
            flash('settings_success', 'Saved successfully.');
            redirect(page_url('my_settings', 'navType=basic'));
        }

        $conn->rollback();
        $fail('Unable to delete the out of office approver.');
    }

    if ($action === 'save_delegate') {
        $delegateUserId = (int) ($_POST['delegate_user_id'] ?? 0);
        $startDate = settings_parse_date_input((string) ($_POST['delegate_start_date'] ?? ''));
        $endDate = settings_parse_date_input((string) ($_POST['delegate_end_date'] ?? ''));
        $accessType = strtolower(trim((string) ($_POST['delegate_access_type'] ?? 'submit')));

        if ($delegateUserId <= 0) {
            $fail('Please select a delegate.');
        } elseif ($startDate === null) {
            $fail('Please enter a valid start date.');
        } elseif ($endDate === null) {
            $fail('Please enter a valid end date.');
        } elseif ($endDate < $startDate) {
            $fail('End date cannot be earlier than start date.');
        } else {
            $delegateUser = fetch_one(
                'SELECT id, business_name, email
                 FROM users
                 WHERE id = ?
                 LIMIT 1',
                'i',
                [$delegateUserId]
            );

            if (!$delegateUser) {
                $fail('Selected delegate could not be found.');
            }

            $canCreate = 1;
            $canSubmit = 1;
            $canApprove = 0;

            if ($accessType === 'approve') {
                $canCreate = 0;
                $canSubmit = 0;
                $canApprove = 1;
            } elseif ($accessType === 'submit_approve') {
                $canApprove = 1;
            } else {
                $accessType = 'submit';
            }

            $conn = db();
            $conn->begin_transaction();

            $deactivated = execute_query(
                'UPDATE user_delegates
                 SET status = "inactive", is_primary = 0
                 WHERE user_id = ? AND status = "active"',
                'i',
                [$userId]
            );

            $insertId = $deactivated >= 0 ? execute_query(
                'INSERT INTO user_delegates
                    (user_id, delegate_name, delegate_email, can_create, can_submit, can_approve, start_date, end_date, is_primary, status)
                 VALUES (?, ?, ?, ?, ?, ?, ?, ?, 1, "active")',
                'issiiiss',
                [
                    $userId,
                    trim((string) $delegateUser['business_name']),
                    trim((string) $delegateUser['email']),
                    $canCreate,
                    $canSubmit,
                    $canApprove,
                    $startDate,
                    $endDate,
                ]
            ) : -1;

            if ($deactivated >= 0 && $insertId > 0) {
                $conn->commit();
                flash('settings_success', 'Saved successfully.');
                redirect(page_url('my_settings', 'navType=basic'));
            }

            $conn->rollback();
            $fail('Unable to save the delegate.');
        }
    }

    if ($action === 'save_travel_profile') {
        $failureRedirect = page_url('my_settings', 'navType=travel&travelTab=profile');
        $passportName = trim((string) ($_POST['passport_name'] ?? ''));
        $workPhone = trim((string) ($_POST['work_phone'] ?? ''));
        $homeAddress = trim((string) ($_POST['home_address'] ?? ''));

        if ($passportName === '') {
            $fail('Please enter the passport name.');
        } elseif ($workPhone === '') {
            $fail('Please enter the work phone.');
        } elseif ($homeAddress === '') {
            $fail('Please enter the home address.');
        } else {
            $existingTravelProfile = fetch_one(
                'SELECT id
                 FROM user_travel_profiles
                 WHERE user_id = ?
                 ORDER BY id DESC
                 LIMIT 1',
                'i',
                [$userId]
            );

            $saved = $existingTravelProfile
                ? execute_query(
                    'UPDATE user_travel_profiles
                     SET passport_name = ?, work_phone = ?, home_address = ?, status = "active"
                     WHERE id = ?',
                    'sssi',
                    [$passportName, $workPhone, $homeAddress, (int) $existingTravelProfile['id']]
                )
                : execute_query(
                    'INSERT INTO user_travel_profiles (user_id, passport_name, work_phone, home_address, status)
                     VALUES (?, ?, ?, ?, "active")',
                    'isss',
                    [$userId, $passportName, $workPhone, $homeAddress]
                );

            if ($saved >= 0) {
                flash('settings_success', 'Saved successfully.');
                redirect(page_url('my_settings', 'navType=travel&travelTab=profile'));
            }

            $fail('Unable to save the travel profile.');
        }
    }

    if ($action === 'save_loyalty_program') {
        $failureRedirect = page_url('my_settings', 'navType=travel&travelTab=loyalty');
        $programType = strtolower(trim((string) ($_POST['program_type'] ?? 'frequent_flyer')));
        $programName = trim((string) ($_POST['program_name'] ?? ''));
        $programNumber = trim((string) ($_POST['program_number'] ?? ''));
        $allowedProgramTypes = ['frequent_flyer', 'hotel', 'car_rental'];

        if ($userId <= 0 || (int) ($organization['id'] ?? 0) <= 0) {
            $fail('Your account is not ready yet.');
        } elseif (!in_array($programType, $allowedProgramTypes, true)) {
            $fail('Please select a valid program type.');
        } elseif ($programName === '') {
            $fail('Please select a program name.');
        } elseif ($programNumber === '') {
            $fail('Please enter the program number.');
        } else {
            $existingLoyaltyProgram = fetch_one(
                'SELECT id
                 FROM user_loyalty_programs
                 WHERE user_id = ?
                 ORDER BY id DESC
                 LIMIT 1',
                'i',
                [$userId]
            );

            $saved = $existingLoyaltyProgram
                ? execute_query(
                    'UPDATE user_loyalty_programs
                     SET program_type = ?, program_name = ?, program_number = ?, provider_name = ?, membership_number = ?, status = "active"
                     WHERE id = ?',
                    'sssssi',
                    [$programType, $programName, $programNumber, $programType, $programNumber, (int) $existingLoyaltyProgram['id']]
                )
                : execute_query(
                    'INSERT INTO user_loyalty_programs (organization_id, user_id, program_type, program_name, program_number, provider_name, membership_number, status)
                     VALUES (?, ?, ?, ?, ?, ?, ?, "active")',
                    'iisssss',
                    [$organization['id'] ?? 0, $userId, $programType, $programName, $programNumber, $programType, $programNumber]
                );

            if ($saved >= 0) {
                flash('settings_success', 'Saved successfully.');
                redirect(page_url('my_settings', 'navType=travel&travelTab=loyalty'));
            }

            $fail('Unable to save the loyalty program.');
        }
    }

    if ($action === 'save_travel_document') {
        $failureRedirect = page_url('my_settings', 'navType=travel&travelTab=documents');
        $documentType = strtolower(trim((string) ($_POST['document_type'] ?? 'passport')));
        $documentCountry = trim((string) ($_POST['document_country'] ?? ''));
        $documentNumber = trim((string) ($_POST['document_number'] ?? ''));
        $issuedOn = settings_parse_date_input((string) ($_POST['issued_on'] ?? ''));
        $validFrom = settings_parse_date_input((string) ($_POST['valid_from'] ?? ''));
        $expiresOn = settings_parse_date_input((string) ($_POST['expires_on'] ?? ''));
        $consentGiven = isset($_POST['consent_given']) ? 1 : 0;
        $existingFilePath = trim((string) ($_POST['existing_file_path'] ?? ''));
        $uploadedFilePath = settings_store_uploaded_file($_FILES['document_file'] ?? [], 'uploads/travel_documents', 'travel_document');
        $filePath = $uploadedFilePath !== '' ? $uploadedFilePath : $existingFilePath;
        $allowedDocumentTypes = ['passport', 'visa', 'id_card', 'other'];

        if ($userId <= 0 || (int) ($organization['id'] ?? 0) <= 0) {
            $fail('Your account is not ready yet.');
        } elseif (!in_array($documentType, $allowedDocumentTypes, true)) {
            $fail('Please select a valid document type.');
        } elseif ($documentCountry === '') {
            $fail('Please select a country.');
        } elseif ($documentNumber === '') {
            $fail('Please enter the document number.');
        } elseif ($issuedOn === null) {
            $fail('Please enter a valid issued date.');
        } elseif ($validFrom === null) {
            $fail('Please enter a valid start date.');
        } elseif ($expiresOn === null) {
            $fail('Please enter a valid expiry date.');
        } elseif ($expiresOn < $validFrom) {
            $fail('Expiry date cannot be earlier than the start date.');
        } elseif ($filePath === '') {
            $fail('Please attach a document file.');
        } elseif ($consentGiven !== 1) {
            $fail('Please accept the authorization checkbox.');
        } else {
            $existingTravelDocument = fetch_one(
                'SELECT id
                 FROM user_travel_documents
                 WHERE user_id = ?
                 ORDER BY id DESC
                 LIMIT 1',
                'i',
                [$userId]
            );

            $saved = $existingTravelDocument
                ? execute_query(
                    'UPDATE user_travel_documents
                     SET document_name = ?, document_type = ?, document_country = ?, document_number = ?, issued_on = ?, valid_from = ?, expires_on = ?, file_path = ?, consent_given = 1, status = "active"
                     WHERE id = ?',
                    'ssssssssi',
                    [
                        $documentType . ' ' . $documentCountry,
                        $documentType,
                        $documentCountry,
                        $documentNumber,
                        $issuedOn,
                        $validFrom,
                        $expiresOn,
                        $filePath,
                        (int) $existingTravelDocument['id'],
                    ]
                )
                : execute_query(
                    'INSERT INTO user_travel_documents (organization_id, user_id, travel_profile_id, document_name, document_type, document_country, document_number, issued_on, valid_from, expires_on, file_path, consent_given, status)
                     VALUES (?, ?, NULL, ?, ?, ?, ?, ?, ?, ?, ?, ?, 1, "active")',
                    'iisssssssss',
                    [
                        (int) ($organization['id'] ?? 0),
                        $userId,
                        $documentType . ' ' . $documentCountry,
                        $documentType,
                        $documentCountry,
                        $documentNumber,
                        $issuedOn,
                        $validFrom,
                        $expiresOn,
                        $filePath,
                        $consentGiven,
                    ]
                );

            if ($saved >= 0) {
                flash('settings_success', 'Saved successfully.');
                redirect(page_url('my_settings', 'navType=travel&travelTab=documents'));
            }

            $fail('Unable to save the travel document.');
        }
    }

    if ($action === 'save_trip_defaults') {
        $tripType = trim((string) ($_POST['trip_type'] ?? 'Business'));
        $travelMode = trim((string) ($_POST['travel_mode'] ?? 'Economy'));
        $billableTo = trim((string) ($_POST['billable_to'] ?? 'Personal'));
        $projectName = trim((string) ($_POST['project_name'] ?? ''));
        $clientName = trim((string) ($_POST['client_name'] ?? ''));
        $defaultCurrency = trim((string) ($_POST['default_currency'] ?? 'INR'));

        $existingTripDefaults = fetch_one(
            'SELECT id
             FROM user_default_trip_values
             WHERE user_id = ?
             ORDER BY id DESC
             LIMIT 1',
            'i',
            [$userId]
        );

        $saved = $existingTripDefaults
            ? execute_query(
                'UPDATE user_default_trip_values
                 SET trip_type = ?, travel_mode = ?, billable_to = ?, project_name = ?, client_name = ?, default_currency = ?
                 WHERE id = ?',
                'ssssssi',
                [$tripType, $travelMode, $billableTo, $projectName, $clientName, $defaultCurrency, (int) $existingTripDefaults['id']]
            )
            : execute_query(
                'INSERT INTO user_default_trip_values (user_id, trip_type, travel_mode, billable_to, project_name, client_name, default_currency)
                 VALUES (?, ?, ?, ?, ?, ?, ?)',
                'issssss',
                [$userId, $tripType, $travelMode, $billableTo, $projectName, $clientName, $defaultCurrency]
            );

        if ($saved >= 0) {
            flash('settings_success', 'Saved successfully.');
            redirect(page_url('my_settings', 'navType=preferences'));
        }

        $fail('Unable to save the trip default values.');
    }

    if ($action === 'save_expense_defaults') {
        $expenseCategory = trim((string) ($_POST['expense_category'] ?? ''));
        $expenseType = trim((string) ($_POST['expense_type'] ?? ''));
        $paymentMode = trim((string) ($_POST['payment_mode'] ?? 'Cash'));
        $defaultCurrency = trim((string) ($_POST['default_currency'] ?? 'INR'));
        $taxIncluded = isset($_POST['tax_included']) ? 1 : 0;
        $comments = trim((string) ($_POST['comments'] ?? ''));

        $existingExpenseDefaults = fetch_one(
            'SELECT id
             FROM user_default_expense_values
             WHERE user_id = ?
             ORDER BY id DESC
             LIMIT 1',
            'i',
            [$userId]
        );

        $saved = $existingExpenseDefaults
            ? execute_query(
                'UPDATE user_default_expense_values
                 SET expense_category = ?, expense_type = ?, payment_mode = ?, default_currency = ?, tax_included = ?, comments = ?
                 WHERE id = ?',
                'ssssisi',
                [$expenseCategory, $expenseType, $paymentMode, $defaultCurrency, $taxIncluded, $comments, (int) $existingExpenseDefaults['id']]
            )
            : execute_query(
                'INSERT INTO user_default_expense_values (user_id, expense_category, expense_type, payment_mode, default_currency, tax_included, comments)
                 VALUES (?, ?, ?, ?, ?, ?, ?)',
                'issssis',
                [$userId, $expenseCategory, $expenseType, $paymentMode, $defaultCurrency, $taxIncluded, $comments]
            );

        if ($saved >= 0) {
            flash('settings_success', 'Saved successfully.');
            redirect(page_url('my_settings', 'navType=preferences'));
        }

        $fail('Unable to save the expense default values.');
    }
}

$activeTab = settings_normalize_tab((string) ($_GET['navType'] ?? $_GET['tab'] ?? 'basic'));
$activeTravelTab = settings_normalize_travel_tab((string) ($_GET['travelTab'] ?? 'profile'));

$profile = [
    'display_name' => $displayName,
    'email' => $email !== '' ? $email : 'balachandarkathir@gmail.com',
    'employee_id' => '2520',
    'mobile_number' => '-',
    'department' => 'it',
    'date_of_joining' => '05/03/2026',
    'date_of_birth' => '05/10/2002',
    'designation' => 'deve',
    'role_name' => 'Admin',
    'submits_to' => '-',
    'policy_name' => 'demo',
];

$bankAccount = [
    'bank_name' => 'HDFC Bank',
    'account_holder_name' => $displayName,
    'account_number' => 'XXXX XXXX XXXX 2520',
    'ifsc_code' => 'HDFC0002520',
    'account_type' => 'savings',
];
$bankAccountExists = false;

$delegate = [
    'name' => '',
    'email' => '',
    'start_date' => '',
    'end_date' => '',
    'access_type' => 'submit',
];
$delegateExists = false;
$previousDelegates = [];

$outOfOfficeApprover = [
    'name' => '',
    'email' => '',
    'start_date' => '',
    'end_date' => '',
];

$receiptForwarding = [
    'forward_email' => 'balachandark.n896parg_zhs2xq54@inbox.zohoexpense.in',
    'provider' => 'Gmail',
];

$travelProfile = [
    'passport_name' => $displayName,
    'work_phone' => $profile['mobile_number'] === '-' ? '' : $profile['mobile_number'],
    'home_address' => 'Add details such as your name, work phone, and address.',
];
$travelProfileExists = false;

$travelDocument = [
    'document_name' => '',
    'document_type' => 'passport',
    'document_country' => '',
    'document_number' => '',
    'issued_on' => '',
    'valid_from' => '',
    'expires_on' => '',
    'file_path' => '',
    'consent_given' => 0,
];
$travelDocumentExists = false;

$travelLoyaltyProgram = [
    'program_type' => 'frequent_flyer',
    'program_name' => '',
    'program_number' => '',
];
$travelLoyaltyProgramExists = false;

$tripDefaults = [
    'trip_type' => 'Business',
    'travel_mode' => 'Economy',
    'billable_to' => 'Personal',
    'project_name' => '',
    'client_name' => '',
    'default_currency' => 'INR',
];
$tripDefaultsExists = false;

$expenseDefaults = [
    'expense_category' => '',
    'expense_type' => '',
    'payment_mode' => 'Cash',
    'default_currency' => 'INR',
    'tax_included' => 0,
    'comments' => '',
];
$expenseDefaultsExists = false;

$budgetPeriod = [
    'label' => 'Apr 2026 - Mar 2027',
    'count' => 0,
];

$budgetPeriods = [
    'Apr 2022 - Mar 2023',
    'Apr 2023 - Mar 2024',
    'Apr 2024 - Mar 2025',
    'Apr 2025 - Mar 2026',
    'Apr 2026 - Mar 2027',
];

$travelDocumentCountries = [
    'India',
    'United States',
    'United Kingdom',
    'Canada',
    'Australia',
    'Singapore',
    'United Arab Emirates',
];

$travelProgramNameOptions = [
    'frequent_flyer' => [
        'Select',
        'AAdvantage',
        'SkyMiles',
        'MileagePlus',
        'Executive Club',
        'Flying Blue',
    ],
    'hotel' => [
        'Select',
        'Marriott Bonvoy',
        'Hilton Honors',
        'World of Hyatt',
        'IHG One Rewards',
        'Accor Live Limitless',
    ],
    'car_rental' => [
        'Select',
        'Hertz Gold Plus Rewards',
        'Avis Preferred',
        'Enterprise Plus',
        'Budget Fastbreak',
        'National Emerald Club',
    ],
];

if ($userId > 0) {
    $dbProfile = fetch_one('SELECT * FROM user_profiles WHERE user_id = ? LIMIT 1', 'i', [$userId]);
    if ($dbProfile) {
        $profile['display_name'] = trim((string) ($dbProfile['display_name'] ?? '')) ?: $profile['display_name'];
        $profile['employee_id'] = trim((string) ($dbProfile['employee_id'] ?? '')) ?: $profile['employee_id'];
        $profile['mobile_number'] = trim((string) ($dbProfile['mobile_number'] ?? '')) ?: $profile['mobile_number'];
        $profile['department'] = trim((string) ($dbProfile['department'] ?? '')) ?: $profile['department'];
        $profile['date_of_joining'] = trim((string) ($dbProfile['date_of_joining'] ?? '')) ?: $profile['date_of_joining'];
        $profile['date_of_birth'] = trim((string) ($dbProfile['date_of_birth'] ?? '')) ?: $profile['date_of_birth'];
        $profile['designation'] = trim((string) ($dbProfile['designation'] ?? '')) ?: $profile['designation'];
        $profile['role_name'] = trim((string) ($dbProfile['role_name'] ?? '')) ?: $profile['role_name'];
        $profile['submits_to'] = trim((string) ($dbProfile['submits_to'] ?? '')) ?: $profile['submits_to'];
        $profile['policy_name'] = trim((string) ($dbProfile['policy_name'] ?? '')) ?: $profile['policy_name'];
        if ($profile['display_name'] === '') {
            $profile['display_name'] = $displayName;
        }
    }

    $dbOrganization = fetch_one(
        'SELECT organization_name, organization_location, state_union_territory, industry
         FROM organizations
         WHERE user_id = ?
         ORDER BY id DESC
         LIMIT 1',
        'i',
        [$userId]
    );
    if ($dbOrganization && $profile['policy_name'] === 'demo') {
        $profile['policy_name'] = trim((string) ($dbOrganization['organization_name'] ?? '')) ?: 'demo';
    }

    $dbBank = fetch_one(
        'SELECT bank_name, account_holder_name, account_number, ifsc_code, account_type
         FROM user_bank_accounts
         WHERE user_id = ?
         ORDER BY is_primary DESC, id DESC
         LIMIT 1',
        'i',
        [$userId]
    );
    if ($dbBank) {
        $bankAccount['bank_name'] = trim((string) ($dbBank['bank_name'] ?? '')) ?: $bankAccount['bank_name'];
        $bankAccount['account_holder_name'] = trim((string) ($dbBank['account_holder_name'] ?? '')) ?: $bankAccount['account_holder_name'];
        $bankAccount['account_number'] = trim((string) ($dbBank['account_number'] ?? '')) ?: $bankAccount['account_number'];
        $bankAccount['ifsc_code'] = trim((string) ($dbBank['ifsc_code'] ?? '')) ?: $bankAccount['ifsc_code'];
        $bankAccount['account_type'] = trim((string) ($dbBank['account_type'] ?? 'savings')) ?: 'savings';
        $bankAccountExists = true;
    }

    $dbDelegate = fetch_one(
        'SELECT delegate_name, delegate_email
         FROM user_delegates
         WHERE user_id = ? AND status = "active"
         ORDER BY is_primary DESC, id DESC
         LIMIT 1',
        'i',
        [$userId]
    );
    if ($dbDelegate) {
        $delegate['name'] = trim((string) ($dbDelegate['delegate_name'] ?? ''));
        $delegate['email'] = trim((string) ($dbDelegate['delegate_email'] ?? ''));
        $delegate['start_date'] = settings_format_date_display((string) ($dbDelegate['start_date'] ?? ''));
        $delegate['end_date'] = settings_format_date_display((string) ($dbDelegate['end_date'] ?? ''));
        $delegate['access_type'] = !empty($dbDelegate['can_approve'])
            ? (!empty($dbDelegate['can_create']) && !empty($dbDelegate['can_submit']) ? 'submit_approve' : 'approve')
            : 'submit';
        $delegateExists = true;
    }
    $previousDelegates = fetch_all(
        'SELECT delegate_name, delegate_email, start_date, end_date, can_create, can_submit, can_approve, status
         FROM user_delegates
         WHERE user_id = ?
         ORDER BY id DESC
         LIMIT 5',
        'i',
        [$userId]
    );

    $dbOoa = fetch_one(
        'SELECT approver_name, approver_email, start_date, end_date
         FROM user_out_of_office_approvers
         WHERE user_id = ? AND status = "active"
         ORDER BY is_primary DESC, id DESC
         LIMIT 1',
        'i',
        [$userId]
    );
    if ($dbOoa) {
        $outOfOfficeApprover['name'] = trim((string) ($dbOoa['approver_name'] ?? ''));
        $outOfOfficeApprover['email'] = trim((string) ($dbOoa['approver_email'] ?? ''));
        $outOfOfficeApprover['start_date'] = settings_format_date_display((string) ($dbOoa['start_date'] ?? ''));
        $outOfOfficeApprover['end_date'] = settings_format_date_display((string) ($dbOoa['end_date'] ?? ''));
    }

    $dbForwarding = fetch_one(
        'SELECT forward_email, provider_name
         FROM user_receipt_forwarding
         WHERE user_id = ? AND is_enabled = 1
         ORDER BY id DESC
         LIMIT 1',
        'i',
        [$userId]
    );
    if ($dbForwarding) {
        $receiptForwarding['forward_email'] = trim((string) ($dbForwarding['forward_email'] ?? '')) ?: $receiptForwarding['forward_email'];
        $receiptForwarding['provider'] = trim((string) ($dbForwarding['provider_name'] ?? '')) ?: $receiptForwarding['provider'];
    }

    $dbTravelProfile = fetch_one(
        'SELECT passport_name, work_phone, home_address
         FROM user_travel_profiles
         WHERE user_id = ? AND status = "active"
         ORDER BY id DESC
         LIMIT 1',
        'i',
        [$userId]
    );
    if ($dbTravelProfile) {
        $travelProfile['passport_name'] = trim((string) ($dbTravelProfile['passport_name'] ?? '')) ?: $travelProfile['passport_name'];
        $travelProfile['work_phone'] = trim((string) ($dbTravelProfile['work_phone'] ?? '')) ?: $travelProfile['work_phone'];
        $travelProfile['home_address'] = trim((string) ($dbTravelProfile['home_address'] ?? '')) ?: $travelProfile['home_address'];
        $travelProfileExists = true;
    }

    $dbTravelDocument = fetch_one(
        'SELECT document_name, document_type, document_country, document_number, issued_on, valid_from, expires_on, file_path, consent_given
         FROM user_travel_documents
         WHERE user_id = ? AND status = "active"
         ORDER BY id DESC
         LIMIT 1',
        'i',
        [$userId]
    );
    if ($dbTravelDocument) {
        $travelDocument['document_name'] = trim((string) ($dbTravelDocument['document_name'] ?? '')) ?: $travelDocument['document_name'];
        $travelDocument['document_type'] = trim((string) ($dbTravelDocument['document_type'] ?? 'passport')) ?: 'passport';
        $travelDocument['document_country'] = trim((string) ($dbTravelDocument['document_country'] ?? '')) ?: $travelDocument['document_country'];
        $travelDocument['document_number'] = trim((string) ($dbTravelDocument['document_number'] ?? '')) ?: $travelDocument['document_number'];
        $travelDocument['issued_on'] = settings_format_date_display((string) ($dbTravelDocument['issued_on'] ?? '')) ?: $travelDocument['issued_on'];
        $travelDocument['valid_from'] = settings_format_date_display((string) ($dbTravelDocument['valid_from'] ?? '')) ?: $travelDocument['valid_from'];
        $travelDocument['expires_on'] = settings_format_date_display((string) ($dbTravelDocument['expires_on'] ?? '')) ?: $travelDocument['expires_on'];
        $travelDocument['file_path'] = trim((string) ($dbTravelDocument['file_path'] ?? '')) ?: $travelDocument['file_path'];
        $travelDocument['consent_given'] = (int) ($dbTravelDocument['consent_given'] ?? 0);
        $travelDocumentExists = true;
    }

    $dbTravelLoyaltyProgram = fetch_one(
        'SELECT program_type, provider_name, program_name, program_number, membership_number
         FROM user_loyalty_programs
         WHERE user_id = ? AND status = "active"
         ORDER BY id DESC
         LIMIT 1',
        'i',
        [$userId]
    );
    if ($dbTravelLoyaltyProgram) {
        $travelLoyaltyProgram['program_type'] = trim((string) ($dbTravelLoyaltyProgram['program_type'] ?? '')) ?: trim((string) ($dbTravelLoyaltyProgram['provider_name'] ?? 'frequent_flyer')) ?: 'frequent_flyer';
        $travelLoyaltyProgram['program_name'] = trim((string) ($dbTravelLoyaltyProgram['program_name'] ?? '')) ?: $travelLoyaltyProgram['program_name'];
        $travelLoyaltyProgram['program_number'] = trim((string) ($dbTravelLoyaltyProgram['program_number'] ?? '')) ?: trim((string) ($dbTravelLoyaltyProgram['membership_number'] ?? '')) ?: $travelLoyaltyProgram['program_number'];
        $travelLoyaltyProgramExists = true;
    }
    $dbTripDefaults = fetch_one(
        'SELECT trip_type, travel_mode, billable_to, project_name, client_name, default_currency
         FROM user_default_trip_values
         WHERE user_id = ?
         LIMIT 1',
        'i',
        [$userId]
    );
    if ($dbTripDefaults) {
        $tripDefaults['trip_type'] = trim((string) ($dbTripDefaults['trip_type'] ?? 'Business')) ?: $tripDefaults['trip_type'];
        $tripDefaults['travel_mode'] = trim((string) ($dbTripDefaults['travel_mode'] ?? 'Economy')) ?: $tripDefaults['travel_mode'];
        $tripDefaults['billable_to'] = trim((string) ($dbTripDefaults['billable_to'] ?? 'Personal')) ?: $tripDefaults['billable_to'];
        $tripDefaults['project_name'] = trim((string) ($dbTripDefaults['project_name'] ?? '')) ?: $tripDefaults['project_name'];
        $tripDefaults['client_name'] = trim((string) ($dbTripDefaults['client_name'] ?? '')) ?: $tripDefaults['client_name'];
        $tripDefaults['default_currency'] = trim((string) ($dbTripDefaults['default_currency'] ?? 'INR')) ?: $tripDefaults['default_currency'];
        $tripDefaultsExists = true;
    }

    $dbExpenseDefaults = fetch_one(
        'SELECT expense_category, expense_type, payment_mode, default_currency, tax_included, comments
         FROM user_default_expense_values
         WHERE user_id = ?
         LIMIT 1',
        'i',
        [$userId]
    );
    if ($dbExpenseDefaults) {
        $expenseDefaults['expense_category'] = trim((string) ($dbExpenseDefaults['expense_category'] ?? '')) ?: $expenseDefaults['expense_category'];
        $expenseDefaults['expense_type'] = trim((string) ($dbExpenseDefaults['expense_type'] ?? '')) ?: $expenseDefaults['expense_type'];
        $expenseDefaults['payment_mode'] = trim((string) ($dbExpenseDefaults['payment_mode'] ?? 'Cash')) ?: $expenseDefaults['payment_mode'];
        $expenseDefaults['default_currency'] = trim((string) ($dbExpenseDefaults['default_currency'] ?? 'INR')) ?: $expenseDefaults['default_currency'];
        $expenseDefaults['tax_included'] = (int) ($dbExpenseDefaults['tax_included'] ?? 0);
        $expenseDefaults['comments'] = trim((string) ($dbExpenseDefaults['comments'] ?? '')) ?: $expenseDefaults['comments'];
        $expenseDefaultsExists = true;
    }

    $dbBudget = fetch_one(
        'SELECT budget_label
         FROM user_budget_periods
         WHERE user_id = ? AND is_active = 1
         ORDER BY id DESC
         LIMIT 1',
        'i',
        [$userId]
    );
    if ($dbBudget) {
        $budgetPeriod['label'] = trim((string) ($dbBudget['budget_label'] ?? '')) ?: $budgetPeriod['label'];
    }
}

$approverOptions = fetch_all(
    'SELECT id, business_name, email
     FROM users
     ORDER BY business_name, email'
);

$sidebarItems = [
    ['icon' => 'fa-solid fa-house', 'label' => 'Home', 'href' => page_url('dashboard')],
    ['icon' => 'fa-solid fa-compass', 'label' => 'Trips', 'href' => route_url('trips/new/')],
    ['icon' => 'fa-regular fa-credit-card', 'label' => 'Expenses', 'href' => route_url('expenses/new/')],
    ['icon' => 'fa-regular fa-file-lines', 'label' => 'Reports', 'href' => '#'],
    ['icon' => 'fa-solid fa-folder-open', 'label' => 'Advances', 'href' => '#'],
    ['icon' => 'fa-regular fa-credit-card', 'label' => 'Cards', 'href' => page_url('cards')],
    ['icon' => 'fa-solid fa-circle-check', 'label' => 'Approvals', 'href' => '#'],
    ['icon' => 'fa-solid fa-chart-column', 'label' => 'Analytics', 'href' => page_url('analytics')],
    ['icon' => 'fa-solid fa-gear', 'label' => 'My Settings', 'href' => page_url('my_settings'), 'active' => true],
];

$settingTabs = [
    ['key' => 'basic', 'label' => 'Basic Information', 'query' => 'basic'],
    ['key' => 'preferences', 'label' => 'Preferences', 'query' => 'preferences'],
    ['key' => 'travel', 'label' => 'Travel Details', 'query' => 'travelDetails'],
    ['key' => 'budgets', 'label' => 'Budgets', 'query' => 'budgets'],
];

$travelTabs = [
    ['key' => 'profile', 'label' => 'Travel Profile'],
    ['key' => 'loyalty', 'label' => 'Loyalty Programs'],
    ['key' => 'documents', 'label' => 'Travel Documents'],
];

render_header('My Settings | Expense', 'dashboard-page settings-page');
?>
<div class="dashboard-shell settings-shell">
    <aside class="dashboard-sidebar">
        <div class="sidebar-brand">
            <span class="brand-mark">
                <span class="brand-ring"></span>
            </span>
            <span class="brand-text">Expense</span>
        </div>

        <nav class="sidebar-nav" aria-label="Primary">
            <?php foreach ($sidebarItems as $item): ?>
                <a class="sidebar-link<?= !empty($item['active']) ? ' is-active' : '' ?>" href="<?= e($item['href'] ?? '#') ?>">
                    <i class="<?= e($item['icon']) ?>" aria-hidden="true"></i>
                    <span><?= e($item['label']) ?></span>
                </a>
            <?php endforeach; ?>
        </nav>

        <button type="button" class="sidebar-admin-switch">
            <i class="fa-solid fa-shield-halved"></i>
            <span>Switch to Admin View</span>
        </button>

        <button type="button" class="sidebar-collapse" aria-label="Collapse sidebar">
            <i class="fa-solid fa-arrow-left-long"></i>
        </button>
    </aside>

    <div class="dashboard-main settings-main">
        <header class="dashboard-topbar">
            <label class="dashboard-search">
                <i class="fa-solid fa-magnifying-glass" aria-hidden="true"></i>
                <input type="search" placeholder="Search in Expenses ( / )" aria-label="Search in Expenses">
            </label>

            <div class="topbar-right">
                <div class="trial-pill">
                    <span>Trial expires in 12 days.</span>
                    <a href="#">Upgrade Now</a>
                </div>

                <button type="button" class="view-pill">
                    <span class="view-stack">
                        <span class="view-mini">demo</span>
                        <strong>My View</strong>
                    </span>
                    <i class="fa-solid fa-chevron-down" aria-hidden="true"></i>
                </button>

                <div class="topbar-quick-add" data-quick-add>
                    <button type="button" class="topbar-square primary" data-quick-add-toggle aria-haspopup="true" aria-expanded="false" aria-label="Quick add">
                        <i class="fa-solid fa-plus" aria-hidden="true"></i>
                    </button>
                    <div class="quick-add-menu" data-quick-add-menu aria-hidden="true">
                        <div class="quick-add-menu-header">QUICK ADD</div>
                        <a class="quick-add-menu-item" href="<?= e(route_url('trips/new/')) ?>">
                            <span class="quick-add-menu-icon"><i class="fa-solid fa-suitcase" aria-hidden="true"></i></span>
                            <span>Trip</span>
                        </a>
                        <a class="quick-add-menu-item" href="<?= e(route_url('expenses/new/')) ?>">
                            <span class="quick-add-menu-icon"><i class="fa-regular fa-credit-card" aria-hidden="true"></i></span>
                            <span>Expense</span>
                        </a>
                        <a class="quick-add-menu-item" href="<?= e(route_url('reports/new/')) ?>">
                            <span class="quick-add-menu-icon"><i class="fa-regular fa-file-lines" aria-hidden="true"></i></span>
                            <span>Report</span>
                        </a>
                        <a class="quick-add-menu-item" href="<?= e(route_url('advances/new/')) ?>">
                            <span class="quick-add-menu-icon"><i class="fa-solid fa-folder-open" aria-hidden="true"></i></span>
                            <span>Advance</span>
                        </a>
                    </div>
                </div>

                <button type="button" class="topbar-icon" data-topbar-drawer-open="users" aria-expanded="false" aria-label="Delegates">
                    <i class="fa-solid fa-users" aria-hidden="true"></i>
                </button>

                <button type="button" class="topbar-icon" data-topbar-drawer-open="notifications" aria-expanded="false" aria-label="Notifications">
                    <i class="fa-solid fa-bell" aria-hidden="true"></i>
                </button>

                <a class="topbar-icon topbar-icon-link" href="<?= e(page_url('my_settings')) ?>" aria-label="Settings">
                    <i class="fa-solid fa-gear" aria-hidden="true"></i>
                </a>

                <button type="button" class="avatar-button" data-topbar-drawer-open="profile" aria-expanded="false" aria-label="Open profile menu">
                    <img src="../images/img1.jpg" alt="" class="avatar-image">
                </button>

                <button type="button" class="topbar-icon topbar-icon--launcher" data-topbar-drawer-open="apps" aria-expanded="false" aria-label="All Zoho apps">
                    <span class="topbar-launcher" aria-hidden="true">
                        <span></span><span></span><span></span>
                        <span></span><span></span><span></span>
                        <span></span><span></span><span></span>
                    </span>
                </button>
            </div>
        </header>

        <div class="topbar-drawer topbar-drawer--users" data-topbar-drawer="users" aria-hidden="true">
            <button type="button" class="topbar-drawer-backdrop" data-topbar-drawer-close aria-label="Close delegates panel"></button>
            <aside class="topbar-drawer-panel" role="dialog" aria-modal="true" aria-label="Delegates">
                <button type="button" class="topbar-drawer-close" data-topbar-drawer-close aria-label="Close">
                    <i class="fa-solid fa-xmark" aria-hidden="true"></i>
                </button>
                <div class="topbar-drawer-header">
                    <h2>Delegated To Me</h2>
                </div>
                <div class="topbar-drawer-empty" style="min-height: 180px;">
                    <div class="topbar-drawer-empty-icon">
                        <i class="fa-regular fa-circle-user" aria-hidden="true"></i>
                    </div>
                    <p>0 users</p>
                </div>
            </aside>
        </div>

        <div class="topbar-drawer topbar-drawer--notifications" data-topbar-drawer="notifications" aria-hidden="true">
            <button type="button" class="topbar-drawer-backdrop" data-topbar-drawer-close aria-label="Close notifications panel"></button>
            <aside class="topbar-drawer-panel" role="dialog" aria-modal="true" aria-label="Notifications">
                <button type="button" class="topbar-drawer-close" data-topbar-drawer-close aria-label="Close">
                    <i class="fa-solid fa-xmark" aria-hidden="true"></i>
                </button>
                <div class="topbar-drawer-header">
                    <h2>Notifications</h2>
                    <button type="button" class="topbar-drawer-filter">
                        Unread
                        <i class="fa-solid fa-caret-down" aria-hidden="true"></i>
                    </button>
                </div>
                <div class="topbar-drawer-note-row">
                    <div>
                        <strong>Desktop Notifications</strong>
                        <span>Stay up to date while you work.</span>
                    </div>
                    <a href="#">Enable</a>
                </div>
                <div class="topbar-drawer-empty">
                    <div class="topbar-drawer-empty-icon">
                        <i class="fa-regular fa-bell" aria-hidden="true"></i>
                    </div>
                    <p>Uhh... You don't have any notifications at the moment.</p>
                </div>
            </aside>
        </div>

        <div class="topbar-drawer topbar-drawer--profile" data-topbar-drawer="profile" aria-hidden="true">
            <button type="button" class="topbar-drawer-backdrop" data-topbar-drawer-close aria-label="Close profile panel"></button>
            <aside class="topbar-drawer-panel" role="dialog" aria-modal="true" aria-label="Profile menu">
                <button type="button" class="topbar-drawer-close" data-topbar-drawer-close aria-label="Close">
                    <i class="fa-solid fa-xmark" aria-hidden="true"></i>
                </button>

                <div class="topbar-drawer-card">
                    <img src="../images/img1.jpg" alt="" class="topbar-drawer-avatar">
                    <div>
                        <strong><?= e(trim((string) ($_SESSION['user_company'] ?? $_SESSION['user'] ?? 'Expense user'))) ?></strong>
                        <span><?= e(trim((string) ($_SESSION['user_email'] ?? ''))) ?></span>
                        <div class="topbar-drawer-account-links">
                            <a href="<?= e(page_url('my_settings')) ?>">My Account</a>
                            <span aria-hidden="true">&bull;</span>
                            <a href="<?= e(page_url('logout')) ?>">Sign Out</a>
                        </div>
                    </div>
                </div>

                <div class="topbar-drawer-section">
                    <div class="topbar-drawer-note-row">
                        <div>
                            <strong>Delegated To Me</strong>
                            <span>0 users</span>
                        </div>
                        <a href="#">Open</a>
                    </div>
                </div>

                <div class="topbar-drawer-section">
                    <div class="topbar-drawer-links">
                        <a href="#"><i class="fa-regular fa-circle-question" aria-hidden="true"></i><span>Help &amp; Support</span></a>
                        <a href="#"><i class="fa-regular fa-compass" aria-hidden="true"></i><span>Take a Tour</span></a>
                        <a href="#"><i class="fa-regular fa-comment-dots" aria-hidden="true"></i><span>Share Feedback</span></a>
                        <a href="#"><i class="fa-regular fa-keyboard" aria-hidden="true"></i><span>View Keyboard Shortcuts</span> <span class="topbar-drawer-badge">New</span></a>
                        <a href="#"><i class="fa-regular fa-calendar" aria-hidden="true"></i><span>Webinar</span></a>
                    </div>
                </div>

                <div class="topbar-drawer-section">
                    <div class="topbar-drawer-links">
                        <a href="#"><i class="fa-regular fa-lightbulb" aria-hidden="true"></i><span>Request a Feature</span></a>
                        <a href="#"><i class="fa-regular fa-file-lines" aria-hidden="true"></i><span>Request a Demo</span></a>
                        <a href="#"><i class="fa-regular fa-phone" aria-hidden="true"></i><span>Request a Call</span></a>
                        <a href="#"><i class="fa-solid fa-headphones-simple" aria-hidden="true"></i><span>Contact Support</span></a>
                    </div>
                </div>

                <div class="topbar-drawer-divider"></div>

                <div class="topbar-drawer-section">
                    <div class="topbar-drawer-section-title">
                        <i class="fa-solid fa-sparkles" aria-hidden="true"></i>
                        <h3>What's New?</h3>
                    </div>
                    <div class="topbar-drawer-callout">
                        You can directly talk to us every Monday to Friday
                        <strong>18005692747 - 9.00 AM to 7:00 PM</strong>
                    </div>
                    <div class="topbar-drawer-qr">
                        <div class="topbar-drawer-qr-code" aria-hidden="true"></div>
                        <div class="topbar-drawer-qr-copy">
                            Scan the QR code to download the Zoho Expense mobile app.
                            <strong>Available in</strong>
                            <div class="topbar-drawer-qr-apps" aria-label="Available platforms">
                                <i class="fa-brands fa-apple" aria-hidden="true"></i>
                                <i class="fa-brands fa-google-play" aria-hidden="true"></i>
                            </div>
                        </div>
                    </div>
                </div>
            </aside>
        </div>

        <div class="topbar-drawer topbar-drawer--apps" data-topbar-drawer="apps" aria-hidden="true">
            <button type="button" class="topbar-drawer-backdrop" data-topbar-drawer-close aria-label="Close apps panel"></button>
            <aside class="topbar-drawer-panel topbar-drawer-panel--apps" role="dialog" aria-modal="true" aria-label="All Zoho apps">
                <button type="button" class="topbar-drawer-close" data-topbar-drawer-close aria-label="Close">
                    <i class="fa-solid fa-xmark" aria-hidden="true"></i>
                </button>
                <div class="topbar-drawer-header topbar-drawer-header--apps">
                    <h2>All Zoho Apps</h2>
                    <button type="button" class="topbar-drawer-search-toggle" aria-label="Search apps">
                        <i class="fa-solid fa-magnifying-glass" aria-hidden="true"></i>
                    </button>
                </div>
                <label class="topbar-drawer-search">
                    <i class="fa-solid fa-magnifying-glass" aria-hidden="true"></i>
                    <input type="search" data-app-search placeholder="Search apps" aria-label="Search apps">
                </label>

                <section class="topbar-drawer-section" data-app-section>
                    <div class="topbar-drawer-section-label">Finance Apps</div>
                    <div class="topbar-drawer-app-grid">
                        <a href="#" class="topbar-app-item" data-app-item><i class="fa-solid fa-book-bookmark" aria-hidden="true"></i><span class="topbar-app-item-text"><strong>Zoho Books</strong><small>Online Accounting Software</small></span></a>
                        <a href="#" class="topbar-app-item" data-app-item><i class="fa-solid fa-receipt" aria-hidden="true"></i><span class="topbar-app-item-text"><strong>Zoho Billing</strong><small>End-to-end Billing Solution</small></span></a>
                        <a href="#" class="topbar-app-item" data-app-item><i class="fa-solid fa-boxes-stacked" aria-hidden="true"></i><span class="topbar-app-item-text"><strong>Zoho Inventory</strong><small>Order &amp; Inventory Management Software</small></span></a>
                        <a href="#" class="topbar-app-item" data-app-item><i class="fa-solid fa-wallet" aria-hidden="true"></i><span class="topbar-app-item-text"><strong>Zoho Checkout</strong><small>One-time and recurring payments software</small></span></a>
                        <a href="#" class="topbar-app-item" data-app-item><i class="fa-solid fa-cart-shopping" aria-hidden="true"></i><span class="topbar-app-item-text"><strong>Zoho Commerce</strong><small>Ecommerce software</small></span></a>
                        <a href="#" class="topbar-app-item" data-app-item><i class="fa-solid fa-file-invoice-dollar" aria-hidden="true"></i><span class="topbar-app-item-text"><strong>Zoho Payroll</strong><small>Simplified Payroll Management Software</small></span></a>
                    </div>
                </section>

                <section class="topbar-drawer-section" data-app-section>
                    <div class="topbar-drawer-section-label">Email and Collaboration</div>
                    <div class="topbar-drawer-app-grid topbar-drawer-app-grid--compact">
                        <a href="#" class="topbar-app-item topbar-app-item--compact" data-app-item><i class="fa-solid fa-book"></i><span class="topbar-app-item-text"><strong>Notebook</strong></span></a>
                        <a href="#" class="topbar-app-item topbar-app-item--compact" data-app-item><i class="fa-solid fa-circle-play"></i><span class="topbar-app-item-text"><strong>Meeting</strong></span></a>
                        <a href="#" class="topbar-app-item topbar-app-item--compact" data-app-item><i class="fa-solid fa-diagram-project"></i><span class="topbar-app-item-text"><strong>Projects</strong></span></a>
                        <a href="#" class="topbar-app-item topbar-app-item--compact" data-app-item><i class="fa-solid fa-pen-nib"></i><span class="topbar-app-item-text"><strong>Sign</strong></span></a>
                        <a href="#" class="topbar-app-item topbar-app-item--compact" data-app-item><i class="fa-solid fa-jet-fighter-up"></i><span class="topbar-app-item-text"><strong>Sprints</strong></span></a>
                        <a href="#" class="topbar-app-item topbar-app-item--compact" data-app-item><i class="fa-solid fa-inbox"></i><span class="topbar-app-item-text"><strong>TeamInbox</strong></span></a>
                        <a href="#" class="topbar-app-item topbar-app-item--compact" data-app-item><i class="fa-solid fa-envelope"></i><span class="topbar-app-item-text"><strong>Mail</strong></span></a>
                        <a href="#" class="topbar-app-item topbar-app-item--compact" data-app-item><i class="fa-solid fa-comment-dots"></i><span class="topbar-app-item-text"><strong>Cliq</strong></span></a>
                        <a href="#" class="topbar-app-item topbar-app-item--compact" data-app-item><i class="fa-solid fa-table"></i><span class="topbar-app-item-text"><strong>Sheet</strong></span></a>
                        <a href="#" class="topbar-app-item topbar-app-item--compact" data-app-item><i class="fa-solid fa-clapperboard"></i><span class="topbar-app-item-text"><strong>Show</strong></span></a>
                        <a href="#" class="topbar-app-item topbar-app-item--compact" data-app-item><i class="fa-solid fa-file-lines"></i><span class="topbar-app-item-text"><strong>Writer</strong></span></a>
                        <a href="#" class="topbar-app-item topbar-app-item--compact" data-app-item><i class="fa-solid fa-circle-nodes"></i><span class="topbar-app-item-text"><strong>Connect</strong></span></a>
                        <a href="#" class="topbar-app-item topbar-app-item--compact" data-app-item><i class="fa-solid fa-vault"></i><span class="topbar-app-item-text"><strong>Vault</strong></span></a>
                        <a href="#" class="topbar-app-item topbar-app-item--compact" data-app-item><i class="fa-solid fa-folder-open"></i><span class="topbar-app-item-text"><strong>WorkDrive</strong></span></a>
                        <a href="#" class="topbar-app-item topbar-app-item--compact" data-app-item><i class="fa-solid fa-graduation-cap"></i><span class="topbar-app-item-text"><strong>Learn</strong></span></a>
                    </div>
                </section>
            </aside>
        </div>

        <main class="dashboard-content settings-content">
            <section class="settings-head">
                <div>
                    <h1>My Settings</h1>
                    <?php if ($settingsSuccess !== null): ?>
                        <div class="notice success"><?= e($settingsSuccess) ?></div>
                    <?php endif; ?>
                    <?php if ($settingsError !== null): ?>
                        <div class="notice error"><?= e($settingsError) ?></div>
                    <?php endif; ?>
                </div>
                <button type="button" class="settings-help">?</button>
            </section>

            <nav class="settings-tabs" aria-label="Settings sections" data-settings-tabs>
                <?php foreach ($settingTabs as $tab): ?>
                    <button
                        type="button"
                        class="settings-tab<?= $activeTab === $tab['key'] ? ' is-active' : '' ?>"
                        data-settings-tab="<?= e($tab['key']) ?>"
                        data-settings-query="<?= e($tab['query']) ?>"
                    >
                        <?= e($tab['label']) ?>
                    </button>
                <?php endforeach; ?>
            </nav>

            <section class="settings-panel<?= $activeTab === 'basic' ? ' is-active' : '' ?>" data-settings-panel="basic">
                <article class="settings-card settings-card-wide">
                    <header class="settings-card-header">Personal Details</header>
                    <div class="settings-personal-grid">
                        <div class="settings-personal-col">
                            <div class="settings-detail-row"><span>Name</span><strong><?= e($profile['display_name']) ?></strong></div>
                            <div class="settings-detail-row"><span>Email Address</span><strong><?= e($profile['email']) ?></strong></div>
                            <div class="settings-detail-row"><span>Employee ID</span><strong><?= e($profile['employee_id']) ?></strong></div>
                            <div class="settings-detail-row"><span>Mobile</span><strong><?= e($profile['mobile_number']) ?></strong></div>
                            <div class="settings-detail-row"><span>Department</span><strong><?= e($profile['department']) ?></strong></div>
                            <div class="settings-detail-row"><span>Date of Joining</span><strong><?= e($profile['date_of_joining']) ?></strong></div>
                            <div class="settings-detail-row"><span>Date of Birth</span><strong><?= e($profile['date_of_birth']) ?></strong></div>
                            <div class="settings-detail-row"><span>Designation</span><strong><?= e($profile['designation']) ?></strong></div>
                        </div>
                        <div class="settings-personal-divider"></div>
                        <div class="settings-personal-col settings-right-col">
                            <div class="settings-detail-row"><span>Role Name</span><strong><?= e($profile['role_name']) ?></strong></div>
                            <div class="settings-detail-row"><span>Submits To</span><strong><?= e($profile['submits_to']) ?></strong></div>
                            <div class="settings-policies">
                                <span class="settings-subtitle">ASSOCIATED POLICIES</span>
                                <div class="settings-policy-chip">
                                    <span><?= e($profile['policy_name']) ?></span>
                                    <strong>DEFAULT</strong>
                                </div>
                            </div>
                        </div>
                    </div>
                </article>

                <article class="settings-card settings-card-wide">
                    <header class="settings-card-header">My Bank Account</header>
                    <div class="settings-card-body">
                        <?php if ($bankAccountExists): ?>
                            <div class="settings-bank-table">
                                <div class="settings-bank-table-head">
                                    <span>Bank Name</span>
                                    <span>Account Holder Name</span>
                                    <span>Account Number</span>
                                    <span></span>
                                </div>
                                <div class="settings-bank-table-row">
                                    <strong><?= e($bankAccount['bank_name']) ?></strong>
                                    <strong><?= e($bankAccount['account_holder_name']) ?></strong>
                                    <strong><?= e(settings_mask_account_number($bankAccount['account_number'])) ?></strong>
                                    <button type="button" class="settings-bank-edit" data-settings-open="bank-account" aria-label="Edit bank account">
                                        <i class="fa-regular fa-pen-to-square" aria-hidden="true"></i>
                                    </button>
                                </div>
                                <div class="settings-bank-meta">
                                    <span>IFSC</span>
                                    <strong><?= e($bankAccount['ifsc_code']) ?></strong>
                                </div>
                            </div>
                        <?php else: ?>
                            <p>Add your bank account and get your expenses reimbursed quickly.</p>
                        <?php endif; ?>
                        <?php if (!$bankAccountExists): ?>
                            <div class="settings-divider-line"></div>
                            <button type="button" class="settings-primary-action" data-settings-open="bank-account">+ Add Bank Account</button>
                        <?php endif; ?>
                    </div>
                </article>

                <div class="settings-two-up">
                    <article class="settings-card">
                        <header class="settings-card-header">My Delegate</header>
                        <div class="settings-card-body">
                            <?php if ($delegateExists): ?>
                                <div class="settings-bank-table">
                                    <div class="settings-bank-table-head">
                                        <span>Delegate Name</span>
                                        <span>Email</span>
                                        <span>Access</span>
                                        <span></span>
                                    </div>
                                    <div class="settings-bank-table-row">
                                        <strong><?= e($delegate['name']) ?></strong>
                                        <strong><?= e($delegate['email']) ?></strong>
                                        <strong><?= e(settings_delegate_access_label($delegate)) ?></strong>
                                        <button type="button" class="settings-bank-edit" data-settings-open="delegate" aria-label="Edit delegate">
                                            <i class="fa-regular fa-pen-to-square" aria-hidden="true"></i>
                                        </button>
                                    </div>
                                </div>
                            <?php else: ?>
                                <p>Authorize another user to create, submit and approve expense records on your behalf. <a href="#">Learn More</a></p>
                            <?php endif; ?>
                            <div class="settings-divider-line"></div>
                            <div class="settings-inline-actions">
                                <button type="button" class="settings-secondary-action" data-settings-open="delegate"><?= $delegateExists ? 'Edit Delegate' : '+ Add Delegate' ?></button>
                                <button type="button" class="settings-link-action" data-settings-open="previous-delegates">View Previous Delegates</button>
                            </div>
                        </div>
                    </article>

                    <article class="settings-card">
                        <header class="settings-card-header">Out of Office Approver</header>
                        <div class="settings-card-body">
                            <?php if (!empty($outOfOfficeApprover['name'])): ?>
                                <div class="settings-bank-table">
                                    <div class="settings-bank-table-head">
                                        <span>User</span>
                                        <span>Start Date</span>
                                        <span>End Date</span>
                                        <span></span>
                                    </div>
                                    <div class="settings-bank-table-row">
                                        <strong><?= e($outOfOfficeApprover['name']) ?></strong>
                                        <strong><?= e($outOfOfficeApprover['start_date'] ?: '-') ?></strong>
                                        <strong><?= e($outOfOfficeApprover['end_date'] ?: '-') ?></strong>
                                        <button type="button" class="settings-bank-edit" data-settings-open="out-of-office" aria-label="Edit out of office approver">
                                            <i class="fa-regular fa-pen-to-square" aria-hidden="true"></i>
                                        </button>
                                    </div>
                                </div>
                            <?php else: ?>
                                <p>Assign another user to automatically receive reports submitted to you and approve them in your absence. <a href="#">Learn More</a></p>
                                <div class="settings-divider-line"></div>
                                <button type="button" class="settings-primary-action" data-settings-open="out-of-office">+ Add Out of Office Approver</button>
                            <?php endif; ?>
                        </div>
                    </article>
                </div>
            </section>

            <section class="settings-panel<?= $activeTab === 'preferences' ? ' is-active' : '' ?>" data-settings-panel="preferences">
                <div class="settings-preference-grid">
                    <article class="settings-card">
                        <header class="settings-card-header">Email Receipt Forwarding</header>
                        <div class="settings-card-body settings-preference-body">
                            <div class="settings-preference-text">
                                <p>Forward emails with receipts to <a href="#"><?= e($receiptForwarding['forward_email']) ?></a>. Zoho Expense automatically scans and converts receipts into expenses.</p>
                                <a href="#" class="settings-text-link">Update</a>
                            </div>
                            <div class="settings-receipt-help">
                                <h4>How do I auto-forward receipts?</h4>
                                <div class="settings-provider-icons">
                                    <span class="provider-badge mail"><i class="fa-regular fa-envelope"></i></span>
                                    <span class="provider-badge gmail">G</span>
                                    <span class="provider-badge outlook">O</span>
                                </div>
                            </div>
                        </div>
                    </article>

                    <section class="settings-defaults">
                        <h2>Default Values</h2>
                        <p>Assign default values to fields and create trips and expenses faster.</p>

                        <div class="settings-default-card">
                            <header>
                                <i class="fa-solid fa-suitcase" aria-hidden="true"></i>
                                <span>TRIPS</span>
                                <?php if ($tripDefaultsExists): ?>
                                    <button type="button" class="settings-bank-edit" data-settings-open="trip-defaults" aria-label="Edit trip defaults">
                                        <i class="fa-regular fa-pen-to-square" aria-hidden="true"></i>
                                    </button>
                                <?php endif; ?>
                            </header>
                            <div class="settings-default-copy">
                                <p>Set default values for fields in trips creation page.</p>
                                <?php if ($tripDefaultsExists): ?>
                                    <div class="settings-bank-table settings-summary-table settings-summary-table--two">
                                        <div class="settings-bank-table-head">
                                            <span>Field</span>
                                            <span>Value</span>
                                        </div>
                                        <div class="settings-bank-table-row">
                                            <strong>Trip Type</strong>
                                            <strong><?= e($tripDefaults['trip_type']) ?></strong>
                                        </div>
                                        <div class="settings-bank-table-row">
                                            <strong>Travel Mode</strong>
                                            <strong><?= e($tripDefaults['travel_mode']) ?></strong>
                                        </div>
                                        <div class="settings-bank-table-row">
                                            <strong>Billable To</strong>
                                            <strong><?= e($tripDefaults['billable_to']) ?></strong>
                                        </div>
                                    </div>
                                <?php endif; ?>
                                <button type="button" class="settings-text-link button-link" data-settings-open="trip-defaults"><?= $tripDefaultsExists ? 'Update' : 'Configure' ?></button>
                            </div>
                        </div>

                        <div class="settings-default-card">
                            <header>
                                <i class="fa-regular fa-credit-card" aria-hidden="true"></i>
                                <span>EXPENSES</span>
                                <?php if ($expenseDefaultsExists): ?>
                                    <button type="button" class="settings-bank-edit" data-settings-open="expense-defaults" aria-label="Edit expense defaults">
                                        <i class="fa-regular fa-pen-to-square" aria-hidden="true"></i>
                                    </button>
                                <?php endif; ?>
                            </header>
                            <div class="settings-default-copy">
                                <p>Set default values for fields in expenses creation page.</p>
                                <?php if ($expenseDefaultsExists): ?>
                                    <div class="settings-bank-table settings-summary-table settings-summary-table--two">
                                        <div class="settings-bank-table-head">
                                            <span>Field</span>
                                            <span>Value</span>
                                        </div>
                                        <div class="settings-bank-table-row">
                                            <strong>Paid Through</strong>
                                            <strong><?= e($expenseDefaults['payment_mode']) ?></strong>
                                        </div>
                                        <div class="settings-bank-table-row">
                                            <strong>Expense Category</strong>
                                            <strong><?= e($expenseDefaults['expense_category'] ?: '-') ?></strong>
                                        </div>
                                        <div class="settings-bank-table-row">
                                            <strong>Tax Included</strong>
                                            <strong><?= !empty($expenseDefaults['tax_included']) ? 'Yes' : 'No' ?></strong>
                                        </div>
                                    </div>
                                <?php endif; ?>
                                <button type="button" class="settings-text-link button-link" data-settings-open="expense-defaults"><?= $expenseDefaultsExists ? 'Update' : 'Configure' ?></button>
                            </div>
                        </div>
                    </section>
                </div>
            </section>

            <section class="settings-panel<?= $activeTab === 'travel' ? ' is-active' : '' ?>" data-settings-panel="travel">
                <div class="settings-subtabs" data-travel-tabs>
                    <?php foreach ($travelTabs as $tab): ?>
                        <button
                            type="button"
                            class="settings-pill<?= $activeTravelTab === $tab['key'] ? ' is-active' : '' ?>"
                            data-travel-subtab="<?= e($tab['key']) ?>"
                        >
                            <i class="fa-regular fa-circle" aria-hidden="true"></i>
                            <span><?= e($tab['label']) ?></span>
                        </button>
                    <?php endforeach; ?>
                </div>

                <div class="settings-travel-panels">
                    <article class="settings-card settings-travel-panel<?= $activeTravelTab === 'profile' ? ' is-active' : '' ?>" data-travel-subpanel="profile">
                        <header class="settings-card-header">Travel Profile</header>
                        <div class="settings-card-body">
                            <?php if ($travelProfileExists): ?>
                                <div class="settings-bank-table settings-summary-table settings-summary-table--three">
                                    <div class="settings-bank-table-head">
                                        <span>Field</span>
                                        <span>Value</span>
                                        <span></span>
                                    </div>
                                    <div class="settings-bank-table-row">
                                        <strong>Passport Name</strong>
                                        <strong><?= e($travelProfile['passport_name']) ?></strong>
                                        <a class="settings-bank-edit" href="travel_profile.php?edit=1" aria-label="Edit travel profile">
                                            <i class="fa-regular fa-pen-to-square" aria-hidden="true"></i>
                                        </a>
                                    </div>
                                    <div class="settings-bank-table-row">
                                        <strong>Work Phone</strong>
                                        <strong><?= e($travelProfile['work_phone'] ?: '-') ?></strong>
                                        <span></span>
                                    </div>
                                    <div class="settings-bank-table-row">
                                        <strong>Home Address</strong>
                                        <strong><?= e($travelProfile['home_address']) ?></strong>
                                        <span></span>
                                    </div>
                                </div>
                                <div class="settings-divider-line"></div>
                                <a class="settings-primary-action settings-anchor-action" href="travel_profile.php?edit=1">Edit Travel Profile</a>
                            <?php else: ?>
                                <p>Add details such as name (as in your passport), work phone, and address so that your travel team can use these details to make bookings for your business trips. <a href="#">Learn More</a></p>
                                <div class="settings-divider-line"></div>
                                <a class="settings-primary-action settings-anchor-action" href="travel_profile.php?edit=1">+ Add Travel Profile</a>
                            <?php endif; ?>
                        </div>
                    </article>

                    <article class="settings-card settings-travel-panel<?= $activeTravelTab === 'loyalty' ? ' is-active' : '' ?>" data-travel-subpanel="loyalty">
                        <header class="settings-card-header">Loyalty Programs</header>
                        <div class="settings-card-body">
                            <p>Loyalty Programs allows you to keep track of and manage your loyalty points and rewards from airlines, hotels and car rental agencies within Zoho Expense</p>

                            <?php if ($travelLoyaltyProgramExists): ?>
                                <div class="settings-bank-table settings-summary-table settings-summary-table--three settings-loyalty-summary">
                                    <div class="settings-bank-table-head">
                                        <span>Program</span>
                                        <span>Number</span>
                                        <span></span>
                                    </div>
                                    <div class="settings-bank-table-row">
                                        <strong><?= e(settings_labelize($travelLoyaltyProgram['program_type'])) ?></strong>
                                        <strong><?= e($travelLoyaltyProgram['program_number']) ?></strong>
                                        <a class="settings-bank-edit" href="#" aria-label="Edit loyalty program">
                                            <i class="fa-regular fa-pen-to-square" aria-hidden="true"></i>
                                        </a>
                                    </div>
                                    <div class="settings-bank-table-row">
                                        <strong>Program Name</strong>
                                        <strong><?= e($travelLoyaltyProgram['program_name']) ?></strong>
                                        <span></span>
                                    </div>
                                </div>
                            <?php endif; ?>

                            <div class="settings-divider-line"></div>
                            <div class="settings-loyalty-actions">
                                <div class="settings-dropdown" data-loyalty-dropdown>
                                    <button type="button" class="settings-primary-action settings-dropdown-toggle" data-loyalty-toggle aria-expanded="false">
                                        <span>Add New Program</span>
                                        <i class="fa-solid fa-caret-down" aria-hidden="true"></i>
                                    </button>
                                    <div class="settings-dropdown-menu" data-loyalty-menu>
                                        <button type="button" class="settings-dropdown-item" data-settings-open="travel-loyalty" data-loyalty-program-type="frequent_flyer">
                                            Frequent Flyer Program
                                        </button>
                                        <button type="button" class="settings-dropdown-item" data-settings-open="travel-loyalty" data-loyalty-program-type="hotel">
                                            Hotel Loyalty Program
                                        </button>
                                        <button type="button" class="settings-dropdown-item" data-settings-open="travel-loyalty" data-loyalty-program-type="car_rental">
                                            Car Rental Loyalty Program
                                        </button>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </article>

                    <article class="settings-card settings-travel-panel<?= $activeTravelTab === 'documents' ? ' is-active' : '' ?>" data-travel-subpanel="documents">
                        <header class="settings-card-header">Travel Documents</header>
                        <div class="settings-card-body">
                            <p>Travel documents added here can be accessed by the travel team to facilitate booking.</p>
                            <?php if ($travelDocumentExists): ?>
                                <div class="settings-bank-table settings-summary-table settings-summary-table--four settings-document-summary">
                                    <div class="settings-bank-table-head">
                                        <span>Type</span>
                                        <span>Country</span>
                                        <span>Number</span>
                                        <span></span>
                                    </div>
                                    <div class="settings-bank-table-row">
                                        <strong><?= e(settings_labelize($travelDocument['document_type'])) ?></strong>
                                        <strong><?= e($travelDocument['document_country'] ?: '-') ?></strong>
                                        <strong><?= e($travelDocument['document_number'] ?: '-') ?></strong>
                                        <a class="settings-bank-edit" href="#" aria-label="Edit travel document">
                                            <i class="fa-regular fa-pen-to-square" aria-hidden="true"></i>
                                        </a>
                                    </div>
                                </div>
                            <?php endif; ?>
                            <div class="settings-divider-line"></div>
                            <button type="button" class="settings-primary-action" data-settings-open="travel-document">+ Add Travel Document</button>
                        </div>
                    </article>
                </div>
            </section>

            <section class="settings-panel<?= $activeTab === 'budgets' ? ' is-active' : '' ?>" data-settings-panel="budgets">
                <div class="budget-filter-row">
                    <button type="button" class="budget-filter-chip">
                        <i class="fa-solid fa-filter" aria-hidden="true"></i>
                    </button>
                    <div class="budget-select" data-budget-select>
                        <button type="button" class="budget-select-trigger" data-budget-toggle aria-expanded="false">
                            <span>Budget Period : <?= e($budgetPeriod['label']) ?></span>
                            <i class="fa-solid fa-chevron-down" aria-hidden="true"></i>
                        </button>
                        <div class="budget-menu" data-budget-menu>
                            <?php foreach ($budgetPeriods as $period): ?>
                                <button type="button" class="budget-menu-item<?= $period === $budgetPeriod['label'] ? ' is-active' : '' ?>">
                                    <?= e($period) ?>
                                </button>
                            <?php endforeach; ?>
                        </div>
                    </div>
                </div>

                <div class="budget-empty-state">
                    <div class="budget-empty-graphic">
                        <i class="fa-solid fa-calculator" aria-hidden="true"></i>
                    </div>
                    <p>No budget found for the selected time period.</p>
                </div>
            </section>
        </main>
    </div>
</div>

<div class="settings-overlay" data-settings-overlay aria-hidden="true">
    <div class="settings-overlay-backdrop" data-settings-close></div>

    <section class="settings-dialog settings-dialog--center" data-settings-dialog="bank-account" role="dialog" aria-modal="true" aria-labelledby="bankAccountTitle">
        <form method="post">
            <header class="settings-dialog-header">
                <h3 id="bankAccountTitle"><?= $bankAccountExists ? 'Edit Bank Account' : 'Add Bank Account' ?></h3>
                <button type="button" class="settings-dialog-close" data-settings-close aria-label="Close">
                    <i class="fa-solid fa-xmark" aria-hidden="true"></i>
                </button>
            </header>
            <div class="settings-dialog-body">
                <div class="settings-form-grid">
                    <label class="settings-field">
                        <span>Account Holder Name *</span>
                        <input type="text" name="account_holder_name" value="<?= e($bankAccount['account_holder_name']) ?>" placeholder="" required>
                    </label>
                    <label class="settings-field">
                        <span>Bank Name *</span>
                        <input type="text" name="bank_name" value="<?= e($bankAccount['bank_name']) ?>" placeholder="" required>
                    </label>
                    <label class="settings-field">
                        <span>Account Number *</span>
                        <input type="text" name="account_number" value="<?= e($bankAccount['account_number']) ?>" required>
                    </label>
                    <label class="settings-field">
                        <span>Retype Account No. *</span>
                        <input type="text" name="retype_account_number" value="<?= e($bankAccount['account_number']) ?>" required>
                    </label>
                    <label class="settings-field">
                        <span>Account Type *</span>
                        <select name="account_type" required>
                            <option value="" disabled<?= empty($bankAccount['account_type']) ? ' selected' : '' ?>>Select</option>
                            <option value="savings"<?= ($bankAccount['account_type'] ?? 'savings') === 'savings' ? ' selected' : '' ?>>Savings</option>
                            <option value="current"<?= ($bankAccount['account_type'] ?? 'savings') === 'current' ? ' selected' : '' ?>>Current</option>
                            <option value="salary"<?= ($bankAccount['account_type'] ?? 'savings') === 'salary' ? ' selected' : '' ?>>Salary</option>
                            <option value="other"<?= ($bankAccount['account_type'] ?? 'savings') === 'other' ? ' selected' : '' ?>>Other</option>
                        </select>
                    </label>
                    <label class="settings-field">
                        <span>IFSC *</span>
                        <input type="text" name="ifsc_code" value="<?= e($bankAccount['ifsc_code']) ?>" placeholder="AAAA0000000" required>
                    </label>
                </div>
            </div>
            <footer class="settings-dialog-footer">
                <button type="submit" name="settings_action" value="save_bank_account" class="settings-dialog-primary">Save</button>
                <button type="button" class="settings-dialog-secondary" data-settings-close>Cancel</button>
            </footer>
        </form>
    </section>

    <section class="settings-dialog settings-dialog--center" data-settings-dialog="delegate" role="dialog" aria-modal="true" aria-labelledby="delegateTitle">
        <form method="post">
            <header class="settings-dialog-header">
                <h3 id="delegateTitle"><?= $delegateExists ? 'Edit Delegate' : 'Add Delegate' ?></h3>
                <button type="button" class="settings-dialog-close" data-settings-close aria-label="Close">
                    <i class="fa-solid fa-xmark" aria-hidden="true"></i>
                </button>
            </header>
            <div class="settings-dialog-body">
                <div class="settings-avatar-pair">
                    <span class="settings-avatar current"><img src="../images/img1.jpg" alt=""></span>
                    <span class="settings-avatar arrow"><i class="fa-solid fa-chevron-right"></i></span>
                    <span class="settings-avatar target"><i class="fa-solid fa-user"></i></span>
                </div>
                <div class="settings-callout warning">
                    The delegate you add here will have access to perform actions on your behalf.
                </div>
                <label class="settings-field">
                    <span>Delegate access to *</span>
                    <select name="delegate_user_id" required>
                        <option value="">Select</option>
                        <?php foreach ($approverOptions as $userOption): ?>
                            <?php
                                $optionLabel = trim((string) ($userOption['business_name'] ?? ''));
                                $optionEmail = trim((string) ($userOption['email'] ?? ''));
                                $optionValue = (int) ($userOption['id'] ?? 0);
                                $isSelected = $delegateExists && $delegate['name'] === $optionLabel && $delegate['email'] === $optionEmail;
                            ?>
                            <option value="<?= e((string) $optionValue) ?>"<?= $isSelected ? ' selected' : '' ?>>
                                <?= e($optionLabel !== '' ? ($optionEmail !== '' ? $optionLabel . ' (' . $optionEmail . ')' : $optionLabel) : 'User ' . $optionValue) ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                </label>
                <div class="settings-form-grid two-col">
                    <label class="settings-field">
                        <span>Start Date</span>
                        <input type="text" name="delegate_start_date" value="<?= e($delegate['start_date']) ?>" placeholder="dd/mm/yyyy">
                    </label>
                    <label class="settings-field">
                        <span>End Date</span>
                        <input type="text" name="delegate_end_date" value="<?= e($delegate['end_date']) ?>" placeholder="dd/mm/yyyy">
                    </label>
                </div>
                <label class="settings-field">
                    <span>Access Type</span>
                    <select name="delegate_access_type">
                        <option value="submit"<?= $delegate['access_type'] === 'submit' ? ' selected' : '' ?>>Submit access</option>
                        <option value="approve"<?= $delegate['access_type'] === 'approve' ? ' selected' : '' ?>>Approve access</option>
                        <option value="submit_approve"<?= $delegate['access_type'] === 'submit_approve' ? ' selected' : '' ?>>Submit and approve</option>
                    </select>
                </label>
                <ul class="settings-access-list">
                    <li><i class="fa-solid fa-check"></i> Create and submit expense reports</li>
                    <li><i class="fa-solid fa-check"></i> Create and submit trips</li>
                    <li><i class="fa-solid fa-check"></i> Record advances</li>
                    <li><i class="fa-solid fa-check"></i> Manage card transactions</li>
                </ul>
            </div>
            <footer class="settings-dialog-footer">
                <button type="submit" name="settings_action" value="save_delegate" class="settings-dialog-primary"><?= $delegateExists ? 'Save Changes' : 'Grant Access' ?></button>
                <button type="button" class="settings-dialog-secondary" data-settings-close>Cancel</button>
            </footer>
        </form>
    </section>

    <section class="settings-dialog settings-dialog--center" data-settings-dialog="out-of-office" role="dialog" aria-modal="true" aria-labelledby="ooaTitle">
        <form method="post">
            <header class="settings-dialog-header">
                <h3 id="ooaTitle">Out of Office Approver</h3>
                <button type="button" class="settings-dialog-close" data-settings-close aria-label="Close">
                    <i class="fa-solid fa-xmark" aria-hidden="true"></i>
                </button>
            </header>
            <div class="settings-dialog-body">
                <div class="settings-callout info">
                    The approval requests submitted to you within the configured duration will be auto-forwarded to the assigned Out of Office Approver.
                </div>
                <label class="settings-field">
                    <span>User *</span>
                    <select name="approver_user_id" required>
                        <option value="">Select</option>
                        <?php foreach ($approverOptions as $approverOption): ?>
                            <?php
                                $optionLabel = trim((string) ($approverOption['business_name'] ?? ''));
                                $optionEmail = trim((string) ($approverOption['email'] ?? ''));
                                $optionValue = (int) ($approverOption['id'] ?? 0);
                                $isSelected = $optionLabel !== '' && $outOfOfficeApprover['name'] === $optionLabel && $outOfOfficeApprover['email'] === $optionEmail;
                            ?>
                            <option value="<?= e((string) $optionValue) ?>"<?= $isSelected ? ' selected' : '' ?>>
                                <?= e($optionLabel !== '' ? ($optionEmail !== '' ? $optionLabel . ' (' . $optionEmail . ')' : $optionLabel) : 'User ' . $optionValue) ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                </label>
                <div class="settings-form-grid two-col">
                    <label class="settings-field">
                        <span>Start Date *</span>
                        <input type="text" name="start_date" value="<?= e((string) ($outOfOfficeApprover['start_date'] ?? '')) ?>" placeholder="dd/mm/yyyy" required>
                    </label>
                    <label class="settings-field">
                        <span>End Date *</span>
                        <input type="text" name="end_date" value="<?= e((string) ($outOfOfficeApprover['end_date'] ?? '')) ?>" placeholder="dd/mm/yyyy" required>
                    </label>
                </div>
            </div>
            <footer class="settings-dialog-footer settings-dialog-footer--split">
                <div class="settings-dialog-actions">
                    <button type="submit" name="settings_action" value="save_ooa" class="settings-dialog-primary">Save</button>
                    <button type="button" class="settings-dialog-secondary" data-settings-close>Cancel</button>
                </div>
                <button type="submit" name="settings_action" value="delete_ooa" class="settings-trash-button" aria-label="Delete out of office approver" formnovalidate>
                    <i class="fa-regular fa-trash-can"></i>
                </button>
            </footer>
        </form>
    </section>

    <section class="settings-dialog settings-dialog--center" data-settings-dialog="travel-profile" role="dialog" aria-modal="true" aria-labelledby="travelProfileTitle">
        <form method="post">
            <header class="settings-dialog-header">
                <h3 id="travelProfileTitle"><?= $travelProfileExists ? 'Edit Travel Profile' : 'Travel Profile' ?></h3>
                <button type="button" class="settings-dialog-close" data-settings-close aria-label="Close">
                    <i class="fa-solid fa-xmark" aria-hidden="true"></i>
                </button>
            </header>
            <div class="settings-dialog-body">
                <p class="settings-dialog-text">Add details such as your passport name, work phone, and address for travel bookings.</p>
                <label class="settings-field">
                    <span>Passport Name *</span>
                    <input type="text" name="passport_name" value="<?= e($travelProfile['passport_name']) ?>" required>
                </label>
                <div class="settings-form-grid two-col">
                    <label class="settings-field">
                        <span>Work Phone *</span>
                        <input type="text" name="work_phone" value="<?= e($travelProfile['work_phone']) ?>" required>
                    </label>
                    <label class="settings-field">
                        <span>Home Address *</span>
                        <input type="text" name="home_address" value="<?= e($travelProfile['home_address']) ?>" required>
                    </label>
                </div>
            </div>
            <footer class="settings-dialog-footer">
                <button type="submit" name="settings_action" value="save_travel_profile" class="settings-dialog-primary"><?= $travelProfileExists ? 'Save Changes' : 'Add Travel Profile' ?></button>
                <button type="button" class="settings-dialog-secondary" data-settings-close>Cancel</button>
            </footer>
        </form>
    </section>

    <section class="settings-dialog settings-dialog--center" data-settings-dialog="travel-loyalty" role="dialog" aria-modal="true" aria-labelledby="travelLoyaltyTitle">
        <form method="post">
            <header class="settings-dialog-header">
                <h3 id="travelLoyaltyTitle"><?= $travelLoyaltyProgramExists ? 'Edit Loyalty Program' : 'New Loyalty Program' ?></h3>
                <button type="button" class="settings-dialog-close" data-settings-close aria-label="Close">
                    <i class="fa-solid fa-xmark" aria-hidden="true"></i>
                </button>
            </header>
            <div class="settings-dialog-body">
                <div class="settings-form-grid">
                    <label class="settings-field">
                        <span>Program Type *</span>
                        <select name="program_type" data-loyalty-program-type-select required>
                            <option value="frequent_flyer"<?= $travelLoyaltyProgram['program_type'] === 'frequent_flyer' ? ' selected' : '' ?>>Frequent Flyer Program</option>
                            <option value="hotel"<?= $travelLoyaltyProgram['program_type'] === 'hotel' ? ' selected' : '' ?>>Hotel Loyalty Program</option>
                            <option value="car_rental"<?= $travelLoyaltyProgram['program_type'] === 'car_rental' ? ' selected' : '' ?>>Car Rental Loyalty Program</option>
                        </select>
                    </label>
                    <label class="settings-field">
                        <span>Program Name *</span>
                        <select
                            name="program_name"
                            data-loyalty-program-name
                            data-loyalty-program-options='<?= e(json_encode($travelProgramNameOptions, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES) ?: "{}") ?>'
                            required
                        >
                            <option value="">Select</option>
                            <?php foreach ($travelProgramNameOptions[$travelLoyaltyProgram['program_type']] ?? ['Select'] as $programOption): ?>
                                <?php if ($programOption !== 'Select'): ?>
                                    <option value="<?= e($programOption) ?>"<?= $travelLoyaltyProgram['program_name'] === $programOption ? ' selected' : '' ?>><?= e($programOption) ?></option>
                                <?php endif; ?>
                            <?php endforeach; ?>
                        </select>
                    </label>
                    <label class="settings-field">
                        <span>Program Number *</span>
                        <input type="text" name="program_number" value="<?= e($travelLoyaltyProgram['program_number']) ?>" placeholder="" required>
                    </label>
                </div>
            </div>
            <footer class="settings-dialog-footer">
                <button type="submit" name="settings_action" value="save_loyalty_program" class="settings-dialog-primary"><?= $travelLoyaltyProgramExists ? 'Save Changes' : 'Save' ?></button>
                <button type="button" class="settings-dialog-secondary" data-settings-close>Cancel</button>
            </footer>
        </form>
    </section>

    <section class="settings-dialog settings-dialog--center settings-dialog--travel-document" data-settings-dialog="travel-document" role="dialog" aria-modal="true" aria-labelledby="travelDocumentTitle">
        <form method="post" enctype="multipart/form-data">
            <header class="settings-dialog-header">
                <h3 id="travelDocumentTitle"><?= $travelDocumentExists ? 'Edit Travel Document' : 'New Travel Document' ?></h3>
                <button type="button" class="settings-dialog-close" data-settings-close aria-label="Close">
                    <i class="fa-solid fa-xmark" aria-hidden="true"></i>
                </button>
            </header>
            <div class="settings-dialog-body settings-dialog-body--travel-document">
                <div class="travel-document-upload">
                    <label class="travel-upload-dropzone">
                        <input type="file" name="document_file" accept=".pdf,.jpg,.jpeg,.png,.webp">
                        <span class="travel-upload-icon">
                            <i class="fa-solid fa-arrow-up" aria-hidden="true"></i>
                        </span>
                        <strong>Attach documents from computer or cloud</strong>
                        <span class="travel-upload-note">Current file: <?= e($travelDocument['file_path'] !== '' ? basename($travelDocument['file_path']) : 'No file attached') ?></span>
                    </label>
                    <input type="hidden" name="existing_file_path" value="<?= e($travelDocument['file_path']) ?>">
                </div>

                <div class="settings-dialog-form settings-dialog-form--travel-document">
                    <label class="settings-field">
                        <span>Type *</span>
                        <select name="document_type" required>
                            <option value="">Select</option>
                            <option value="passport"<?= $travelDocument['document_type'] === 'passport' ? ' selected' : '' ?>>Passport</option>
                            <option value="visa"<?= $travelDocument['document_type'] === 'visa' ? ' selected' : '' ?>>Visa</option>
                            <option value="id_card"<?= $travelDocument['document_type'] === 'id_card' ? ' selected' : '' ?>>ID Card</option>
                            <option value="other"<?= $travelDocument['document_type'] === 'other' ? ' selected' : '' ?>>Other</option>
                        </select>
                    </label>
                    <label class="settings-field">
                        <span>Country *</span>
                        <select name="document_country" required>
                            <option value="">Country</option>
                            <?php foreach ($travelDocumentCountries as $country): ?>
                                <option value="<?= e($country) ?>"<?= $travelDocument['document_country'] === $country ? ' selected' : '' ?>><?= e($country) ?></option>
                            <?php endforeach; ?>
                        </select>
                    </label>
                    <label class="settings-field">
                        <span>Document Number *</span>
                        <input type="text" name="document_number" value="<?= e($travelDocument['document_number']) ?>" required>
                    </label>
                    <label class="settings-field">
                        <span>Issued On *</span>
                        <input type="text" name="issued_on" value="<?= e($travelDocument['issued_on']) ?>" placeholder="eg: 31/01/2025" required>
                    </label>
                    <label class="settings-field">
                        <span>Valid From *</span>
                        <input type="text" name="valid_from" value="<?= e($travelDocument['valid_from']) ?>" placeholder="eg: 31/01/2025" required>
                    </label>
                    <label class="settings-field">
                        <span>Expires On *</span>
                        <input type="text" name="expires_on" value="<?= e($travelDocument['expires_on']) ?>" placeholder="eg: 31/01/2025" required>
                    </label>
                </div>
                <label class="settings-check-row settings-check-row--document">
                    <input type="checkbox" name="consent_given" value="1"<?= !empty($travelDocument['consent_given']) ? ' checked' : '' ?>>
                    <span>I authorize Zoho Expense to store and process my travel document for the purpose of fulfilling my business travel requests.</span>
                </label>
            </div>
            <footer class="settings-dialog-footer">
                <button type="submit" name="settings_action" value="save_travel_document" class="settings-dialog-primary"><?= $travelDocumentExists ? 'Save Changes' : 'Save' ?></button>
                <button type="button" class="settings-dialog-secondary" data-settings-close>Cancel</button>
            </footer>
        </form>
    </section>

    <section class="settings-dialog settings-dialog--drawer" data-settings-dialog="previous-delegates" role="dialog" aria-modal="true" aria-labelledby="previousDelegatesTitle">
        <header class="settings-drawer-header">
            <h3 id="previousDelegatesTitle">Previous Delegates</h3>
            <button type="button" class="settings-dialog-close" data-settings-close aria-label="Close">
                <i class="fa-solid fa-xmark" aria-hidden="true"></i>
            </button>
        </header>
        <div class="settings-drawer-body">
            <?php if (!empty($previousDelegates)): ?>
                <div class="settings-bank-table">
                    <div class="settings-bank-table-head">
                        <span>Delegate</span>
                        <span>Dates</span>
                        <span>Status</span>
                        <span></span>
                    </div>
                    <?php foreach ($previousDelegates as $previousDelegate): ?>
                        <div class="settings-bank-table-row">
                            <strong><?= e(trim((string) ($previousDelegate['delegate_name'] ?? ''))) ?></strong>
                            <strong><?= e((settings_format_date_display((string) ($previousDelegate['start_date'] ?? '')) ?: '-') . ' to ' . (settings_format_date_display((string) ($previousDelegate['end_date'] ?? '')) ?: '-')) ?></strong>
                            <strong><?= e(settings_labelize((string) ($previousDelegate['status'] ?? ''))) ?></strong>
                            <span></span>
                        </div>
                    <?php endforeach; ?>
                </div>
            <?php else: ?>
                <p>There are no previous delegates</p>
            <?php endif; ?>
        </div>
    </section>

    <section class="settings-dialog settings-dialog--drawer" data-settings-dialog="trip-defaults" role="dialog" aria-modal="true" aria-labelledby="tripDefaultsTitle">
        <form method="post">
            <header class="settings-drawer-header">
                <h3 id="tripDefaultsTitle">Trip Default Values</h3>
                <button type="button" class="settings-dialog-close" data-settings-close aria-label="Close">
                    <i class="fa-solid fa-xmark" aria-hidden="true"></i>
                </button>
            </header>
            <div class="settings-drawer-body">
                <p>Configure default values for trips created from this workspace.</p>
                <label class="settings-field">
                    <span>Trip Type</span>
                    <input type="text" name="trip_type" value="<?= e($tripDefaults['trip_type']) ?>">
                </label>
                <label class="settings-field">
                    <span>Travel Mode</span>
                    <input type="text" name="travel_mode" value="<?= e($tripDefaults['travel_mode']) ?>">
                </label>
                <label class="settings-field">
                    <span>Billable To</span>
                    <input type="text" name="billable_to" value="<?= e($tripDefaults['billable_to']) ?>">
                </label>
                <label class="settings-field">
                    <span>Project Name</span>
                    <input type="text" name="project_name" value="<?= e($tripDefaults['project_name']) ?>">
                </label>
                <label class="settings-field">
                    <span>Client Name</span>
                    <input type="text" name="client_name" value="<?= e($tripDefaults['client_name']) ?>">
                </label>
                <label class="settings-field">
                    <span>Default Currency</span>
                    <input type="text" name="default_currency" value="<?= e($tripDefaults['default_currency']) ?>">
                </label>
            </div>
            <footer class="settings-drawer-footer">
                <button type="submit" name="settings_action" value="save_trip_defaults" class="settings-dialog-primary">Save</button>
                <button type="button" class="settings-dialog-secondary" data-settings-close>Cancel</button>
            </footer>
        </form>
    </section>

    <section class="settings-dialog settings-dialog--drawer" data-settings-dialog="expense-defaults" role="dialog" aria-modal="true" aria-labelledby="expenseDefaultsTitle">
        <form method="post">
            <header class="settings-drawer-header">
                <h3 id="expenseDefaultsTitle">Expense Default Values</h3>
                <button type="button" class="settings-dialog-close" data-settings-close aria-label="Close">
                    <i class="fa-solid fa-xmark" aria-hidden="true"></i>
                </button>
            </header>
            <div class="settings-drawer-body">
                <p>Configure default values for expenses created from this workspace.</p>
                <label class="settings-field">
                    <span>Expense Category</span>
                    <input type="text" name="expense_category" value="<?= e($expenseDefaults['expense_category']) ?>">
                </label>
                <label class="settings-field">
                    <span>Expense Type</span>
                    <input type="text" name="expense_type" value="<?= e($expenseDefaults['expense_type']) ?>">
                </label>
                <label class="settings-field">
                    <span>Payment Mode</span>
                    <input type="text" name="payment_mode" value="<?= e($expenseDefaults['payment_mode']) ?>">
                </label>
                <label class="settings-field">
                    <span>Default Currency</span>
                    <input type="text" name="default_currency" value="<?= e($expenseDefaults['default_currency']) ?>">
                </label>
                <label class="settings-field">
                    <span>Comments</span>
                    <input type="text" name="comments" value="<?= e($expenseDefaults['comments']) ?>">
                </label>
                <label class="settings-check-row">
                    <input type="checkbox" name="tax_included"<?= !empty($expenseDefaults['tax_included']) ? ' checked' : '' ?>>
                    <span>Tax included</span>
                </label>
            </div>
            <footer class="settings-drawer-footer">
                <button type="submit" name="settings_action" value="save_expense_defaults" class="settings-dialog-primary">Save</button>
                <button type="button" class="settings-dialog-secondary" data-settings-close>Cancel</button>
            </footer>
        </form>
    </section>
</div>
<?php render_footer(); ?>
