<?php defined('BASEPATH') or exit('No direct script access allowed'); ?>
<div class="<?php if ($openEdit == true) {
    echo 'open-edit ';
} ?>lead-wrapper" <?php if (isset($lead) && ($lead->junk == 1 || $lead->lost == 1)) {
     echo 'lead-is-junk-or-lost';
 } ?>>
<style>
    .select-status{
        width: 100%;
    }
    [data-id="status"] {
    border-bottom-right-radius: .375rem !important;
    border-top-right-radius: .375rem !important;
}


</style>
<?php $current_staff_role = get_current_staff_role($this, get_staff_user_id()); ?>
    <?php if (isset($lead)) {
        if ($samegroup) { ?>
                            <div class="btn-group pull-right mleft5" id="lead-more-btn">
                                <a href="#" class="btn btn-default dropdown-toggle lead-top-btn" data-toggle="dropdown" aria-haspopup="true"
                                    aria-expanded="false">
                                    <?php echo _l('more'); ?>
                                    <span class="caret"></span>
                                </a>
                                <?php if ($lead->multiple_cases != 0) { ?>
                                        <ul class="dropdown-menu dropdown-menu-left" id="lead-more-dropdown">

                                            <?php if ((has_permission('leads', '', 'delete') && $lead_locked == false) || is_admin()) { ?>
                                                        <li>
                                                            <a href="<?php echo admin_url('leads/delete/' . $lead->id); ?>" class="text-danger delete-text _delete"
                                                                data-toggle="tooltip" title="">
                                                                <i class="fa fa-remove"></i>
                                                                <?php echo 'Delete Case'; ?>
                                                            </a>
                                                        </li>
                                            <?php } ?>
                                        </ul>
                                <?php } ?>

                            </div>
                <?php } ?>
                <!-- <div class="pull-right mleft5">
            <a data-toggle="tooltip" class="btn btn-default lead-print-btn lead-top-btn lead-view"
                onclick="print_lead_information(); return false;" data-placement="top" title="<?php echo _l('print'); ?>"
                href="#">
                <i class="fa fa-print"></i>
            </a>
        </div> -->
                <?php
                if ($samegroup) {
                    ?>
                            <div class="mleft5 pull-right<?php echo $lead_locked == true ? ' hide' : ''; ?>">
                                <a href="#" lead-edit data-toggle="tooltip" data-title="<?php echo _l('edit'); ?>"
                                    class="btn btn-default lead-top-btn profile_edit_button">

                                    <i class="fa-regular fa-pen-to-square"></i>
                                </a>
                            </div>
                <?php } ?>
                <?php
                $client = false;
                $convert_to_client_tooltip_email_exists = '';
                if (total_rows(db_prefix() . 'contacts', ['email' => $lead->email]) > 0 && total_rows(db_prefix() . 'clients', ['leadid' => $lead->id]) == 0) {
                    $convert_to_client_tooltip_email_exists = _l('lead_email_already_exists');
                    $text = _l('lead_convert_to_client');
                } elseif (total_rows(db_prefix() . 'clients', ['leadid' => $lead->id])) {
                    $client = true;
                } else {
                    $text = _l('lead_convert_to_client');
                }
                ?>

                <?php if ($lead_locked == false) { ?>
                            <div class="lead-edit<?php if (isset($lead)) {
                                echo ' hide';
                            } ?>">
                                <button type="button" class="btn btn-primary pull-right lead-top-btn lead-save-btn"
                                    onclick="document.getElementById('lead-form-submit').click();">
                                    <?php echo _l('submit'); ?>
                                </button>
                            </div>
                <?php } ?>

    <?php } ?>

    <div class="clearfix no-margin"></div>

    <?php if (isset($lead)) { ?>

                <div class="row mbot15" style="margin-top:12px;">
                    <hr class="no-margin" />
                </div>

                <div class="alert alert-warning hide mtop20" role="alert" id="lead_proposal_warning">
                    <?php echo _l('proposal_warning_email_change', [_l('lead_lowercase'), _l('lead_lowercase'), _l('lead_lowercase')]); ?>
                    <hr />
                    <a href="#" onclick="update_all_proposal_emails_linked_to_lead(<?php echo $lead->id; ?>); return false;">
                        <?php echo _l('update_proposal_email_yes'); ?>
                    </a>
                    <br />
                    <a href="#" onclick="init_lead_modal_data(<?php echo $lead->id; ?>); return false;">
                        <?php echo _l('update_proposal_email_no'); ?>
                    </a>
                </div>
    <?php } ?>

    <?php echo form_open((isset($lead) ? admin_url('leads/lead/' . $lead->id) : admin_url('leads/lead')), ['id' => 'lead_form']); ?>
    <div class="row">
        <div id="lead_view" class="lead-view<?php if (!isset($lead)) {
            echo ' hide';
        } ?>" id="leadViewWrapper">
        <?php if ($total_notes == 0) { ?>
                    <?php if ($samegroup === 2) { ?>
                        <?php } else if ($samegroup) { ?>
                                        <div class="col-md-12" style="">
                                            <a href="#" id="file_notes_tab_move">
                                                <div class="alert alert-danger" style="width:100%;">
                                                    <h4 class="no-margin font-medium-xs bold">
                                                <?php echo _l('Please make introductory call to the client.'); ?>
                                                    </h4>
                                                </div>
                                            </a>
                                        </div>
                        <?php } ?>
        <?php } ?>
            <div class="col-md-4 col-xs-12 lead-information-col">
                <div class="alert alert-info">
                    <h4 class="no-margin font-medium-xs bold">
                        <?php echo _l('Personal Information'); ?>
                    </h4>
                </div>
                <dl>
                    <!-- <dt class="lead-field-heading tw-font-medium tw-text-neutral-500">
                        <img loading="lazy" style="width: 50%; border-radius: 5%;" src="<?php echo $profile_url; ?>" alt="">
                    </dt> -->
                    <?php if (!empty($leads_borrow)): ?>
                                <span class="btn btn-primary" style="text-align: center; font-size: medium; font-weight: 700;margin-top:15px;">First Party</span>
                    <?php endif; ?>
                 
                    <dt class="lead-field-heading tw-font-medium tw-text-neutral-500">
                        <?php echo _l('lead_add_edit_name'); ?>
                    </dt>
                    <dd class="tw-text-neutral-900 tw-mt-1 lead-name">
                        <?php echo (isset($lead) && $lead->name != '' ? $lead->name : '-') ?>
                    </dd>

                    <dt class="lead-field-heading tw-font-medium tw-text-neutral-500">
                        <?php echo _l('lead_add_edit_email'); ?>
                    </dt>
                    <dd class="tw-text-neutral-900 tw-mt-1">
                        <?php echo (isset($lead) && $lead->email != '' ? '<a href="mailto:' . $lead->email . '">' . $lead->email . '</a>' : '-') ?>
                    </dd>

                    <dt class="lead-field-heading tw-font-medium tw-text-neutral-500">
                        <?php echo _l('lead_add_edit_phonenumber'); ?>
                    </dt>
                    <dd class="tw-text-neutral-900 tw-mt-1">
                        <?php echo (isset($lead) && $lead->phonenumber != '' ? '<a href="tel:' . formatted_number($lead->phonenumber) . '">' . formatted_number($lead->phonenumber) . '</a>' : '-') ?>
                    </dd>

                    <!-- <dt class="lead-field-heading tw-font-medium tw-text-neutral-500">
                        <?php echo _l('lead_company'); ?>
                    </dt>
                    <dd class="tw-text-neutral-900 tw-mt-1">
                        <?php echo (isset($lead) && $lead->company != '' ? $lead->company : '-') ?>
                    </dd> -->
                    <!-- <dt class="lead-field-heading tw-font-medium tw-text-neutral-500">
                        <?php echo _l('Secondary Email'); ?>
                    </dt>
                    <dd class="tw-text-neutral-900 tw-mt-1">
                        <?php echo (isset($lead) && $lead->additional_email != '' ? '<a href="mailto:' . $lead->additional_email . '">' . $lead->additional_email . '</a>' : '-') ?>
                    </dd> -->
                    <!-- <dt class="lead-field-heading tw-font-medium tw-text-neutral-500">
                        <?php echo _l('Secondary name'); ?>
                    </dt> -->
                    <dd class="tw-text-neutral-900 tw-mt-1">
                        <?php echo (isset($lead) && $lead->secondary_name != '' ? $lead->secondary_name : '-') ?>
                    </dd>
                    <dt class="lead-field-heading tw-font-medium tw-text-neutral-500">
                        <?php echo _l('lead_address'); ?>
                    </dt>
                    <dd class="tw-text-neutral-900 tw-mt-1">
                        <?php echo (isset($lead) && $lead->address != '' ? $lead->address : '-') ?>
                    </dd>
                    <dt class="lead-field-heading tw-font-medium tw-text-neutral-500">
                        <?php echo _l('lead_city'); ?>
                    </dt>
                    <dd class="tw-text-neutral-900 tw-mt-1">
                        <?php echo (isset($lead) && $lead->city != '' ? $lead->city : '-') ?>
                    </dd>
                    <dt class="lead-field-heading tw-font-medium tw-text-neutral-500">
                        <?php echo "Province"; ?>
                    </dt>
                    <dd class="tw-text-neutral-900 tw-mt-1">
                        <?php echo (isset($lead) && $lead->state != '' ? $lead->state : '-') ?>
                    </dd>
                    <dt class="lead-field-heading tw-font-medium tw-text-neutral-500">
                        <?php echo _l('lead_country'); ?>
                    </dt>
                    <dd class="tw-text-neutral-900 tw-mt-1">
                        <?php echo (isset($lead) && $lead->country != 0 ? get_country($lead->country)->short_name : '-') ?>
                    </dd>
                    <dt class="lead-field-heading tw-font-medium tw-text-neutral-500">
                        <?php echo _l('Postal code'); ?>
                    </dt>
                    <dd class="tw-text-neutral-900 tw-mt-1">
                        <?php echo (isset($lead) && $lead->zip != '' ? $lead->zip : '-') ?>
                    </dd>
                    <dt class="lead-field-heading tw-font-medium tw-text-neutral-500">
                        <?php echo 'Position'; ?>
                    </dt>
                    <dd class="tw-text-neutral-900 tw-mt-1 mbot15">
                        <?php echo (isset($lead) && $lead->lead_borrow_position != '' ? $lead->lead_borrow_position : '-') ?>
                    </dd>
                        <?php if (!empty($leads_borrow)): ?>
                                    <?php
                                    $i = 2;
                                    $text = '';
                                    ?>
                                        <?php foreach ($leads_borrow as $borrow):
                                            switch ($i) {
                                                case 2:
                                                    $text = 'Second Party';
                                                    break;
                                                case 3:
                                                    $text = 'Third Party';
                                                    break;
                                                case 4:
                                                    $text = 'Fourth Party';
                                                    break;
                                                default:
                                                    $text = 'Party'; // Add a default case if needed
                                            }
                                            $i++;
                                            ?>
                                                    <span class="btn btn-primary" style="text-align: center; font-size: medium; font-weight: 700;margin-bottom:15px;"><?php echo $text; ?></span>
                                                    <dt class="lead-field-heading tw-font-medium tw-text-neutral-500">
                                                        <?php echo 'Name'; ?>
                                                    </dt>
                                                    <dd class="tw-text-neutral-900 tw-mt-1 mbot15">
                                                        <?php echo htmlspecialchars($borrow['borrow_firstname']) . ' ' . htmlspecialchars($borrow['borrow_middlename']) . ' ' . htmlspecialchars($borrow['borrow_lastname']) ?: '-'; ?>
                                                    </dd>
                                                    <dt class="lead-field-heading tw-font-medium tw-text-neutral-500">
                                                        <?php echo 'Email'; ?>
                                                    </dt>
                                                    <dd class="tw-text-neutral-900 tw-mt-1 mbot15">
                                                        <?php echo htmlspecialchars($borrow['borrow_email'] ?: '-'); ?>
                                                    </dd>
                                                    <dt class="lead-field-heading tw-font-medium tw-text-neutral-500">
                                                        <?php echo 'Phone'; ?>
                                                    </dt>
                                                    <dd class="tw-text-neutral-900 tw-mt-1 mbot15">
                                                        <?php echo htmlspecialchars($borrow['borrow_phone'] ?: '-'); ?>
                                                    </dd>
                                                    <dt class="lead-field-heading tw-font-medium tw-text-neutral-500">
                                                        <?php echo 'Address'; ?>
                                                    </dt>
                                                    <dd class="tw-text-neutral-900 tw-mt-1 mbot15">
                                                        <?php echo htmlspecialchars($borrow['borrow_address'] ?: '-'); ?>
                                                    </dd>
                                                    <dt class="lead-field-heading tw-font-medium tw-text-neutral-500">
                                                        <?php echo 'Position'; ?>
                                                    </dt>
                                                    <dd class="tw-text-neutral-900 tw-mt-1 mbot15">
                                                        <?php echo htmlspecialchars($borrow['borrow_position'] ?: '-'); ?>
                                                    </dd>
                                                    <dt class="lead-field-heading tw-font-medium tw-text-neutral-500">
                                                        <?php echo 'Marital Status'; ?>
                                                    </dt>
                                                    <dd>
                                                        <?php echo htmlspecialchars($borrow['borrow_martial_status'] ?: '-'); ?>
                                                    </dd>
                                                    <dt class="lead-field-heading tw-font-medium tw-text-neutral-500">
                                                        <?php echo 'Borrower City'; ?>
                                                    </dt>
                                                    <dd>
                                                        <?php echo htmlspecialchars($borrow['borrow_city'] ?: '-'); ?>
                                                    </dd>
                                                    <dt class="lead-field-heading tw-font-medium tw-text-neutral-500">
                                                        <?php echo 'Borrower Province'; ?>
                                                    </dt>
                                                    <dd>
                                                        <?php echo htmlspecialchars($borrow['borrow_province'] ?: '-'); ?>
                                                    </dd>
                                                    <dt class="lead-field-heading tw-font-medium tw-text-neutral-500">
                                                        <?php echo 'Postal code'; ?>
                                                    </dt>
                                                    <dd style="margin-bottom:15px;">
                                                        <?php echo htmlspecialchars($borrow['borrow_zipcode'] ?: '-'); ?>
                                                    </dd>
                                   
                                    <?php endforeach; ?>
                        <?php endif; ?>
                </dl>
            </div>
            <div class="col-md-4 col-xs-12 lead-information-col">
                <div class="alert alert-info">
                    <h4 class="no-margin font-medium-xs bold">
                        <?php echo 'General info'; ?>
                    </h4>
                </div>
                <dl> 
                    <?php
                    // if($current_staff_role != 2){
                    ?>
                    <dt class="lead-field-heading tw-font-medium tw-text-neutral-500">
                        <?php echo _l('Assigned Group'); ?>
                    </dt>
                    <dd class="tw-text-neutral-900 tw-mt-1 mbot15">
                        <?php echo (isset($lead) && $lead->assign_group != 0 ? $lead->assign_group : '-') ?>
                    </dd>
                    <dt class="lead-field-heading tw-font-medium tw-text-neutral-500">
                        <?php echo _l('Staff Included'); ?>
                    </dt>
                    <dd class="tw-text-neutral-900 tw-mt-1 mbot15">
                        <?php
                        if (!empty($get_staff_name_by_group)) {
                            $concatenated_names = implode(', ', $get_staff_name_by_group);
                            $display_names = strlen($concatenated_names) > 10 ? substr($concatenated_names, 0, 30) . '...' : $concatenated_names;
                            echo '<span class="text-has-action" data-toggle="tooltip" data-title="' . implode(', ', $get_staff_name_by_group) . '">' . $display_names . '</span>';
                        } else {
                            echo '-';
                        }
                        ?>

                    </dd>
                    <?php
                    //  }
                    ?>
                     <dt class="lead-field-heading tw-font-medium tw-text-neutral-500">
                        <?php echo _l('Brokerage'); ?>
                    </dt>
                    <dd class="tw-text-neutral-900 tw-mt-1 mbot15">
                        <?php
                            print_r(get_brokerage_name_using_brokerage_id($this, $lead->brokerage_id));
                        ?>
                    </dd>
                    <dt class="lead-field-heading tw-font-medium tw-text-neutral-500">
                        <?php echo _l('Broker'); ?>
                    </dt>
                    <dd class="tw-text-neutral-900 tw-mt-1 mbot15">
                        <?php
                            print_r($broker_name_profile_show);
                        // if (!empty($broker_name_profile_show)) {
                        //     $concatenated_broker_name = implode(', ', $broker_name_profile_show);
                        //     $display_names = strlen($concatenated_broker_name) > 10 ? substr($concatenated_broker_name, 0, 30) . '...' : $concatenated_broker_name;
                        //     echo '<span class="text-has-action" data-toggle="tooltip" data-title="' . implode(', ', $broker_name_profile_show) . '">' . $display_names . '</span>';
                        // } else {
                        //     echo '-';
                        // }
                        ?>

                    </dd>
                    <dt class="lead-field-heading tw-font-medium tw-text-neutral-500">
                        <?php echo "Case Created"; ?>
                    </dt>
                    <dd class="tw-text-neutral-900 tw-mt-1">
                        <?php $case_created_data = date('Y-m-d', strtotime($lead->dateadded)); ?>
                        <?php echo (isset($lead) && $lead->dateadded != '' ? '<span class="text-has-action" data-toggle="tooltip" data-title="' . time_ago($lead->dateadded) . '">' . _d($case_created_data) . '</span>' : '-') ?>
                    </dd>
                    <?php if ($current_staff_role != 2 || $current_staff_role != 6) { ?>
                            <!-- <dt class="lead-field-heading tw-font-medium tw-text-neutral-500">
                        <?php echo _l('leads_dt_last_contact'); ?>
                    </dt>
                    <dd class="tw-text-neutral-900 tw-mt-1">
                        <?php echo (isset($lead) && $lead->lastcontact != '' ? '<span class="text-has-action" data-toggle="tooltip" data-title="' . time_ago($lead->lastcontact) . '">' . _dt($lead->lastcontact) . '</span>' : '-') ?>
                    </dd> -->
                    <?php } ?>
                    <!-- <dt class="lead-field-heading tw-font-medium tw-text-neutral-500">
                        <?php echo _l('lead_public'); ?>
                    </dt>
                    <dd class="tw-text-neutral-900 tw-mt-1 mbot15">
                        <?php if (isset($lead)) {
                            if ($lead->is_public == 1) {
                                echo _l('lead_is_public_yes');
                            } else {
                                echo _l('lead_is_public_no');
                            }
                        } else {
                            echo '-';
                        }
                        ?>
                    </dd> -->
                    <?php if (isset($lead) && $lead->from_form_id != 0) { ?>
                                <dt class="lead-field-heading tw-font-medium tw-text-neutral-500">
                                    <?php echo _l('web_to_lead_form'); ?>
                                </dt>
                                <dd class="tw-text-neutral-900 tw-mt-1 mbot15">
                                    <?php echo $lead->form_data->name; ?>
                                </dd>
                    <?php } ?>
                </dl>
                <!-- <div class="alert alert-info">
                    <h4 class="no-margin font-medium-xs bold">
                        <?php echo 'Second Broker Details'; ?>
                    </h4>
                </div>
                <dl>
                    <dt class="lead-field-heading tw-font-medium tw-text-neutral-500">
                        <?php echo "First Name"; ?>
                    </dt>
                    <dd class="tw-text-neutral-900 tw-mt-1 mbot15">
                        <?php echo ($lead->second_broker_firstname) ? $lead->second_broker_firstname : '-'; ?>
                    </dd>
                    <dt class="lead-field-heading tw-font-medium tw-text-neutral-500">
                        <?php echo "Last Name"; ?>
                    </dt>
                    <dd class="tw-text-neutral-900 tw-mt-1 mbot15">
                        <?php echo ($lead->second_broker_lastname) ? $lead->second_broker_lastname : '-'; ?>
                    </dd>
                    <dt class="lead-field-heading tw-font-medium tw-text-neutral-500">
                        <?php echo "Email"; ?>
                    </dt>
                    <dd class="tw-text-neutral-900 tw-mt-1 mbot15">
                        <?php echo ($lead->second_broker_email) ? $lead->second_broker_email : '-'; ?>
                    </dd>
                </dl> -->
            </div>
            <div class="col-md-4 col-xs-12 lead-information-col">
                <div class="alert alert-info">
                    <h4 class="no-margin font-medium-xs bold">
                        <?php echo 'Other info'; ?>
                    </h4>
                </div>
                <dl>

                    <dt class="lead-field-heading tw-font-medium tw-text-neutral-500">
                        <?php echo 'Marital status'; ?>
                    </dt>
                    <dd class="tw-text-neutral-900 tw-mt-1 mbot15">
                        <?php echo (isset($lead) && $lead->martial_status != '' ? $lead->martial_status : '-') ?>
                    </dd>
                    <?php if ($current_staff_role != 2 || $current_staff_role != 6) { ?>
                        <dt class="lead-field-heading tw-font-medium tw-text-neutral-500">
                            <?php echo 'Pin Check'; ?>
                        </dt>
                        <dd class="tw-text-neutral-900 tw-mt-1 mbot15">
                            <?php echo (isset($lead) && $lead->pin_check != '' ? $lead->pin_check : '-') ?>
                        </dd>
                    <?php } ?>
                    <!-- <dt class="lead-field-heading tw-font-medium tw-text-neutral-500">
                        <?php echo 'Transaction'; ?>
                    </dt>
                    <dd class="tw-text-neutral-900 tw-mt-1 mbot15">
                        <?php echo (isset($lead) && $lead->transaction != '' ? $lead->transaction : '-') ?>
                    </dd> -->
                    <dt class="lead-field-heading tw-font-medium tw-text-neutral-500">
                        <?php echo 'Preferred Contact Method'; ?>
                    </dt>
                    <dd class="tw-text-neutral-900 tw-mt-1 mbot15">
                    <?php
                    echo (isset($lead) && $lead->preferred_contact_method != '' ? $lead->preferred_contact_method : '-')
                        ?>
                    </dd>
                    <!-- <dt class="lead-field-heading tw-font-medium tw-text-neutral-500">
                        <?php echo 'Loan Amount'; ?>
                    </dt>
                    <dd class="tw-text-neutral-900 tw-mt-1 mbot15">
                        <?php echo (isset($lead) && $lead->loan_amount != '' ? $lead->loan_amount : '-') ?>
                    </dd> -->
                    <dt class="lead-field-heading tw-font-medium tw-text-neutral-500">
                        <?php echo 'Target Closing Date'; ?>
                    </dt>
                    <?php $target_close_date = date('Y-m-d', strtotime($lead->excepting_closing_date)); ?>
                    <dd class="tw-text-neutral-900 tw-mt-1 mbot15">
                        <span class="text-has-action" data-toggle="tooltip" data-title="<?php echo (isset($lead) && $lead->excepting_closing_date != '' ? time_ago($lead->excepting_closing_date) : '') ?>"> <?php echo (isset($lead) && $lead->excepting_closing_date != '' ? _d($target_close_date) : '-') ?></span>
                    </dd>
                </dl>
                <!-- <div class="col-md-12"> -->
                    <dl>
                        <dt class="lead-field-heading tw-font-medium tw-text-neutral-500">
                            <?php echo _l('Special Note'); ?>
                        </dt>
                        <dd class="tw-text-neutral-900 tw-mt-1">
                            <?php echo (isset($lead) && $lead->description != '' ? $lead->description : '-') ?>
                        </dd>
                    </dl>
                    <dl>
                        <dt class="lead-field-heading tw-font-medium tw-text-neutral-500">
                            <?php echo _l('Prepaid Interest'); ?>
                        </dt>
                        <dd class="tw-text-neutral-900 tw-mt-1">
                            <?php echo (isset($lead) && $lead->prepaid_rate != '' ? $lead->prepaid_rate : '-') ?>
                        </dd>
                    </dl>
                    <?php if ($current_staff_role != 2 || $current_staff_role != 6) { ?>
                                <dl>
                                    <dt class="lead-field-heading tw-font-medium tw-text-neutral-500">
                                        <?php echo 'LRO Docket'; ?>
                                    </dt>
                                    <dd class="tw-text-neutral-900 tw-mt-1">
                                        <?php echo (isset($lead) && $lead->contacted_notes != '' ? $lead->contacted_notes : '-') ?>
                                    </dd>
                                </dl>
                    <?php } ?>
                    <!-- <dt class="lead-field-heading tw-font-medium tw-text-neutral-500">
                        <?php /* echo 'Lender Name'; */?>
                    </dt> -->
                    <!-- <dd class="tw-text-neutral-900 tw-mt-1 mbot15">
                        <?php /* echo (isset($lead) && $lead->lender_ids != '' ? get_lender_name_by_lender_id($this, $lead->lender_ids) : '-') */?>
                    </dd> -->
                    <dt class="lead-field-heading tw-font-medium tw-text-neutral-500">
                        <?php echo 'Lender Details'; ?>
                    </dt>
                    <dd class="tw-text-neutral-900 tw-mt-1 mbot15">
                        <?php echo get_lender_details_show($this, $lead->id, $lead->lender_ids); ?>
                    </dd>
                <!-- </div> -->
            </div>
            <div class="col-md-4 col-xs-12 lead-information-col">
                <?php if (total_rows(db_prefix() . 'customfields', ['fieldto' => 'leads', 'active' => 1]) > 0 && isset($lead)) { ?>
                            <div class="lead-info-heading">
                                <h4>
                                    <?php echo _l('custom_fields'); ?>
                                </h4>
                            </div>
                            <dl>
                                <?php
                                $custom_fields = get_custom_fields('leads');
                                foreach ($custom_fields as $field) {
                                    $value = get_custom_field_value($lead->id, $field['id'], 'leads'); ?>
                                            <dt class="lead-field-heading tw-font-medium tw-text-neutral-500 no-mtop">
                                                <?php echo $field['name']; ?>
                                            </dt>
                                            <dd class="tw-text-neutral-900 tw-mt-1 tw-break-words">
                                                <?php echo ($value != '' ? $value : '-') ?>
                                            </dd>
                                            <?php
                                } ?>
                    <?php } ?>
                </dl>
            </div>
            <div class="clearfix"></div>
        </div>
        <div class="clearfix"></div>
        <div id="lead_edit" class="lead-edit<?php if (isset($lead)) {
            echo ' hide';
        } ?>">
        <?php if ($current_staff_role != 2 || $current_staff_role != 6) { ?>
                    <div class="col-md-4">
                        <?php
                        $selected = '';
                        if (isset($lead)) {
                            $selected = $lead->status;
                        } elseif (isset($status_id)) {
                            $selected = $status_id;
                        }
                        echo render_leads_status_select($statuses, $selected, 'lead_add_edit_status');
                        ?>
                    </div>
        <?php } else { ?>
                    <input type="hidden" name="status" id="status" value="1">
            <?php } ?>
            <!-- <div class="col-md-4">
                <?php
                $assigned_attrs = [];
                $selected = (isset($lead) ? $lead->assigned : get_staff_user_id());
                if (
                    isset($lead)
                    && $lead->assigned == get_staff_user_id()
                    && $lead->addedfrom != get_staff_user_id()
                    && !is_admin($lead->assigned)
                    && !has_permission('leads', '', 'view')
                ) {
                    $assigned_attrs['disabled'] = true;
                }
                echo render_select('assigned', $members, ['staffid', ['firstname', 'lastname']], 'lead_add_edit_assigned', $selected, $assigned_attrs); ?>
            </div> -->
            <?php
            /* if (!empty(is_admin())) {  */
            if ($current_staff_role != 2 && $current_staff_role != 6) {
                ?>
                        <!-- chekc broker upload file or not if upload then admin assign the case otherwise not and when case is assign then case acitve -->
                        <?php /*if(!empty($broker_upload_file)){*/ ?>
                            <div class="col-md-4">
                                <div class="form-group form-group-select-input-status input-group-select">
                                    <?php
                                    $imp_html = "<label for='assign_group' class='control-label'>Assign Groups</label>";
                                    $imp_html .= "<select name='assign_group' id='assign_group' class='form-control selectpicker' data-width='100%' data-none-selected-text='Nothing selected' data-live-search='true' tabindex='-98'>";
                                    $imp_html .= "<option value=''>Not assigned yet</option>";
                                    $get_current_staff_group = get_group_name_of_staff($this, get_staff_user_id());
                                    foreach ($staff_group as $imp) {
                                        if (!empty($lead->assign_group)) {
                                            $selected = (isset($lead) && $imp == $lead->assign_group ? 'selected' : '');
                                        } else {
                                            $selected = ($imp == $get_current_staff_group ? 'selected' : '');
                                        }
                                        $imp_html .= "<option value='$imp' $selected>Team $imp</option>";
                                    }
                                    $imp_html .= "</select>";
                                    echo $imp_html;
                                    ?>
                                </div>
                            </div>  
                        <?php /*}*/ ?>
            <?php } ?>
            <div class="col-md-4">
                <div class="form-group form-group-select-input-status input-group-select">
                    <?php
                    $imp_html = "<label for='total_fields' class='control-label'>Number of parties</label>";
                    $imp_html .= "<select name='total_fields' id='total_fields' class='form-control selectpicker' data-width='100%' data-none-selected-text='Nothing selected' data-live-search='true' tabindex='-98' onchange='updateFields()'>";
                    $imp_html .= "<option value=''>1</option>";
                    // $imp_html .= "<option value='1' >1</option>";
                    if ($leads_borrow_count >= 2) {
                    } else {
                        $imp_html .= "<option value='2' >2</option>";
                    }
                    if ($leads_borrow_count >= 3) {
                    } else {
                        $imp_html .= "<option value='3' >3</option>";
                    }
                    if ($leads_borrow_count >= 4) {
                    } else {
                        $imp_html .= "<option value='4' >4</option>";
                    }
                    $imp_html .= "</select>";
                    echo $imp_html;
                    ?>
                </div>
            </div>
            <!-- show the dropdown of company -->
            <div class="col-md-4" style="">
                <div class="form-group form-group-select-input-status input-group-select">
                    <?php
                    $imp_html = "<small class='req text-danger'>*</small> <label for='brokerage_id' class='control-label'>Select Brokerage</label>";
                    $imp_html .= "<select name='brokerage_id' id='brokerage_id' class='form-control selectpicker' data-width='100%' data-none-selected-text='Nothing selected' data-live-search='true' tabindex='-98' required>";

                    if (!empty($brokerage_data)) {
                        $role = get_current_staff_role($this, get_staff_user_id());
                        $brokerage_id = get_current_staff_brokerage_id($this, get_staff_user_id());
                        $imp_html .= "<option value=''>Select Brokerage</option>";
                        foreach ($brokerage_data as $id => $name) {
                            $mandatory_value = get_brokerage_mandatory_details($this, $id);
                            if($role == 2 || $role == 6){
                                if($brokerage_id == $id){
                                    $id = htmlspecialchars($id);
                                    $name = htmlspecialchars($name);
                                    $selected = (isset($lead_selected_brokerage_id) && in_array($id, explode(',', $lead_selected_brokerage_id))) ? 'selected' : '';

                                    $imp_html .= "<option value='$id' data-id='$mandatory_value' $selected>$name</option>";
                                }
                            }else{
                                $id = htmlspecialchars($id);
                                $name = htmlspecialchars($name);
                                $selected = (isset($lead_selected_brokerage_id) && in_array($id, explode(',', $lead_selected_brokerage_id))) ? 'selected' : '';

                                $imp_html .= "<option value='$id' data-id='$mandatory_value' $selected>$name</option>";
                            }
                           
                        }
                    } else {
                        $imp_html .= "<option disabled>No Brokerages Available</option>";
                    }

                    $imp_html .= "</select>";
                    echo $imp_html;
                    ?>
                </div>
            </div>
            <?php /*if(get_current_staff_role($this, get_staff_user_id()) != 2){*/ ?>
                <div class="col-md-4" style="">
                    <div class="form-group form-group-select-input-status input-group-select">
                        <?php
                        $imp_html = "<small class='req text-danger' id='addedfrom_field_star_show'>*</small> <label for='addedfrom' class='control-label'>Broker Assigned</label>";
                        $imp_html .= "<select name='addedfrom[]' id='addedfrom' class='form-control selectpicker' data-width='100%' data-none-selected-text='Nothing selected' data-live-search='true' tabindex='-98' multiple>";
                        $imp_html .= "<option value='' disabled>Select Broker</option>";
                        $imp_html .= "</select>";
                        echo $imp_html;
                        ?>
                    </div>
            <?php /*}*/ ?>
            </div>
            <div class="col-md-12 col-xs-12 lead-information-col" id="staff_names_list_main_div" style='display:none;'>
                <div class="" style="font-weight: 800;padding: 18px;width: 100%; height: 100%;background-color: #b0d1f7db;font-size: medium;border-radius: 6px;">
                    <span class="no-margin font-medium-xs bold" >
                        <bold class="font-medium-xs bold" id="staff_names_list" class="staff_names_list"></bold>
                    </span>
                </div>
            </div>
            <div class="clearfix"></div>
            <hr class="mtop5 mbot10" />
            <div class="row" style="display:flex;justify-content:center;margin-bottom:10px;">
                <span class="col-md-6 btn btn-primary" style="text-align: center; font-size: medium; font-weight: 700;pointer-events: none; ">Lender Details</span>
            </div>
            <div class="row">
                <div class="col-md-4">
                <?php
                $imp_html = "<div class='form-group' style='margin-left:15px;'><label style='margin-top: 5px;margin-bottom:5px;' for='lender_ids' class='control-label'>Select Lender</label>";
                $imp_html .= "<select name='lender_ids[]' id='lender_ids' class='form-control selectpicker' data-width='100%' data-none-selected-text='Nothing selected' data-live-search='true' tabindex='-98' multiple>";
                $lender_names_array = isset($lead) ? explode(',', $lead->lender_ids) : [];
                foreach ($lender_data as $imp) {
                    $lender_name = $imp['bank_name'];
                    $lender_id = $imp['id'];
                    $selected = in_array($lender_id, $lender_names_array) ? 'selected' : '';

                    $imp_html .= "<option value='$lender_id' $selected>$lender_name</option>";
                }
                $imp_html .= "</select></div>";
                echo $imp_html;
                ?>
                </div>
                <input type="text" id="loan_total_post_req" name="loan_total_post_req[]" readonly style="display:none;">
                <div id="lender_fields_appened_div"></div>
            </div>
            <div class="clearfix"></div>
            <hr class="mtop5 mbot10" />
            <div class="col-md-6">
                <?php
                $nameParts = explode(' ', $lead->name);

                $firstName = $nameParts[0];
                $middleName = '';
                $lastName = '';

                if (count($nameParts) == 2) {
                    // If there are only two parts, treat them as first and last names
                    $lastName = $nameParts[1];
                } elseif (count($nameParts) > 2) {
                    // If there are more than two parts, treat the second part as the middle name
                    $middleName = $nameParts[1];
                    // Combine all remaining parts as the last name
                    $lastName = implode(' ', array_slice($nameParts, 2));
                }
                ?>
                <span class=" btn btn-primary" style="text-align: center; font-size: medium; font-weight: 700;margin-bottom:15px;">First Party</span>
                <?php $firstname = (isset($firstName) ? $firstName : ''); ?>
                <?php echo render_input('firstname', '<span style="color:red;">*</span> First Name', $firstname, 'required'); ?>

                <?php $middlename = (isset($middleName) ? $middleName : ''); ?>
                <?php echo render_input('middlename', 'Middle Name', $middlename); ?>

                <?php $lastname = (isset($lastName) ? $lastName : ''); ?>
                <?php echo render_input('lastname', '<span style="color:red;">*</span> Last Name', $lastname, 'required'); ?>
                <!-- <?php $value = (isset($lead) ? $lead->secondary_name : ''); ?>
                <?php echo render_input('secondary_name', 'Secondary name', $value, ); ?> -->
                <?php $value = (isset($lead) ? $lead->title : ''); ?>
                <?php $value = (isset($lead) ? $lead->email : ''); ?>
                <?php echo render_input('email', '<span style="color:red;">*</span> Enter Email', $value, 'required'); ?>
                <?php
                $value = (!empty($lead->phonenumber) ? formatted_number($lead->phonenumber) : ''); ?>
                <?php echo render_input('phonenumber', 'lead_add_edit_phonenumber', $value); ?>
                <?php
                $imp_html = "<div class='form-group'><label style='margin-top: 5px;margin-bottom:5px;' for='preferred_contact_method[]' class='control-label'>Preferred Contact Method</label>";
                $imp_html .= "<select name='preferred_contact_method[]' id='preferred_contact_method' class='form-control selectpicker' data-width='100%'  data-none-selected-text='Nothing selected' data-live-search='true' tabindex='-98'>";

                foreach ($preferred_contact_method_array as $key => $value) {
                    $selected = (isset($lead->preferred_contact_method) && strpos($lead->preferred_contact_method, (string) $key) !== false) ? 'selected' : '';
                    $imp_html .= "<option value='$key' $selected>$value</option>";
                }
                $imp_html .= "</select></div>";
                echo $imp_html; ?>
                <?php
                $preferred_content_style_email = ($lead->preferred_contact_method == 'Email') ? 'display:block;' : 'display:none;';
                $preferred_content_style_phone = ($lead->preferred_contact_method == 'Phone') ? 'display:block;' : 'display:none;';
                ?>
                <div id="borrower1_phonenumber_div" style="<?php echo $preferred_content_style_phone; ?>">
                </div>
                <?php
                $value = (!empty($lead->excepting_closing_date) ? _d($lead->excepting_closing_date) : ''); ?>
                <?php echo render_date_input('excepting_closing_date', 'Target Closing Date', $value, []); ?>
                <?php
                $imp_html = "<div class='form-group'><label style='margin-top: 5px;margin-bottom:5px;' for='lead_borrow_position' class='control-label'>Parties Position</label>";
                $imp_html .= "<select name='lead_borrow_position' id='lead_borrow_position' class='form-control selectpicker' data-width='100%' data-none-selected-text='Nothing selected' data-live-search='true' tabindex='-98'>";
                $imp_html .= "<option value=''>Not assigned yet</option>";
                foreach ($borrow_position as $imp) {
                    $selected = (isset($lead) && $imp == $lead->lead_borrow_position ? 'selected' : '');

                    $imp_html .= "<option value='$imp' $selected>$imp</option>";
                }
                $imp_html .= "</select></div>";
                echo $imp_html; ?>
            </div>

            <div class="col-md-6">
                <?php $value = (isset($lead) ? $lead->address : ''); ?>
                <?php echo render_textarea('address', 'lead_address', $value, ['rows' => 1, 'style' => 'height:36px;font-size:100%;']); ?>
                <?php $value = (isset($lead) ? $lead->city : ''); ?>
                <?php echo render_input('city', 'lead_city', $value); ?>
                <!-- <?php $value = (isset($lead) ? $lead->state : ''); ?> -->
                <?php $value = (isset($lead) ? 'Ontario' : 'Ontario'); ?>
                <span style="">
                    <?php echo render_input('state', 'Province', $value); ?>
                </span>
                <span style="display:none;">
                <?php
                $countries = get_all_countries();
                $customer_default_country = get_option('customer_default_country');
                // $selected = (isset($lead) ? $lead->country : $customer_default_country);
                $selected = 40;
                echo render_select('country', $countries, ['country_id', ['short_name']], 'lead_country', $selected, ['data-none-selected-text' => _l('dropdown_non_selected_tex'), 'style' => 'display:none;']);
                ?>
                </span>
                <?php $value = (isset($lead) ? $lead->zip : ''); ?>
                <?php echo render_input('zip', 'Postal code', $value); ?>
                <!-- martial and transition status -->
                <!-- <?php $value = (isset($lead) ? $lead->company : ''); ?>
                <?php echo render_input('company', 'lead_company', $value); ?> -->
                <!-- <div id="new_lender_name_div" style="display:none;">
                    <?php echo render_input('new_lender_name', 'New Lender Name', '', 'text', ['id' => 'new_lender_name']); ?>
                </div> -->
                <!-- <?php /* 
                $value = (!empty($lead->loan_amount) ? $lead->loan_amount : ''); ?>
                <?php echo render_input('loan_amount', 'New Loan Amount', $value, 'text'); ?>
                <?php

                $imp_html = "<div class='form-group'><label for='transaction' class='control-label'>Transaction</label>";
                $imp_html .= "<select name='transaction' id='transaction' class='form-control selectpicker' data-width='100%' data-none-selected-text='Nothing selected' data-live-search='true' tabindex='-98'>";
                $imp_html .= "<option value=''>Not assigned yet</option>";
                foreach ($transaction as $imp) {
                    $get_transaction_name = $imp['name'];
                    $selected = (isset($lead) && $get_transaction_name == $lead->transaction ? 'selected' : '');

                    $imp_html .= "<option value='$get_transaction_name' $selected>$get_transaction_name</option>";
                }
                $imp_html .= "<option value='other'>others</option>";
                $imp_html .= "</select></div>";
                echo $imp_html;  */?>
                <div id="new_transaction_div" style="display:none;">
                    <?php /*  echo render_input('new_transaction_name', 'New Transaction Details', '', 'text', ['id' => 'new_transaction_name']); */?>
                </div> -->
                 <?php
                 $imp_html = "<div class='form-group'><label style='margin-top: 5px;margin-bottom:5px;' for='martial_status' class='control-label'>Marital Status</label>";
                 $imp_html .= "<select name='martial_status' id='martial_status' class='form-control selectpicker' data-width='100%' data-none-selected-text='Nothing selected' data-live-search='true' tabindex='-98'>";
                 $imp_html .= "<option value=''>Not assigned yet</option>";
                 foreach ($merital_s as $imp) {
                     $selected = (isset($lead) && $imp == $lead->martial_status ? 'selected' : '');

                     $imp_html .= "<option value='$imp' $selected>$imp</option>";
                 }
                 $imp_html .= "</select></div>";
                 echo $imp_html; ?>
                <?php
                if ($current_staff_role != 2 || $current_staff_role != 6) {
                    $imp_html = "<div class='form-group'><label style='margin-top: 5px;margin-bottom:5px;' for='pin_check' class='control-label'>Pin check</label>";
                    $imp_html .= "<select name='pin_check' id='pin_check' class='form-control selectpicker' data-width='100%' data-none-selected-text='Nothing selected' data-live-search='true' tabindex='-98'>";
                    $Yesselected = (isset($lead) && $lead->pin_check == 'Yes' ? 'selected' : '');
                    $Noselected = (isset($lead) && $lead->pin_check == 'No' ? 'selected' : '');
                    $imp_html .= "<option value=''>Not assigned yet</option>";
                    $imp_html .= "<option value='Yes' $Yesselected>Yes</option>";
                    $imp_html .= "<option value='No' $Noselected>No</option>";
                    $imp_html .= "</select></div>";
                    echo $imp_html;
                }
                ?>
            </div>
            
            <div class="col-md-12">
                <div id="fields_container"></div>
            </div>
            <div class="col-md-12">
                <?php
                if (!empty($leads_borrow)):
                    $count = 0;
                    ?>
                            <hr class="-tw-mx-4 tw-border-neutral-200 col-md-12" style="margin-top: 20px; margin-bottom: 20px; border-width: 10px 0px 0px; border-top-style: solid; border-right-style: initial; border-bottom-style: initial; border-left-style: initial; border-top-color: rgb(133 151 243); border-right-color: initial; border-bottom-color: initial; border-left-color: initial; border-image: initial;">
                            <?php
                            $i = 2;
                            foreach ($leads_borrow as $borrow):
                                switch ($i) {
                                    case 1:
                                        $text = 'First Party';
                                        break;
                                    case 2:
                                        $text = 'Second Party';
                                        break;
                                    case 3:
                                        $text = 'Third Party';
                                        break;
                                    case 4:
                                        $text = 'Fourth Party';
                                        break;
                                    default:
                                        $text = ' Party';
                                        break;
                                }
                                ?>
                                        <div class="col-md-6">
                                        <span class=" btn btn-primary" style="text-align: center; font-size: medium; font-weight: 700;margin-bottom:15px;1"><?php echo $text; ?></span>
                                            <div class="form-group">
                                                <!-- Hidden input field to store borrow_id -->
                                                <input type="hidden" name="borrow_id[]" value="<?php echo $borrow['id']; ?>">
                                
                                                <label for="borrow_firstname">First Name</label>
                                                <input type="text" name="borrow_firstname[]" class="form-control" value="<?php echo htmlspecialchars($borrow['borrow_firstname']); ?>">
                                            </div>
                                            <div class="form-group">
                                                <label for="borrow_middlename">Middle Name</label>
                                                <input type="text" name="borrow_middlename[]" class="form-control" value="<?php echo htmlspecialchars($borrow['borrow_middlename']); ?>">
                                            </div>
                                            <div class="form-group">
                                                <label for="borrow_lastname">Last Name</label>
                                                <input type="text" name="borrow_lastname[]" class="form-control" value="<?php echo htmlspecialchars($borrow['borrow_lastname']); ?>">
                                            </div>
                                            <div class="form-group">
                                                <label for="borrow_address">Address</label>
                                                <input type="text" name="borrow_address[]" class="form-control" value="<?php echo htmlspecialchars($borrow['borrow_address']); ?>">
                                            </div>
                                            <div class="form-group">
                                                <label for="borrow_city">City</label>
                                                <input type="text" name="borrow_city[]" class="form-control" value="<?php echo htmlspecialchars($borrow['borrow_city']); ?>">
                                            </div>
                                            <div class="form-group">
                                                <label for="borrow_province">Province</label>
                                                <input type="text" name="borrow_province[]" class="form-control" value="<?php echo htmlspecialchars($borrow['borrow_province']); ?>">
                                            </div>
                                            <div class="form-group">
                                                <label for="borrow_zipcode">Postal code</label>
                                                <input type="text" name="borrow_zipcode[]" class="form-control" value="<?php echo htmlspecialchars($borrow['borrow_zipcode']); ?>">
                                            </div>
                                            <?php
                                                // Begin form group for Marital Status
                                                $imp_html = "<div class='form-group'>";
                                                $imp_html .= "<label for='borrow_martial_status{$i}' class='control-label' style='margin-top: 5px; margin-bottom: 5px;'>Marital Status</label>";

                                                // Start select field
                                                $imp_html .= "<select name='borrow_martial_status[]{$i}'id='borrow_martial_status{$i}' class='form-control selectpicker' data-width='100%'data-none-selected-text='Nothing selected' data-live-search='true'>";

                                                $imp_html .= "<option value=''>Not assigned yet</option>";
                                                foreach ($merital_s as $imp) {
                                                    $selected = (isset($lead) && $imp == $borrow['borrow_martial_status']) ? 'selected' : '';
                                                    $imp_html .= "<option value='{$imp}' {$selected}>{$imp}</option>";
                                                }
                                                $imp_html .= "</select>";
                                                $imp_html .= "</div>";
                                                echo $imp_html;
                                            ?>
                                            <?php
                                            $borrow_email_style = ($borrow['borrow_preferred_method'] == 'Email') ? 'display:block;' : '';
                                            $borrow_phone_style = ($borrow['borrow_preferred_method'] == 'Phone') ? 'display:block;' : '';
                                            ?>
                                            <div class="form-group" id="borrow_email_div<?php echo $i; ?>" style="<?php echo $borrow_email_style; ?>">
                                                <label>Email</label>
                                                <input type="email" class="form-control" name="borrow_email[]" id="borrow_email<?php echo $i; ?>" value="<?php echo htmlspecialchars($borrow['borrow_email']); ?>">
                                            </div>
                                            <div class="form-group" id="borrow_phone_div<?php echo $i; ?>" style="<?php echo $borrow_phone_style; ?>">
                                                <label>Phone</label>
                                                <input type="text" class="form-control" name="borrow_phone[]" id="borrow_phone<?php echo $i; ?>" value="<?php echo htmlspecialchars($borrow['borrow_phone']); ?>">
                                            </div>
                                            <div class="form-group">
                                                <label for="borrow_preferred_method">Preferred Contact Method</label>
                                                <select name="borrow_preferred_method[]" id="borrow_preferred_method<?= $i ?>" class="form-control">
                                                <option value="" >Nothing Selected</option>
                                                    <option value="Email" <?php if ($borrow['borrow_preferred_method'] == 'Email')
                                                        echo 'selected'; ?>>Email</option>
                                                    <option value="Phone" <?php if ($borrow['borrow_preferred_method'] == 'Phone')
                                                        echo 'selected'; ?>>Phone</option>
                                                </select>
                                            </div>
                                            <div class="form-group">
                                                <label for="borrow_position">Parties Position</label>
                                                <select name="borrow_position[]" class="form-control">
                                                    <option value="Borrower" <?php if ($borrow['borrow_position'] == 'Borrower')
                                                        echo 'selected'; ?>>Borrower</option>
                                                    <option value="Consenting Spouse" <?php if ($borrow['borrow_position'] == 'Consenting Spouse')
                                                        echo 'selected'; ?>>Consenting Spouse</option>
                                                    <option value="Guarantor" <?php if ($borrow['borrow_position'] == 'Guarantor')
                                                        echo 'selected'; ?>>Guarantor</option>
                                                </select>
                                            </div>
                                        </div>                    
                                    <?php
                                    $count++;
                                    if ($count == 2 || $count == 4 || $count == 6 || $count == 8):
                                        ?>
                                            <hr class="-tw-mx-4 tw-border-neutral-200 col-md-12" style="margin-top: 20px; margin-bottom: 20px; border-width: 5px 0px 0px; border-top-style: solid; border-right-style: initial; border-bottom-style: initial; border-left-style: initial; border-top-color: rgb(133 151 243); border-right-color: initial; border-bottom-color: initial; border-left-color: initial; border-image: initial;">
                                            <?php
                                    endif;
                                    $i++;
                            endforeach;
                            ?>
                            <hr class="-tw-mx-4 tw-border-neutral-200 col-md-12" style="margin-top: 20px; margin-bottom: 20px; border-width: 10px 0px 0px; border-top-style: solid; border-right-style: initial; border-bottom-style: initial; border-left-style: initial; border-top-color: rgb(133 151 243); border-right-color: initial; border-bottom-color: initial; border-left-color: initial; border-image: initial;">
                            <?php
                endif;
                ?>
            </div>
            <div class="col-md-12" style='margin-top: 10px'>
                <?php $value = (isset($lead) ? $lead->description : ''); ?>
                <?php echo render_textarea('description', 'Special Note', $value); ?>
                <!-- prepaid notes -->
                <?php $value = (isset($lead) ? $lead->prepaid_rate : ''); ?>
                <?php echo render_textarea('prepaid_rate', 'Prepaid Interest', $value); ?>
                <div class="row">
                    <div class="col-md-12">
                        <?php if (!isset($lead)) { ?>
                                    <div class="lead-select-date-contacted hide">
                                        <?php echo render_datetime_input('custom_contact_date', 'lead_add_edit_datecontacted', '', ['data-date-end-date' => date('Y-m-d')]); ?>
                                    </div>
                        <?php } else { ?>
                                    <?php echo render_datetime_input('lastcontact', 'leads_dt_last_contact', _dt($lead->lastcontact), ['data-date-end-date' => date('Y-m-d')]); ?>
                        <?php } ?>
                        <!-- <div class="checkbox-inline checkbox checkbox-primary<?php if (isset($lead)) {
                            echo ' hide';
                        } ?><?php if (isset($lead) && (is_lead_creator($lead->id) || has_permission('leads', '', 'edit'))) {
                             echo ' lead-edit';
                         } ?>">
                            <input type="checkbox" name="is_public" <?php if (isset($lead)) {
                                if ($lead->is_public == 1) {
                                    echo 'checked';
                                }
                            }
                            ; ?> id="lead_public">
                            <label for="lead_public">
                                <?php echo _l('lead_public'); ?>
                            </label>
                        </div> -->
                        <?php if (!isset($lead)) { ?>
                                    <div class="checkbox-inline checkbox checkbox-primary" <?php echo ($current_staff_role == 2 || $current_staff_role == 6) ? 'style="display:none;"' : ''; ?>>
                                        <input type="checkbox" name="contacted_today" id="contacted_today" checked>
                                        <label for="contacted_today">
                                            <?php echo _l('lead_add_edit_contacted_today'); ?>
                                        </label>
                                    </div>
                        <?php } ?>
                        <!-- when case created then show -->
                        <?php if ($current_staff_role != 2 && $current_staff_role != 6) { ?>
                                <?php if (!isset($lead)) { ?>
                                        <div id="contacted_notes_div" style="display:block;">
                                            <?php $value = (isset($lead) ? $lead->contacted_notes : ''); ?>
                                            <?php echo render_textarea('contacted_notes', 'LRO Docket', $value); ?>
                                        </div>
                                <?php } ?>
                                <!-- when case update then show  -->
                                <?php if (isset($lead)) { ?>
                                        <div>
                                            <?php $value = (isset($lead) ? $lead->contacted_notes : ''); ?>
                                            <?php echo render_textarea('contacted_notes', 'LRO Docket', $value); ?>
                                        </div>
                                <?php } ?>
                        <?php } ?>
                            <div class="checkbox-inline checkbox checkbox-primary">
                                <input type="checkbox" name="secondary_email_check" id="secondary_email_check" 
                                <?php if ($lead->secondary_email_check == 'on') {
                                    echo 'checked';
                                } ?>
                                >
                                <label for="secondary_email_check">
                                    <?php echo 'Would you like to receive notifications and updates at your secondary email address as well?'; ?>
                                </label>
                            </div>

                    </div>
                </div>
            </div>
            <div class="col-md-12 mtop15">
                <?php $rel_id = (isset($lead) ? $lead->id : false); ?>
                <?php echo render_custom_fields('leads', $rel_id); ?>
            </div>
            <div class="clearfix"></div>
        </div>
    </div>
    <?php if ($lead_locked == false) { ?>
                <div id="lead_edit_button" class="lead-edit<?php echo isset($lead) ? ' hide' : ''; ?>">
                    <hr class="-tw-mx-4 tw-border-neutral-200" />
                    <button type="submit" class="btn btn-primary pull-right lead-save-btn" id="lead-form-submit">
                        <?php echo _l('submit'); ?>
                    </button>
                    <button type=" button" class="btn btn-default pull-right mright5" data-dismiss="modal">
                        <?php echo _l('close'); ?>
                    </button>
                </div>
    <?php } ?>
    <div class="clearfix"></div>
    <?php echo form_close(); ?>
</div>
<?php if (isset($lead) && $lead_locked == true) { ?>
            <script>
                $(function () {
                    // Set all fields to disabled if lead is locked        
                    $.each($('.lead-wrapper').find('input, select, textarea'), function () {
                        $(this).attr('disabled', true);
                        if ($(this).is('select')) {
                            $(this).selectpicker('refresh');
                        }
                    });
                });

            </script>
<?php } ?>
<script>
    document.getElementById('phonenumber').addEventListener('input', function (e) {
        var x = e.target.value.replace(/\D/g, '').match(/(\d{0,3})(\d{0,3})(\d{0,4})/);
        e.target.value = !x[2] ? x[1] : '(' + x[1] + ') ' + x[2] + (x[3] ? '-' + x[3] : '');

        $(".lead-save-btn").attr('disabled', false);
        if (e.target.value.length <= 13) {
            $("#phonenumber_error").show();
            // $(".lead-save-btn").attr('disabled', true);
        } else {
            $("#phonenumber_error").hide();
        }
    });
</script>
<script>

    $('#assign_group').on('change', function () {
        var assignGroup = $(this).val();
        $.ajax({
            url: '<?php echo base_url('admin/staff/fetchStaffNames'); ?>',
            method: 'POST',
            data: { assign_group: assignGroup },
            dataType: 'json',
            success: function (response) {
                var staffNames = response.staff_names ? response.staff_names : ['No Members Found.'];
                var staffNamesList = $('#staff_names_list');
                $('#staff_names_list_main_div').css('display', 'flex');
                staffNamesList.empty();
                staffNamesList.append('<h4 class="no-margin font-medium-xs bold" style="color:#2d2defc2;font-weight:800;">' + staffNames.join(', ') + '</h4>');
            }

        });
    });
</script>
<script>
$(document).ready(function() {
     // Convert PHP array to JavaScript object
    //  var leadsBankDetails =;
    // // Initialize fields based on existing lender IDs
    // if (leadsBankDetails) {
    //     var lender_ids = "";
    //     var lenderIdsArray = lender_ids.split(',').map(id => id.trim());
    //     updateLenderFields(lenderIdsArray);
    // }
    // Function to format loan amounts with a dollar sign, commas, and two decimal places
    // function formatLoanAmount(value) {
    //     value = value.replace(/[^0-9.]/g, '');
    //     let numericValue = parseFloat(value) || 0;
    //     let formattedValue = numericValue.toFixed(2);
    //     formattedValue = formattedValue.replace(/\B(?=(\d{3})+(?!\d))/g, ',');
    //     return '$' + formattedValue;
    // }

    // // Function to handle formatting of loan amount fields dynamically
    // function bindLoanAmountFormatting(lenderId) {
    //     var $loanAmountField = $('#loan_amount_' + lenderId);
    //     $loanAmountField.on('input', function(event) {
    //         var value = $(this).val();
    //         var numericValue = value.replace(/[^0-9.]/g, '');
    //         var formattedValue = formatLoanAmount(numericValue);
    //         $(this).val(formattedValue);
    //         var decimalPosition = formattedValue.indexOf('.');
    //         if (decimalPosition !== -1) {
    //             this.selectionStart = this.selectionEnd = decimalPosition;
    //         }
    //     });
    //     $loanAmountField.on('blur', function() {
    //         var value = $(this).val();
    //         $(this).val(formatLoanAmount(value.replace(/[^0-9.]/g, '')));
    //     });
    // }

    // Function to handle changes to the lender selection
    // $('#lender_ids').on('change', function() {
    //     updateLenderFields($(this).val());
    // });

    // Function to update lender fields based on selected lenders
    // function updateLenderFields(selectedLenders) {
    //     $('#lender_fields_appened_div').empty();
    //     if (selectedLenders) {
    //         $.each(selectedLenders, function(index, lenderId) {
    //             var lenderName = $('#lender_ids option[value="' + lenderId + '"]').text();
    //             var dynamicFields = generateDynamicFields(lenderId, lenderName);
    //             $('#lender_fields_appened_div').append(dynamicFields);
    //             initializeSelectPicker(lenderId);
    //             bindLoanAmountFormatting(lenderId);
    //             if(leadsBankDetails){
    //                 var matchedRecord = leadsBankDetails.find(function(record) {
    //                     return record.bank_id == lenderId;
    //                 });
    //                 if (matchedRecord) {
    //                     $('#loan_amount_' + lenderId).val(formatLoanAmount(matchedRecord.loan_amount));
    //                     $('#transaction_' + lenderId).val(matchedRecord.transaction_id).selectpicker('refresh');
    //                 }
    //             }
    //         });
    //     }
    // }

    // // Function to generate dynamic fields for each selected lender
    // function generateDynamicFields(lenderId, lenderName) {
    //     // other option is user for transaction  <option value='other'>Others</option>
    //     return `
    //     <div class="clearfix"></div>
    //     <hr class="mtop5 mbot10" />
    //     <div class="row" style="margin-left:5px;border: 3px solid #0000ff70;">
    //         <span class="col-md-12" style="padding: 7px 30px;font-weight: 800;font-size: large;"> ${lenderName}</span>
    //         <div class="col-md-4" style="margin-left:15px;">
    //             <div class='form-group'>
    //                 <label for='loan_amount_${lenderId}' class='control-label'>New Loan Amount </label>
    //                 <input type='text' id='loan_amount_${lenderId}' name='loan_amount_${lenderId}' class='form-control' />
    //             </div>
    //         </div>
    //         <div class="col-md-4" style="margin-left:15px;">
    //             <div class='form-group'>
    //                 <label for='transaction_${lenderId}' class='control-label'>Transaction</label>
    //                 <select name='transaction_${lenderId}' id='transaction_${lenderId}' class='form-control selectpicker' data-width='100%' data-none-selected-text='Nothing selected' data-live-search='true' tabindex='-98'>
    //                     <option value=''>Not assigned yet</option>
    //                   
    //                 </select>
    //             </div>
    //             <div id='new_transaction_div_${lenderId}' style='display:none;'>
    //                 <input type='text' id='new_transaction_name_${lenderId}' name='new_transaction_name_${lenderId}' class='form-control' placeholder='New Transaction Details' />
    //             </div>
    //         </div>
    //     </div>
    //     `;
    // }

    // // Function to initialize selectpicker and handle additional logic
    // function initializeSelectPicker(lenderId) {
    //     $('.selectpicker').selectpicker();
    //     $('#transaction_' + lenderId).on('change', function() {
    //         if ($(this).val() === 'other') {
    //             $('#new_transaction_div_' + lenderId).show();
    //         } else {
    //             $('#new_transaction_div_' + lenderId).hide();
    //         }
    //     });
    // }
    var leadsBankDetails = <?php echo json_encode($leads_bank_details ?: []); ?>;
    var lenderSections = {};
    var selectedLenders = [];
    let lenderDetailsArray = [];

    // if (leadsBankDetails && Array.isArray(leadsBankDetails)) {
    //     var lender_ids = "";
    //     if (lender_ids) {
    //         var lenderIdsArray = lender_ids.split(',').map(id => id.trim());
    //         updateLenderFields(lenderIdsArray);
    //     }
    //     let renderedIndexes = {}; 

    //     leadsBankDetails.forEach(detail => {
    //         let lenderId = detail.bank_id;
    //         let index = detail.index;
    //         let loanAmount = detail.loan_amount || '';
    //         let transactionId = detail.transaction_id || '';
    //         if (index > 0 && !renderedIndexes[lenderId]) {
    //             renderedIndexes[lenderId] = new Set();
    //         }
    //         if (index > 0 && !renderedIndexes[lenderId].has(index)) {
    //             createOrUpdateSection(lenderId, index, loanAmount, transactionId);
    //             renderedIndexes[lenderId].add(index);
    //         }
    //     });
    // }
    if (leadsBankDetails && Array.isArray(leadsBankDetails)) {
        var lender_ids = "<?php echo $lead->lender_ids; ?>";
        let renderedIndexes = {};
        if (lender_ids) {
            var lenderIdsArray = lender_ids.split(',').map(id => id.trim());
            lenderIdsArray.forEach(lenderId => {
                let details = leadsBankDetails.filter(item => item.bank_id == lenderId && item.index == 0);
                if (details.length > 0) {
                    details.forEach(detail => {
                        updateLenderFields([...selectedLenders, lenderId], detail.index, detail.loan_amount || '', detail.transaction_id || '');
                    });
                } else {
                    updateLenderFields([...selectedLenders, lenderId], 0, '', '');
                }
            });
        }

        leadsBankDetails.forEach(detail => {
            let lenderId = detail.bank_id;
            let index = detail.index;
            let loanAmount = detail.loan_amount || '';
            let transactionId = detail.transaction_id || '';

            if (index > 0 && !renderedIndexes[lenderId]) {
                renderedIndexes[lenderId] = new Set();
            }
            if (index > 0 && !renderedIndexes[lenderId].has(index)) {
                createOrUpdateSection(lenderId, index, loanAmount, transactionId);
                renderedIndexes[lenderId].add(index);
            }
        });
    }


    function createOrUpdateSection(lenderId, index, loanAmount = '', transactionId = '') {
        if (!(lenderId in lenderSections)) {
            lenderSections[lenderId] = 0;
        }
        lenderSections[lenderId] = Math.max(lenderSections[lenderId], index);
        let lenderName = $('#lender_ids option[value="' + lenderId + '"]').text();
        var dynamicFields = generateDynamicFields(lenderId, lenderName, index, false, loanAmount, transactionId);
        $('#lender_fields_appened_div').append(dynamicFields);
        initializeSelectPicker(lenderId + '_' + index);
        bindLoanAmountFormatting(lenderId + '_' + index);
        updateLenderDetailsIndex(lenderId, index);
    }

    function updateLenderFields(newSelectedLenders, index = '', loanAmount = '', transactionId = '') {
        if (newSelectedLenders && newSelectedLenders.length) {
            var unselectedLenders = selectedLenders.filter(lenderId => !newSelectedLenders.includes(lenderId));
            unselectedLenders.forEach(lenderId => {
                removeAllLenderSections(lenderId);
                delete lenderSections[lenderId];
            });
            var newlySelectedLenders = newSelectedLenders.filter(lenderId => !selectedLenders.includes(lenderId));
            selectedLenders = newSelectedLenders;
            newlySelectedLenders.forEach(lenderId => {
                createOrUpdateSection(lenderId, 0, loanAmount, transactionId);
            });
        } else {
            $('#lender_fields_appened_div').empty();
            lenderSections = {};
            selectedLenders = [];
            lenderDetailsArray = [];
            updateLoanTotalInput(); 
        }
    }

    function removeAllLenderSections(lenderId) {
        $('.lender-section[data-lender-id="' + lenderId + '"]').remove();
    }

    function generateDynamicFields(lenderId, lenderName, index, isFirstSection, loanAmount = '', transactionId = '') {
        var uniqueId = lenderId + '_' + index;
        var buttonHtml = index === 0
        ? `<button type="button" class="btn btn-primary add-more-lender-section" data-lender-id="${lenderId}" style="border-radius:50%;height:25px;width:25px;display:flex;justify-content:center;align-items:center;">+</button>`
        : `<button type="button" class="btn btn-danger remove-lender-section" data-lender-id="${lenderId}" data-index="${index}" style="border-radius:50%;height:25px;width:25px;display:flex;justify-content:center;align-items:center;">-</button>`;

        return `
            <div class="clearfix"></div>
            <hr class="mtop5 mbot10" />
            <div class="row lender-section" data-lender-id="${lenderId}" data-index="${index}" style="margin-left:5px;border: 3px solid #0000ff70;">
                <span class="col-md-12" style="padding: 7px 30px;font-weight: 800;font-size: large;">${lenderName}</span>
                <div class="col-md-4" style="margin-left:15px;">
                    <div class='form-group'>
                        <label for='loan_amount_${uniqueId}' class='control-label'>New Loan Amount</label>
                        <input type='text' id='loan_amount_${uniqueId}' name='loan_amount_${uniqueId}' class='form-control loan-amount-input' value="${loanAmount}" />
                    </div>
                </div>
                <div class="col-md-4" style="margin-left:15px;">
                    <div class='form-group'>
                        <label for='transaction_${uniqueId}' class='control-label'>Transaction</label>
                        <select name='transaction_${uniqueId}' id='transaction_${uniqueId}' class='form-control selectpicker' data-width='100%' data-none-selected-text='Nothing selected' data-live-search='true' tabindex='-98'>
                            <option value=''>Not assigned yet</option>
                            ${generateTransactionOptions(transactionId)}
                        </select>
                    </div>
                    <div id='new_transaction_div_${uniqueId}' style='display:none;'>
                        <input type='text' id='new_transaction_name_${uniqueId}' name='new_transaction_name_${uniqueId}' class='form-control' placeholder='New Transaction Details' />
                    </div>
                </div>
                <div class="col-md-2" style="margin-top: 25px;">
                    ${buttonHtml}
                </div>
            </div>
        `;
    }

    function generateTransactionOptions(transactionId = '') {
        var options = '';
        <?php foreach ($transaction as $transaction) { ?>
            if(transactionId == <?php echo $transaction['id'];?>){
                options += `<option value='<?php echo $transaction['id']; ?>' selected><?php echo $transaction['name']; ?></option>`;
            }else{
                options += `<option value='<?php echo $transaction['id']; ?>'><?php echo $transaction['name']; ?></option>`;
            }
        <?php } ?>
        return options;
    }

    function addMoreLenderSection(lenderId) {
        if (!(lenderId in lenderSections)) {
            lenderSections[lenderId] = 0;
        }
        lenderSections[lenderId]++;
        var lenderName = $('#lender_ids option[value="' + lenderId + '"]').text();
        createOrUpdateSection(lenderId, lenderSections[lenderId]);
    }

    function removeLenderSection(lenderId, index) {
        $('.lender-section[data-lender-id="' + lenderId + '"][data-index="' + index + '"]').remove();
        removeLenderDetailsIndex(lenderId, index);
        if (lenderSections[lenderId] > 0) {
            lenderSections[lenderId]--;
        } else {
            delete lenderSections[lenderId];
        }
        if ($('.lender-section[data-lender-id="' + lenderId + '"]').length === 0) {
            selectedLenders = selectedLenders.filter(id => id !== lenderId);
        }
    }


    function updateLenderDetailsIndex(lenderId, index) {
        let existingIndex = lenderDetailsArray.findIndex(item => item.lenderId === lenderId && item.index === index);
        if (existingIndex === -1) {
            lenderDetailsArray.push({ lenderId: lenderId, index: index });
        } 
        updateLoanTotalInput();
    }

    function removeLenderDetailsIndex(lenderId, index) {
        lenderDetailsArray = lenderDetailsArray.filter(item => !(item.lenderId == lenderId && item.index == index));
        console.log("Updated lenderDetailsArray after removal:", lenderDetailsArray);
        updateLoanTotalInput();
    }

    function updateLoanTotalInput() {
        console.log(lenderDetailsArray);
        $('#loan_total_post_req').val(JSON.stringify(lenderDetailsArray)).trigger('change');
    }

    function initializeSelectPicker(uniqueId) {
        $('#transaction_' + uniqueId).selectpicker();
        $('#transaction_' + uniqueId).on('change', function() {
            if ($(this).val() === 'other') {
                $('#new_transaction_div_' + uniqueId).show();
            } else {
                $('#new_transaction_div_' + uniqueId).hide();
            }
        });
    }

    function formatLoanAmount(value) {
        value = value.replace(/[^0-9.]/g, '');
        let numericValue = parseFloat(value) || 0;
        let formattedValue = numericValue.toFixed(2);
        formattedValue = formattedValue.replace(/\B(?=(\d{3})+(?!\d))/g, ',');
        return '$' + formattedValue;
    }

    function bindLoanAmountFormatting(lenderId) {
        var $loanAmountField = $('#loan_amount_' + lenderId);
        $loanAmountField.on('input', function(event) {
            var value = $(this).val();
            var numericValue = value.replace(/[^0-9.]/g, '');
            var formattedValue = formatLoanAmount(numericValue);
            $(this).val(formattedValue);
            var decimalPosition = formattedValue.indexOf('.');
            if (decimalPosition !== -1) {
                this.selectionStart = this.selectionEnd = decimalPosition;
            }
        });
        $loanAmountField.on('blur', function() {
            var value = $(this).val();
            $(this).val(formatLoanAmount(value.replace(/[^0-9.]/g, '')));
        });
    }
    $(document).off('click', '.add-more-lender-section').on('click', '.add-more-lender-section', function() {
        var lenderId = $(this).data('lender-id');
        addMoreLenderSection(lenderId);
    });

    $(document).off('click', '.remove-lender-section').on('click', '.remove-lender-section', function() {
        var lenderId = $(this).data('lender-id');
        var index = $(this).data('index');
        removeLenderSection(lenderId, index);
    });

    $('#lender_ids').off('change').on('change', function() {
        var selectedLenderIds = $(this).val(); 
        if (!selectedLenderIds) {
            selectedLenderIds = []; 
        }
        updateLenderFields(selectedLenderIds); 
    });

    $('#email').change(function() {
        var email = $(this).val();
        $.ajax({
            url: '<?php echo base_url('admin/leads/get_secondary_email'); ?>',
            type: 'POST',
            data: { email: email },
            success: function(response) {
                var jsonResponse = JSON.parse(response);

                if (jsonResponse.success) {
                    // $('#additional_email').hide();
                    // $('label[for="additional_email"]').hide();
                    // secondary email checkbox can be checkable
                    $('#secondary_email_check').hide();
                    $('label[for="secondary_email_check"]').hide();
                } else {
                    // $('#additional_email').slideDown();
                    // $('label[for="additional_email"]').slideDown();
                    // secondary email checkbox can be checkable
                    $('#secondary_email_check').slideDown();
                    $('label[for="secondary_email_check"]').slideDown();
                    
                }
            },
            error: function(xhr, status, error) {
                console.error(xhr.responseText);
            }
        });
    });
});
</script>

<script>
    // Function to set the values if they are not empty
    function setValue(selector, value) {
        if (value && value.trim() !== '') {
            $(selector).val(value.trim());
        }
    }
   function updateFields() {
    var totalFields = document.getElementById("total_fields").value;
    var fieldsContainer = document.getElementById("fields_container");
    if(<?php echo $leads_borrow_count; ?>){
    var for_update_show_fields = <?php echo $leads_borrow_count; ?>
    }
    // Clear existing fields
    fieldsContainer.innerHTML = "";

    if (totalFields !== "") {
         // Add line break
         var hr = document.createElement("hr");
            hr.className = "-tw-mx-4 tw-border-neutral-200";
            hr.style.marginTop = "20px";
            hr.style.marginBottom = "20px";
            hr.style.border = "0";
            hr.style.borderTop = "10px solid #dbd8d8";
            fieldsContainer.appendChild(hr);
            var text = '';
        if(for_update_show_fields && for_update_show_fields != 0 && for_update_show_fields != 1){
            // this condition is used for update
            var default_value = for_update_show_fields;
            var condition = '< ' + totalFields;
        }else{
            // this condition is user for creating a new case
            var default_value = 2;
            var condition = '<= ' + totalFields;
        }
        for (var i = default_value; eval(i + condition); i++) {
            if(for_update_show_fields && for_update_show_fields != 0 && for_update_show_fields != 1){
                switch (i+1) {
                    case 2:
                        text = 'Second Party';
                        break;
                    case 3:
                        text = 'Third Party';
                        break;
                    case 4:
                        text = 'Fourth Party';
                        break;
                    default:
                        text = ' Party'; 
                }
            }else{
                switch (i) {
                    case 2:
                        text = 'Second Party';
                        break;
                    case 3:
                        text = 'Third Party';
                        break;
                    case 4:
                        text = 'Fourth Party';
                        break;
                    default:
                        text = ' Party'; 
                }
            }
            if(i == 4){
            var hr = document.createElement("hr");
            hr.className = "-tw-mx-4 tw-border-neutral-200 col-md-12";
            hr.style.marginTop = "20px";
            hr.style.marginBottom = "20px";
            hr.style.border = "0";
            hr.style.borderTop = "5px solid #dbd8d8";
            fieldsContainer.appendChild(hr);
            }
            var columnDiv = document.createElement("div");
            columnDiv.classList.add("col-md-6");

            var spantext = document.createElement("span");
            spantext.textContent = text;
            spantext.classList.add("col-md-12", "btn", "btn-primary");
            // Add the styles to the span element
            spantext.style.textAlign = "center";
            spantext.style.fontSize = "medium";
            spantext.style.fontWeight = "700";
            columnDiv.appendChild(spantext);

            // Create form group
            var formGroup = document.createElement("div");
            formGroup.classList.add("form-group");
            // Append firstname label and input
            var fields = ["First Name", "Middle Name", "Last Name", "Address","City","Province","Zip Code", "Email", "Phone"];
            for (var j = 0; j < fields.length; j++) {
                var fieldDiv = document.createElement("div"); 
                fieldDiv.classList.add("form-group"); 

                var label = document.createElement("label");
                label.textContent = fields[j];
                fieldDiv.appendChild(label);

                var input = document.createElement("input");
                var fieldName = fields[j].toLowerCase().replace(/\s+/g, '');
                if (fields[j] === "Phone") {
                    input.setAttribute("type", "text");
                }else if(fields[j] === "Email" ){
                    input.setAttribute("type", "email");
                }else{
                    input.setAttribute("type", "text");
                }
                input.setAttribute("name", "borrow_" + fieldName + i);
                input.setAttribute("id", "borrow_" + fieldName + i);
                input.classList.add("form-control");
                // set the default valur for provaince
                if (fields[j] === "Province") {
                input.setAttribute("value", 'Ontario');
                }
                fieldDiv.appendChild(input);

                if (fields[j] === "Email" || fields[j] === "Phone") {
                    // fieldDiv.style.display = "none"; 
                    fieldDiv.style.display = ""; 
                    fieldDiv.setAttribute("id", "borrow_" + fieldName + "_div" + i);
                }

                formGroup.appendChild(fieldDiv); 
                // apply phonenumber validation
                if (fields[j] === "Phone") {
                    input.addEventListener('input', function (e) {
                        var x = e.target.value.replace(/\D/g, '').match(/(\d{0,3})(\d{0,3})(\d{0,4})/);
                        e.target.value = !x[2] ? x[1] : '(' + x[1] + ') ' + x[2] + (x[3] ? '-' + x[3] : '');

                        $(".lead-save-btn").attr('disabled', false);
                        if (e.target.value.length < 14) {
                            // Show error message
                            if (!document.getElementById(e.target.id + "-error")) {
                                var errorSpan = document.createElement("span");
                                errorSpan.id = e.target.id + "-error";
                                errorSpan.style.color = "red";
                                errorSpan.textContent = "Please enter a valid phone number.";
                                e.target.parentElement.appendChild(errorSpan);
                            }
                            $(".lead-save-btn").attr('disabled', true);
                        } else {
                            // Hide error message
                            var errorSpan = document.getElementById(e.target.id + "-error");
                            if (errorSpan) {
                                errorSpan.remove();
                            }
                        }
                    });
                }
            }


            // Append preferred contact method dropdown
            // Create a div element for the preferred method dropdown
            var preferedMethodDiv = document.createElement("div");
            preferedMethodDiv.classList.add("form-group");

            // Append label to the div
            var preferedMethodLabel = document.createElement("label");
            preferedMethodLabel.textContent = "Select Preferred Method";
            preferedMethodDiv.appendChild(preferedMethodLabel);

            // Append select element to the div
            var dropdownSelectPreferedMethod = document.createElement("select");
            dropdownSelectPreferedMethod.setAttribute("name", "borrow_preferred_method" + i);
            dropdownSelectPreferedMethod.setAttribute("id", "borrow_preferred_method" + i);
            dropdownSelectPreferedMethod.classList.add("form-control");

            var options = ["Nothing Selected", "Email", "Phone"];
            for (var k = 0; k < options.length; k++) {
                var option = document.createElement("option");
                option.text = options[k];
                option.value = options[k];
                dropdownSelectPreferedMethod.appendChild(option);
            }

            preferedMethodDiv.appendChild(dropdownSelectPreferedMethod);

            // Append the div containing the label and select element to the formGroup
            formGroup.appendChild(preferedMethodDiv);

            
            // Append position dropdown
            var positionDiv = document.createElement("div");
            positionDiv.classList.add("form-group");

            var dropdownLabel = document.createElement("label");
            dropdownLabel.textContent = "Select Position";
            positionDiv.appendChild(dropdownLabel);

            var dropdownSelect = document.createElement("select");
            dropdownSelect.setAttribute("name", "borrow_position" + i);
            dropdownSelect.setAttribute("id", "borrow_position" + i);
            dropdownSelect.classList.add("form-control");

            var positions = ["Nothing Selected", "Borrower", "Consenting Spouse", "Guarantor"];
            for (var l = 0; l < positions.length; l++) {
                var positionOption = document.createElement("option");
                positionOption.text = positions[l];
                positionOption.value = positions[l];
                dropdownSelect.appendChild(positionOption);
            }

            positionDiv.appendChild(dropdownSelect);

            formGroup.appendChild(positionDiv);
           
            // Martial status dropdown code
            var borrower_martial_status_Div = document.createElement("div");
            borrower_martial_status_Div.classList.add("form-group");

            var borrow_martial_status_dropdownLabel = document.createElement("label");
            borrow_martial_status_dropdownLabel.textContent = "Select Marital Status";
            borrower_martial_status_Div.appendChild(borrow_martial_status_dropdownLabel);

            var borrow_martial_status_dropdown = document.createElement("select");
            borrow_martial_status_dropdown.setAttribute("name", "borrow_martial_status" + i);
            borrow_martial_status_dropdown.setAttribute("id", "borrow_martial_status" + i);
            borrow_martial_status_dropdown.classList.add("form-control");

            var positions = [
                "Nothing Selected", "Common Law", "Divorced", "Married", 
                "Single", "Separated", "Consenting/spouse & guarantor", 
                "Consenting/spouse", "Widowed"
            ];
            for (var l = 0; l < positions.length; l++) {
                var borrower_marital_status_Option = document.createElement("option");
                borrower_marital_status_Option.text = positions[l];
                borrower_marital_status_Option.value = positions[l];
                borrow_martial_status_dropdown.appendChild(borrower_marital_status_Option);
            }

            borrower_martial_status_Div.appendChild(borrow_martial_status_dropdown);

            formGroup.appendChild(borrower_martial_status_Div);


            // Append form group to column div
            columnDiv.appendChild(formGroup);

            // Append column div to container
            fieldsContainer.appendChild(columnDiv);

        }
         // Add line break
         var hr = document.createElement("hr");
            hr.className = "-tw-mx-4 tw-border-neutral-200 col-md-12";
            hr.style.marginTop = "20px";
            hr.style.marginBottom = "20px";
            hr.style.border = "0";
            hr.style.borderTop = "10px solid #dbd8d8";
            fieldsContainer.appendChild(hr);
    }
    // get the value 
    var get_value_address = $('#address').val();
    var get_value_city = $('#city').val();
    var get_value_zip = $('#zip').val();
    // Check and set the values
    setValue('#borrow_address2', get_value_address);
    setValue('#borrow_address3', get_value_address);
    setValue('#borrow_address4', get_value_address);
    
    setValue('#borrow_city2', get_value_city);
    setValue('#borrow_city3', get_value_city);
    setValue('#borrow_city4', get_value_city);

    setValue('#borrow_zipcode2', get_value_zip);
    setValue('#borrow_zipcode3', get_value_zip);
    setValue('#borrow_zipcode4', get_value_zip);
}
$(document).ready(function() {
    function destroyTinyMCE() {
        tinymce.remove();
        if (tinymce.editors.length > 0) {
            tinymce.editors.forEach(function (editor) {
                editor.remove();
            });
        }
    }
    destroyTinyMCE();
    // brkerage dropdown function
    var lead_id = "<?php echo $lead->id; ?>";
    if(lead_id){
        var lead_selected_brokerage_id = "<?php echo $lead_selected_brokerage_id; ?>";
        brokerage_assign_broker_dropdown(lead_selected_brokerage_id, lead_id);
    }
    $('#brokerage_id').change(function() {
        var selectedBrokerageId = $(this).val();
        var check_mandatory_record = $(this).find('option:selected').data('id');
        if (check_mandatory_record == 1) {
            $('#addedfrom').attr('required', true);
            $('#addedfrom_field_star_show').show();
        } else {
            $('#addedfrom').attr('required', false);
            $('#addedfrom_field_star_show').hide();
        }
        brokerage_assign_broker_dropdown(selectedBrokerageId, '')
    });
    function brokerage_assign_broker_dropdown(brokerage_id, lead_id) {
        var addedfrom_select_check = "<?php echo $addedfrom_select_check; ?>";
        var selected_ids = addedfrom_select_check.split(',').map(Number);
        // get current broker id
        var current_broker_id = "<?php echo get_staff_user_id(); ?>";
        $.ajax({
            url: "<?php echo admin_url('leads/get_brokerage_assign_broker'); ?>",
            type: 'POST',
            data: {
                brokerage_id: brokerage_id,
                lead_id: lead_id,
            },
            success: function(response) {
                var data = JSON.parse(response);
                if (data.length > 0) {
                    var options = "<option value='' disabled>Select Broker</option>"; 
                    $.each(data, function(index, broker) {
                        var fullName = broker.firstname + ' ' + broker.lastname;
                        var selected = '';
                        if (selected_ids.includes(parseInt(broker.staffid))) {
                            selected = 'selected';
                        }
                        if(current_broker_id == broker.staffid){
                            selected = 'selected';
                        }
                        options += "<option value='" + broker.staffid + "' " + selected + ">" + fullName + "</option>";
                    });
                    $('#addedfrom').html(options).selectpicker('refresh'); 
                } else {
                    $('#addedfrom').html("<option disabled>No Brokers Available</option>").selectpicker('refresh');
                }
            },
            error: function() {
            }
        });
    }
    $('#file_notes_tab_move').click(function() {
      $('#lead_notes').tab('show'); 
      $('a[href="#lead_notes"]').tab('show');

      setTimeout(function() {
            var anchor = document.querySelector('a[href="#lead_notes"]');
            if (anchor) {
                anchor.click();
            }
        }, 500);
    });
    // preferred_contact_method[]
    $(document).on('change', '#preferred_contact_method', function() {
        var selectedValue = $(this).val();
        var emailDiv = $('#additional_email_div');
        var phoneDiv = $('#borrower1_phonenumber_div');

        if (selectedValue === 'Email') {
            // emailDiv.show();
            // phoneDiv.hide();
        } else if (selectedValue === 'Phone') {
            // emailDiv.hide();
            // phoneDiv.show();
        } else {
            // emailDiv.hide();
            // phoneDiv.hide();
        }
    });
    // borrow_preferred method 2
    $(document).off('change', '#borrow_preferred_method2').on('change', '#borrow_preferred_method2', function() {
        var selectedValue = $(this).val();
        var emailDiv = $('#borrow_email_div2');
        var phoneDiv = $('#borrow_phone_div2');
        if (selectedValue === 'Email') {
            // emailDiv.show();
            // phoneDiv.hide();
        } else if (selectedValue === 'Phone') {
            // emailDiv.hide();
            // phoneDiv.show();
        } else {
            // emailDiv.hide();
            // phoneDiv.hide();
        }
    });
    // borrow_preferred method 3
    $(document).off('change', '#borrow_preferred_method3').on('change', '#borrow_preferred_method3', function() {
        var selectedValue = $(this).val();
        var emailDiv = $('#borrow_email_div3');
        var phoneDiv = $('#borrow_phone_div3');

        if (selectedValue === 'Email') {
            // emailDiv.show();
            // phoneDiv.hide();
        } else if (selectedValue === 'Phone') {
            // emailDiv.hide();
            // phoneDiv.show();
        } else {
            // emailDiv.hide();
            // phoneDiv.hide();
        }
    });
    // borrow_preferred method 4
    $(document).off('change', '#borrow_preferred_method4').on('change', '#borrow_preferred_method4', function() {
        var selectedValue = $(this).val();
        var emailDiv = $('#borrow_email_div4');
        var phoneDiv = $('#borrow_phone_div4');

        if (selectedValue === 'Email') {
            // emailDiv.show();
            // phoneDiv.hide();
        } else if (selectedValue === 'Phone') {
            // emailDiv.hide();
            // phoneDiv.show();
        } else {
            // emailDiv.hide();
            // phoneDiv.hide();
        }
    });
    // transaction details changed
    $('#transaction').on('change', function() {
        if ($(this).val() === 'other') {
            $('#new_transaction_div').show();
        } else {
            $('#new_transaction_div').hide();
        }
    });
     // Check the initial state of the dropdown in case 'other' is selected by default
     if ($('#transaction').val() === 'other') {
        $('#new_transaction_div').show();
    } else {
        $('#new_transaction_div').hide();
    }
    // contacted notes hide and show
    $('#contacted_today').on('change', function() {
        if ($(this).is(':checked')) {
            $('#contacted_notes_div').show();
        } else {
            $('#contacted_notes_div').hide();
        }
    });

    // Check the initial state of the checkbox
    if ($('#contacted_today').is(':checked')) {
        $('#contacted_notes_div').show();
    } else {
        $('#contacted_notes_div').hide();
    }
    // set the borrower address ids value
    $('#address').on('keyup', function() {
        // Get the value of the address field
        var addressValue = $(this).val();
        // Set the values of the other fields
        $('#borrow_address2').val(addressValue);
        $('#borrow_address3').val(addressValue);
        $('#borrow_address4').val(addressValue);
    });
    // set the borrow city  fileds when city address set
    $('#city').on('keyup', function() {
        // Get the value of the address field
        var city = $(this).val();
        // Set the values of the other fields
        $('#borrow_city2').val(city);
        $('#borrow_city3').val(city);
        $('#borrow_city4').val(city);
    });
    // set the borrow state  fileds when state address set
    $('#state').on('keyup', function() {
        // Get the value of the address field
        var state = $(this).val();
        // Set the values of the other fields
        $('#borrow_province2').val(state);
        $('#borrow_province3').val(state);
        $('#borrow_province4').val(state);
    });
    // set the borrow state  fileds when state address set
    $('#zip').on('keyup', function() {
        // Get the value of the address field
        var state = $(this).val();
        // Set the values of the other fields
        $('#borrow_zipcode2').val(state);
        $('#borrow_zipcode3').val(state);
        $('#borrow_zipcode4').val(state);
    });
    var format = function(num) {
    var str = num.toString().replace("$", ""), parts = false, output = [], i = 1, formatted = null;
    if (str.indexOf(".") > 0) {
        parts = str.split(".");
        str = parts[0];
    }
    str = str.split("").reverse();
    for (var j = 0, len = str.length; j < len; j++) {
        if (str[j] != ",") {
            output.push(str[j]);
            if (i % 3 == 0 && j < (len - 1)) {
                output.push(",");
            }
            i++;
        }
    }
    formatted = output.reverse().join("");
    return("$" + formatted + ((parts) ? "." + parts[1].substr(0, 2) : ""));
};

});
</script>
<script>
    // borow phone 2
    var borrowPhone2 = document.getElementById('borrow_phone2');
    if (borrowPhone2) {
            borrowPhone2.addEventListener('input', function (e) {
                var x = e.target.value.replace(/\D/g, '').match(/(\d{0,3})(\d{0,3})(\d{0,4})/);
                e.target.value = !x[2] ? x[1] : '(' + x[1] + ') ' + x[2] + (x[3] ? '-' + x[3] : '');

                $(".lead-save-btn").attr('disabled', false);
                if (e.target.value.length <= 13) {
                    $("#borrow_email2-error").show();
                    // $(".lead-save-btn").attr('disabled', true);
                } else {
                    $("#borrow_email2-error").hide();
                }
            });
    }
    // borrower 3 phone number validation
    var borrow_phone3 = document.getElementById('borrow_phone3');
    if (borrow_phone3) {
        borrow_phone3.addEventListener('input', function (e) {
            var x = e.target.value.replace(/\D/g, '').match(/(\d{0,3})(\d{0,3})(\d{0,4})/);
            e.target.value = !x[2] ? x[1] : '(' + x[1] + ') ' + x[2] + (x[3] ? '-' + x[3] : '');

            $(".lead-save-btn").attr('disabled', false);
            if (e.target.value.length <= 13) {
                $("#phonenumber_error").show();
                // $(".lead-save-btn").attr('disabled', true);
            } else {
                $("#phonenumber_error").hide();
            }
        });
    }
    // borrower 4 phone numer validation
    var borrow_phone4 = document.getElementById('borrow_phone4');
    if (borrow_phone4) {
        borrow_phone4.addEventListener('input', function (e) {
            var x = e.target.value.replace(/\D/g, '').match(/(\d{0,3})(\d{0,3})(\d{0,4})/);
            e.target.value = !x[2] ? x[1] : '(' + x[1] + ') ' + x[2] + (x[3] ? '-' + x[3] : '');

            $(".lead-save-btn").attr('disabled', false);
            if (e.target.value.length <= 13) {
                $("#phonenumber_error").show();
                // $(".lead-save-btn").attr('disabled', true);
            } else {
                $("#phonenumber_error").hide();
            }
        });
    }

</script>