<?php defined('BASEPATH') or exit ('No direct script access allowed'); ?>
<?php  $current_staff_role = get_current_staff_role($this, get_staff_user_id());?>
<?php init_head(); ?>
<div id="wrapper">
    <div class="content">
        <div class="row">
            <div class="col-md-12">
                <div class="_buttons tw-mb-2 sm:tw-mb-4">
                    <a href="#" onclick="init_lead(); return false;"
                        class="btn btn-primary mright5 pull-left display-block">
                        <i class="fa-regular fa-plus tw-mr-1"></i>
                        <?php echo 'New Case'; ?>
                    </a>
                    <?php if($current_staff_role != 2 && $current_staff_role != 6 ):?>
                        <?php if (!$isKanBan) { ?>
                            <a href="#" id="kanban-advance-filter-btn" class="btn btn-primary mright5 pull-left display-block">
                                <i class="fa fa-filter tw-mr-1"></i>
                                <?php echo 'Advance Filter'; ?>
                            </a>
                        <?php  } ?>
                    <?php endif;?>
                    <?php if (is_admin() || get_option('allow_non_admin_members_to_import_leads') == '1') { ?>
                        <!-- <a href="<?php echo admin_url('leads/import'); ?>"
                            class="btn btn-primary pull-left display-block hidden-xs">
                            <i class="fa-solid fa-upload tw-mr-1"></i>
                            <?php echo 'Import Cases'; ?>
                        </a> -->
                    <?php } ?>
                    <div class="row">
                        <div class="col-sm-5 ">
                            <?php if ($samegroup) { ?>
                                <a href="#" class="btn btn-default btn-with-tooltip"
                                    style="<?php echo ($samegroup === 2) ? 'display:none;' : ''; ?>" data-toggle="tooltip"
                                    data-title="<?php echo 'Cases Summary'; ?>" data-placement="top"
                                    onclick="slideToggle('.leads-overview'); return false;"><i
                                        class="fa fa-bar-chart"></i></a>

                            <?php } ?>
                            <a href="<?php echo admin_url('leads/switch_kanban/' . $switch_kanban); ?>" style="<?php echo ($samegroup === 2) ? 'display:none;' : ''; ?>"
                                class="btn btn-default mleft5 hidden-xs" data-toggle="tooltip" data-placement="top"
                                data-title="<?php echo $switch_kanban == 0 ? _l('leads_switch_to_kanban') : _l('switch_to_list_view'); ?>">
                                <?php if ($switch_kanban == 0) { ?>
                                    <i class="fa-solid fa-grip-vertical"></i>
                                <?php } else { ?>
                                    <i class="fa-solid fa-table-list"></i>
                                <?php }
                                ; ?>
                            </a>
                        </div>
                        <!-- <div class="col-sm-4 col-xs-12 pull-right leads-search"> -->
                            <?php /*if ($this->session->userdata('leads_kanban_view') == 'true') { ?>
                                <div data-toggle="tooltip" data-placement="top"
                                    data-title="<?php echo _l('search_by_tags'); ?>">
                                    <?php echo render_input('search', '', '', 'search', ['data-name' => 'search', 'onkeyup' => 'leads_kanban();', 'placeholder' => 'Search Cases'], [], 'no-margin') ?>
                                </div>
                            <?php } */?>
                            <?php echo form_hidden('sort_type'); ?>
                            <?php echo form_hidden('sort', (get_option('default_leads_kanban_sort') != '' ? get_option('default_leads_kanban_sort_type') : '')); ?>
                        <!-- </div> -->
                    </div>
                    <div class="clearfix"></div>
                    <div <?php if ($switch_kanban == 0): ?> class="leads-overview tw-mt-2 sm:tw-mt-4 tw-mb-4 sm:tw-mb-0" style="display:block;" <?php else: ?> class="hide leads-overview tw-mt-2 sm:tw-mt-4 tw-mb-4 sm:tw-mb-0"<?php endif; ?>>
                        <h4 class="tw-mt-0 tw-font-semibold tw-text-lg">
                            <?php echo 'Cases Summary'; ?>
                        </h4>
                        <div class="tw-flex tw-flex-wrap tw-flex-col lg:tw-flex-row tw-w-full tw-gap-3 lg:tw-gap-6">
                            <?php
                            foreach ($summary as $status) { ?>
                                <div
                                    class="lg:tw-border-r lg:tw-border-solid lg:tw-border-neutral-300 tw-flex-1 tw-flex tw-items-center last:tw-border-r-0">
                                    <span class="tw-font-semibold tw-mr-3 rtl:tw-ml-3 tw-text-lg">
                                        <?php
                                        if (isset ($status['percent'])) {
                                            // echo '<span data-toggle="tooltip" data-title="' . $status['total'] . '">' . $status['percent'] . '%</span>';
                                        } else {
                                            // Is regular status
                                            echo $status['total'];
                                        }
                                        ?>
                                    </span>
                                    <?php if (!isset ($status['percent'])) { ?>
                                        <span style="color:<?php echo $status['color']; ?>"
                                            class="<?php echo isset ($status['junk']) || isset ($status['lost']) ? 'text-danger' : ''; ?>">
                                            <?php echo $status['name']; ?>
                                        </span>
                                    <?php } ?>
                                </div>
                            <?php } ?>
                        </div>

                    </div>
                </div>
                <div class="<?php echo $isKanBan ? '' : 'panel_s'; ?>">
                    <div class="<?php echo $isKanBan ? '' : 'panel-body'; ?>">
                        <div class="kanban-filter-loader" id="kanban-filter-loader" style="display: none;">
                            <div class="spinner"></div>
                        </div>

                        <div class="tab-content">
                            <?php
                            if (!$isKanBan) { ?>

                                <div class="active kan-ban-tab" id="kan-ban-tab" style="overflow:auto;">
                                    <div class="kanban-leads-sort">
                                        <span class="bold">
                                            <?php echo _l('leads_sort_by'); ?>:
                                        </span>
                                        <a href="#" onclick="leads_kanban_sort('name');return false;"
                                            class="name">
                                            <?php if (get_option('default_leads_kanban_sort') == 'name') {
                                                echo '<i class="kanban-sort-icon fa fa-sort-amount-' . strtolower(get_option('default_leads_kanban_sort_type')) . '"></i> ';
                                            } ?>
                                            <?php echo _l(' Name'); ?>
                                        </a>
                                        |
                                        <a href="#" onclick="leads_kanban_sort('id');return false;"
                                            class="id">
                                            <?php if (get_option('default_leads_kanban_sort') == 'id') {
                                                echo '<i class="kanban-sort-icon fa fa-sort-amount-' . strtolower(get_option('default_leads_kanban_sort_type')) . '"></i> ';
                                            } ?>
                                            <?php echo _l('Case-ID'); ?>
                                        </a>
                                        |
                                        <a href="#" onclick="leads_kanban_sort('dateadded'); return false"
                                            class="dateadded">
                                            <?php if (get_option('default_leads_kanban_sort') == 'dateadded') {
                                                echo '<i class="kanban-sort-icon fa fa-sort-amount-' . strtolower(get_option('default_leads_kanban_sort_type')) . '"></i> ';
                                            } ?>
                                            <?php echo _l('leads_sort_by_datecreated'); ?>
                                        </a>
                                        |
                                        <a href="#" onclick="leads_kanban_sort('leadorder');return false;"
                                            class="leadorder">
                                            <?php if (get_option('default_leads_kanban_sort') == 'leadorder') {
                                                echo '<i class="kanban-sort-icon fa fa-sort-amount-' . strtolower(get_option('default_leads_kanban_sort_type')) . '"></i> ';
                                            } ?>
                                            <?php echo _l('leads_sort_by_kanban_order'); ?>
                                        </a>
                                        |
                                        <a href="#" onclick="leads_kanban_sort('lastcontact');return false;"
                                            class="lastcontact">
                                            <?php if (get_option('default_leads_kanban_sort') == 'lastcontact') {
                                                echo '<i class="kanban-sort-icon fa fa-sort-amount-' . strtolower(get_option('default_leads_kanban_sort_type')) . '"></i> ';
                                            } ?>
                                            <?php echo _l('leads_sort_by_lastcontact'); ?>
                                        </a>
                                    </div>
                                    <!-- Advance kanban filters -->
                                    <div class="row mbot15" id="kanban_filters_row" style="display:none;margin-left:5px;">
                                        <div class="clearfix"></div>
                                        <hr class="-tw-mx-4 tw-border-neutral-200" style="border-top: 5px solid #eee;" />
                                        <div class="col-md-2">
                                            <label for="filter_lead_id">Case ID</label>
                                            <input type="number" class="form-control" id="filter_lead_id" placeholder="Case ID">
                                        </div>
                                        <div class="col-md-2">
                                            <label for="filter_name">Name</label>
                                            <input type="text" class="form-control" id="filter_name" placeholder="Name">
                                        </div>
                                        <div class="col-md-2">
                                            <label for="filter_email">Email</label>
                                            <input type="text" class="form-control" id="filter_email" placeholder="Email">
                                        </div>
                                        <div class="col-md-2">
                                            <label for="filter_phone">Phone</label>
                                            <input type="text" class="form-control" id="filter_phone" placeholder="Phone Number">
                                        </div>
                                        <div class="col-md-2">
                                            <label for="filter_address">Address</label>
                                            <input type="text" class="form-control" id="filter_address" placeholder="Address">
                                        </div>
                                        <div class="col-md-2">
                                            <label for="filter_city">Province</label>
                                            <input type="text" class="form-control" id="filter_state" placeholder="State">
                                        </div>
                                        <div class="col-md-2" style="margin-top:10px;">
                                            <label for="filter_group">Select Groups</label>
                                            <select class="form-control selectpicker" multiple data-live-search="true" name="filter_group" id="filter_group">
                                                <?php foreach ($staff_group as $group): ?>
                                                    <option value="<?= $group['group_name'] ?>"><?= $group['group_name'] ?></option>
                                                <?php endforeach; ?>
                                            </select>
                                        </div>
                                        <div class="col-md-2" style="margin-top:10px;">
                                            <label for="stage_status_filter">Select Stage</label>
                                            <select class="form-control selectpicker" multiple data-live-search="true" name="stage_status_filter" id="stage_status_filter">
                                                <?php foreach ($statuses as $status): ?>
                                                    <option value="<?= $status['id'] ?>"><?= $status['name'] ?></option>
                                                <?php endforeach; ?>
                                            </select>
                                        </div>
                                        <div class="col-md-2" style="margin-top:10px;">
                                            <?php
                                            echo '<div id="">';
                                            echo render_select('brokers_filter', $broker_data, ['staffid', 'firstname', 'lastname'], 'Select Broker', $selected, ['data-width' => '100%', 'data-none-selected-text' => _l('leads_all'), 'multiple' => true, 'data-actions-box' => true], [], 'no-mbot', '', false);
                                            echo '</div>';
                                            ?>
                                        </div>
                                        <div class="col-md-2" style="margin-top:10px;">
                                            <?php 
                                                echo '<div id="">';
                                                echo render_select('brokerage_filter', $brokerage_data, ['id', 'name'], 'Select Brokerage', '', ['data-width' => '100%', 'data-none-selected-text' => _l('leads_all'), 'multiple' => true, 'data-actions-box' => true], [], 'no-mbot', '', false);
                                                echo '</div>';
                                            ?>
                                        </div>
                                        <?php
                                        $selected = [];
                                        $kanban_offer_in_out_options = [
                                            ['id' => 'ids_not_completed',     'name' => 'ID not Complete'],
                                            ['id' => 'ids_completed',     'name' => 'ID Complete'],
                                            ['id' => 'idv_in',    'name' => 'IDV In / IDV N/A'],
                                            ['id' => 'idv_not_in', 'name' => 'IDV Not In'],
                                            ['id' => 'ins_in', 'name' => 'Instruction In'],
                                        ];
                                        ?>
                                        <div class="col-md-2" style="margin-top:10px;">
                                            <label for="kanban_offer_in_out">Select Offer In/Out</label>
                                            <select class="form-control selectpicker" multiple data-live-search="true" name="kanban_offer_in_out" id="kanban_offer_in_out">
                                                <?php foreach ($kanban_offer_in_out_options as $kanban_offer_in_out): ?>
                                                    <option value="<?= $kanban_offer_in_out['id'] ?>"><?= $kanban_offer_in_out['name'] ?></option>
                                                <?php endforeach; ?>
                                            </select>
                                        </div>
                                        <?php
                                        $selected = [];
                                        $kanban_active_closed_case = [
                                            ['id' => 'active',     'name' => 'Active'],
                                            ['id' => 'closed',    'name' => 'Closed'],
                                        ];
                                        foreach ($kanban_active_closed_case as $key => $agent_status) {
                                            if (!empty ($agent_status['id'])) {
                                                $kanban_active_closed_case[$key]['option_attributes'] = ['' => $agent_status['name']];
                                            }
                                        }
                                        ?>
                                        <div class="col-md-2" style="margin-top:10px;">
                                            <label for="kanban_active_record">Active / Inactive Cases</label>
                                            <select class="form-control selectpicker" multiple data-live-search="true" name="kanban_active_record" id="kanban_active_record">
                                                <?php foreach ($kanban_active_closed_case as $active_closed_case_data): ?>
                                                    <option value="<?= $active_closed_case_data['id'] ?>"><?= $active_closed_case_data['name'] ?></option>
                                                <?php endforeach; ?>
                                            </select>
                                        </div>

                                        <div class="col-md-12 mt-2" style="margin-top:20px;display:flex;justify-content:end;">
                                            <button class="btn btn-info" id="clear_filters_btn" style="margin-right: 5px;" disabled>Clear Filters</button>
                                            <button class="btn btn-info" id="apply_filters_btn">Apply Filters</button>
                                        </div>
                                        <div class="clearfix"></div>
                                        <hr class="-tw-mx-4 tw-border-neutral-200" style="border-top: 5px solid #eee;"/>
                                    </div>
                                    
                                    <div class="row">
                                        <div class="container-fluid leads-kan-ban">
                                            <div id="kan-ban"></div>
                                        </div>
                                    </div>
                                </div>
                            <?php } else { ?>
                                <div class="row" id="leads-table">
                                    <div class="col-md-12">
                                        <div class="row" style="display:none;">
                                            <div class="col-md-12">
                                                <p class="bold">
                                                    <?php echo _l('filter_by'); ?>
                                                </p>
                                            </div>
                                            <?php if (has_permission('leads', '', 'view')) { ?>
                                                <div class="col-md-3 leads-filter-column">
                                                    <?php echo render_select('view_assigned', $staff_group, ['group_name', ['group_name']], 'Assigned', '', ['data-width' => '100%', 'data-none-selected-text' => _l('leads_dt_assigned')], [], 'no-mbot'); ?>
                                                </div>
                                            <?php } ?>
                                            <div class="col-md-3 leads-filter-column">
                                                <?php
                                                $selected = [];
                                                if ($this->input->get('status')) {
                                                    $selected[] = $this->input->get('status');
                                                } else {
                                                    foreach ($statuses as $key => $status) {
                                                        if ($status['isdefault'] == 0) {
                                                            $selected[] = $status['id'];
                                                        } else {
                                                            $statuses[$key]['option_attributes'] = ['data-subtext' => _l('leads_converted_to_client')];
                                                        }
                                                    }
                                                }
                                                echo '<div id="leads-filter-status">';
                                                echo render_select('view_status[]', $statuses, ['id', 'name'], 'Status', $selected, ['data-width' => '100%', 'data-none-selected-text' => _l('leads_all'), 'multiple' => true, 'data-actions-box' => true], [], 'no-mbot', '', false);
                                                echo '</div>';
                                                ?>
                                            </div>

                                        </div>
                                        <hr class=""
                                            style="margin-top: 28px;margin-bottom: 28px;border: 0;border-top: 5px solid #d2d2d280" />
                                    </div>
                                    <?php if (get_current_staff_role($this, get_staff_user_id()) != 2 || get_current_staff_role($this,get_staff_user_id()) != 6) { ?>
                                        <div style="<?php echo ($samegroup === 2) ? 'display:none;' : ''; ?>">
                                            <!-- Time taken  -->
                                            <h4 style="text-align: left;" class="col-md-12 btn btn-primary">Retrieve Reports on
                                                Overall Time Consumption</h4>
                                            <div class="col-md-12 leads-filter-column" style="padding: 16px 15px;">
                                                <button type="button" class="btn btn-primary mright5 pull-left display-block"
                                                    id="resetFieldsButton" <?php if (!empty($reports_stage) || !empty($reports_broker) || !empty($stage_group)): ?>  <?php else: ?> disabled <?php endif; ?>>Reset Filters</button>
                                            </div>
                                            <div class="col-md-3 leads-filter-column"
                                                style="margin-top: 15px;margin-bottom: 15px;">
                                                <?php echo render_select('cases_completed_time', '', ['id', ['name']], 'Selected Case', '', ['data-width' => '100%', 'data-none-selected-text' => _l('leads_dt_assigned')], [], 'no-mbot'); ?>
                                            </div>
                                            <div class="col-md-12">
                                                <div
                                                    class="tw-flex tw-flex-wrap tw-flex-col lg:tw-flex-row tw-w-full tw-gap-3 lg:tw-gap-6">
                                                    <div id="count_time_taken_from_instruction_to_id_received_toggle"
                                                        class="lg:tw-border-r lg:tw-border-solid lg:tw-border-neutral-300 tw-flex-1 tw-flex tw-items-center last:tw-border-r-0">
                                                        <p>
                                                            <span id="count_time_taken_from_instruction_to_id_received"
                                                                class="tw-font-semibold tw-mr-3 rtl:tw-ml-3 tw-text-lg">0</span>
                                                            <span id="count_time_taken_from_instruction_to_id_received_color"
                                                                style="color:#7cb342">Time taken from instruction to full
                                                                ID received</span>
                                                        </p>
                                                    </div>
                                                    <div id="count_time_taken_from_instruction_to_offer_received_toggle"
                                                        class="lg:tw-border-r lg:tw-border-solid lg:tw-border-neutral-300 tw-flex-1 tw-flex tw-items-center last:tw-border-r-0">
                                                        <p>
                                                            <span id="count_time_taken_from_instruction_to_offer_received"
                                                                class="tw-font-semibold tw-mr-3 rtl:tw-ml-3 tw-text-lg">0</span>
                                                            <span id="count_time_taken_from_instruction_to_offer_received_color"
                                                                style="color:#374d6e">Time taken from instruction to offer
                                                                received</span>
                                                        </p>
                                                    </div>
                                                    <div id="count_time_taken_from_offer_to_closing_toggle"
                                                        class="lg:tw-border-r lg:tw-border-solid lg:tw-border-neutral-300 tw-flex-1 tw-flex tw-items-center last:tw-border-r-0">
                                                        <p>
                                                            <span id="count_time_taken_from_offer_to_closing"
                                                                class="tw-font-semibold tw-mr-3 rtl:tw-ml-3 tw-text-lg">0</span>
                                                            <span id="count_time_taken_from_offer_to_closing_color"
                                                                style="color:#b317a3">Time taken from offer to
                                                                closing</span>
                                                        </p>
                                                    </div>
                                                    <div id="count_time_taken_from_instruction_to_closing_toggle"
                                                        class="lg:tw-border-r lg:tw-border-solid lg:tw-border-neutral-300 tw-flex-1 tw-flex tw-items-center last:tw-border-r-0">
                                                        <p>
                                                            <span id="count_time_taken_from_instruction_to_closing"
                                                                class="tw-font-semibold tw-mr-3 rtl:tw-ml-3 tw-text-lg">0</span>
                                                            <span id="count_time_taken_from_instruction_to_closing_color"
                                                                style="color:#7cb342">Time taken from instruction to
                                                                closing</span>
                                                        </p>
                                                    </div>
                                                </div>
                                                <hr class=""
                                                    style="margin-top: 28px;margin-bottom: 28px;border: 0;border-top: 5px solid #d2d2d280" />
                                            </div>
                                            <div class="clearfix"></div>
                                            <div class="col-md-12">
                                                <div class="row">
                                                    <div class="col-md-12">
                                                        <p class="bold">
                                                            <?php echo "Advance Filter"; ?>
                                                        </p>
                                                    </div>
                                                    <div class="col-md-3 leads-filter-column">
                                                        <?php echo render_date_input('start_date', '<span style="color:red;">*</span> Start date', '', ''); ?>
                                                    </div>
                                                    <div class="col-md-3 leads-filter-column">
                                                        <?php echo render_date_input('end_date', '<span style="color:red;">*</span> End date', ''); ?>
                                                    </div>
                                                    <!-- select offer type -->
                                                    <div class="col-md-3 leads-filter-column mt-2">
                                                        <?php ?>
                                                    </div>
                                                </div>
                                                <hr
                                                    style="margin-top: 28px;margin-bottom: 28px;border: 0;border-top: 3px solid #d2d2d280">
                                            </div>
                                            <div class="clearfix"></div>
                                            <h4 style="text-align:left; margin-bottom:30px;" class="col-md-12 btn btn-primary">
                                                Retrieve Reports on Total Time Consumption by Lender and Appointment Completion
                                            </h4>
                                            <div class="col-md-12">
                                                <div class="row">
                                                    <div class="col-md-3 leads-filter-column mt-2" style="margin-bottom:40px;">
                                                        <?php
                                                        echo render_select('lender', $lender_data, ['id', ['bank_name']], 'Select Lender', '', ['data-width' => '100%', 'data-none-selected-text' => _l('leads_dt_assigned')], [], 'no-mbot'); ?>
                                                    </div>
                                                    <div class="col-md-3 leads-filter-column" style="margin-bottom:40px;">
                                                        <?php echo render_select('appointment_completed_by', $staff_record, ['staffid', ['firstname', 'lastname']], 'Appointment Completed By', '', ['data-width' => '100%', 'data-none-selected-text' => _l('leads_dt_assigned')], [], 'no-mbot'); ?>
                                                    </div>

                                                </div>
                                            </div>
                                            <div class="col-md-12">
                                                <div
                                                    class="tw-flex tw-flex-wrap tw-flex-col lg:tw-flex-row tw-w-full tw-gap-3 lg:tw-gap-6">
                                                    <div id="toggle_style_overall_total_count" style="pointer-events: none;"
                                                        class="lg:tw-border-r lg:tw-border-solid lg:tw-border-neutral-300 tw-flex-1 tw-flex tw-items-center last:tw-border-r-0">
                                                        <p><span id="overall_total_count"
                                                                class="tw-font-semibold tw-mr-3 rtl:tw-ml-3 tw-text-lg">

                                                            </span><span id="toggle_style_overall_total_count_color"
                                                                style="color:#7cb342">Total Files</span></p>
                                                    </div>
                                                    <div id="file_open_count_without_offer_toggle" style="pointer-events: none;"
                                                        class="lg:tw-border-r lg:tw-border-solid lg:tw-border-neutral-300 tw-flex-1 tw-flex tw-items-center last:tw-border-r-0">
                                                        <p><span id="file_open_count_without_offer_count"
                                                                class="tw-font-semibold tw-mr-3 rtl:tw-ml-3 tw-text-lg">

                                                            </span><span id="file_open_count_without_offer_toggle_color"
                                                                style="color:#374d6e">Total Files Opened without
                                                                offer</span></p>
                                                    </div>
                                                    <div id="file_open_count_with_offer_count_toggle" style="pointer-events: none;"
                                                        class="lg:tw-border-r lg:tw-border-solid lg:tw-border-neutral-300 tw-flex-1 tw-flex tw-items-center last:tw-border-r-0">
                                                        <p><span id="file_open_count_with_offer_count"
                                                                class="tw-font-semibold tw-mr-3 rtl:tw-ml-3 tw-text-lg">

                                                            </span><span id="file_open_count_with_offer_count_color"
                                                                style="color:#b317a3">Total Files Opened with offer</span>
                                                        </p>
                                                    </div>
                                                    <div id="files_offer_no_ids_toggle" style="pointer-events: none;"
                                                        class="lg:tw-border-r lg:tw-border-solid lg:tw-border-neutral-300 tw-flex-1 tw-flex tw-items-center last:tw-border-r-0">
                                                        <p>
                                                            <span id="files_offer_no_ids"
                                                                class="tw-font-semibold tw-mr-3 rtl:tw-ml-3 tw-text-lg">
                                                            </span>
                                                            <span id="files_offer_no_ids_color" style="color:#3aca52">Total
                                                                Files
                                                                with offer and no
                                                                ids</span>
                                                        </p>
                                                    </div>
                                                    <div id="overall_total_count_for_on_hold_toggle" style="pointer-events: none;"
                                                        class="lg:tw-border-r lg:tw-border-solid lg:tw-border-neutral-300 tw-flex-1 tw-flex tw-items-center last:tw-border-r-0">
                                                        <p><span id="overall_total_count_for_on_hold"
                                                                class="tw-font-semibold tw-mr-3 rtl:tw-ml-3 tw-text-lg">

                                                            </span><span id="overall_total_count_for_on_hold_color"
                                                                style="color:#b317a3">Total Files On Hold</span></p>
                                                    </div>
                                                    <div id="total_count_for_lender_toggle" style="display:none;pointer-events: none;"
                                                        class="lg:tw-border-r lg:tw-border-solid lg:tw-border-neutral-300 tw-flex-1 tw-flex tw-items-center last:tw-border-r-0 btn btn-primary">
                                                        <p>
                                                            <span id="total_count_for_lender"
                                                                class="tw-font-semibold tw-mr-3 rtl:tw-ml-3 tw-text-lg"></span>
                                                            <span style="">Total Particular lender</span>
                                                        </p>
                                                    </div>
                                                    <div id="total_count_for_appointment_completed_by_staff_toggle" style="pointer-events: none;"
                                                        class="lg:tw-border-r lg:tw-border-solid lg:tw-border-neutral-300 tw-flex-1 tw-flex tw-items-center last:tw-border-r-0">
                                                        <p>
                                                            <span id="total_count_for_appointment_completed_by_staff"
                                                                class="tw-font-semibold tw-mr-3 rtl:tw-ml-3 tw-text-lg"></span>
                                                            <span id="total_count_for_appointment_completed_by_staff_color"
                                                                style="color:#7cb342">Total Completed Appointment</span>
                                                        </p>
                                                    </div>
                                                    <div id="total_flies_open_with_specific_time_toggle" style="display:none;pointer-events: none;"
                                                        class="lg:tw-border-r lg:tw-border-solid lg:tw-border-neutral-300 tw-flex-1 tw-flex tw-items-center last:tw-border-r-0 btn btn-primary">
                                                        <p><span id="total_flies_open_with_specific_time"
                                                                class="tw-font-semibold tw-mr-3 rtl:tw-ml-3 tw-text-lg">
                                                            </span><span style="">Total files opened within the
                                                                specified time frame</span></p>
                                                    </div>
                                                    <div id="total_flies_closed_with_specific_time_toggle" style="display:none;pointer-events: none;"
                                                        class="lg:tw-border-r lg:tw-border-solid lg:tw-border-neutral-300 tw-flex-1 tw-flex tw-items-center last:tw-border-r-0 btn btn-primary">
                                                        <p><span id="total_flies_closed_with_specific_time"
                                                                class="tw-font-semibold tw-mr-3 rtl:tw-ml-3 tw-text-lg">
                                                            </span><span style="">Total files closed within the
                                                                specified time frame</span></p>
                                                    </div>
                                                </div>
                                                <hr class=""
                                                    style="margin-top: 28px;margin-bottom: 28px;border: 0;border-top: 5px solid #d2d2d280" />
                                            </div>
                                            <!-- Advance filter for table -->
                                            <div class="col-md-12">
                                                <div class="row">
                                                    <div class="col-md-3 leads-filter-column">
                                                        <?php
                                                        // reports selected value
                                                        if (!empty ($stage_group)) {
                                                            $group_selected = $stage_group;
                                                        }
                                                        ?>
                                                        <?php echo render_select('group_name', $staff_group, ['group_name', ['group_name']], 'Groups Name', $group_selected, ['data-width' => '100%', 'data-none-selected-text' => _l('leads_dt_assigned')], [], 'no-mbot'); ?>
                                                    </div>

                                                    <div class="col-md-3 leads-filter-column">
                                                        <?php
                                                        $selected = [];
                                                        if ($this->input->get('status')) {
                                                            $selected[] = $this->input->get('status');
                                                        } else {
                                                            foreach ($statuses as $key => $status) {
                                                                if ($status['isdefault'] == 0) {
                                                                    // $selected[] = $status['id'];
                                                                    // reports seleted value
                                                                    if (!empty ($reports_stage)) {
                                                                        $selected = $reports_stage;
                                                                    }
                                                                } else {
                                                                    $statuses[$key]['option_attributes'] = ['data-subtext' => _l('leads_converted_to_client')];
                                                                }
                                                            }
                                                        }
                                                        echo '<div id="leads-filter-status">';
                                                        echo render_select('view_status_pipeline[]', $statuses, ['id', 'name'], 'Stages Status', $selected, ['data-width' => '100%', 'data-none-selected-text' => _l('leads_dt_status'), 'multiple' => true, 'data-actions-box' => true], [], 'no-mbot', '', false);
                                                        echo '</div>';
                                                        ?>
                                                    </div>
                                                    <div class="col-md-3 leads-filter-column">
                                                        <?php
                                                        $selected = [];
                                                        if (!empty ($reports_broker)) {
                                                            $selected = $reports_broker;
                                                        }
                                                        foreach ($broker_data as $key => $status) {
                                                            if (!empty ($status['staffid'])) {
                                                                $broker_data[$key]['option_attributes'] = ['' => $status['firstname'] . ' ' . $status['lastname']];
                                                            }
                                                        }
                                                        echo '<div id="leads-filter-status">';
                                                        echo render_select('broker_filter[]', $broker_data, ['staffid', 'firstname', 'lastname'], 'Broker', $selected, ['data-width' => '100%', 'data-none-selected-text' => _l('leads_all'), 'multiple' => true, 'data-actions-box' => true], [], 'no-mbot', '', false);
                                                        echo '</div>';
                                                        ?>
                                                    </div>
                                                    <div class="col-md-3 leads-filter-column">
                                                        <?php
                                                        $selected = [];
                                                        foreach ($agent_data as $key => $agent_status) {
                                                            if (!empty ($agent_status['staffid'])) {
                                                                $agent_data[$key]['option_attributes'] = ['' => $agent_status['firstname'] . ' ' . $agent_status['lastname']];
                                                            }
                                                        }
                                                        echo '<div id="leads-filter-status">';
                                                        echo render_select('ld_team[]', $agent_data, ['staff_group', 'firstname', 'lastname'], 'LD-Team Member', $selected, ['data-width' => '100%', 'data-none-selected-text' => _l('leads_all'), 'multiple' => true, 'data-actions-box' => true], [], 'no-mbot', '', false);
                                                        echo '</div>';
                                                        ?>
                                                    </div>
                                                    <div class="col-md-3 leads-filter-column" style="margin-top:15px;">
                                                        <?php
                                                        $selected = [];
                                                        foreach ($brokerage_data as $key => $agent_status) {
                                                            if (!empty ($agent_status['id'])) {
                                                                $brokerage_data[$key]['option_attributes'] = ['' => $agent_status['name']];
                                                            }
                                                        }
                                                        echo '<div id="leads-filter-status">';
                                                        echo render_select('brokerage_filter[]', $brokerage_data, ['id', 'name'], 'Select Brokerage', $selected, ['data-width' => '100%', 'data-none-selected-text' => _l('leads_all'), 'multiple' => true, 'data-actions-box' => true], [], 'no-mbot', '', false);
                                                        echo '</div>';
                                                        ?>
                                                    </div>
                                                    <div class="col-md-3 leads-filter-column" style="margin-top:15px;">
                                                        <?php
                                                        $selected = [];
                                                        $manual_options = [
                                                            ['id' => 'ids_not_completed',     'name' => 'ID not Complete'],
                                                            ['id' => 'ids_completed',     'name' => 'ID Complete'],
                                                            ['id' => 'idv_in',    'name' => 'IDV In / IDV N/A'],
                                                            ['id' => 'idv_not_in', 'name' => 'IDV Not In'],
                                                            ['id' => 'ins_in', 'name' => 'Instruction In'],
                                                        ];
                                                        echo '<div id="leads-filter-status">';
                                                        echo render_select('offer_in_out[]',$manual_options,['id', 'name'],'Select IDs In/Out',$selected,['data-width' => '100%','data-none-selected-text' => _l('leads_all'),'multiple' => true,'data-actions-box' => true],[],'no-mbot','',false);
                                                        echo '</div>';
                                                        ?>
                                                    </div>
                                                    <div class="col-md-3 leads-filter-column" style="margin-top:15px;">
                                                        <?php
                                                        $selected = [];
                                                        $manual_options = [
                                                            ['id' => 'nothing_selected',     'name' => 'Nothing Selected'],
                                                            ['id' => 'active',     'name' => 'Active'],
                                                            ['id' => 'closed',    'name' => 'Closed'],
                                                        ];
                                                        foreach ($manual_options as $key => $agent_status) {
                                                            if (!empty ($agent_status['id'])) {
                                                                $manual_options[$key]['option_attributes'] = ['' => $agent_status['name']];
                                                            }
                                                        }
                                                        echo '<div id="leads-filter-status">';
                                                        echo render_select('active_record', $manual_options, ['id', 'name'], 'Active / Inactive Cases', $selected, ['data-width' => '100%', 'data-none-selected-text' => _l('leads_all'),'data-actions-box' => true], [], 'no-mbot', '', false);
                                                        echo '</div>';
                                                        ?>
                                                    </div>
                                                </div>
                                                <hr class=""
                                                    style="margin-top: 28px;margin-bottom: 28px;border: 0;border-top: 5px solid #d2d2d280" />
                                            </div>
                                        </div>
                                    <?php } ?>
                                    <div class="col-md-12">
                                        <a href="#" data-toggle="modal" data-table=".table-leads"
                                            data-target="#leads_bulk_actions" class="hide bulk-actions-btn table-btn">
                                            <?php echo _l('bulk_actions'); ?>
                                        </a>

                                        <?php if ($samegroup): ?>
                                            <div class="modal fade bulk_actions" id="leads_bulk_actions" tabindex="-1"
                                                role="dialog">
                                                <div class="modal-dialog" role="document">
                                                    <div class="modal-content">
                                                        <div class="modal-header">
                                                            <button type="button" class="close" data-dismiss="modal"
                                                                aria-label="Close"><span
                                                                    aria-hidden="true">&times;</span></button>
                                                            <h4 class="modal-title">
                                                                <?php echo _l('bulk_actions'); ?>
                                                            </h4>
                                                        </div>
                                                        <div class="modal-body">
                                                            <?php if (has_permission('leads', '', 'delete')) { ?>
                                                                <div class="checkbox checkbox-danger">
                                                                    <input type="checkbox" name="mass_delete" id="mass_delete">
                                                                    <label for="mass_delete">
                                                                        <?php echo _l('mass_delete'); ?>
                                                                    </label>
                                                                </div>
                                                                <hr class="mass_delete_separator" />
                                                            <?php } ?>
                                                            <div id="bulk_change">
                                                                <?php echo render_select('move_to_status_leads_bulk', $statuses, ['id', 'name'], 'ticket_single_change_status'); ?>
                                                                <?php
                                                                ?>
                                                                <div style="display: none;">
                                                                    <?php
                                                                    echo render_select('move_to_source_leads_bulk', $sources, ['id', 'name'], 'lead_source');
                                                                    ?>
                                                                </div>
                                                                <?php
                                                                echo render_datetime_input('leads_bulk_last_contact', 'leads_dt_last_contact');
                                                                echo render_select('assign_to_leads_bulk', $staff_group, ['group_name', ['group_name']], 'leads_dt_assigned');
                                                                ?>
                                                                <div class="form-group" style="display:none;">
                                                                    <?php echo '<p><b><i class="fa fa-tag" aria-hidden="true"></i> ' . _l('tags') . ':</b></p>'; ?>
                                                                    <input type="text" class="tagsinput" id="tags_bulk"
                                                                        name="tags_bulk" value="" data-role="tagsinput">
                                                                </div>
                                                            </div>
                                                        </div>
                                                        <div class="modal-footer">
                                                            <button type="button" class="btn btn-default" data-dismiss="modal">
                                                                <?php echo _l('close'); ?>
                                                            </button>
                                                            <a href="#" class="btn btn-primary"
                                                                style="<?php echo ($samegroup === 2) ? 'display:none;' : ''; ?>"
                                                                onclick="leads_bulk_action(this); return false;">
                                                                <?php echo _l('confirm'); ?>
                                                            </a>
                                                        </div>
                                                    </div>
                                                    <!-- /.modal-content -->
                                                </div>
                                                <!-- /.modal-dialog -->
                                            </div>
                                            <!-- /.modal -->
                                        <?php endif; ?>
                                        <?php

                                        $table_data = [];
                                        $_table_data = [
                                            '<span class="hide"> - </span><div class="checkbox mass_select_all_wrap"><input type="checkbox" id="mass_select_all" data-to-table="leads"><label></label></div>',
                                            [
                                                'name' => _l('the_number_sign'),
                                                'th_attrs' => ['class' => 'toggleable', 'id' => 'th-number'],
                                            ],
                                            [
                                                'name' => _l('leads_dt_name'),
                                                'th_attrs' => ['class' => 'toggleable', 'id' => 'th-name', 'data-order-col' => 2,],
                                            ],
                                        ];
                                        if (is_gdpr() && get_option('gdpr_enable_consent_for_leads') == '1') {
                                            $_table_data[] = [
                                                'name' => _l('gdpr_consent') . ' (' . _l('gdpr_short') . ')',
                                                'th_attrs' => ['id' => 'th-consent', 'class' => 'not-export'],
                                            ];
                                        }

                                        $_table_data[] = [
                                            'name' => _l('leads_dt_email'),
                                            'th_attrs' => ['class' => 'toggleable', 'id' => 'th-email'],
                                        ];
                                        $_table_data[] = [
                                            'name' => _l('leads_dt_phonenumber'),
                                            'th_attrs' => ['class' => 'toggleable', 'id' => 'th-phone'],
                                        ];


                                        $_table_data[] = [
                                            'name' => _l('leads_dt_assigned'),
                                            'th_attrs' => ['class' => 'toggleable', 'id' => 'th-assigned'],
                                        ];

                                        // $_table_data[] = [
                                        //     'name' => 'Offer',
                                        //     'th_attrs' => ['class' => 'toggleable', 'id' => 'th-offer'],
                                        // ];
                                        // $_table_data[] = [
                                        //     'name' => _l('leads_dt_instruction_to_full_id_received'),
                                        //     'th_attrs' => ['class' => 'toggleable', 'id' => 'th-instruction-to-full-id-received'],
                                        // ];
                                        $_table_data[] = [
                                            'name' => 'File Status',
                                            'th_attrs' => ['class' => 'toggleable', 'id' => 'th-filestatus'],
                                        ];
                                        $_table_data[] = [
                                            'name' => _l('leads_dt_status'),
                                            'th_attrs' => ['class' => 'toggleable', 'id' => 'th-status'],
                                        ];
                                        if($current_staff_role != 2 || $current_staff_role != 6){
                                            $_table_data[] = [
                                                'name' => _l('leads_dt_last_contact'),
                                                'th_attrs' => ['class' => 'toggleable', 'id' => 'th-last-contact'],
                                            ];
                                        }
                                        $_table_data[] = [
                                            'name' => _l('leads_dt_datecreated'),
                                            'th_attrs' => ['class' => 'date-created toggleable', 'id' => 'th-date-created'],
                                        ];
                                        foreach ($_table_data as $_t) {
                                            array_push($table_data, $_t);
                                        }
                                        $custom_fields = get_custom_fields('leads', ['show_on_table' => 1]);
                                        foreach ($custom_fields as $field) {
                                            array_push($table_data, [
                                                'name' => $field['name'],
                                                'th_attrs' => ['data-type' => $field['type'], 'data-custom-field' => 1],
                                            ]);
                                        }
                                        $table_data = hooks()->apply_filters('leads_table_columns', $table_data);
                                        ?>
                                        <div id="list-view-filter-loader" style="display: none;"> 
                                            <div class="spinner"></div>
                                        </div>
                                        <div class="panel-table-full" >
                                            <?php
                                            render_datatable(
                                                $table_data,
                                                'leads',
                                                ['customizable-table number-index-2'],
                                                [
                                                    'id' => 'table-leads',
                                                    'data-last-order-identifier' => 'leads',
                                                    'data-default-order' => get_table_last_order('leads'),
                                                ]
                                            );
                                            ?>
                                        </div>
                                    </div>
                                </div>
                            <?php } ?>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
<!-- custom modal code -->
 <!-- Custom Modal -->

 <div class="modal fade" id="custom-modal" tabindex="-3" role="dialog" aria-labelledby="staffModalLabel" aria-hidden="true">
  <div class="modal-dialog" role="document">
    <div class="modal-content">
      <?php $this->load->view('admin/leads/custom_modal'); ?>
    </div>
  </div>
</div>
<!-- custom daily chaser staff dropdown modal -->
<div class="modal fade" id="custom_daily_chase_staffModal" tabindex="-3" role="dialog" aria-labelledby="staffModalLabel" aria-hidden="true">
  <div class="modal-dialog" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="staffModalLabel">Assign Staff</h5>
        <!-- Font Awesome -->
        <button type="button" class="staffclose" data-dismiss="modal" style="float: right; border: none; background: none;">
        <i class="fas fa-times"></i>
        </button>
      </div>
        <div class="modal-body">
            <div id="staffList" class="row"></div>
            <input type="hidden" id="custom_daily_chaser_selectedTaskId">
            <div id="custom_daily_chaser_staff_ids_wrapper"></div>
        </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-primary" id="assignStaffBtn">Assign</button>
      </div>
    </div>
  </div>
</div>

<style>
    .btn-default-dt-options {
        display: none;
    }

    .btn-dt-reload {
        display: block;
    }

    .buttons-collection {
        display: block;
    }
    #custom-modal .modal-dialog {
  max-width: 90%;
  margin: 30px auto;
}
#custom-modal .modal-content.data {
  max-height: 1130px;
  overflow-y: auto;
  overflow-x: hidden;
  border-radius: 8px;
  padding: 15px;
  box-shadow: 0 5px 25px rgba(0, 0, 0, 0.15);
}
.kanban-filter-loader {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background: rgba(255,255,255,0.8);
    z-index: 9999;
    display: flex;
    justify-content: center;
    align-items: center;
}

.kanban-filter-loader .spinner {
    border: 5px solid #f3f3f3;
    border-top: 5px solid #007bff;
    border-radius: 50%;
    width: 40px;
    height: 40px;
    animation: spin 1s linear infinite;
}
#list-view-filter-loader {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background: rgba(255,255,255,0.8);
    z-index: 9999;
    display: flex;
    justify-content: center;
    align-items: center;
}

#list-view-filter-loader .spinner {
    border: 5px solid #f3f3f3;
    border-top: 5px solid #007bff;
    border-radius: 50%;
    width: 40px;
    height: 40px;
    animation: spin 1s linear infinite;
}
.task-placeholder {
  background: rgba(0,0,0,0.03);
  border: 2px dashed #d0d0d0;
  margin: 8px 0;
  border-radius: 6px;
}
.task-wrapper { margin-bottom: 10px; }


@keyframes spin {
    to { transform: rotate(360deg); }
}
</style>
<script id="hidden-columns-table-leads" type="text/json">
<?php echo get_staff_meta(get_staff_user_id(), 'hidden-columns-table-leads'); ?>
</script>
<?php include_once (APPPATH . 'views/admin/leads/status.php'); ?>
<?php init_tail(); ?>
<script>
    var openLeadID = '<?php echo $leadid; ?>';
    $(function () {
        leads_kanban();
        $('#leads_bulk_mark_lost').on('change', function () {
            $('#move_to_status_leads_bulk').prop('disabled', $(this).prop('checked') == true);
            $('#move_to_status_leads_bulk').selectpicker('refresh')
        });
        $('#move_to_status_leads_bulk').on('change', function () {
            if ($(this).selectpicker('val') != '') {
                $('#leads_bulk_mark_lost').prop('disabled', true);
                $('#leads_bulk_mark_lost').prop('checked', false);
            } else {
                $('#leads_bulk_mark_lost').prop('disabled', false);
            }
        });
    });
    $(document).on('click', '.edit-lead-link', function (e) {
        var profileEditButton = document.querySelector('.profile_edit_button');
        if (profileEditButton) {
            profileEditButton.click();
        } else {
            console.error('Element with class ".profile_edit_button" not found.');
        }
    });



    $(document).ready(function () {
        var kanbanView = '<?php echo !$isKanBan ? '0' : '1'; ?>';
        // if kanban view load then onlly kanban function run
       
        setTimeout(function () {
            if (kanbanView == '0' || kanbanView == 0) {
                // kanban filter section toggle
                $('#kanban-advance-filter-btn').on('click', function () {
                    $('#kanban_filters_row').slideToggle(500, function () {
                        const isVisible = $(this).is(':visible');
                        localStorage.setItem('kanban_filter_open', isVisible ? 'true' : 'false');
                    });
                });

                // clear the kanban filters 
               $('#clear_filters_btn').on('click', function () {
                    // Clear all the filter input values
                    $('#filter_lead_id').val('');
                    $('#filter_name').val('');
                    $('#filter_email').val('');
                    $('#filter_phone').val('');
                    $('#filter_address').val('');
                    $('#filter_state').val('');
                    $('#filter_group').val([]);
                    $('#stage_status_filter').val('');
                    $('#brokers_filter').val('');
                    $('#brokerage_filter').val('');
                    $('#kanban_offer_in_out').val('');
                    $('#kanban_active_record').val('');
                    $('.selectpicker').selectpicker('refresh');

                    // Send AJAX to unset session filters
                    $.get(admin_url + 'leads/reset_kanban_filters', function (response) {
                        try {
                            var res = JSON.parse(response);
                            if (res.success) {
                                // Clear UI and refresh Kanban
                                $('.ui-sortable').find('ul').remove();

                                setTimeout(function () {
                                    $('#kanban-filter-loader').hide();
                                    leads_kanban();
                                }, 500);

                                $('#clear_filters_btn').prop('disabled', true);
                                localStorage.setItem('kanban_filter_open', 'false');
                            }
                        } catch (e) {
                            console.error('Invalid response from server');
                        }
                    });
                });

                // kanban filter code
                $('#apply_filters_btn').on('click', function () {
                    $('#clear_filters_btn').prop('disabled', false);
                    $('#kanban-filter-loader').show();
                    $.ajax({
                        url: admin_url + 'leads/kanban',
                        type: 'POST',
                        data: {
                            id: $('#filter_lead_id').val(),
                            name: $('#filter_name').val(),
                            email: $('#filter_email').val(),
                            phone: $('#filter_phone').val(),
                            address: $('#filter_address').val(),
                            state: $('#filter_state').val(),
                            group_ids: $('#filter_group').val(),
                            status: $('#stage_status_filter').val(),
                            brokers_filter: $('#brokers_filter').val(),
                            brokerage_filter: $('#brokerage_filter').val(),
                            kanban_offer_in_out: $('#kanban_offer_in_out').val(), 
                            kanban_active_record: $('#kanban_active_record').val(),
                        },
                        success: function (response) {
                            // $('#kan-ban').html($(response).find('#kan-ban').html());
                            // init_kanban();
                            $('.ui-sortable').find('ul').remove();
                            $('.ui-sortable').append(response);
                            $('.kan-ban-content').css({
                                'overflow-y': 'scroll',
                                'height': '800px',
                            });
                            // hide kanban filter
                            $('#kanban-filter-loader').hide();
                        }
                    });
                });
            }
        }, 3000);
        // if list view load then only list view function run
        if(kanbanView == '1' || kanbanView == 1){
            // reset the all fields
            function removeThebuttonclassCount_for_total_time_taken_flies() {
                // Time taken count
                // style for instruction to full id received
                $('#count_time_taken_from_instruction_to_id_received_toggle').addClass('btn btn-primary');
                $('#count_time_taken_from_instruction_to_id_received_color').removeAttr('style');
                // style time taken from instruction to offer received
                $('#count_time_taken_from_instruction_to_offer_received_toggle').addClass('btn btn-primary');
                $('#count_time_taken_from_instruction_to_offer_received_color').removeAttr('style');
                // Style time taken form offer to closing
                $('#count_time_taken_from_offer_to_closing_toggle').addClass('btn btn-primary');
                $('#count_time_taken_from_offer_to_closing_color').removeAttr('style');
                // Style Time taken from instruction to closing 
                $('#count_time_taken_from_instruction_to_closing_toggle').addClass('btn btn-primary');
                $('#count_time_taken_from_instruction_to_closing_color').removeAttr('style');
            }
            function removeThebuttonclassCount_for_total_files() {
                // Total files count
                $('#toggle_style_overall_total_count').removeClass('btn btn-primary');
                $('#toggle_style_overall_total_count_color').attr('style', 'color: #7cb342');
                // Total files opened without offer
                $('#file_open_count_without_offer_toggle').removeClass('btn btn-primary');
                $('#file_open_count_without_offer_toggle_color').attr('style', 'color: #374d6e');
                // Total Files Opened with offer
                $('#file_open_count_with_offer_count_toggle').removeClass('btn btn-primary');
                $('#file_open_count_with_offer_count_color').attr('style', 'color: #b317a3');
                // Total Files with offer and no ids
                $('#files_offer_no_ids_toggle').removeClass('btn btn-primary');
                $('#files_offer_no_ids_color').attr('style', 'color: #3aca52');
                // overall total count
                $('#overall_total_count_for_on_hold_toggle').removeClass('btn btn-primary');
                $('#overall_total_count_for_on_hold_color').attr('style', 'color: #b317a3');
                // Total completed appointment
                $('#total_count_for_appointment_completed_by_staff_toggle').removeClass('btn btn-primary');
                $('#total_count_for_appointment_completed_by_staff_color').attr('style', 'color: #7cb342');
            }
            function AddThebuttonclassCount_for_total_time_taken_flies() {
                // Time taken count
                $('#count_time_taken_from_instruction_to_id_received_toggle').removeClass('btn btn-primary');
                $('#count_time_taken_from_instruction_to_id_received_color').attr('style', 'color: #7cb342');
                // style time taken from instruction to offer received
                $('#count_time_taken_from_instruction_to_offer_received_toggle').removeClass('btn btn-primary');
                $('#count_time_taken_from_instruction_to_offer_received_color').attr('style', 'color: #374d6e');
                // Style time taken form offer to closing
                $('#count_time_taken_from_offer_to_closing_toggle').removeClass('btn btn-primary');
                $('#count_time_taken_from_offer_to_closing_color').attr('style', 'color: #b317a3');
                // Style Time taken from instruction to closing 
                $('#count_time_taken_from_instruction_to_closing_toggle').removeClass('btn btn-primary');
                $('#count_time_taken_from_instruction_to_closing_color').attr('style', 'color: #7cb342');
            }
            function AddThebuttonclassCount_for_total_files() {
                // Total files count
                $('#toggle_style_overall_total_count').addClass('btn btn-primary');
                $('#toggle_style_overall_total_count_color').removeAttr('style');
                // Total files open without offer 
                $('#file_open_count_without_offer_toggle').addClass('btn btn-primary');
                $('#file_open_count_without_offer_toggle_color').removeAttr('style');
                // Total Files Opened with offer
                $('#file_open_count_with_offer_count_toggle').addClass('btn btn-primary');
                $('#file_open_count_with_offer_count_color').removeAttr('style');
                // Total Files with offer and no ids
                $('#files_offer_no_ids_toggle').addClass('btn btn-primary');
                $('#files_offer_no_ids_color').removeAttr('style');
                // Total files on hold
                $('#overall_total_count_for_on_hold_toggle').addClass('btn btn-primary');
                $('#overall_total_count_for_on_hold_color').removeAttr('style');
                // total completed appointment
                $('#total_count_for_appointment_completed_by_staff_toggle').addClass('btn btn-primary');
                $('#total_count_for_appointment_completed_by_staff_color').removeAttr('style');
            }
            // Function to enable/disable reset button based on select values
            function toggleResetButton() {
                var inputs = $('input[type="text"]');
                var selects = ['#start_date', '#end_date', '#lender', '#appointment_completed_by', '#cases_completed_time', '#group_name', '#view_status_pipeline', '#broker_filter', '#ld_team', '#offer_in_out', '#active_record'];
                var enableReset = false;

                // Check select elements
                for (var i = 0; i < selects.length; i++) {
                    if ($(selects[i]).val() !== null) {
                        enableReset = true;
                        break;
                    }
                }

                // Check input elements
                inputs.each(function () {
                    if ($(this).val().trim() !== '') {
                        enableReset = true;
                        return false; // Break the loop
                    }
                });

                $('#resetFieldsButton').prop('disabled', !enableReset);
            }

            // Trigger toggleResetButton initially
            // toggleResetButton();

            // Listen for change events on select and input elements
            $('select, input[type="text"]').on('change', function () {
                toggleResetButton();
            });

            $('#resetFieldsButton').click(function () {
                // Reset select fields
                // $('select').val(null).trigger('change');
                $('#start_date').val(null).trigger('change');
                $('#end_date').val(null).trigger('change');
                $('#lender').val(null).trigger('change');
                $('#appointment_completed_by').val(null).trigger('change');
                // $('#cases_completed_time').val(null).trigger('change');
                $('#group_name').val(null).trigger('change');
                $('#view_status_pipeline').val(null).trigger('change');
                $('#broker_filter').val(null).trigger('change');
                $('#view_status_pipeline\\[\\], #broker_filter\\[\\], #ld_team\\[\\]').val(null).trigger('change');
                $('#ld_team\\[\\]').val(null);
                $('#ld_team\\[\\]').trigger('change');
                $('#ld_team\\[\\]').selectpicker('deselectAll');
                $('#ld_team\\[\\]').val([]);
                removeThebuttonclassCount_for_total_time_taken_flies();
                removeThebuttonclassCount_for_total_files();
                // Disable the reset button after resetting
                $(this).prop('disabled', true);
            });
            // bulk action checked then button show otherwise disabled
            $('#mass_select_all').change(function () {
                // Check if the bulk checkbox is checked
                if ($(this).is(':checked')) {
                    // If checked, display the element
                    $('.btn-default-dt-options').css('display', 'block');
                } else {
                    // If unchecked, hide the element
                    $('.btn-default-dt-options').css('display', 'none');
                    $('.buttons-collection').css('display', 'block');
                    $('.btn-dt-reload').css('display', 'block');
                }
            });
            // single checkbox checked or not then button show otherwise disabled
            $(document).on('change', '#bulk_checkbox', function () {
                // Check if any checkbox is checked
                var anyChecked = $('input[type="checkbox"]:checked').length > 0;
                // Apply CSS based on whether any checkbox is checked
                if (!anyChecked) {
                    // If any checkbox is checked, hide the element
                    $('.btn-default-dt-options').css('display', 'none');
                    $('.buttons-collection').css('display', 'block');
                    $('.btn-dt-reload').css('display', 'block');
                } else {
                    // If no checkbox is checked, display the element
                    $('.btn-default-dt-options').css('display', 'block');
                    $('.buttons-collection').css('display', 'block');
                    $('.btn-dt-reload').css('display', 'block');
                }
            });



            setTimeout(function () {
                overall_total_number_of_files();
                total_number_of_file_open_with_offer_count();
                total_number_of_file_open_without_offer_count();
                total_count_for_appointment_completed_by();
                total_on_hold_files_count();
                files_with_offer_no_ids();
            }, 5000);
            // specific time period count 
            // $('#start_date,#end_date').change(function () {
            $(document).off('change', '#start_date, #end_date').on('change', '#start_date, #end_date', function () {
                var start_date = $('#start_date').val();
                var end_date = $('#end_date').val();
                if (!start_date || !end_date) {
                    $('#total_flies_open_with_specific_time_toggle').hide();
                    $('#total_flies_closed_with_specific_time_toggle').hide();
                    setTimeout(function () {
                        overall_total_number_of_files();
                        total_number_of_file_open_with_offer_count();
                        total_number_of_file_open_without_offer_count();
                        total_count_for_appointment_completed_by();
                        total_on_hold_files_count();
                        files_with_offer_no_ids();
                    }, 5000);
                    return;
                } else {

                    AddThebuttonclassCount_for_total_files();
                }
                // it is used when only have a start date and end date
                total_count_for_appointment_completed_by();
                $.ajax({
                    url: '<?php echo admin_url('leads/file_opened_in_a_given_time_frame_count'); ?>',
                    method: 'POST',
                    data: {
                        start_date: start_date,
                        end_date: end_date
                    },
                    success: function (response) {
                        if (response.total_file_opened_timeframe) {
                            $('#total_flies_open_with_specific_time_toggle').show();
                            $('#total_flies_open_with_specific_time').text(response.total_file_opened_timeframe);
                        } else {
                            $('#total_flies_open_with_specific_time_toggle').hide();
                            $('#total_count_for_lender_toggle').hide();
                        }
                    },
                    error: function (xhr, status, error) {
                        // Handle error if needed
                    }
                });
                // file closed in a given time frame
                $.ajax({
                    url: '<?php echo admin_url('leads/file_closed_in_a_given_time_frame_count'); ?>',
                    method: 'POST',
                    data: {
                        start_date: start_date,
                        end_date: end_date
                    },
                    success: function (response) {
                        if (response.total_file_closed_timeframe) {
                            $('#total_flies_closed_with_specific_time_toggle').show();
                            $('#total_flies_closed_with_specific_time').text(response.total_file_closed_timeframe);
                        } else {
                            $('#total_flies_closed_with_specific_time_toggle').hide();
                        }
                    },
                    error: function (xhr, status, error) {
                        // Handle error if needed
                    }
                });
                // file opened in a given time frame without offer
                $.ajax({
                    url: '<?php echo admin_url('leads/total_number_of_file_open_without_offer_count'); ?>',
                    method: 'POST',
                    data: {
                        start_date: start_date,
                        end_date: end_date
                    },
                    success: function (response) {
                        if (response.file_open_count_without_offer_count) {
                            $('#file_open_count_without_offer_toggle').show();
                            $('#file_open_count_without_offer_count').text(response.file_open_count_without_offer_count);
                        } else {
                            $('#file_open_count_without_offer_toggle').hide();
                        }
                    },
                    error: function (xhr, status, error) {
                        // Handle error if needed
                    }
                });
                // total number of file opened with offer count
                $.ajax({
                    url: '<?php echo admin_url('leads/total_number_of_file_open_with_offer_count'); ?>',
                    method: 'POST',
                    data: {
                        start_date: start_date,
                        end_date: end_date
                    },
                    success: function (response) {
                        if (response.file_open_count_with_offer_count) {
                            $('#file_open_count_without_offer_toggle').show();
                            $('#file_open_count_with_offer_count').text(response.file_open_count_with_offer_count);
                        } else {
                            $('#file_open_count_without_offer_toggle').hide();
                        }
                    },
                    error: function (xhr, status, error) {
                        // Handle error if needed
                    }
                });
                // overall total number of files
                $.ajax({
                    url: '<?php echo admin_url('leads/overall_total_number_of_files'); ?>',
                    method: 'POST',
                    data: {
                        start_date: start_date,
                        end_date: end_date
                    },
                    success: function (response) {
                        if (response.total_count) {
                            $('#overall_total_count').text(response.total_count);
                        }
                    },
                    error: function (xhr, status, error) {
                        // Handle error if needed
                    }
                });
                // overall total on hold files
                $.ajax({
                    url: '<?php echo admin_url('leads/total_count_for_on_hold'); ?>',
                    method: 'POST',
                    data: {
                        start_date: start_date,
                        end_date: end_date
                    },
                    success: function (response) {
                        if (response.total_on_hold_file) {
                            $('#overall_total_count_for_on_hold').text(response.total_on_hold_file);
                        }
                    },
                    error: function (xhr, status, error) {
                        // Handle error if needed
                    }
                });
                // overall total no files with offer and no ids
                $.ajax({
                    url: '<?php echo admin_url('leads/total_file_with_offer_and_no_ids'); ?>',
                    method: 'POST',
                    data: {
                        start_date: start_date,
                        end_date: end_date
                    },
                    success: function (response) {
                        if (response.offer_no_ids_count) {
                            $('#files_offer_no_ids').text(response.offer_no_ids_count);
                        }
                    },
                    error: function (xhr, status, error) {
                        // Handle error if needed
                    }
                });
            });
            // Time taken count for all cases
            // $('#cases_completed_time').change(function () {
            //     var id = $(this).val();
            //     $.ajax({
            //         url: '<?php echo admin_url('leads/total_count_for_time_taken_file'); ?>',
            //         method: 'POST',
            //         data: { id: id },
            //         success: function (response) {
            //             if (!empty(id)) {
            //                 removeThebuttonclassCount_for_total_time_taken_flies();
            //             } else {

            //                 AddThebuttonclassCount_for_total_time_taken_flies();
            //             }
            //             // Count time taken instruction to id received
            //             if (response.instruction_to_full_id_received_time) {
            //                 $('#count_time_taken_from_instruction_to_id_received').text(response.instruction_to_full_id_received_time);
            //             }
            //             // For all cases in the pipeline, time taken from instruction to offer received
            //             if (response.instruction_to_offer_received) {
            //                 $('#count_time_taken_from_instruction_to_offer_received').text(response.instruction_to_offer_received);
            //             }
            //             // For all cases in the pipeline, time taken from offer to closing
            //             if (response.offer_to_closing_time_taken) {
            //                 $('#count_time_taken_from_offer_to_closing').text(response.offer_to_closing_time_taken);
            //             }
            //             // For all cases in the pipeline, time taken from instruction to closing

            //             if (response.instruction_to_closing_time_taken) {
            //                 $('#count_time_taken_from_instruction_to_closing').text(response.instruction_to_closing_time_taken);
            //             }
            //         },
            //         error: function (xhr, status, error) {
            //         }
            //     });
            // });
            // overall total count for files with offer and no ids
            function files_with_offer_no_ids() {
                $.ajax({
                    url: '<?php echo admin_url('leads/total_file_with_offer_and_no_ids'); ?>',
                    method: 'POST',
                    data: {
                    },
                    success: function (response) {
                        if (response.offer_no_ids_count) {
                            $('#files_offer_no_ids').text(response.offer_no_ids_count);
                        }
                    },
                    error: function (xhr, status, error) {
                        // Handle error if needed
                    }
                });
            }
            // overall total on hold files
            function total_on_hold_files_count() {
                $.ajax({
                    url: '<?php echo admin_url('leads/total_count_for_on_hold'); ?>',
                    method: 'POST',
                    data: {
                    },
                    success: function (response) {
                        if (response.total_on_hold_file) {
                            $('#overall_total_count_for_on_hold').text(response.total_on_hold_file);
                        }
                    },
                    error: function (xhr, status, error) {
                        // Handle error if needed
                    }
                });
            }
            // overall total number of files
            function overall_total_number_of_files() {
                $.ajax({
                    url: '<?php echo admin_url('leads/overall_total_number_of_files'); ?>',
                    method: 'POST',
                    data: {
                        start_date: '',
                        end_date: ''
                    },
                    success: function (response) {
                        if (response.total_count) {
                            $('#overall_total_count').text(response.total_count);
                        }
                    },
                    error: function (xhr, status, error) {
                        // Handle error if needed
                    }
                });
            }
            // file opened in a given time frame with offer
            function total_number_of_file_open_with_offer_count() {
                $.ajax({
                    url: '<?php echo admin_url('leads/total_number_of_file_open_with_offer_count'); ?>',
                    method: 'POST',
                    data: {
                        start_date: '',
                        end_date: ''
                    },
                    success: function (response) {
                        if (response.file_open_count_with_offer_count) {
                            $('#file_open_count_with_offer_count').text(response.file_open_count_with_offer_count);
                        }
                    },
                    error: function (xhr, status, error) {
                        // Handle error if needed
                    }
                });
            }
            // file opened in a given time frame without offer
            function total_number_of_file_open_without_offer_count() {
                $.ajax({
                    url: '<?php echo admin_url('leads/total_number_of_file_open_without_offer_count'); ?>',
                    method: 'POST',
                    data: {
                        start_date: '',
                        end_date: ''
                    },
                    success: function (response) {
                        if (response.file_open_count_without_offer_count) {
                            // $('#file_open_count_without_offer_toggle').show();
                            $('#file_open_count_without_offer_count').text(response.file_open_count_without_offer_count);
                        } else {
                            // $('#file_open_count_without_offer_toggle').hide();
                        }
                    },
                    error: function (xhr, status, error) {
                        // Handle error if needed
                    }
                });
            }
            // ajax run for appointment completed by
            function total_count_for_appointment_completed_by() {
                var start_date = $('#start_date').val();
                var end_date = $('#end_date').val();
                if (empty(start_date) || empty(end_date)) {
                    $.ajax({
                        url: '<?php echo admin_url('leads/total_count_for_appointment_completed_by'); ?>',
                        method: 'POST',
                        data: {
                            start_date: '',
                            end_date: ''
                        },
                        success: function (response) {
                            $('#total_count_for_appointment_completed_by_staff').text(response.total_completed_appintment);
                        },
                        error: function (xhr, status, error) {
                            // Handle error if needed
                        }
                    });
                } else {
                    $.ajax({
                        url: '<?php echo admin_url('leads/total_count_for_appointment_completed_by'); ?>',
                        method: 'POST',
                        data: {
                            start_date: start_date,
                            end_date: end_date
                        },
                        success: function (response) {
                            $('#total_count_for_appointment_completed_by_staff').text(response.total_completed_appintment);
                        },
                        error: function (xhr, status, error) {
                            // Handle error if needed
                        }
                    });
                }
            }
        
            $('#appointment_completed_by').change(function () {
                var appointment_completed_by = $(this).val();
                var start_date = $('#start_date').val();
                var end_date = $('#end_date').val();
                $.ajax({
                    url: '<?php echo admin_url('leads/total_count_for_appointment_completed_by'); ?>',
                    method: 'POST',
                    data: {
                        appointment_completed_by: appointment_completed_by,
                        start_date: start_date,
                        end_date: end_date
                    },
                    success: function (response) {
                        if (!empty(appointment_completed_by)) {
                            // Total appointment completed by staff
                            $('#total_count_for_appointment_completed_by_staff').text(response.total_completed_appintment);
                            // appointment button show 
                            $('#total_count_for_appointment_completed_by_staff_toggle').addClass('btn btn-primary');
                            $('#total_count_for_appointment_completed_by_staff_color').removeAttr('style');
                        } else {
                            $('#total_count_for_appointment_completed_by_staff').text(response.total_completed_appintment);
                            $('#total_count_for_appointment_completed_by_staff_toggle').removeClass('btn btn-primary');
                            $('#total_count_for_appointment_completed_by_staff_color').attr('style', 'color: #7cb342');
                        }
                    },
                    error: function (xhr, status, error) {
                        // Handle error if needed
                    }
                });
            });
            // ajax for particular lender
            $.ajax({
                url: '<?php echo admin_url('leads/total_count_for_lender_by'); ?>',
                method: 'POST',
                data: {
                    lender: ''
                },
                success: function (response) {
                    $('#total_count_for_lender').text(response.total_lender_count);
                },
                error: function (xhr, status, error) {
                    // Handle error if needed
                }
            });
            $('#lender').change(function () {
                var lender_id = $(this).val();
                var start_date = $('#start_date').val();
                var end_date = $('#end_date').val();
                $.ajax({
                    url: '<?php echo admin_url('leads/total_count_for_lender_by'); ?>',
                    method: 'POST',
                    data: {
                        lender: lender_id,
                        start_date: start_date,
                        end_date: end_date
                    },
                    success: function (response) {
                        if (response.total_lender_count) {
                            $('#total_count_for_lender_toggle').show();
                            $('#total_count_for_lender').text(response.total_lender_count);
                        } else {
                            $('#total_count_for_lender_toggle').hide();
                        }
                    },
                    error: function (xhr, status, error) {
                        // Handle error if needed
                    }
                });
            });
        }
        // custom chaser daily task code
        $('.show-form-btn').on('click', function () {
            const type = $(this).data('type');
            $('#' + type + '-form').slideDown();
            $(this).hide();
        });
        // custom daily chaser staff model hide
        $('.staffclose').on('click', function () {
            $('#custom_daily_chase_staffModal').modal('hide');
        });
        // Cancel and hide the form
        $('.cancel-task-btn').on('click', function () {
            const type = $(this).data('type');
            $('#' + type + '-form').slideUp();
            $('[data-type="' + type + '"].show-form-btn').show();
            $('#' + type + '-input').val('');
            $('#' + type + '-error').hide();
        });

        // Save the task
        let all_daily_chaser_staff_list = [];

        function loadAllLDTeamStaff(callback) {
            $.ajax({
                url: '<?= admin_url('leads/get_all_ldteam_record'); ?>',
                type: 'GET',
                dataType: 'json',
                success: function (response) {
                    if (response.success && response.data.length > 0) {
                        all_daily_chaser_staff_list = response.data;
                        if (callback) callback(); 
                    }
                },
                error: function () {
                    console.error('Failed to fetch staff data');
                    if (callback) callback(); 
                }
            });
        }
        loadAllLDTeamStaff();
        $('.save-task-btn').off('click').on('click', function () {
            const type = $(this).data('type');
            const input = $('#' + type + '-input');
            const inputVal = input.val().trim();
            const errorEl = $('#' + type + '-error');

            errorEl.hide();

            if (inputVal === '') {
            errorEl.text('Please enter a task!').show();
            return;
            }

            // AJAX request to save the task
            $.ajax({
                url: '<?php echo admin_url('leads/add_daily_task'); ?>',
                type: 'POST',
                data: {
                    task_type: type,
                    task_value: inputVal
                },
                dataType: 'json',
                success: function (response) {
                    if (response.success) {
                        const taskType = response.data.type.includes('morning') ? 'morning' : 'evening';
                        appenedTaskSection(taskType, response.data.id, response.data.name, 0, response.data.staff_ids);
                    } else {
                        errorEl.text(response.message || 'Failed to save task.').show();
                    }
                },
                error: function () {
                    errorEl.text('Something went wrong. Please try again.').show();
                }
                });

            // Reset form
            $('#' + type + '-form').slideUp();
            $('[data-type="' + type + '"].show-form-btn').show();
            input.val('');
        });
        function fetchDailyTasks() {
            $.ajax({
                url: '<?php echo admin_url('leads/get_daily_tasks'); ?>',
                type: 'GET',
                dataType: 'json',
                success: function (response) {
                    if (response.success) {
                        $('#morning-task-list').empty();
                        $('#evening-task-list').empty();

                        response.data.forEach(task => {
                            const taskType = task.type.includes('morning') ? 'morning' : 'evening';
                            const selectedStaffIds = task.staff_ids 
                                ? task.staff_ids.split(',').map(id => id.trim()) 
                                : [];

                            appenedTaskSection(taskType, task.id, task.name, task.checkbox_status, selectedStaffIds, task.order_no);
                        });

                        // Initialize sortable after tasks are appended
                        initSortableTaskList();
                    }
                }
            });
        }
        // function appened task function
        function appenedTaskSection(taskType, taskId, taskName, checkbox_checked, selected_staff_ids = [], order_no = null) {
            const target = $('#' + taskType + '-task-list');
            const checkAttr = (checkbox_checked == 1) ? 'checked="checked"' : '';
            let staffHTML = '';
            const placeholder = "<?= base_url('assets/images/user-placeholder.webp'); ?>";

            if (selected_staff_ids.length > 0 && all_daily_chaser_staff_list.length > 0) {
                selected_staff_ids.forEach(function (staff_id) {
                    const staff = all_daily_chaser_staff_list.find(item => item.staffid == staff_id);
                    if (staff) {
                        const fullName = staff.firstname + ' ' + staff.lastname;
                        const image = staff.image ? staff.image : placeholder;
                        staffHTML += `
                            <div class="d-flex align-items-center gap-2 mb-1" style="margin-right:6px;">
                                <img src="${image}" alt="${fullName}" 
                                    style="border-radius: 50px; box-shadow: 0 1px 2px rgba(0,0,0,0.08);" 
                                    width="30" height="30" 
                                    class="rounded-circle" 
                                    data-toggle="tooltip" data-title="${fullName}">
                            </div>
                        `;
                    }
                });
            }

            const taskHTML = `
            <div class="task-wrapper connected-task-item" data-id="${taskId}" data-order_no="${order_no}">
                <div class="single-task-card" 
                    style="
                        margin-bottom: 15px;
                        margin-top: 15px;
                        background-color: #ffffff;
                        border: 1px solid #e0e0e0;
                        border-radius: 8px;
                        box-shadow: 0 1px 3px rgba(0,0,0,0.04);
                        transition: box-shadow 0.2s ease-in-out, border-color 0.2s ease-in-out;
                    "
                    onmouseover="this.style.boxShadow='0 3px 8px rgba(0,0,0,0.06)'; this.style.borderColor='#d0d0d0';" 
                    onmouseout="this.style.boxShadow='0 1px 3px rgba(0,0,0,0.04)'; this.style.borderColor='#e0e0e0';"
                >
                    <!-- Task Header -->
                    <div class="single-task-item" style="
                        display:flex; 
                        justify-content:space-between; 
                        align-items:center; 
                        padding: 12px 15px;
                        border-bottom: 1px solid #f0f0f0;
                    ">
                        <div style="display:flex; align-items:center; width: 85%;">
                            <input type="checkbox" class="task-checkbox" id="task_checkbox_${taskId}" data-id="${taskId}" style="margin-right:10px;" ${checkAttr}>
                            <span class="task-name" data-id="${taskId}" style="margin-right: 20px; font-weight:500; color:#333;">${taskName}</span>
                        </div>
                        <div style="width: 15%; display: flex; justify-content: space-between; align-items: center;">
                            <button class="btn btn-danger btn-sm custom-daily-chaserdelete-task" data-id="${taskId}">
                                <i class="fa fa-trash" style="color:white;"></i>
                            </button>
                            <button class="btn btn-success btn-sm add-staff" data-id="${taskId}" style="margin-left: 10px;">
                                <i class="fa fa-users" style="color:white;"></i>
                            </button>
                        </div>
                    </div>

                    <!-- Staff Section -->
                    <div class="selected-staff" id="task_staff_${taskId}" 
                        style="
                            display:flex; 
                            flex-wrap:wrap; 
                            padding: 10px 15px;
                            align-items:center;
                            min-height: 40px;
                            background-color: #fafafa;
                            border-radius: 0 0 8px 8px;
                        ">
                        ${staffHTML || '<span style="color:#aaa; font-size:13px;">No staff assigned</span>'}
                    </div>
                </div>
            </div>
            `;
            target.append(taskHTML);
        }



        // Initial fetch of daily tasks
        function initSortableTaskList() {
            // Destroy only if already initialized
            if ($("#morning-task-list").data("ui-sortable")) {
                $("#morning-task-list").sortable("destroy");
            }
            if ($("#evening-task-list").data("ui-sortable")) {
                $("#evening-task-list").sortable("destroy");
            }

            // Ensure lists have the connecting class
            $("#morning-task-list, #evening-task-list").addClass("connected-task-list");

            $("#morning-task-list, #evening-task-list").sortable({
                connectWith: ".connected-task-list",
                items: "> .task-wrapper",            
                placeholder: "task-placeholder",
                forcePlaceholderSize: true,
                tolerance: "pointer",          
                helper: "clone",
                appendTo: "body",               
                cursor: "move",
                start: function(e, ui) {
                    // make placeholder match the dragging item's height
                    ui.placeholder.height(ui.item.height());
                },
                update: function(event, ui) {
                    // save when reorder or cross-list drop happened
                    // ui.sender is present for cross-list source; we always save both lists
                    saveAllTaskOrders();
                }
            }).disableSelection();
        }

        function saveAllTaskOrders() {
            let morningData = [];
            let eveningData = [];

            $("#morning-task-list .task-wrapper").each(function(index) {
                morningData.push({
                    id: $(this).data("id"), // changed here
                    order_no: index + 1
                });
            });

            $("#evening-task-list .task-wrapper").each(function(index) {
                eveningData.push({
                    id: $(this).data("id"), // changed here
                    order_no: index + 1
                });
            });

            $.ajax({
                url: "<?php echo admin_url('leads/update_daily_task_order'); ?>",
                type: "POST",
                data: {
                    morning_order: JSON.stringify(morningData),
                    evening_order: JSON.stringify(eveningData)
                },
                dataType: "json",
                success: function(response) {
                    if (response.success) {
                        console.log("Order updated successfully");
                    }
                }
            });
        }





        $(document).off('change', '.task-checkbox').on('change', '.task-checkbox', function () {
            const taskId = $(this).data('id');
            const isChecked = $(this).is(':checked') ? 1 : 0; 

            $.ajax({
                url: '<?= admin_url('leads/update_daily_task_status'); ?>', 
                type: 'POST',
                data: {
                    task_id: taskId,
                    checked: isChecked
                },
                dataType: 'json',
                success: function (response) {
                    if (response.success) {
                        alert_float('success', 'Task status updated!');
                    } else {
                        alert_float('danger', 'Task status not updated!');
                    }
                },
                error: function () {
                    console.error('AJAX error');
                }
            });
        });
        // delete daily custom task
        $(document).off('click', '.custom-daily-chaserdelete-task').on('click', '.custom-daily-chaserdelete-task', function () {
            const taskId = $(this).data('id');
            const $taskItem = $(this).closest('.single-task-item');
            $.ajax({
                url: '<?= admin_url('leads/delete_daily_custom_task'); ?>',
                type: 'POST',
                data: { task_id: taskId },
                dataType: 'json',
                success: function (response) {
                    if (response.success) {
                        $taskItem.remove();
                        $("#task_staff_" + taskId).remove();
                        alert_float('success', 'Task deleted successfully!');
                    } else {
                        alert_float('danger','Failed to delete task.');
                    }
                },
                error: function () {
                alert_float('danger','Something went wrong. Please try again.');
                }
            });
        });
        // when click on add staff button 
        $(document).off('click', '.add-staff').on('click', '.add-staff', function () {
            const taskId = $(this).data('id');
            $('#custom_daily_chaser_selectedTaskId').val(taskId);

            $.ajax({
                url: '<?= admin_url('leads/get_all_ldteam_record'); ?>', 
                type: 'POST',
                dataType: 'json',
                data: {
                    task_id: taskId
                },
                success: function (response) {
                    if (response.success && response.data.length > 0) {
                        const staffList = $('#staffList');
                        staffList.empty();

                        const selectedStaffIds = Array.isArray(response.selected_staff_ids) 
                            ? response.selected_staff_ids.map(id => String(id)) 
                            : [];
                        const placeholder = "<?php echo base_url('assets/images/user-placeholder.webp'); ?>";

                        $.each(response.data, function (index, staff) {
                            const image = staff.image ? staff.image : placeholder;
                            const fullName = staff.firstname + ' ' + staff.lastname;
                            const isChecked = selectedStaffIds.includes(String(staff.staffid));

                            const card = `
                                <div class="col-md-6 mb-2">
                                    <label class="d-flex align-items-center gap-2 border p-2 rounded">
                                        <input type="checkbox" class="staff-checkbox me-2"
                                            value="${staff.staffid}" ${isChecked ? 'checked' : ''}>
                                        <img src="${image}" alt="${fullName}" width="35" height="35" class="rounded-circle me-2">
                                        <span>${fullName}</span>
                                    </label>
                                </div>
                            `;
                            staffList.append(card);
                        });

                        updateSelectedStaffIds(); 
                        $('#custom_daily_chase_staffModal').modal('show');
                    } else {
                        alert_float('danger','No staff found.');
                    }
                },
                error: function () {
                    alert_float('danger','Error fetching staff. Please try again later.');
                }
            });
        });

        // Update hidden inputs when checkboxes change
        $(document).off('change', '.staff-checkbox').on('change', '.staff-checkbox', function () {
            updateSelectedStaffIds();
        });

        function updateSelectedStaffIds() {
            const wrapper = $('#custom_daily_chaser_staff_ids_wrapper');
            wrapper.empty();

            $('.staff-checkbox:checked').each(function () {
                const staffId = $(this).val();
                wrapper.append(
                    `<input type="hidden" name="custom_daily_chaser_staff_ids[]" value="${staffId}">`
                );
            });
        }
        // assign the all staff details
        $(document).off('click', '#assignStaffBtn').on('click', '#assignStaffBtn', function () {
            const taskId = $('#custom_daily_chaser_selectedTaskId').val();

            const selectedStaffIds = $('[name="custom_daily_chaser_staff_ids[]"]').map(function () {
                return $(this).val();
            }).get();

            if (selectedStaffIds.length === 0) {
                alert("Please select at least one staff member.");
                return;
            }

            $.ajax({
                url: '<?= admin_url('leads/custom_daily_chaser_assign_staff_to_task'); ?>', 
                type: 'POST',
                dataType: 'json',
                data: {
                    task_id: taskId,
                    staff_ids: selectedStaffIds
                },
                success: function (response) {
                    if (response.success) {
                        alert_float('success','Staff successfully assigned!');
                        fetchDailyTasks();
                        $('#custom_daily_chase_staffModal').modal('hide');
                        // Optional: Refresh the task list or UI
                    } else {
                        alert(response.message || 'Failed to assign staff.');
                    }
                },
                error: function () {
                    alert('Something went wrong while assigning staff.');
                }
            });
        });
        // edit the task details 
        $(document).on("click", ".task-name", function () {
        const span = $(this);
        const taskId = span.data("id");
        const oldValue = span.text().trim();

      
        if (span.find("input").length > 0) return;

        const input = $("<input>", {
            type: "text",
            class: "task-input",
            value: oldValue,
            "data-id": taskId
        });

        span.html(input);
        input.focus();
       
        input.on("keypress", function (e) {
            if (e.which === 13) {
                saveTask(input);
            }
        });

        $(document).on("click.task", function (e) {
            if (!$(e.target).is(input)) {
                saveTask(input);
                $(document).off("click.task"); 
            }
        });
    });

    function saveTask(input) {
        const newValue = input.val().trim();
        const taskId = input.data("id");
        const span = input.closest(".task-name");

        if (newValue === "") {
            span.text("Unnamed Task");
            return;
        }

        span.text(newValue);

        $.ajax({
            url: '<?= admin_url('leads/update_daily_custom_chaser_record'); ?>', 
            method: "POST",
            data: {
                task_id: taskId,
                task_name: newValue
            },
            success: function (response) {
                if(response.success) {
                    alert_float('success', 'Task updated successfully!');
                } else {
                    alert_float('danger', response.message || 'Failed to update task.');
                }
            },
            error: function (err) {
                alert_float('danger', response.message);
            }
        });
    }

        fetchDailyTasks();
    
    });



</script>
</body>

</html>