<?php

use app\services\imap\Imap;
use app\services\LeadProfileBadges;
use app\services\leads\LeadsKanban;
use app\services\imap\ConnectionErrorException;
use Ddeboer\Imap\Exception\MailboxDoesNotExistException;

header('Content-Type: text/html; charset=utf-8');
defined('BASEPATH') or exit('No direct script access allowed');

class Leads extends AdminController
{
    public function __construct()
    {
        parent::__construct();
        $this->load->model('leads_model');
        $this->load->helper('email_config_helper');
        $this->load->helper('staff_helper');
        $this->load->helper('leads_helper');
        $this->load->library('form_validation');
        $this->load->library('Slack');
        $this->load->library('sms/Sms_twilio');
        $this->load->model('Token_model');
        $this->load->model('Outbox_model');
        $this->load->model('MergingDoc_model');
    }
    public function testsms()
    {
        // print_r(base_url());
        // $timestamp = time();
        // echo $timestamp;
        // $output = $this->load->view('check_php_ini', [], true); // Enable return of the view as a string
        // echo $output; 
        // $refresh_token_change = $this->leads_model->refresh_dropbox_token_get();
        // print_r($$refresh_token_change);
        // echo "testsms function is running <br>";
        // $message = "test notification";
        // $this->slack->sendnotification($message, 817, 'Ninja');
        // $this->slack->sendnotification($message, 817, 'Power');
        // $this->slack->sendnotification($message, 817, 'Rocket');
        // echo "Function calls completed <br>";

        // echo '#$#$%$#%$^$#%#$%#$';
        // print_r(get_afternoon_and_morning());
        // $slack_message = "\n - Stage Complete: ID Complete \n- Send ID Complete update \n- Send preliminary e-mail";
        // $this->slack->sendnotification($slack_message, 899, '', 'hassn nasir');


        // nuborrow doc upload testing 
        //         $uploaded_files = [
        //     [
        //         'doc_title' => 'LD Consent',
        //         'file_url' => 'https://nuborrow-crm-storage.nyc3.digitaloceanspaces.com/nuborrow/attachments/115362/1749758478_115362_1749752629_110045_Screenshot_2025-06-03_021216.png',
        //     ],
        //     [
        //         'doc_title' => 'Appraisal',
        //         'file_url' => 'https://nuborrow-crm-storage.nyc3.digitaloceanspaces.com/nuborrow/attachments/115362/1749758466_115362_1749741159_114531_Screenshot_2025-06-10_223204.png',
        //     ],
        //     [
        //         'doc_title' => 'Property Taxes',
        //         'file_url' => 'https://nuborrow-crm-storage.nyc3.digitaloceanspaces.com/attachments/115362/1749670048_115362_Screenshot_2025-05-13_230537.png',
        //     ],
        //     [
        //         'doc_title' => 'Others',
        //         'file_url' => 'https://nuborrow-crm-storage.nyc3.digitaloceanspaces.com/attachments/115362/1749564561_115362_Screenshot_2025-05-28_013513.png',
        //     ],
        //     [
        //         'doc_title' => 'Commitment',
        //         'file_url' => 'https://nuborrow-crm-storage.nyc3.digitaloceanspaces.com/attachments/115362/1749564559_115362_Screenshot_2025-05-29_234935.png',
        //     ],
        //     [
        //         'doc_title' => 'Draft Figures',
        //         'file_url' => 'https://nuborrow-crm-storage.nyc3.digitaloceanspaces.com/attachments/115362/1749564558_115362_Screenshot_2025-05-29_234936.png',
        //     ],
        // ];

        //         foreach ($uploaded_files as $file) {
        //             $doc_title = $file['doc_title'];
        //             $file_url = $file['file_url'];

        //             $upload_response = $this->leads_model->upload_remote_file_to_dropbox(
        //                 $file_url,
        //                 $doc_title,
        //                 963,
        //                 'Avinash ',
        //                 'Mago'
        //             );
        //             print_r($upload_response);
        //             echo "#############";   echo "#############";   echo "#############";   echo "#############";

        //             // Log, return, or handle $upload_response as needed
        //         }

        // $total = 25000;

        // $firstNames = ['John', 'Alice', 'Mark', 'Emily', 'David', 'Sophia', 'Chris', 'Emma', 'Daniel', 'Olivia'];
        // $lastNames = ['Smith', 'Johnson', 'Brown', 'Williams', 'Jones', 'Miller', 'Davis', 'Garcia', 'Rodriguez', 'Wilson'];
        // $assignGroups = ['Ninja', 'Power', 'Rocket'];

        // // Get latest sample records
        // $contact_sample = $this->db->order_by('userid', 'DESC')->get('tblcontacts', 1)->row_array();
        // $client_sample = $this->db->order_by('userid', 'DESC')->get('tblclients', 1)->row_array();
        // $lead_sample = $this->db->order_by('id', 'DESC')->get('tblleads', 1)->row_array();

        // // Clean up dynamic keys
        // unset($contact_sample['userid'], $contact_sample['id'], $contact_sample['firstname'], $contact_sample['lastname'], $contact_sample['email']);
        // unset($client_sample['userid'], $client_sample['leadid']);
        // unset($lead_sample['id'], $lead_sample['client_id'], $lead_sample['name'], $lead_sample['email'], $lead_sample['hash'], $lead_sample['multiple_cases']);

        // for ($i = 1; $i <= $total; $i++) {
        //     $fname = $firstNames[array_rand($firstNames)];
        //     $lname = $lastNames[array_rand($lastNames)];
        //     $fullname = "$fname $lname";
        //     $email = strtolower($fname . $lname . uniqid()) . '@mailinator.com';

        //     /** 🔹 Step 1: Insert into tblcontacts */
        //     $contact_data = $contact_sample;
        //     $contact_data['firstname'] = $fname;
        //     $contact_data['lastname'] = $lname;
        //     $contact_data['email'] = $email;
        //     $this->db->insert('tblcontacts', $contact_data);
        //     $userid = $this->db->insert_id();

        //     /** 🔹 Step 2: Insert into tblleads */
        //     $lead_data = $lead_sample;
        //     $lead_data['client_id'] = $userid;
        //     $lead_data['name'] = $fullname;
        //     $lead_data['email'] = $email;
        //     $lead_data['multiple_cases'] = 0;
        //     $lead_data['hash'] = bin2hex(random_bytes(32));
        //     $lead_data['status'] = rand(1, 9);
        //     $lead_data['assign_group'] = $assignGroups[array_rand($assignGroups)];
        //     $lead_data['brokerage_id'] = rand(1, 5);
        //     $lead_data['lastcontact'] = date('Y-m-d H:i:s');
        //     $lead_data['dateadded'] = date('Y-m-d H:i:s');
        //     $lead_data['is_public'] = 1;
        //     $this->db->insert('tblleads', $lead_data);
        //     $lead_id = $this->db->insert_id();

        //     /** 🔹 Step 3: Insert into tblclients */
        //     $client_data = $client_sample;
        //     $client_data['userid'] = $userid;
        //     $client_data['leadid'] = $lead_id;
        //     $this->db->insert('tblclients', $client_data);

        //     if ($i % 1000 == 0) {
        //         echo "✅ Inserted $i records<br>";
        //     }
        // }

        echo "<strong>✅ Done: 25,000 fully linked records inserted with random status, assign_group, and brokerage_id.</strong>";
    }
    public function testsmsuser()
    {
        // $message = 'test';
        // $email = 'fantech.developer@gmail.com';
        // $_POST['get_afternoon_and_morning'] = get_afternoon_and_morning();
        // $subject = 'Appointement Request';
        // $html_content_confirmation_email_to_broker = $this->load->view('admin/leads/Email_template/appointment_request', $_POST, TRUE);
        // $replay_to_mail = get_all_staff_to_replay_email($this, get_staff_user_id(), 'Ninja');
        // $cc_emails = '';
        // $bcc_emails = '';
        // print_r($replay_to_mail['email']);
        // // $result = send_mailchimp_email('hassannasir6321@gmail.com', $subject, $html_content_confirmation_email_to_broker, $replay_to_mail,'','');
        // $result = send_mailchimp_email('hassannasir6321@gmail.com', $subject, $html_content_confirmation_email_to_broker, $replay_to_mail, $cc_emails, $bcc_emails);

        // if ($result) {
        //     echo 'Email sent successfully.';
        // } else {
        //     echo 'Failed to send email.';
        // }
        // echo "testsms function is running <br>";
        // $message = "test notification";
        // $this->slack->sendnotification($message, 10, 'Ninja', 'hassan');
        // $this->slack->sendnotification($message, 10, 'Power', 'hassan');
        // $data = $this->slack->sendnotification($message, 10, 'Rocket', 'hassan');
        // print_r($data);
        // echo "Function calls completed <br>";
        // $twilio_lock = getenv('Dropbox_Lock_signature');
        // $original = getenv('DROPBOX_CLIENT_SECRET_PROD');


        // $encrypted = transmute_layer($original, $twilio_lock);
        // echo "Encrypted: " . $encrypted . "<br>";

        // $decrypted = unlayer_extract($encrypted, $twilio_lock);
        // echo "Decrypted: " . $decrypted . "<br>";
    }

    /* List all leads */
    public function index($id = '')
    {
        close_setup_menu();

        if (!is_staff_member()) {
            access_denied('Cases');
        }

        $data['switch_kanban'] = true;

        if ($this->session->userdata('leads_kanban_view') == 'true') {
            $data['switch_kanban'] = false;
            $data['bodyclass'] = 'kan-ban-body';
        }

        $data['staff'] = $this->staff_model->get('', ['active' => 1]);
        if (is_gdpr() && get_option('gdpr_enable_consent_for_leads') == '1') {
            $this->load->model('gdpr_model');
            $data['consent_purposes'] = $this->gdpr_model->get_consent_purposes();
        }
        $data['summary'] = get_leads_summary();
        $data['statuses'] = $this->leads_model->get_status();
        $data['sources'] = $this->leads_model->get_source();
        $data['title'] = "Cases";
        // in case accesed the url leads/index/ directly with id - used in search
        $data['leadid'] = $id;
        $data['isKanBan'] = $this->session->has_userdata('leads_kanban_view') &&
            $this->session->userdata('leads_kanban_view') == 'true';
        // get all group names
        $this->db->select('id, group_name');
        $query = $this->db->get(db_prefix() . 'group');
        $staff_group = array();
        if ($query->num_rows() > 0) {
            $staff_group = $query->result_array();
        }
        $data['staff_group'] = $staff_group;
        $this->db->select('staffid, role, firstname, lastname');
        $this->db->where('role', 2);
        $staff_query = $this->db->get(db_prefix() . 'staff');
        $staff_data = $staff_query->result_array();

        $data['broker_data'] = $staff_data;
        $this->db->select('staffid, role, firstname, lastname,staff_group');
        $this->db->where('role', 1);
        $staff_query = $this->db->get(db_prefix() . 'staff');
        $staff_data = $staff_query->result_array();

        $data['agent_data'] = $staff_data;
        // get all lenders/bank names
        $this->db->select('*');
        $this->db->order_by('bank_name', 'ASC');
        $lender_data = $this->db->get(db_prefix() . 'bank')->result_array();
        $data['lender_data'] = $lender_data;
        $data['staff_record'] = get_all_staff($this);
        // get the brokerage data
        $get_brokerage_data = get_brokerage_data($this);
        $brokerage_record = array();
        foreach ($get_brokerage_data as $record) {
            $brokerage_record[] = array(
                'id' => $record['id'],
                'name' => $record['name']
            );
        }
        $data['brokerage_data'] = $brokerage_record;
        // reports data load only when list view load
        if ($this->session->userdata('leads_kanban_view') == 'true') {
            $data['file_open_without_offer'] = total_number_of_file_open_without_offer($this);
            $data['file_open_with_offer'] = total_number_of_file_open_with_offer($this);
            $data['files_with_offer_and_no_ids'] = total_number_of_files_with_offer_and_no_ids($this);
            $data['total_number_files'] = total_number_files($this);
            $data['total_file_on_hold'] = total_file_on_hold($this);
        }
        // get the cases id and name for total time count
        // $this->db->select('id,name');
        // $cases_record = $this->db->get(db_prefix() . 'leads')->result_array();
        // $data['cases_record'] = $cases_record;
        // broker and group wise hide and show content
        $this->db->select('assign_group');
        $this->db->where('id', $id);
        $lead_data = $this->db->get(db_prefix() . 'leads')->row();
        $staff_group_name = get_group_name_of_staff($this, get_staff_user_id());
        $data['samegroup'] = case_crud_permissions_by_role($this, $lead_data->assign_group, $staff_group_name);
        $data['ldteam_record'] = get_ld_team_staff_record($this);

        // Kanban filter reset when new page load
        $this->session->unset_userdata('kanban_filters');

        $this->load->view('admin/leads/manage_leads', $data);
    }
    // check kanban last update
    public function check_kanban_leads_update()
    {
        $this->db->select('last_update');
        $this->db->from('tblkanban_lead_updates');
        $query = $this->db->get();
        $result = $query->row();
        if ($result) {
            echo json_encode(['last_update' => $result->last_update]);
        } else {
            echo json_encode(['last_update' => null]);
        }
    }

    // read the notification when case open 
    public function check_notification_type()
    {
        $lead_id = $this->input->post('lead_id');

        // update the Upload Review tag
        $this->leads_model->update_review_upload_tag($lead_id, 0);

        // update the notificatoin of case for current user 
        $update_notify_response = $this->leads_model->update_notification_count_for_specific_user($lead_id);
        if ($update_notify_response) {
            $response = array(
                'success' => true
            );
        } else {
            $response = array(
                'success' => false
            );
        }
        $this->output
            ->set_content_type('application/json')
            ->set_output(json_encode($response));
    }

    public function table()
    {
        if (!is_staff_member()) {
            ajax_access_denied();
        }
        $this->app->get_table_data('leads');
    }

    public function kanban()
    {
        if (!is_staff_member()) {
            ajax_access_denied();
        }

        $filters = [
            'id' => $this->input->post('id'),
            'name' => $this->input->post('name'),
            'email' => $this->input->post('email'),
            'phone' => $this->input->post('phone'),
            'address' => $this->input->post('address'),
            'state' => $this->input->post('state'),
            'group_ids' => $this->input->post('group_ids'),
            'status' => $this->input->post('status'),
            'brokers_filter' => $this->input->post('brokers_filter'),
            'brokerage_filter' => $this->input->post('brokerage_filter'),
            'kanban_offer_in_out' => $this->input->post('kanban_offer_in_out'),
            'kanban_active_record' => $this->input->post('kanban_active_record'),
        ];

        // 🔄 Store filters in session
        $this->session->set_userdata('kanban_filters', $filters);

        $data['statuses'] = $this->leads_model->get_status();
        $data['base_currency'] = get_base_currency();
        $data['summary'] = get_leads_summary();
        $data['filters'] = $filters;

        echo $this->load->view('admin/leads/kan-ban', $data, true);
    }

    // Reset the kanban fileter from the session
    public function reset_kanban_filters()
    {
        if (!is_staff_member()) {
            ajax_access_denied();
        }

        $this->session->unset_userdata('kanban_filters');
        echo json_encode(['success' => true]);
        exit;
    }


    /* Add or update lead */
    public function lead($id = '')
    {
        if (!is_staff_member() || ($id != '' && !$this->leads_model->staff_can_access_lead($id))) {
            ajax_access_denied();
        }

        if ($this->input->post()) {
            $get_mail_subject = get_mail_subject($this, $id);
            if ($id == '') {
                // check this email is exits in the staff table or not if exist then show error
                $this->db->select('email');
                $this->db->from(db_prefix() . 'staff');
                $this->db->where('email', $this->input->post('email'));
                $Staff_query = $this->db->get();
                if ($Staff_query->num_rows() > 0) {
                    set_alert('danger', 'Staff Email Already in Use. Please choose a different email address for the case.');
                    echo json_encode([
                        'success' => false,
                        'alert_type' => "warning",
                        'message' => "Staff Email Already in Use. Please choose a different email address for the case.",
                    ]);
                    die;
                }
                $data_add = $this->leads_model->add($this->input->post());
                $new_transaction_name = $this->input->post('new_transaction_name');
                // store new transaction in table
                if (!empty($new_transaction_name)) {
                    $new_transaction_name = array(
                        'name' => $new_transaction_name
                    );
                    $this->db->insert(db_prefix() . 'leads_transaction_details', $new_transaction_name);
                }
                $id = $data_add['id'];

                // add the lender Details 
                // $lenderIds = $this->input->post('lender_ids');
                // if (!empty($lenderIds)) {
                //     foreach ($lenderIds as $lenderId) {
                //         $loanAmountField = $this->input->post('loan_amount_' . $lenderId);
                //         $transactionField = $this->input->post('transaction_' . $lenderId);
                //         $Lender_details_data = array(
                //             'lead_id' => $id,
                //             'bank_id' => $lenderId,
                //             'transaction_id' => $transactionField,
                //             'loan_amount' => $loanAmountField,
                //             'created_at' => date('Y:m:d H:i:s')
                //         );
                //         $this->db->insert(db_prefix() . 'leads_bank_details', $Lender_details_data);
                //     }
                // }     
                $lenderDetailsJson = $this->input->post('loan_total_post_req');
                if (is_array($lenderDetailsJson) && isset($lenderDetailsJson[0])) {
                    $lenderDetailsJson = $lenderDetailsJson[0];
                }
                $lenderDetailsArray = json_decode($lenderDetailsJson, true);
                foreach ($lenderDetailsArray as $lender) {
                    if (!isset($lender['lenderId'], $lender['index']))
                        continue;
                    $lenderId = (string) $lender['lenderId'];
                    $index = (int) $lender['index'];
                    $loanAmount = $this->input->post("loan_amount_{$lenderId}_{$index}");
                    $transaction = $this->input->post("transaction_{$lenderId}_{$index}");
                    $data = [
                        'lead_id' => $id,
                        'bank_id' => $lenderId,
                        'index' => $index,
                        'transaction_id' => $transaction,
                        'loan_amount' => $loanAmount,
                        'created_at' => date('Y-m-d H:i:s')
                    ];
                    $this->db->insert(db_prefix() . 'leads_bank_details', $data);
                }
                // add the borrow records
                $total_borrow_fields_selected = $this->input->post('total_fields');
                for ($i = 2; $i <= $total_borrow_fields_selected; $i++) {
                    $leads_borrow_data = array(
                        'lead_id' => $id,
                        'borrow_firstname' => isset($_POST['borrow_firstname' . $i]) ? $this->input->post('borrow_firstname' . $i) : '',
                        'borrow_middlename' => isset($_POST['borrow_middlename' . $i]) ? $this->input->post('borrow_middlename' . $i) : '',
                        'borrow_lastname' => isset($_POST['borrow_lastname' . $i]) ? $this->input->post('borrow_lastname' . $i) : '',
                        'borrow_address' => isset($_POST['borrow_address' . $i]) ? $this->input->post('borrow_address' . $i) : '',
                        'borrow_position' => isset($_POST['borrow_position' . $i]) ? $this->input->post('borrow_position' . $i) : '',
                        'borrow_city' => isset($_POST['borrow_city' . $i]) ? $this->input->post('borrow_city' . $i) : '',
                        'borrow_province' => isset($_POST['borrow_province' . $i]) ? $this->input->post('borrow_province' . $i) : '',
                        'borrow_zipcode' => isset($_POST['borrow_zipcode' . $i]) ? $this->input->post('borrow_zipcode' . $i) : '',
                        'borrow_email' => isset($_POST['borrow_email' . $i]) ? $this->input->post('borrow_email' . $i) : '',
                        'borrow_phone' => isset($_POST['borrow_phone' . $i]) ? $this->input->post('borrow_phone' . $i) : '',
                        'borrow_martial_status' => isset($_POST['borrow_martial_status' . $i]) ? $this->input->post('borrow_martial_status' . $i) : '',
                        'borrow_preferred_method' => isset($_POST['borrow_preferred_method' . $i]) ? $this->input->post('borrow_preferred_method' . $i) : '',
                        'created_at' => date('Y-m-d H:i:s'),
                    );
                    // Check if any of the required fields are empty
                    if ($leads_borrow_data['borrow_firstname'] != '' || $leads_borrow_data['borrow_lastname'] != '') {
                        $lead_borrower_id = $this->leads_model->add_leads_borrow_records($leads_borrow_data);
                        // creating a preloaded borrower checklist item
                        $this->db->select('id');
                        // $this->db->where_in('order_no', [1, 2, 3, 4, 5, 6]);
                        $this->db->where('type', 'client');
                        $this->db->where('case_status', 1);
                        $query = $this->db->get(db_prefix() . 'checklist_templates');
                        $checklist_template_ids = array_column($query->result_array(), 'id');
                        preloaded_file_opened_borrower_checklist_template_add_in_task_table($this, $checklist_template_ids, $id, 1, $lead_borrower_id);
                    }
                }
                $this->db->select('multiple_cases,name,assign_group,phonenumber,addedfrom,email');
                $this->db->where('id', $id);
                $query = $this->db->get(db_prefix() . 'leads');

                if ($query->num_rows() > 0) {
                    $lead = $query->row();
                    $multiple_cases = $lead->multiple_cases;
                    $check_assign_group = $lead->assign_group;
                    $case_name = $lead->name;
                    $email = $this->input->post('email');
                    $firstname = $this->input->post('firstname');
                    $middlename = $this->input->post('middlename');
                    $lastname = $this->input->post('lastname');
                    $user_name = $firstname . ' ' . $middlename . ' ' . $lastname;
                    // Assuming send_mail_template function takes care of sending emails
                    $_POST['broker_id'] = ($lead->addedfrom) ? $lead->addedfrom : get_staff_user_id();
                    // send notificationa and email to broker when cases created
                    $broker_data = get_multiple_broker_details_using_addedfrom($this, $lead->addedfrom);
                    // $_POST['case_url'] = admin_url('cases/index/') . $id;
                    $_POST['case_url'] = get_the_redirect_email_case_url($id, 'broker');
                    if (!empty($broker_data)) {
                        foreach ($broker_data as $broker) {
                            $_POST['broker_name'] = $broker['firstname'] . ' ' . $broker['lastname'];
                            $broker_email = $broker['email'];
                            $role = get_current_staff_role($this, $broker['staffid']);
                            if (!empty($broker['staffid']) || $role == 2 || $role == 6) {
                                $broker_message_for_case_created = "This is Legal Direct. Thank you for submitting the case. To ensure smooth processing, please ensure that all necessary documents are uploaded correctly and completely. Your cooperation in this matter is greatly appreciated.";
                                $this->db->select('staffid');
                                $this->db->where('role', 4);
                                $get_admin_id = $this->db->get(db_prefix() . 'staff')->row();
                                $this->leads_model->custom_lead_assigned_member_notification('staff', $id, $broker['staffid'], get_staff_user_id(), '', $broker_message_for_case_created);
                            }
                        }
                        // send the all admin notification and email to the admin broker
                        $brokerage_id = get_brokerage_id_using_leadid($this, $id);
                        $admin_broker_ids = get_all_admin_broker_role_staff_ids($this, $brokerage_id);
                        foreach ($admin_broker_ids as $admin_broker_email) {
                            if (get_staff_user_id() != $admin_broker_email['staffid'] && !in_array($admin_broker_email['staffid'], explode(',', $lead->addedfrom))) {
                                $_POST['broker_name'] = $admin_broker_email['firstname'] . ' ' . $admin_broker_email['lastname'];
                                $role = get_current_staff_role($this, $admin_broker_email['staffid']);
                                if (!empty($broker['staffid']) || $role == 2 || $role == 6) {
                                    $broker_message_for_case_created = "This is Legal Direct. Thank you for submitting the case. To ensure smooth processing, please ensure that all necessary documents are uploaded correctly and completely. Your cooperation in this matter is greatly appreciated.";
                                    $this->leads_model->custom_lead_assigned_member_notification('staff', $id, $admin_broker_email['staffid'], get_staff_user_id(), '', $broker_message_for_case_created);
                                }
                            }
                        }
                    }
                    // DL check other type item create
                    $this->db->where('type', 'other');
                    $this->db->where('case_status', 1);
                    $this->db->order_by('order_no', 'asc');
                    $query = $this->db->get(db_prefix() . 'checklist_templates');
                    $checklist_template_ids_for_other = array_column($query->result_array(), 'id');
                    if ($checklist_template_ids_for_other) {
                        preloaded_file_opened_checklist_template_add_in_task_table($this, $checklist_template_ids_for_other, $id, 1, 'dl-check-user-task');
                    }
                    // dynamically create a checklist item 
                    $this->db->where('type', 'broker');
                    $this->db->where('case_status', 1);
                    $this->db->order_by('order_no', 'asc');
                    $query = $this->db->get(db_prefix() . 'checklist_templates');
                    $checklist_template_ids_for_broker = array_column($query->result_array(), 'id');
                    if ($checklist_template_ids_for_broker) {
                        preloaded_file_opened_checklist_template_add_in_task_table($this, $checklist_template_ids_for_broker, $id, 1);
                    }
                    // creating a checklist for file opened stage
                    $this->db->select('id');
                    $this->db->where('type', 'client');
                    $this->db->where('case_status', 1);
                    $this->db->order_by('order_no', 'asc');
                    $query = $this->db->get(db_prefix() . 'checklist_templates');
                    $checklist_template_ids = array_column($query->result_array(), 'id');
                    preloaded_file_opened_checklist_template_add_in_task_table($this, $checklist_template_ids, $id, 1);
                    // Outstanding item checklist
                    // check item checklist item exit or not
                    $this->db->select('id');
                    $this->db->where('type', 'client');
                    $this->db->where('case_status', 3);
                    $this->db->order_by('order_no', 'asc');
                    $query = $this->db->get(db_prefix() . 'checklist_templates');
                    $checklist_template_ids = array_column($query->result_array(), 'id');
                    preloaded_file_opened_checklist_template_add_in_task_table($this, $checklist_template_ids, $id, 3);
                    // secure payout item checklist
                    $this->db->where('lead_id', $id);
                    $this->db->where('leads_status', 3);
                    $check_item_outstanding_ld_team = $this->db->get(db_prefix() . 'cases_checkboxes')->row();
                    if (empty($check_item_outstanding_ld_team)) {
                        $this->db->select('id');
                        $this->db->where('type', 'ld_team');
                        $this->db->where('case_status', 3);
                        $this->db->order_by('order_no', 'asc');
                        $ld_query = $this->db->get(db_prefix() . 'checklist_templates');
                        $checklist_template_ids_for_ldteam = array_column($ld_query->result_array(), 'id');
                        preloaded_outstanding_item_for_ld_team($this, $checklist_template_ids_for_ldteam, $id, 3, 'other_items');
                    }
                    // outstanding secure payout item details
                    $this->db->where('lead_id', $id);
                    $this->db->where('leads_status', 7);
                    $check_item_outstanding_ld_team_payouts = $this->db->get(db_prefix() . 'cases_checkboxes')->row();
                    if (empty($check_item_outstanding_ld_team_payouts)) {
                        $this->db->select('id');
                        $this->db->where('type', 'secure_charge');
                        $this->db->where('case_status', 7);
                        $this->db->order_by('order_no', 'asc');
                        $ld_query = $this->db->get(db_prefix() . 'checklist_templates');
                        $checklist_template_ids_for_ldteam_payouts = array_column($ld_query->result_array(), 'id');
                        preloaded_outstanding_item_for_ld_team($this, $checklist_template_ids_for_ldteam_payouts, $id, 7, '');
                        // secure private charge loaded
                        $this->db->select('id');
                        $this->db->where('type', 'app_general');
                        $this->db->where('case_status', 7);
                        $this->db->order_by('order_no', 'asc');
                        $ld_query = $this->db->get(db_prefix() . 'checklist_templates');
                        $checklist_template_ids_for_ldteam_payouts = array_column($ld_query->result_array(), 'id');
                        preloaded_outstanding_item_for_ld_team($this, $checklist_template_ids_for_ldteam_payouts, $id, 7, '');
                    }
                    // get the checklist template ids for request for funds  for ld-team
                    $this->db->select('id');
                    $this->db->where('type', 'ld_team');
                    $this->db->where('case_status', 4);
                    $query = $this->db->get(db_prefix() . 'checklist_templates');
                    $checklist_template_ids_for_request_for_funds = array_column($query->result_array(), 'id');
                    preloaded_request_for_funds_checklist_template_add_in_task_table($this, $checklist_template_ids_for_request_for_funds, $id, 4);
                    // send notification and email when admin case group assign
                    if (!empty($check_assign_group)) {
                        // send email to broker when case group assign
                        $this->send_mail_to_broker_when_group_assign($lead, $id, $check_assign_group, '');
                        // notificaation line of code  and sms line of code 
                        $title = 'Case Assigned';
                        $new_case_message = 'New case (ID: #' . $id . ' & Name:' . $case_name . ') assigned by ' . get_staff_full_name() . '.';
                        $this->db->select('id,multiple_cases,client_id,phonenumber,name,email,addedfrom');
                        $this->db->where('id', $id);
                        $lead_data_check = $this->db->get(db_prefix() . 'leads');
                        if ($lead_data_check->num_rows() > 0) {
                            $lead_data = $lead_data_check->row();
                            $client_id = get_client_id_using_contact_id($this, $lead_data->client_id, $lead_data->multiple_cases);
                            $contact_id = get_contact_id_using_client_id($this, $client_id);
                            // send notification to client when caseee create
                            $notification_type = get_notification_type(1);
                            // send  notiication in crm to all the team group member and staff
                            $this->db->select('assign_group,assigned,case_creator_id');
                            $this->db->where('id', $id);
                            $lead_data_for_get_assign_group = $this->db->get(db_prefix() . 'leads')->row();
                            $current_staff_data = get_staff_ids_by_group($this, $lead_data_for_get_assign_group->assign_group);
                            $get_staff_data = get_staff_email_by_staffid($this, get_staff_user_id());
                            if (!empty($get_staff_data) && $get_staff_data->email == 'ft@legaldirect.ca' && base_url() == 'https://platform.legaldirect.ca/') {
                                $ld_team_notify_title = 'Case Assigned';
                                $ld_team_notify_message = 'New case (ID: #' . $id . ' & Name:' . $case_name . ') assigned by ' . get_staff_full_name() . '.';
                                // send_notification_in_mobile('staff', $get_staff_data->staffid, $contact_id, $client_id, $id, $ld_team_notify_title, $ld_team_notify_message, $notification_type, '');
                                // send notificastion in crm
                                $this->leads_model->custom_lead_assigned_member_notification('staff', $id, $get_staff_data->staffid, get_staff_user_id(), '', $ld_team_notify_message);
                            } else {
                                foreach ($current_staff_data as $staff_notifiy_data) {
                                    $ld_team_notify_title = 'Case Assigned';
                                    $ld_team_notify_message = 'New case (ID: #' . $id . ' & Name:' . $case_name . ') assigned by ' . get_staff_full_name() . '.';
                                    // send_notification_in_mobile('staff', $staff_notifiy_data['staffid'], $contact_id, $client_id, $id, $ld_team_notify_title, $ld_team_notify_message, $notification_type, '');
                                    // send notiifcatino in crm
                                    $this->leads_model->custom_lead_assigned_member_notification('staff', $id, $staff_notifiy_data['staffid'], get_staff_user_id(), '', $new_case_message);
                                }
                            }
                            // get the all admin staff ids
                            $admin_ids = get_all_admin_role_staff_ids($this);
                            foreach ($admin_ids as $admin_email) {
                                if (get_staff_user_id() != $admin_email['staffid']) {
                                    $admin_notify_title = 'Case Assigned';
                                    $admin_notify_message = 'New case (ID: #' . $id . ' & Name:' . $case_name . ') assigned by ' . get_staff_full_name() . '.';
                                    // send_notification_in_mobile('staff', $admin_email['staffid'], $contact_id, $client_id, $id, $admin_notify_title, $admin_notify_message, $notification_type, '');
                                    // crm notification send 
                                    $this->leads_model->custom_lead_assigned_member_notification('staff', $id, $admin_email['staffid'], get_staff_user_id(), '', $new_case_message);
                                }
                            }
                        }
                        // check task/checklist item create or not if create then not again create
                        $this->db->select('id');
                        $this->db->where('rel_id', $id);
                        $this->db->where('rel_type', 'user-task');
                        $this->db->where('type', 'client');
                        $preloaded_task_check = $this->db->get(db_prefix() . 'tasks')->row();
                        if (empty($preloaded_task_check->id)) {
                            // if ($multiple_cases == 0) {
                            //     $_POST['password'] = '123456A@';
                            //     $_POST['name'] = $user_name;
                            //     $html_content_welcome_email_to_user = $this->load->view('admin/leads/Email_template/account_activation', $_POST, TRUE);
                            //     //send_mail_template('New_case_added', $id, $email);
                            //     // $subject = 'Welcome on Legal Direct';
                            //     $subject = $get_mail_subject;
                            //     $replay_to_mail = get_staff_email_by_id($this, get_staff_user_id());
                            //     send_mailchimp_email($email, $subject, $html_content_welcome_email_to_user, $replay_to_mail, '', '');
                            //     // send mail to a secondary email
                            //     $get_secondary_emali = get_the_secondary_email($this, $id);
                            //     if (!empty($get_secondary_emali)) {
                            //         send_mailchimp_email($get_secondary_emali, $subject, $html_content_welcome_email_to_user, $replay_to_mail, '', '');
                            //     }

                            // } else {
                            //     $_POST['name'] = $user_name;
                            //     $html_content_welcome_email_to_user = $this->load->view('admin/leads/Email_template/account_activation', $_POST, TRUE);
                            //     //send_mail_template('Returning_case_added', $id, $email);
                            //     // $subject = 'Welcome again on Legal Direct';
                            //     $subject = $get_mail_subject;
                            //     $replay_to_mail = get_staff_email_by_id($this, get_staff_user_id());
                            //     send_mailchimp_email($email, $subject, $html_content_welcome_email_to_user, $replay_to_mail, '', '');
                            //     // send mail to a secondary email
                            //     $get_secondary_emali = get_the_secondary_email($this, $id);
                            //     if (!empty($get_secondary_emali)) {
                            //         $replay_to_mail = get_staff_email_by_id($this, get_staff_user_id());
                            //         send_mailchimp_email($get_secondary_emali, $subject, $html_content_welcome_email_to_user, $replay_to_mail, '', '');
                            //     }
                            // }
                            // get the checklist template ids for file opened and add the checklist item preloaded for client
                            // $this->db->select('id');
                            // // $this->db->where_in('order_no', [1, 2, 3, 4, 5, 6]);
                            // $this->db->where('type', 'client');
                            // $this->db->where('case_status', 1);
                            // $query = $this->db->get(db_prefix() . 'checklist_templates');
                            // $checklist_template_ids = array_column($query->result_array(), 'id');
                            // preloaded_file_opened_checklist_template_add_in_task_table($this, $checklist_template_ids, $id, 1);
                            // get the checklist template ids for file opened and add the checklist item preloaded for Broker
                            // $this->db->select('id');

                            // dynamically checklist item create for the case for all stages
                            // $this->db->where('type', 'broker');
                            // $this->db->order_by('order_no', 'asc');
                            // $this->db->where('case_status', 1);
                            // $query = $this->db->get(db_prefix() . 'checklist_templates');
                            // $checklist_template_ids_for_broker = array_column($query->result_array(), 'id');
                            // if ($checklist_template_ids_for_broker) {
                            //     preloaded_file_opened_checklist_template_add_in_task_table($this, $checklist_template_ids_for_broker, $id, 1);
                            // }
                            // // creating a checklist for file opened stage
                            // $this->db->select('id');
                            // // $this->db->where_in('order_no', [1, 2, 3, 4, 5, 6]);
                            // $this->db->where('type', 'client');
                            // $this->db->where('case_status', 1);
                            // $query = $this->db->get(db_prefix() . 'checklist_templates');
                            // $checklist_template_ids = array_column($query->result_array(), 'id');
                            // preloaded_file_opened_checklist_template_add_in_task_table($this, $checklist_template_ids, $id, 1);
                            // // Outstanding item checklist
                            // // check item checklist item exit or not
                            // $this->db->select('id');
                            // // $this->db->where_in('order_no', [1, 2, 3]);
                            // $this->db->where('type', 'client');
                            // $this->db->where('case_status', 3);
                            // $query = $this->db->get(db_prefix() . 'checklist_templates');
                            // $checklist_template_ids = array_column($query->result_array(), 'id');
                            // preloaded_file_opened_checklist_template_add_in_task_table($this, $checklist_template_ids, $id, 3);
                            // // get the checklist template ids for request for funds  for ld-team
                            // $this->db->select('id');
                            // // $this->db->where_in('order_no', [1, 2, 3]);
                            // $this->db->where('type', 'ld_team');
                            // $this->db->where('case_status', 4);
                            // $query = $this->db->get(db_prefix() . 'checklist_templates');
                            // $checklist_template_ids_for_request_for_funds = array_column($query->result_array(), 'id');
                            // preloaded_request_for_funds_checklist_template_add_in_task_table($this, $checklist_template_ids_for_request_for_funds, $id, 4);

                        }

                        // send slack notification for ld-channel
                        $lead_name = leads_splitFullName($case_name);
                        $slack_message = "\n Intro: Team " . $check_assign_group . " Designated \n - Open File";
                        $this->slack->sendnotification($slack_message, $id, $check_assign_group, $lead_name['lastname'] . ', ' . $lead_name['firstname'] . ' ' . $lead_name['middlename']);
                    }
                    // send notification to the admin case created by broker
                    // get the all admin staff ids
                    // if case group not assign its means broker can not upload the doc
                    if (empty($check_assign_group)) {
                        $new_case_message = 'New case (ID: #' . $id . ' & Name:' . $case_name . ') assigned by ' . get_staff_full_name() . '.';
                        $notification_type = get_notification_type(1);
                        $this->db->select('assign_group,assigned,case_creator_id');
                        $this->db->where('id', $id);
                        $lead_data_for_get_assign_group = $this->db->get(db_prefix() . 'leads')->row();
                        $current_staff_data = get_staff_ids_by_group($this, $lead_data_for_get_assign_group->assign_group);
                        $get_staff_data = get_staff_email_by_staffid($this, get_staff_user_id());
                        if (!empty($get_staff_data) && $get_staff_data->email == 'ft@legaldirect.ca') {
                            $ld_team_notify_title = 'Case Assigned';
                            $ld_team_notify_message = 'New case (ID: #' . $id . ' & Name:' . $case_name . ') assigned by ' . get_staff_full_name() . '.';
                            // send_notification_in_mobile('staff', $get_staff_data->staffid, $contact_id, $client_id, $id, $ld_team_notify_title, $ld_team_notify_message, $notification_type, '');
                        } else {
                            foreach ($current_staff_data as $staff_notifiy_data) {
                                $ld_team_notify_title = 'Case Assigned';
                                $ld_team_notify_message = 'New case (ID: #' . $id . ' & Name:' . $case_name . ') assigned by ' . get_staff_full_name() . '.';
                                // send_notification_in_mobile('staff', $staff_notifiy_data['staffid'], $contact_id, $client_id, $id, $ld_team_notify_title, $ld_team_notify_message, $notification_type, '');
                                // send notification in crm
                                $this->leads_model->custom_lead_assigned_member_notification('staff', $id, $staff_notifiy_data['staffid'], get_staff_user_id(), '', $ld_team_notify_title);
                            }
                        }
                        $admin_ids = get_all_admin_role_staff_ids($this);
                        $notification_type = get_notification_type(1);
                        foreach ($admin_ids as $admin_email) {
                            if (get_staff_user_id() != $admin_email['staffid']) {
                                $admin_notify_title = 'Case Assigned';
                                $admin_notify_message = 'The Case (ID: #' . $id . ' & Name:' . $case_name . ') has been created by ' . get_staff_full_name();
                                // send_notification_in_mobile('staff', $admin_email['staffid'], $contact_id, $client_id, $id, $admin_notify_title, $admin_notify_message, $notification_type, '');
                                // Crm notification line of code 
                                $this->leads_model->custom_lead_assigned_member_notification('staff', $id, $admin_email['staffid'], get_staff_user_id(), '', $admin_notify_message);
                            }
                        }
                        // send slack notification for ld-channel
                        $lead_name = leads_splitFullName($case_name);
                        $slack_message = "- NEW File! \n - A new file has been opened by the broker on Directly \n - Review and assign";
                        $this->slack->sendnotification($slack_message, $id, $check_assign_group, $lead_name['lastname'] . ', ' . $lead_name['firstname'] . ' ' . $lead_name['middlename']);
                    }
                    // send mail and notification to the broker
                    if (get_current_staff_role($this, get_staff_user_id()) == 2 || get_current_staff_role($this, get_staff_user_id()) == 6) {
                        $_POST['generic_email_title'] = 'Case Created';
                        $_POST['generic_email_back_to_case_url'] = 'Please <a href="' . htmlspecialchars($_POST['case_url'], ENT_QUOTES, 'UTF-8') . '">Click here</a> to access the file and allocate it to the relevant team.';
                        $_POST['generic_email_content'] = 'Congratulations ! We have received a new case on the Legal Directly Case Management System.';
                        $html_content_welcome_email_to_user = $this->load->view('admin/leads/Email_template/generic_email_template', $_POST, TRUE);
                        $subject = 'New Case: ' . reverseName($case_name);
                        $replay_to_mail = get_all_staff_to_replay_email($this, get_staff_user_id(), $lead_data_for_get_assign_group->assign_group);
                        // creating a seperate email for tester and bob for different server
                        $get_test_staff_data = get_staff_data_by_id($this, get_staff_user_id());
                        if (base_url() == 'https://dev.platform.legaldirect.ca/') {
                            $send_email_result = send_mailchimp_email('hassannasir6321@gmail.com', $subject, $html_content_welcome_email_to_user, $replay_to_mail, '', '', $id);
                            // add the record for outbox emails 
                            $outbox_id = $this->Outbox_model->save_outbox_email('hassannasir6321@gmail.com', '', '', $subject, $_POST['generic_email_content'], '', $id, 1, $html_content_welcome_email_to_user, $replay_to_mail, $send_email_result['status'], $send_email_result['mandrill_id'], 1);
                        } else {
                            $send_email_result = send_mailchimp_email('newcases@legaldirect.ca', $subject, $html_content_welcome_email_to_user, $replay_to_mail, '', '', $id);
                            // add the record for outbox emails 
                            $outbox_id = $this->Outbox_model->save_outbox_email('hassannasir6321@gmail.com', '', '', $subject, $_POST['generic_email_content'], '', $id, 1, $html_content_welcome_email_to_user, $replay_to_mail, $send_email_result['status'], $send_email_result['mandrill_id'], 1);
                        }
                        // send notification in crm to all admins
                        $case_created_message = 'New case (ID: #' . $id . ' & Name:' . $case_name . ') created by ' . get_staff_full_name() . '.';
                        $admin_ids = get_all_admin_role_staff_ids($this);
                        foreach ($admin_ids as $admin_email) {
                            if (get_staff_user_id() != $admin_email['staffid']) {
                                $admin_notify_title = 'Case Closed';
                                $admin_notify_message = 'New case (ID: #' . $id . ' & Name:' . $case_name . ') created by ' . get_staff_full_name() . '.';
                                // send_notification_in_mobile('staff', $admin_email['staffid'], $contact_id, $client_id, $id, $admin_notify_title, $admin_notify_message, $notification_type, '');
                                // send notification in crm
                                // $this->leads_model->custom_lead_assigned_member_notification('staff', $id, $admin_email['staffid'], get_staff_user_id(), '', $admin_notify_message);
                            }
                        }
                    }
                }
                // update key to show the Review ledgers in kanban card
                if ($role != 2 && $role != 6) {
                    update_key_of_upload_docs($this, $id, 0);
                }
                // add the app message 
                $app_message = 'Your case has been opened. Please check your email for the first step, the ID requirements. For your ease, convenience, and safety, where possible, we aim to provide advice remotely and by video conference. As per the 2024 Law Society of Ontario regulations, for all virtual appointments, we are now required to electronically AUTHENTICATE and also VERIFY your identification.Please ensure the IDs show all EDGES, are CLEAR, have NO flash spots, and are valid (NOT expired). IDs uploaded are via this secure app and are only used for the purposes of your transaction.';
                store_app_message_for_client($this, $id, $app_message, 1);
                $message = $id ? _l('added_successfully', 'Case') : '';

                echo json_encode([
                    'success' => $id ? true : false,
                    'id' => $id,
                    'message' => $message,
                    'leadView' => $id ? $this->_get_lead_data($id) : [],
                ]);
            } else {
                // get the recored before update 
                $this->db->select('multiple_cases,name,assign_group,phonenumber');
                $this->db->where('id', $id);
                $before_update_record = $this->db->get(db_prefix() . 'leads')->row();
                $emailOriginal = $this->db->select('email')->where('id', $id)->get(db_prefix() . 'leads')->row()->email;
                $proposalWarning = false;
                $message = '';
                // add the borrow records
                $total_borrow_fields_selected = $this->input->post('total_fields');
                // $new_lender_name = $this->input->post('new_lender_name');
                $new_transaction_name = $this->input->post('new_transaction_name');
                for ($i = 2; $i <= $total_borrow_fields_selected; $i++) {
                    $leads_borrow_data = array(
                        'lead_id' => $id,
                        'borrow_firstname' => isset($_POST['borrow_firstname' . $i]) ? $this->input->post('borrow_firstname' . $i) : '',
                        'borrow_middlename' => isset($_POST['borrow_middlename' . $i]) ? $this->input->post('borrow_middlename' . $i) : '',
                        'borrow_lastname' => isset($_POST['borrow_lastname' . $i]) ? $this->input->post('borrow_lastname' . $i) : '',
                        'borrow_address' => isset($_POST['borrow_address' . $i]) ? $this->input->post('borrow_address' . $i) : '',
                        'borrow_position' => isset($_POST['borrow_position' . $i]) ? $this->input->post('borrow_position' . $i) : '',
                        'borrow_city' => isset($_POST['borrow_city' . $i]) ? $this->input->post('borrow_city' . $i) : '',
                        'borrow_province' => isset($_POST['borrow_province' . $i]) ? $this->input->post('borrow_province' . $i) : '',
                        'borrow_zipcode' => isset($_POST['borrow_zipcode' . $i]) ? $this->input->post('borrow_zipcode' . $i) : '',
                        'borrow_preferred_method' => isset($_POST['borrow_preferred_method' . $i]) ? $this->input->post('borrow_preferred_method' . $i) : '',
                        'borrow_email' => isset($_POST['borrow_email' . $i]) ? $this->input->post('borrow_email' . $i) : '',
                        'borrow_phone' => isset($_POST['borrow_phone' . $i]) ? $this->input->post('borrow_phone' . $i) : '',
                        'borrow_martial_status' => isset($_POST['borrow_martial_status' . $i]) ? $this->input->post('borrow_martial_status' . $i) : '',
                        'created_at' => date('Y-m-d H:i:s'),
                    );
                    // Check if any of the required fields are empty
                    if ($leads_borrow_data['borrow_firstname'] != '' || $leads_borrow_data['borrow_middlename'] != '' || $leads_borrow_data['borrow_lastname'] != '') {
                        $lead_borrower_id = $this->leads_model->add_leads_borrow_records($leads_borrow_data);
                        // creating a preloaded borrower checklist item
                        $this->db->select('id');
                        $this->db->where('type', 'client');
                        $this->db->where('case_status', 1);
                        $query = $this->db->get(db_prefix() . 'checklist_templates');
                        $checklist_template_ids = array_column($query->result_array(), 'id');
                        preloaded_file_opened_borrower_checklist_template_add_in_task_table($this, $checklist_template_ids, $id, 1, $lead_borrower_id);
                    }
                }
                // update the borrow record
                $borrow_ids = $this->input->post('borrow_id');
                $borrow_firstnames = $this->input->post('borrow_firstname');
                $borrow_middlename = $this->input->post('borrow_middlename');
                $borrow_lastnames = $this->input->post('borrow_lastname');
                $borrow_addresses = $this->input->post('borrow_address');
                $borrow_positions = $this->input->post('borrow_position');
                $borrow_city = $this->input->post('borrow_city');
                $borrow_province = $this->input->post('borrow_province');
                $borrow_zipcode = $this->input->post('borrow_zipcode');
                $borrow_preferred_method = $this->input->post('borrow_preferred_method');
                $borrow_email = $this->input->post('borrow_email');
                $borrow_phone = $this->input->post('borrow_phone');
                $borrow_martial_status = $this->input->post('borrow_martial_status');
                if ($borrow_firstnames != '' || $borrow_lastnames != '' || $borrow_email != '') {
                    $this->leads_model->update_leads_borrow_records($borrow_ids, $borrow_firstnames, $borrow_middlename, $borrow_lastnames, $borrow_addresses, $borrow_positions, $borrow_city, $borrow_province, $borrow_zipcode, $borrow_preferred_method, $borrow_email, $borrow_phone, $borrow_martial_status);
                }
                // add the lender Details 
                // $lenderIds = $this->input->post('lender_ids');
                // if (!empty($lenderIds)) {
                //     $existingLenders = $this->db->select('bank_id')
                //         ->where('lead_id', $id)
                //         ->get(db_prefix() . 'leads_bank_details')
                //         ->result_array();

                //     $existingLenderIds = array_column($existingLenders, 'bank_id');

                //     foreach ($lenderIds as $lenderId) {
                //         $loanAmountField = $this->input->post('loan_amount_' . $lenderId);
                //         $transactionField = $this->input->post('transaction_' . $lenderId);

                //         $Lender_details_data = array(
                //             'lead_id' => $id,
                //             'bank_id' => $lenderId,
                //             'transaction_id' => $transactionField,
                //             'loan_amount' => $loanAmountField,
                //         );

                //         if (in_array($lenderId, $existingLenderIds)) {
                //             $this->db->where('lead_id', $id);
                //             $this->db->where('bank_id', $lenderId);
                //             $this->db->update(db_prefix() . 'leads_bank_details', $Lender_details_data);
                //         } else {
                //             $this->db->insert(db_prefix() . 'leads_bank_details', $Lender_details_data);
                //         }
                //     }
                // }
                $lenderDetailsJson = $this->input->post('loan_total_post_req');
                $processedLenders = [];
                if (!empty($lenderDetailsJson)) {
                    $lenderDetailsJson = is_array($lenderDetailsJson) ? $lenderDetailsJson[0] : $lenderDetailsJson;
                    $lenderDetailsArray = json_decode($lenderDetailsJson, true);
                    $existingLenders = $this->db->select('bank_id, index')
                        ->where('lead_id', $id)
                        ->get(db_prefix() . 'leads_bank_details')
                        ->result_array();
                    $existingLenderRecords = [];
                    foreach ($existingLenders as $record) {
                        $existingLenderRecords[$record['bank_id']][] = $record['index'];
                    }
                    $processedGroups = [];
                    foreach ($lenderDetailsArray as $lender) {
                        if (!isset($lender['lenderId'], $lender['index']))
                            continue;
                        $lenderId = (string) $lender['lenderId'];
                        $index = (int) $lender['index'];
                        $processedGroups[$lenderId][] = $index;
                        $loanAmount = $this->input->post("loan_amount_{$lenderId}_{$index}");
                        $transaction = $this->input->post("transaction_{$lenderId}_{$index}");
                        if ($loanAmount !== null || $transaction !== null) {
                            $data = [
                                'lead_id' => $id,
                                'bank_id' => $lenderId,
                                'index' => $index,
                                'transaction_id' => $transaction,
                                'loan_amount' => $loanAmount,
                                'created_at' => date('Y-m-d H:i:s')
                            ];

                            if (isset($existingLenderRecords[$lenderId]) && in_array($index, $existingLenderRecords[$lenderId])) {
                                $this->db->where(['lead_id' => $id, 'bank_id' => $lenderId, 'index' => $index])
                                    ->update(db_prefix() . 'leads_bank_details', $data);
                            } else {
                                $this->db->insert(db_prefix() . 'leads_bank_details', $data);
                            }
                        }
                    }
                }
                if (!empty($processedGroups)) {
                    foreach ($existingLenderRecords as $bankId => $indexes) {
                        if (!isset($processedGroups[$bankId])) {
                            $this->db->where(['lead_id' => $id, 'bank_id' => $bankId])->delete(db_prefix() . 'leads_bank_details');
                        } else {
                            $indexesToDelete = array_diff($indexes, $processedGroups[$bankId]);
                            if (!empty($indexesToDelete)) {
                                $this->db->where(['lead_id' => $id, 'bank_id' => $bankId])
                                    ->where_in('index', $indexesToDelete)
                                    ->delete(db_prefix() . 'leads_bank_details');
                            }
                        }
                    }
                }

                $success = $this->leads_model->update($this->input->post(), $id);

                if ($success) {
                    // store new transaction in table
                    if (!empty($new_transaction_name)) {
                        $new_transaction_name = array(
                            'name' => $new_transaction_name
                        );
                        $this->db->insert(db_prefix() . 'leads_transaction_details', $new_transaction_name);
                    }
                    // send and preloaded checklist create for client when case group assign
                    $this->db->select('multiple_cases,name,assign_group,phonenumber,addedfrom');
                    $this->db->where('id', $id);
                    $query = $this->db->get(db_prefix() . 'leads');

                    if ($query->num_rows() > 0) {
                        $lead = $query->row();
                        $multiple_cases = $lead->multiple_cases;
                        $check_assign_group = $lead->assign_group;
                        $update_case_name = $lead->name;
                        $email = $this->input->post('email');
                        $firstname = $this->input->post('firstname');
                        $middlename = $this->input->post('middlename');
                        $lastname = $this->input->post('lastname');
                        $user_name = $firstname . ' ' . $middlename . ' ' . $lastname;
                        // Assuming send_mail_template function takes care of sending emails
                        $_POST['broker_id'] = ($lead->addedfrom) ? $lead->addedfrom : get_staff_user_id();
                        $role = get_current_staff_role($this, $_POST['broker_id']);
                        // send notification and email when admin case group assign or changed
                        if (!empty($check_assign_group) && !empty($before_update_record) && $before_update_record->assign_group !== $check_assign_group) {
                            $this->send_mail_to_broker_when_group_assign($lead, $id, $check_assign_group, '');
                            // get the checklist template ids for file opened and add the checklist item preloaded for client
                            $this->db->select('id');
                            $this->db->where('rel_id', $id);
                            $this->db->where('rel_type', 'user-task');
                            $this->db->where('type', 'client');
                            $preloaded_task_check = $this->db->get(db_prefix() . 'tasks')->row();
                            if (empty($preloaded_task_check->id)) {
                                $this->db->select('id');
                                $this->db->where('type', 'client');
                                $this->db->where('case_status', 1);
                                $this->db->order_by('order_no', 'asc');
                                $query = $this->db->get(db_prefix() . 'checklist_templates');
                                $checklist_template_ids = array_column($query->result_array(), 'id');
                                preloaded_file_opened_checklist_template_add_in_task_table($this, $checklist_template_ids, $id, 1);
                                // get the checklist template ids for file opened and add the checklist item preloaded for Broker

                                // get the checklist template ids for request for funds  for ld-team
                                $this->db->select('id');
                                $this->db->where('type', 'ld_team');
                                $this->db->where('case_status', 4);
                                $query = $this->db->get(db_prefix() . 'checklist_templates');
                                $checklist_template_ids_for_request_for_funds = array_column($query->result_array(), 'id');
                                preloaded_request_for_funds_checklist_template_add_in_task_table($this, $checklist_template_ids_for_request_for_funds, $id, 4);
                                // Outstanding item checklist
                                // check item checklist item exit or not
                                $this->db->where('rel_id', $id);
                                $this->db->where('rel_type', 'user-task');
                                $this->db->where('leads_status', 3);
                                $check_item_outstanding_client = $this->db->get(db_prefix() . 'tasks')->row();
                                if (empty($check_item_outstanding_client)) {
                                    $this->db->select('id');
                                    $this->db->where('type', 'client');
                                    $this->db->where('case_status', 3);
                                    $this->db->order_by('order_no', 'asc');
                                    $query = $this->db->get(db_prefix() . 'checklist_templates');
                                    $checklist_template_ids = array_column($query->result_array(), 'id');
                                    preloaded_file_opened_checklist_template_add_in_task_table($this, $checklist_template_ids, $id, 3);
                                }
                                // notificaation line of code  and sms line of code 
                                $title = 'Case Assigned';
                                $new_case_message = 'New case (ID: #' . $id . ' & Name: ' . $update_case_name . ') assigned by ' . get_staff_full_name() . '.';
                                $this->db->select('id,multiple_cases,client_id,phonenumber,name,email,addedfrom');
                                $this->db->where('id', $id);
                                $lead_data_check = $this->db->get(db_prefix() . 'leads');
                                if ($lead_data_check->num_rows() > 0) {
                                    $lead_data = $lead_data_check->row();
                                    $client_id = get_client_id_using_contact_id($this, $lead_data->client_id, $lead_data->multiple_cases);
                                    $contact_id = get_contact_id_using_client_id($this, $client_id);
                                    $notification_type = get_notification_type(1);
                                    // send notification if stage are not close

                                    // send notificaitonto the staff
                                    $this->db->select('assign_group,assigned');
                                    $this->db->where('id', $id);
                                    $lead_data_for_get_assign_group = $this->db->get(db_prefix() . 'leads')->row();
                                    $current_staff_data = get_staff_ids_by_group($this, $lead_data_for_get_assign_group->assign_group);
                                    if (!empty($current_staff_data)) {
                                        foreach ($current_staff_data as $staff_notifiy_data) {
                                            $ld_team_notify_title = 'Case Assigned';
                                            $ld_team_notify_message = 'New case (ID: #' . $id . ' & Name: ' . $update_case_name . ') assigned by ' . get_staff_full_name() . '.';
                                            // send_notification_in_mobile('staff', $staff_notifiy_data['staffid'], $contact_id, $client_id, $id, $ld_team_notify_title, $ld_team_notify_message, $notification_type, '');
                                        }
                                    }
                                    $client_notify_title = 'Case Created';
                                    $client_notify_message = "Congratulations! Your new case (ID: #' . $id . ' & Name: ' . $update_case_name . ') is now active. Please proceed to upload the required documents according to the outlined specifications.";
                                    // send_notification_in_mobile('client', get_staff_user_id(), $contact_id, $client_id, $id, $client_notify_title, $client_notify_message, $notification_type, '');
                                    // send  notiication in crm to all the team group member and staff
                                    $this->db->select('assign_group,assigned');
                                    $this->db->where('id', $id);
                                    $lead_data_for_get_assign_group = $this->db->get(db_prefix() . 'leads')->row();
                                    $current_staff_data = get_staff_ids_by_group($this, $lead_data_for_get_assign_group->assign_group);
                                    foreach ($current_staff_data as $staff_notifiy_data) {
                                        if (get_staff_user_id() != $staff_notifiy_data['staffid']) {
                                            $this->leads_model->custom_lead_assigned_member_notification('staff', $id, $staff_notifiy_data['staffid'], get_staff_user_id(), '', $new_case_message);
                                        }
                                    }
                                    // get the all admin staff ids
                                    $admin_ids = get_all_admin_role_staff_ids($this);
                                    foreach ($admin_ids as $admin_email) {
                                        if (get_staff_user_id() != $admin_email['staffid']) {
                                            $admin_notify_title = 'Case Assigned';
                                            $admin_notify_message = 'New case (ID: #' . $id . ' & Name: ' . $update_case_name . ') assigned by ' . get_staff_full_name() . '.';
                                            // send_notification_in_mobile('staff', $admin_email['staffid'], $contact_id, $client_id, $id, $admin_notify_title, $admin_notify_message, $notification_type, '');
                                            //  send notification in crm
                                            $this->leads_model->custom_lead_assigned_member_notification('staff', $id, $admin_email['staffid'], get_staff_user_id(), '', $new_case_message);
                                        }
                                    }
                                    // $all_client_phone_list = get_all_client_phonenumber_using_lead_id($this, $id);
                                    // $this->send_sms($all_client_phone_list, $sms_message_case_active, $sms_message_case_active, $id, '', '');
                                }
                            }
                            // send slack notification for ld-channel
                            $lead_name = leads_splitFullName($update_case_name);
                            $slack_message = "\n Intro: Team " . $check_assign_group . " Designated \n- Open File";
                            $this->slack->sendnotification($slack_message, $id, $check_assign_group, $lead_name['lastname'] . ', ' . $lead_name['firstname'] . ' ' . $lead_name['middlename']);
                        }
                    }
                    $emailNow = $this->db->select('email')->where('id', $id)->get(db_prefix() . 'leads')->row()->email;

                    $proposalWarning = (total_rows(db_prefix() . 'proposals', [
                        'rel_type' => 'lead',
                        'rel_id' => $id,
                    ]) > 0 && ($emailOriginal != $emailNow) && $emailNow != '') ? true : false;

                    $message = _l('updated_successfully', 'Case');
                }
                echo json_encode([
                    'success' => $success,
                    'message' => $message,
                    'id' => $id,
                    'proposal_warning' => $proposalWarning,
                    'leadView' => $this->_get_lead_data($id),
                ]);
            }
            die;
        }

        echo json_encode([
            'leadView' => $this->_get_lead_data($id),
        ]);
    }
    // send email to broker when case group assign 


    private function send_mail_to_broker_when_group_assign($lead, $lead_id, $check_assign_group, $staff_list)
    {
        $broker_data = get_multiple_broker_details_using_addedfrom($this, $lead->addedfrom);
        if (!empty($broker_data)) {
            foreach ($broker_data as $broker) {
                $_POST['broker_name'] = $broker['firstname'] . ' ' . $broker['lastname'];
                $broker_email = $broker['email'];
                $role = get_current_staff_role($this, $broker['broker_id']);
                if (isset($broker['staffid']) || $role == 2 || $role == 6) {
                    $_POST['lead_id'] = $lead_id;
                    $_POST['case_name'] = $lead->name;
                    $_POST['case_url'] = get_the_redirect_email_case_url($lead_id, 'broker');
                    $_POST['check_assign_group'] = $check_assign_group;
                    $_POST['get_staff_group_details'] = get_all_staff_ids_by_group_name($this, $check_assign_group);
                    $subject = 'New Case: ' . reverseName($lead->name);
                    $replay_to_mail = get_all_staff_to_replay_email($this, get_staff_user_id(), $check_assign_group);
                    $html_content_confirmation_email_to_broker = $this->load->view('admin/leads/Email_template/Email_to_broker', $_POST, TRUE);
                    $send_email_result = send_mailchimp_email($broker_email, $subject, $html_content_confirmation_email_to_broker, $replay_to_mail, '', '', $lead_id);
                    // add the record for outbox emails 
                    $outbox_content = 'Thank you for your kind instruction. We look forward to working with you on this transaction';
                    $outbox_id = $this->Outbox_model->save_outbox_email($broker_email, '', '', $subject, $outbox_content, '', $lead_id, 1, $html_content_confirmation_email_to_broker, $replay_to_mail, $send_email_result['status'], $send_email_result['mandrill_id'], 1);

                    $new_case_message = 'Please check your email. The case group has been updated by ' . get_staff_full_name() . ' for case (ID: #' . $lead_id . ' & Name: ' . $lead->name . ').';
                    // send notificaiton in crm to the broker
                    $this->leads_model->custom_lead_assigned_member_notification('staff', $lead_id, $broker['staffid'], get_staff_user_id(), '', $new_case_message);
                    // add the activity for admin and ld 
                    $add_activity_data = [
                        'leadid' => $lead_id,
                        'staffid' => get_staff_user_id(),
                        'full_name' => get_staff_full_name(),
                        'description' => '<p>Dear Colleague</p>
                                                    <p>Thank you for your kind instruction. We look forward to working with you on this transaction.</p>
                                                    <p>The file of <span style="font-weight:800;">#' . $_POST['lead_id'] . ',' . $_POST['update_case_name'] . '</span> has been assigned to Team ' . $_POST['check_assign_group'] . ' comprising:</p>
                                                    <ul style="list-style-type: disc;">' . $staff_list . '</ul>',
                        'date' => date('Y-m-d H:i:s'),
                    ];
                    $this->db->insert(db_prefix() . 'lead_activity_log', $add_activity_data);
                }
            }
            // send the all admin notification and email to the admin broker
            $brokerage_id = get_brokerage_id_using_leadid($this, $lead_id);
            $admin_broker_ids = get_all_admin_broker_role_staff_ids($this, $brokerage_id);
            foreach ($admin_broker_ids as $admin_broker_email) {
                if (get_staff_user_id() != $admin_broker_email['staffid'] && !in_array($admin_broker_email['staffid'], explode(',', $lead->addedfrom))) {
                    $_POST['broker_name'] = $admin_broker_email['firstname'] . ' ' . $admin_broker_email['lastname'];
                    $broker_email = $admin_broker_email['email'];
                    $role = get_current_staff_role($this, $broker['broker_id']);
                    if (isset($broker['staffid']) || $role == 2 || $role == 6) {
                        $_POST['lead_id'] = $lead_id;
                        $_POST['case_name'] = $lead->name;
                        $_POST['case_url'] = get_the_redirect_email_case_url($lead_id, 'broker');
                        $_POST['check_assign_group'] = $check_assign_group;
                        $_POST['get_staff_group_details'] = get_all_staff_ids_by_group_name($this, $check_assign_group);
                        $subject = 'Thank you! Your Case is Received';
                        $replay_to_mail = get_all_staff_to_replay_email($this, get_staff_user_id(), $check_assign_group);
                        $html_content_confirmation_email_to_broker = $this->load->view('admin/leads/Email_template/Email_to_broker', $_POST, TRUE);
                        $send_email_result = send_mailchimp_email($broker_email, $subject, $html_content_confirmation_email_to_broker, $replay_to_mail, '', '', $lead_id);
                        // add the record for outbox emails 
                        $outbox_content = 'Thank you for your kind instruction. We look forward to working with you on this transaction';
                        $outbox_id = $this->Outbox_model->save_outbox_email($broker_email, '', '', $subject, $outbox_content, '', $lead_id, 1, $html_content_confirmation_email_to_broker, $replay_to_mail, $send_email_result['status'], $send_email_result['mandrill_id'], 1);

                        $new_case_message = 'Please check your email. The case group has been updated by ' . get_staff_full_name() . ' for case (ID: #' . $lead_id . ' & Name: ' . $lead->name . ').';
                        // send notificaiton in crm to the broker
                        $this->leads_model->custom_lead_assigned_member_notification('staff', $lead_id, $admin_broker_email['staffid'], get_staff_user_id(), '', $new_case_message);
                        // add the activity for admin and ld 
                        $add_activity_data = [
                            'leadid' => $lead_id,
                            'staffid' => get_staff_user_id(),
                            'full_name' => get_staff_full_name(),
                            'description' => '<p>Dear Colleague</p>
                                                        <p>Thank you for your kind instruction. We look forward to working with you on this transaction.</p>
                                                        <p>The file of <span style="font-weight:800;">#' . $_POST['lead_id'] . ',' . $_POST['update_case_name'] . '</span> has been assigned to Team ' . $_POST['check_assign_group'] . ' comprising:</p>
                                                        <ul style="list-style-type: disc;">' . $staff_list . '</ul>',
                            'date' => date('Y-m-d H:i:s'),
                        ];
                        $this->db->insert(db_prefix() . 'lead_activity_log', $add_activity_data);
                    }
                }
            }
        }
    }
    // send sms function 
    private function send_sms($phonenumber, $msg, $activity_logs_msg = '', $lead_id, $lead_name = '', $lead_email = '', $sms_shout = '')
    {
        $message = strip_tags($msg);
        $reciever_number = $phonenumber;
        $message = str_replace("<br>", "\n", $message);
        $check_sms_send = $this->sms_twilio->send($reciever_number, $message, $sms_shout);
        // add the emali in activity logs
        if ($check_sms_send) {
            // $insert_task_activity = array(
            //     'leadid' => $lead_id,
            //     'staffid' => get_staff_user_id(),
            //     'full_name' => get_staff_full_name(),
            //     'description' => $activity_logs_msg,
            //     'date' => date('Y-m-d H:i:s'),
            // );
            // leads_activity_log($this, $insert_task_activity);
            return true;
        } else {
            return false;
        }
    }
    // total file get count for time taken
    public function total_count_for_time_taken_file()
    {
        $lead_id = $this->input->post('id');
        //  For all cases in the pipeline, time taken from instruction to full ID received
        $instruction_to_full_id_received_time = count_time_instruction_to_full_id_received_time_taken($this, $lead_id);
        // For all cases in the pipeline, time taken from instruction to offer received
        $instruction_to_offer_received = count_instruction_receive_to_offer_received_time_taken($this, $lead_id);
        // For all cases in the pipeline, time taken from offer to closing
        $offer_to_closing_time_taken = count_offer_to_closing_time_taken($this, $lead_id);
        // For all cases in the pipeline, time taken from instruction to closing
        $instruction_to_closing_time_taken = count_instruction_to_closing_time_taken($this, $lead_id);
        $record = array(
            'instruction_to_full_id_received_time' => $instruction_to_full_id_received_time ?? '0',
            'instruction_to_offer_received' => $instruction_to_offer_received ?? '0',
            'offer_to_closing_time_taken' => $offer_to_closing_time_taken ?? '0',
            'instruction_to_closing_time_taken' => $instruction_to_closing_time_taken ?? '0'
        );
        $this->output
            ->set_content_type('application/json')
            ->set_output(json_encode($record));
    }
    // Total number of files with offer and no ids
    public function total_file_with_offer_and_no_ids()
    {
        $start_date = $this->input->post('start_date');
        $end_date = $this->input->post('end_date');
        // filter record using start and end date
        $format_start_date = date('Y-m-d', strtotime($start_date));
        $format_end_date = date('Y-m-d', strtotime($end_date));
        if ($this->input->post('start_date') && $this->input->post('end_date')) {
            $total_record = total_number_of_files_with_offer_and_no_ids($this, $format_start_date, $format_end_date);
        } else {
            $total_record = total_number_of_files_with_offer_and_no_ids($this);
        }
        $record = array(
            'offer_no_ids_count' => $total_record
        );
        $this->output
            ->set_content_type('application/json')
            ->set_output(json_encode($record));
    }
    // total coundt for file on hold
    public function total_count_for_on_hold()
    {
        $start_date = $this->input->post('start_date');
        $end_date = $this->input->post('end_date');
        // filter record using start and end date
        $format_start_date = date('Y-m-d', strtotime($start_date));
        $format_end_date = date('Y-m-d', strtotime($end_date));
        if ($this->input->post('start_date') && $this->input->post('end_date')) {
            $total_on_hold_count = total_file_on_hold($this, $format_start_date, $format_end_date);
        } else {
            $total_on_hold_count = total_file_on_hold($this);
        }
        $record = array(
            'total_on_hold_file' => $total_on_hold_count
        );
        $this->output
            ->set_content_type('application/json')
            ->set_output(json_encode($record));
    }
    // total count for appointment completed by for reports
    public function total_count_for_appointment_completed_by()
    {
        $appinment_completed_by = $this->input->post('appointment_completed_by');
        $start_date = $this->input->post('start_date');
        $end_date = $this->input->post('end_date');
        // filter record using start and end date
        $format_start_date = date('Y-m-d', strtotime($start_date));
        $format_end_date = date('Y-m-d', strtotime($end_date));
        if ($this->input->post('start_date') && $this->input->post('end_date')) {
            $total_completed_appintment = total_number_of_appointment_completed_by($this, $appinment_completed_by, $format_start_date, $format_end_date);
            if (!empty($total_completed_appintment)) {
                $record = array('total_completed_appintment' => $total_completed_appintment);
            } else {
                $record = array('total_completed_appintment' => 0);
            }
        } else {
            $total_completed_appintment = total_number_of_appointment_completed_by($this, $appinment_completed_by);
            if (!empty($total_completed_appintment)) {
                $record = array('total_completed_appintment' => $total_completed_appintment);
            } else {
                $record = array('total_completed_appintment' => 0);
            }
        }
        $this->output
            ->set_content_type('application/json')
            ->set_output(json_encode($record));
    }
    // get the address of lender
    public function get_lender_address($lender_id)
    {
        $address = get_lender_address_by_lender_id($this, $lender_id);
        if (!empty($address)) {
            $response = array(
                'success' => true,
                'address' => $address
            );
        } else {
            $response = array(
                'success' => false,
                'address' => ''
            );
        }
        $this->output
            ->set_content_type('application/json')
            ->set_output(json_encode($response));
    }
    // total count for particular lender by for reports
    public function total_count_for_lender_by()
    {
        $lender_id = $this->input->post('lender');
        $start_date = $this->input->post('start_date');
        $end_date = $this->input->post('end_date');
        // filter record using start and end date
        $format_start_date = date('Y-m-d', strtotime($start_date));
        $format_end_date = date('Y-m-d', strtotime($end_date));
        if ($this->input->post('start_date') && $this->input->post('end_date')) {
            $data = total_file_with_a_particular_lender($this, $lender_id, $format_start_date, $format_end_date);
        } else if (!empty($lender_id)) {
            $data = total_file_with_a_particular_lender($this, $lender_id);
        } else {
            $data = 0;
        }
        $record = array(
            'total_lender_count' => $data
        );
        $this->output
            ->set_content_type('application/json')
            ->set_output(json_encode($record));
    }
    public function file_opened_in_a_given_time_frame_count()
    {
        $start_date = $this->input->post('start_date');
        $end_date = $this->input->post('end_date');
        // filter record using start and end date
        $format_start_date = date('Y-m-d', strtotime($start_date));
        $format_end_date = date('Y-m-d', strtotime($end_date));
        if ($this->input->post('start_date') && $this->input->post('end_date')) {
            $total_file_opened_timeframe = file_opened_in_a_given_time_frame($this, $format_start_date, $format_end_date);
        }
        $record = array(
            'total_file_opened_timeframe' => $total_file_opened_timeframe
        );
        $this->output
            ->set_content_type('application/json')
            ->set_output(json_encode($record));
    }
    public function file_closed_in_a_given_time_frame_count()
    {
        $start_date = $this->input->post('start_date');
        $end_date = $this->input->post('end_date');
        // filter record using start and end date
        $format_start_date = date('Y-m-d', strtotime($start_date));
        $format_end_date = date('Y-m-d', strtotime($end_date));
        if ($this->input->post('start_date') && $this->input->post('end_date')) {
            $total_file_closed_timeframe = file_closed_in_a_given_time_frame($this, $format_start_date, $format_end_date);
        }
        $record = array(
            'total_file_closed_timeframe' => $total_file_closed_timeframe
        );
        $this->output
            ->set_content_type('application/json')
            ->set_output(json_encode($record));
    }
    public function total_number_of_file_open_without_offer_count()
    {
        $start_date = $this->input->post('start_date');
        $end_date = $this->input->post('end_date');
        // filter record using start and end date
        $format_start_date = date('Y-m-d', strtotime($start_date));
        $format_end_date = date('Y-m-d', strtotime($end_date));
        if ($this->input->post('start_date') && $this->input->post('end_date')) {
            $file_open_count_without_offer_count = total_number_of_file_open_without_offer($this, $format_start_date, $format_end_date);
        } else {
            $file_open_count_without_offer_count = total_number_of_file_open_without_offer($this);
        }
        $record = array(
            'file_open_count_without_offer_count' => $file_open_count_without_offer_count
        );
        $this->output
            ->set_content_type('application/json')
            ->set_output(json_encode($record));
    }
    public function total_number_of_file_open_with_offer_count()
    {
        $start_date = $this->input->post('start_date');
        $end_date = $this->input->post('end_date');
        // filter record using start and end date
        $format_start_date = date('Y-m-d', strtotime($start_date));
        $format_end_date = date('Y-m-d', strtotime($end_date));
        if ($this->input->post('start_date') && $this->input->post('end_date')) {
            $file_open_count_with_offer_count = total_number_of_file_open_with_offer($this, $format_start_date, $format_end_date);
        } else {
            $file_open_count_with_offer_count = total_number_of_file_open_with_offer($this);
        }
        $record = array(
            'file_open_count_with_offer_count' => $file_open_count_with_offer_count
        );
        $this->output
            ->set_content_type('application/json')
            ->set_output(json_encode($record));
    }
    public function overall_total_number_of_files()
    {
        $start_date = $this->input->post('start_date');
        $end_date = $this->input->post('end_date');
        // filter record using start and end date
        $format_start_date = date('Y-m-d', strtotime($start_date));
        $format_end_date = date('Y-m-d', strtotime($end_date));
        if ($this->input->post('start_date') && $this->input->post('end_date')) {
            $total_count = total_number_files($this, $format_start_date, $format_end_date);
        } else {
            $total_count = total_number_files($this);
        }
        $record = array(
            'total_count' => $total_count
        );
        $this->output
            ->set_content_type('application/json')
            ->set_output(json_encode($record));
    }
    // get the IDV scanario 
    public function get_idv_user_email($lead_id)
    {
        $idv_client_id = $this->input->post('user_id');
        $client_email = '';
        $borrower_type = ($lead_id == $idv_client_id) ? 'Client' : 'Borrower';
        if ($borrower_type == 'Client') {
            $client_email = get_client_email_using_lead_id($this, $lead_id);
            $client_name = get_client_name_using_lead_id($this, $idv_client_id);
            $response = array(
                'success' => true,
                'email' => $client_email,
                'client_name' => $client_name
            );
        } else {
            $get_all_clients_emails_count = get_all_clients_email_counts_separately($this, $lead_id);

            $client_email = ($get_all_clients_emails_count['borrower_email_count'] > 0) ? get_borrower_email_using_borrower_id($this, $idv_client_id) : get_client_email_using_lead_id($this, $lead_id);
            $client_name = get_borrower_name_using_borrower_id($this, $idv_client_id);
            $response = array(
                'success' => true,
                'email' => $client_email,
                'client_name' => $client_name
            );
        }
        $this->output
            ->set_content_type('application/json')
            ->set_output(json_encode($response));
    }
    // upload id verification doc in dropbox
    public function id_verification_attachment()
    {
        $lead_id = $this->input->post('lead_id');
        $select_user = $this->input->post('select_user');
        $borrower_type = ($lead_id == $select_user) ? 'Client' : 'Borrower';
        $description = $this->input->post('idv_description');
        $idv_done_by = $this->input->post('idv_done_by');
        $idv_done_through_other_tincymac = $this->input->post('idv_done_through_other_tincymac', FALSE);
        $idv_done_through_ot_docsign_tincymac = $this->input->post('idv_done_through_ot_docsign_tincymac', FALSE);
        $idv_done_through_ot_hosper_tincymac = $this->input->post('idv_done_through_ot_hosper_tincymac', FALSE);
        $idv_done_through_ot_fct_tincymac = $this->input->post('idv_done_through_ot_fct_tincymac', FALSE);
        $idv_received_no_tinymce = $this->input->post('idv_received_no_tinymce', FALSE);
        $idv_received_yes_pass_yes_tinymce = $this->input->post('idv_received_yes_pass_yes_tinymce', FALSE);
        $idv_received_yes_pass_no_tinymce = $this->input->post('idv_received_yes_pass_no_tinymce', FALSE);
        $idv_received = $this->input->post('idv_received');
        $idv_received_pass = $this->input->post('idv_received_pass');
        $dl_check_completed = $this->input->post('dl_check_completed');
        $dl_check_completed_at = $this->input->post('dl_check_completed_at');
        // TO and cc and bcc for Question1 IDV Begin Done through
        $to_idv_done_through = $this->input->post('to_idv_done_through');
        $cc_idv_done_through = $this->input->post('cc_idv_done_through');
        $bcc_idv_done_through = $this->input->post('bcc_idv_done_through');
        // convert into array
        $to_idv_done_through_emails = array_map('trim', explode(',', $to_idv_done_through));
        $cc_idv_done_through_emails = array_map('trim', explode(',', $cc_idv_done_through));
        $bcc_idv_done_through_emails = array_map('trim', explode(',', $bcc_idv_done_through));
        // TO and CC and Bcc for Question 2 IDV pass or not
        $to_idv_received = $this->input->post('to_idv_received');
        $cc_idv_received = $this->input->post('cc_idv_received');
        $bcc_idv_received = $this->input->post('bcc_idv_received');
        // convert into array
        $to_idv_received_emails = array_map('trim', explode(',', $to_idv_received));
        $cc_idv_received_emails = array_map('trim', explode(',', $cc_idv_received));
        $bcc_idv_received_emails = array_map('trim', explode(',', $bcc_idv_received));

        $this->db->select('email,phonenumber,name');
        $this->db->where('id', $lead_id);
        $result = $this->db->get(db_prefix() . 'leads')->row();
        $getemail = $result->email;
        $getphonenumber = $result->phonenumber;
        $get_lead_name = $result->name;
        $get_lead_email = $result->email;
        $data = $this->Token_model->getToken();
        $get_id = array_column($data, 'token');
        $access_token = implode(',', $get_id);
        $data = $this->Contacts_model->getEmail($getemail);
        $get_id = array_column($data, 'id');
        $get_userid = array_column($data, 'userid');
        $get_firstname = array_column($data, 'firstname');
        $get_lastname = array_column($data, 'lastname');
        $dropbox_firstname = implode(',', $get_firstname);
        $dropbox_lastname = implode(',', $get_lastname);
        $get_id = implode(',', $get_id);
        $userid = implode(',', $get_userid);
        $leadData = $this->leads_model->get_lead_id($get_id);
        $user_id = $leadData->id;
        $user_name = $leadData->name;
        if ($_SERVER['REQUEST_METHOD'] === 'POST') {
            // Get form data
            // $files = $_FILES['bank_file'];

            // Validate form data
            // $this->form_validation->set_rules('description', 'Description', 'required');
            $instruction_date = array(
                'lead_id' => $lead_id,
                'borrower_id' => $select_user,
                'borrower_type' => $borrower_type,
                'description' => $description,
                'stage_id' => 8,
                'idv_done_by' => $idv_done_by,
                'idv_received' => $idv_received,
                'idv_received_pass' => $idv_received_pass,
                'dl_check_completed' => $dl_check_completed ?? '',
                'dl_check_completed_at' => to_sql_date($dl_check_completed_at, true) ?? '',
                'action_by' => get_staff_full_name(),
                'created_at' => date('Y-m-d H:i:s')
            );
            $this->db->insert(db_prefix() . 'instruction', $instruction_date);
            $insert_id_of_instruction = $this->db->insert_id();
            // if (!empty($_FILES['id_verification_file']['name'])) {
            //     foreach ($_FILES['id_verification_file']['name'] as $key => $name) {
            //         $tmp_file = $_FILES['id_verification_file']['tmp_name'][$key];
            //         if (is_uploaded_file($tmp_file)) {
            //             $file_name = $_FILES['id_verification_file']['name'][$key];
            //             $data = $this->leads_model->upload_to_dropbox($access_token, $tmp_file, $file_name, $user_id, $dropbox_firstname, $dropbox_lastname);
            //             if ($data['status'] != 200) {
            //                 $this->leads_model->add_errors_logs($lead_id, get_staff_user_id(), get_staff_full_name(), 'idv document uploads', $data, $data['status'], 'Staff');
            //                 echo json_encode(
            //                     array(
            //                         'success' => false,
            //                         'response' => $data
            //                     )
            //                 );
            //                 exit;
            //             }
            //             $instruction_file_data = array(
            //                 'instruction_id' => $insert_id_of_instruction,
            //                 'file_name' => $data['file_name'],
            //                 'file_type' => $data['file_type'],
            //                 'file_url' => $data['file_url'],
            //                 'downnload_file_url' => $data['download_file_url'],
            //                 'created_at' => date('Y-m-d H:i:s')
            //             );
            //             $this->db->insert(db_prefix() . 'instruction_file', $instruction_file_data);
            //         }
            //     }
            // }
            $this->db->select('*');
            $this->db->from(db_prefix() . 'instruction');
            $this->db->join(db_prefix() . 'instruction_file', db_prefix() . 'instruction.id = ' . db_prefix() . 'instruction_file.instruction_id', 'left');
            $query = $this->db->get();
            $save = $query->result_array();
            if ($save) {
                // add the data in lead activity log
                $insert_task_activity = array(
                    'leadid' => $lead_id,
                    'staffid' => get_staff_user_id(),
                    'full_name' => get_staff_full_name(),
                    'activity_type' => '',
                    'description' => "Id verification doc uploaded by " . get_staff_full_name(),
                    'date' => date('Y-m-d H:i:s'),
                );
                leads_activity_log($this, $insert_task_activity);
                // pass and refesh code in front end side
                $leads_status_value = '#id_verification';
                $complete_stage_button = 8;
                $response = array(
                    'success' => true,
                    'message' => 'Data saved successfully',
                    'data' => $save,
                    'leads_status' => $leads_status_value,
                    'complete_stage_button' => $complete_stage_button,
                    'id' => $lead_id,
                    'leadView' => $this->_get_lead_data($lead_id),
                );
                $get_mail_subject = get_mail_subject_for_case_stages($this, $lead_id, 8);
                // First question for id verification work
                // notification send code
                $this->db->select('multiple_cases,client_id,phonenumber,name,email,addedfrom,assign_group');
                $this->db->where('id', $lead_id);
                $lead_data_check = $this->db->get(db_prefix() . 'leads');
                if ($lead_data_check->num_rows() > 0) {
                    $lead_data = $lead_data_check->row();
                    $case_name = $lead_data->name;
                    $client_id = get_client_id_using_contact_id($this, $lead_data->client_id, $lead_data->multiple_cases);
                    $contact_id = get_contact_id_using_client_id($this, $client_id);
                }
                if ($idv_done_by == 'DOCUSIGN') {
                    $slack_message = 'IDV successfully completed via DOCUSIGN, and the email has been sent to the client. Action performed by ' . get_staff_full_name() . '.';

                    $_POST['user_name'] = $get_lead_name;
                    $_POST['generic_email_title'] = '';
                    $_POST['generic_email_back_to_case_url'] = '';
                    $_POST['generic_email_content'] = $idv_done_through_ot_docsign_tincymac;
                    $html_content_welcome_email_to_user = $this->load->view('admin/leads/Email_template/generic_email_template', $_POST, TRUE);
                    $subject = $get_mail_subject;
                    $replay_to_mail = get_all_staff_to_replay_email($this, get_staff_user_id(), $lead_data->assign_group, $to_idv_done_through_emails);
                    $send_email_result = send_mailchimp_email($to_idv_done_through_emails, $subject, $html_content_welcome_email_to_user, $replay_to_mail, $cc_idv_done_through_emails, $bcc_idv_done_through_emails, $lead_id);
                    // add the record for outbox emails 
                    $outbox_id = $this->Outbox_model->save_outbox_email($to_idv_done_through_emails, $cc_idv_done_through_emails, $bcc_idv_done_through_emails, $subject, $idv_done_through_ot_docsign_tincymac, '', $lead_id, 8, $html_content_welcome_email_to_user, $replay_to_mail, $send_email_result['status'], $send_email_result['mandrill_id'], 1);
                    // add the email in activity logs
                    $add_email_content_in_activity_logs = $idv_done_through_ot_fct_tincymac;
                    $insert_task_activity = array(
                        'leadid' => $lead_id,
                        'staffid' => get_staff_user_id(),
                        'full_name' => get_staff_full_name(),
                        'description' => get_staff_full_name() . " sent an email to " . $get_lead_name . ' <br>' . $add_email_content_in_activity_logs,
                        'date' => date('Y-m-d H:i:s'),
                    );
                    leads_activity_log($this, $insert_task_activity);
                    if ($borrower_type == 'Client') {
                        // add the app message 
                        $app_message = 'Please now check your email to complete the ID Verification process with DocuSign.';
                        store_app_message_for_client($this, $lead_id, $app_message, 8);
                        // Send notification in mobile side
                        $notification_type = get_notification_type(1);
                        $client_notify_title = 'IDV Verification';
                        $client_notify_message = 'Please complete the ID Verification process.';
                        send_notification_in_mobile('client', get_staff_user_id(), $contact_id, $client_id, $lead_id, $client_notify_title, $client_notify_message, $notification_type, '');
                    }
                } elseif ($idv_done_by == 'FCT') {
                    $slack_message = 'IDV successfully completed via FCT, and the email has been sent to the client. Action performed by ' . get_staff_full_name() . '.';
                    $_POST['user_name'] = $get_lead_name;
                    $_POST['generic_email_title'] = '';
                    $_POST['generic_email_back_to_case_url'] = '';
                    $_POST['generic_email_content'] = $idv_done_through_ot_fct_tincymac;
                    $html_content_welcome_email_to_user = $this->load->view('admin/leads/Email_template/generic_email_template', $_POST, TRUE);
                    $subject = $get_mail_subject;
                    $replay_to_mail = get_all_staff_to_replay_email($this, get_staff_user_id(), $lead_data->assign_group, $to_idv_done_through_emails);
                    $send_email_result = send_mailchimp_email($to_idv_done_through_emails, $subject, $html_content_welcome_email_to_user, $replay_to_mail, $cc_idv_done_through_emails, $bcc_idv_done_through_emails, $lead_id);
                    // add the record for outbox emails 
                    $outbox_id = $this->Outbox_model->save_outbox_email($to_idv_done_through_emails, $cc_idv_done_through_emails, $bcc_idv_done_through_emails, $subject, $idv_done_through_ot_fct_tincymac, '', $lead_id, 8, $html_content_welcome_email_to_user, $replay_to_mail, $send_email_result['status'], $send_email_result['mandrill_id'], 1);

                    // add the email in activity logs
                    $add_email_content_in_activity_logs = $idv_done_through_ot_fct_tincymac;
                    $insert_task_activity = array(
                        'leadid' => $lead_id,
                        'staffid' => get_staff_user_id(),
                        'full_name' => get_staff_full_name(),
                        'description' => get_staff_full_name() . " sent an email to " . $get_lead_name . ' <br>' . $add_email_content_in_activity_logs,
                        'date' => date('Y-m-d H:i:s'),
                    );
                    leads_activity_log($this, $insert_task_activity);
                    if ($borrower_type == 'Client') {
                        // add the app message 
                        $app_message = 'Please now check your email to complete the ID Verification process with FCT/Bluink.';
                        store_app_message_for_client($this, $lead_id, $app_message, 8);
                        // Send notification in mobile side
                        $notification_type = get_notification_type(1);
                        $client_notify_title = 'IDV Verification';
                        $client_notify_message = 'Please complete the ID Verification process.';
                        send_notification_in_mobile('client', get_staff_user_id(), $contact_id, $client_id, $lead_id, $client_notify_title, $client_notify_message, $notification_type, '');
                    }
                } elseif ($idv_done_by == 'Hosper') {
                    $slack_message = 'IDV successfully completed via Hosper, and the email has been sent to the client. Action performed by ' . get_staff_full_name() . '.';
                    $_POST['user_name'] = $get_lead_name;
                    $_POST['generic_email_title'] = '';
                    $_POST['generic_email_back_to_case_url'] = '';
                    $_POST['generic_email_content'] = $idv_done_through_ot_hosper_tincymac;
                    $html_content_welcome_email_to_user = $this->load->view('admin/leads/Email_template/generic_email_template', $_POST, TRUE);
                    $subject = $get_mail_subject;
                    $replay_to_mail = get_all_staff_to_replay_email($this, get_staff_user_id(), $lead_data->assign_group, $to_idv_done_through_emails);
                    $send_email_result = send_mailchimp_email($to_idv_done_through_emails, $subject, $html_content_welcome_email_to_user, $replay_to_mail, $cc_idv_done_through_emails, $bcc_idv_done_through_emails, $lead_id);
                    // add the record for outbox emails 
                    $outbox_id = $this->Outbox_model->save_outbox_email(
                        $to_idv_done_through_emails,
                        $cc_idv_done_through_emails,
                        $bcc_idv_done_through_emails,
                        $subject,
                        $idv_done_through_ot_hosper_tincymac,
                        '',
                        $lead_id,
                        8,
                        $html_content_welcome_email_to_user,
                        $replay_to_mail,
                        $send_email_result['status'],
                        $send_email_result['mandrill_id'],
                        1
                    );

                    // add the email in activity logs
                    $add_email_content_in_activity_logs = $idv_done_through_ot_hosper_tincymac;
                    $insert_task_activity = array(
                        'leadid' => $lead_id,
                        'staffid' => get_staff_user_id(),
                        'full_name' => get_staff_full_name(),
                        'description' => get_staff_full_name() . " sent an email to " . $get_lead_name . ' <br>' . $add_email_content_in_activity_logs,
                        'date' => date('Y-m-d H:i:s'),
                    );
                    leads_activity_log($this, $insert_task_activity);
                    if ($borrower_type == 'Client') {
                        // add the app message 
                        $app_message = 'Please now check your email to complete the ID Verification process with FCT/Bluink.';
                        store_app_message_for_client($this, $lead_id, $app_message, 8);
                        // Send notification in mobile side
                        $notification_type = get_notification_type(1);
                        $client_notify_title = 'IDV Verification';
                        $client_notify_message = 'Please complete the ID Verification process.';
                        send_notification_in_mobile('client', get_staff_user_id(), $contact_id, $client_id, $lead_id, $client_notify_title, $client_notify_message, $notification_type, '');
                    }
                } else if ($idv_done_by == 'Other') {
                    $slack_message = 'IDV successfully completed via Hosper, and the email has been sent to the client. Action performed by ' . get_staff_full_name() . '.';
                    $_POST['user_name'] = $get_lead_name;
                    $_POST['generic_email_title'] = '';
                    $_POST['generic_email_back_to_case_url'] = '';
                    $_POST['generic_email_content'] = $idv_done_through_other_tincymac;
                    $html_content_welcome_email_to_user = $this->load->view('admin/leads/Email_template/generic_email_template', $_POST, TRUE);

                    $subject = $get_mail_subject;
                    $replay_to_mail = get_all_staff_to_replay_email($this, get_staff_user_id(), $lead_data->assign_group, $to_idv_done_through_emails);
                    $send_email_result = send_mailchimp_email($to_idv_done_through_emails, $subject, $html_content_welcome_email_to_user, $replay_to_mail, $cc_idv_done_through_emails, $bcc_idv_done_through_emails, $lead_id);
                    // add the record for outbox emails 
                    $outbox_id = $this->Outbox_model->save_outbox_email(
                        $to_idv_done_through_emails,
                        $cc_idv_done_through_emails,
                        $bcc_idv_done_through_emails,
                        $subject,
                        $idv_done_through_other_tincymac,
                        '',
                        $lead_id,
                        8,
                        $html_content_welcome_email_to_user,
                        $replay_to_mail,
                        $send_email_result['status'],
                        $send_email_result['mandrill_id'],
                        1
                    );
                    // add the email in activity logs
                    $add_email_content_in_activity_logs = $idv_done_through_other_tincymac;
                    $insert_task_activity = array(
                        'leadid' => $lead_id,
                        'staffid' => get_staff_user_id(),
                        'full_name' => get_staff_full_name(),
                        'description' => get_staff_full_name() . " sent an email to " . $get_lead_name . ' <br>' . $add_email_content_in_activity_logs,
                        'date' => date('Y-m-d H:i:s'),
                    );
                    leads_activity_log($this, $insert_task_activity);
                    if ($borrower_type == 'Client') {
                        // add the app message 
                        $app_message = 'Please now check your email to complete the ID Verification process.';
                        store_app_message_for_client($this, $lead_id, $app_message, 8);
                        // Send notification in mobile side
                        $notification_type = get_notification_type(1);
                        $client_notify_title = 'IDV Verification';
                        $client_notify_message = 'Please complete the ID Verification process.';
                        send_notification_in_mobile('client', get_staff_user_id(), $contact_id, $client_id, $lead_id, $client_notify_title, $client_notify_message, $notification_type, '');
                    }
                }
                // send sms to the user
                $idv_sms_message = idv_done_by_text_sms($idv_done_by);
                // $all_client_phone_list = get_all_client_phonenumber_using_lead_id($this, $lead_id);
                $client_phone_list = get_client_phonenumber_using_client_id_and_type($this, $select_user, $borrower_type);
                $this->send_sms($client_phone_list, $idv_sms_message, $idv_sms_message, $lead_id, '', '');
                // Second Question for id verification check
                if (!empty($idv_received) && ($idv_received === 'yes' && !empty($idv_received_pass) && $idv_received_pass === 'yes') || $idv_received === 'N/A') {
                    // update idv_in column for use the filter in list view
                    update_idv_in_record($this, $lead_id);
                }
                if (!empty($idv_received) && $idv_received === 'yes') {
                    if (!empty($idv_received_pass) && $idv_received_pass === 'yes') {
                        $slack_message = 'IDV received (Yes) and IDV pass (Yes), email was sent to the client. Action performed by ' . get_staff_full_name() . '.';

                        $get_all_clients_emails_count = get_all_clients_email_counts_separately($this, $lead_id);
                        $_POST['user_name'] = $get_lead_name;
                        $_POST['generic_email_title'] = '';
                        $_POST['generic_email_back_to_case_url'] = '';
                        $_POST['generic_email_content'] = $idv_received_yes_pass_yes_tinymce;
                        $html_content_welcome_email_to_user = $this->load->view('admin/leads/Email_template/generic_email_template', $_POST, TRUE);

                        $subject = $get_mail_subject;
                        $replay_to_mail = get_all_staff_to_replay_email($this, get_staff_user_id(), $lead_data->assign_group, $to_idv_received_emails);

                        $send_email_result = send_mailchimp_email($to_idv_received_emails, $subject, $html_content_welcome_email_to_user, $replay_to_mail, $cc_idv_received_emails, $bcc_idv_received_emails, $lead_id);
                        // add the record for outbox emails 
                        $outbox_id = $this->Outbox_model->save_outbox_email(
                            $to_idv_received_emails,
                            $cc_idv_received_emails,
                            $bcc_idv_received_emails,
                            $subject,
                            $idv_received_yes_pass_yes_tinymce,
                            '',
                            $lead_id,
                            8,
                            $html_content_welcome_email_to_user,
                            $replay_to_mail,
                            $send_email_result['status'],
                            $send_email_result['mandrill_id'],
                            1
                        );
                        // add the email in activity logs
                        $add_email_content_in_activity_logs = $idv_received_yes_pass_yes_tinymce;
                        $insert_task_activity = array(
                            'leadid' => $lead_id,
                            'staffid' => get_staff_user_id(),
                            'full_name' => get_staff_full_name(),
                            'description' => get_staff_full_name() . " sent an email to " . $get_lead_name . ' <br>' . $add_email_content_in_activity_logs,
                            'date' => date('Y-m-d H:i:s'),
                        );
                        leads_activity_log($this, $insert_task_activity);
                        // add the app message 
                        if ($borrower_type == 'Client') {
                            $app_message = ($get_all_clients_emails_count['borrower_email_count'] > 0 || $get_all_clients_emails_count['borrower_count'] > 0) ? 'ID Verification being processed.' : 'Your ID has been verified. Once we have the mortgage documents from your new lender we shall set an appointment with you.';
                            store_app_message_for_client($this, $lead_id, $app_message, 8);
                            // Send notification in mobile side
                            $notification_type = get_notification_type(1);
                            $client_notify_title = 'ID Verification Completed.';
                            $client_notify_message = '';
                            send_notification_in_mobile('client', get_staff_user_id(), $contact_id, $client_id, $lead_id, $client_notify_title, $client_notify_message, $notification_type, '');
                        }
                    } else if (!empty($idv_received_pass) && $idv_received_pass === 'no') {
                        $slack_message = 'IDV received (Yes) and IDV pass (No), email was sent to the client. Action performed by ' . get_staff_full_name() . '.';

                        $_POST['user_name'] = $get_lead_name;
                        $_POST['generic_email_title'] = '';
                        $_POST['generic_email_back_to_case_url'] = '';
                        $_POST['generic_email_content'] = $idv_received_yes_pass_no_tinymce;
                        $html_content_welcome_email_to_user = $this->load->view('admin/leads/Email_template/generic_email_template', $_POST, TRUE);

                        $subject = $get_mail_subject;
                        $replay_to_mail = get_all_staff_to_replay_email($this, get_staff_user_id(), $lead_data->assign_group, $to_idv_received_emails);

                        $send_email_result = send_mailchimp_email($to_idv_received_emails, $subject, $html_content_welcome_email_to_user, $replay_to_mail, $cc_idv_received_emails, $bcc_idv_received_emails, $lead_id);
                        // add the record for outbox emails 
                        $outbox_id = $this->Outbox_model->save_outbox_email(
                            $to_idv_received_emails,
                            $cc_idv_received_emails,
                            $bcc_idv_received_emails,
                            $subject,
                            $idv_received_yes_pass_no_tinymce,
                            '',
                            $lead_id,
                            8,
                            $html_content_welcome_email_to_user,
                            $replay_to_mail,
                            $send_email_result['status'],
                            $send_email_result['mandrill_id'],
                            1
                        );
                        // add the email in activity logs
                        $add_email_content_in_activity_logs = $idv_received_yes_pass_no_tinymce;
                        $insert_task_activity = array(
                            'leadid' => $lead_id,
                            'staffid' => get_staff_user_id(),
                            'full_name' => get_staff_full_name(),
                            'description' => get_staff_full_name() . " sent an email to " . $get_lead_name . ' <br>' . $add_email_content_in_activity_logs,
                            'date' => date('Y-m-d H:i:s'),
                        );
                        leads_activity_log($this, $insert_task_activity);
                        if ($borrower_type == 'Client') {
                            // add the app message 
                            $app_message = 'Please contact our office to discuss your ID Verification process.';
                            store_app_message_for_client($this, $lead_id, $app_message, 8);
                            // Send notification in mobile side
                            $notification_type = get_notification_type(1);
                            $client_notify_title = 'IDV Verification';
                            $client_notify_message = 'Please contact our office to discuss your ID Verification process';
                            send_notification_in_mobile('client', get_staff_user_id(), $contact_id, $client_id, $lead_id, $client_notify_title, $client_notify_message, $notification_type, '');
                        }
                    }
                } else if (!empty($idv_received) && $idv_received === 'no') {
                    $slack_message = 'IDV not received, email was sent to the client. Action performed by ' . get_staff_full_name() . '.';

                    $_POST['user_name'] = $get_lead_name;
                    $_POST['generic_email_title'] = '';
                    $_POST['generic_email_back_to_case_url'] = '';
                    $_POST['generic_email_content'] = $idv_received_no_tinymce;
                    $html_content_welcome_email_to_user = $this->load->view('admin/leads/Email_template/generic_email_template', $_POST, TRUE);

                    $subject = $get_mail_subject;
                    $replay_to_mail = get_all_staff_to_replay_email($this, get_staff_user_id(), $lead_data->assign_group, $to_idv_received_emails);

                    $send_email_result = send_mailchimp_email($to_idv_received_emails, $subject, $html_content_welcome_email_to_user, $replay_to_mail, $cc_idv_received_emails, $bcc_idv_received_emails, $lead_id);
                    // add the record for outbox emails 
                    $outbox_id = $this->Outbox_model->save_outbox_email(
                        $to_idv_received_emails,
                        $cc_idv_received_emails,
                        $bcc_idv_received_emails,
                        $subject,
                        $idv_received_no_tinymce,
                        '',
                        $lead_id,
                        8,
                        $html_content_welcome_email_to_user,
                        $replay_to_mail,
                        $send_email_result['status'],
                        $send_email_result['mandrill_id'],
                        1
                    );
                    // add the email in activity logs
                    $add_email_content_in_activity_logs = $idv_received_no_tinymce;
                    $insert_task_activity = array(
                        'leadid' => $lead_id,
                        'staffid' => get_staff_user_id(),
                        'full_name' => get_staff_full_name(),
                        'description' => get_staff_full_name() . " sent an email to " . $get_lead_name . ' <br>' . $add_email_content_in_activity_logs,
                        'date' => date('Y-m-d H:i:s'),
                    );
                    leads_activity_log($this, $insert_task_activity);
                    if ($borrower_type == 'Client') {
                        // add the app message 
                        $app_message = 'Please contact our office to discuss your ID Verification process.';
                        store_app_message_for_client($this, $lead_id, $app_message, 8);
                    }
                }
                $idv_second_question_sms = idv_received_text_sms($idv_received, $idv_received_pass, $get_all_clients_emails_count['borrower_count']);

                // $all_client_phone_list = get_all_client_phonenumber_using_lead_id($this, $lead_id);
                $all_client_phone_list = get_client_phonenumber_using_client_id_and_type($this, $lead_id, $borrower_type);
                $this->send_sms($all_client_phone_list, $idv_second_question_sms, $idv_second_question_sms, $lead_id, $get_lead_name, $get_lead_email);
            } else {
                $response = array(
                    'success' => false,
                );
            }
            // update the last contact date 
            $this->leads_model->update_leads_last_contact_date($lead_id);
            $this->output
                ->set_content_type('application/json')
                ->set_output(json_encode($response));
        } else {
            show_404();
        }
    }
    public function get_lawyers_by_firm()
    {
        $laywer_firm_id = $this->input->post('laywer_firm_id');

        // Validate firm ID
        if (!$laywer_firm_id) {
            echo json_encode(['success' => false, 'message' => 'Invalid Firm ID']);
            return;
        }

        // Query to fetch lawyers for the selected firm
        $this->db->select('id, CONCAT(firstname, " ", lastname) as name');
        $this->db->where('laywer_firm_id', $laywer_firm_id);
        $this->db->order_by('firstname', 'ASC');
        $lawyers = $this->db->get(db_prefix() . 'laywer')->result_array();

        // Respond with data or an appropriate message
        if (!empty($lawyers)) {
            echo json_encode(['success' => true, 'data' => $lawyers]);
        } else {
            echo json_encode(['success' => false, 'message' => 'No lawyers found for the selected firm.']);
        }
    }
    // send initial email to the laywer/lender
    public function ins_received_initial_email_to_laywer($lead_id)
    {
        $ins_received_initial_email_to_laywer_editorid = $this->input->post('ins_received_initial_email_to_laywer_editorid', FALSE);
        $to_ins_received_initial_laywer_emails = $this->input->post('to_ins_received_initial_laywer_emails');
        $cc_ins_received_initial_laywer_emails = $this->input->post('cc_ins_received_initial_laywer_emails');
        $bcc_ins_received_initial_laywer_emails = $this->input->post('bcc_ins_received_initial_laywer_emails');
        $to_emails = array_map('trim', explode(',', $to_ins_received_initial_laywer_emails));
        $cc_emails = array_map('trim', explode(',', $cc_ins_received_initial_laywer_emails));
        $bcc_emails = array_map('trim', explode(',', $bcc_ins_received_initial_laywer_emails));
        $get_mail_subject = get_mail_subject($this, $lead_id);
        if (!empty($ins_received_initial_email_to_laywer_editorid)) {
            $_POST['case_url'] = '';
            $_POST['generic_email_title'] = '';
            $_POST['generic_email_content_title'] = 'Good ' . get_afternoon_and_morning();
            $_POST['generic_email_back_to_case_url'] = '';
            $_POST['generic_email_content'] = $ins_received_initial_email_to_laywer_editorid;
            $_POST['general_attachment'] = '';
            $html_content_welcome_email_to_laywer = $this->load->view('admin/leads/Email_template/generic_email_template', $_POST, TRUE);

            $subject = $get_mail_subject;
            $assign_group = get_the_group_name_using_leadid($this, $lead_id);
            $replay_to_mail = get_all_staff_to_replay_email($this, get_staff_user_id(), $assign_group, $to_emails);
            $send_email_result = send_mailchimp_email($to_emails, $subject, $html_content_welcome_email_to_laywer, $replay_to_mail, $cc_emails, $bcc_emails, $lead_id);
            // add the record for outbox emails
            $outbox_id = $this->Outbox_model->save_outbox_email(
                $to_emails,
                $cc_emails,
                $bcc_emails,
                $subject,
                $ins_received_initial_email_to_laywer_editorid,
                '',
                $lead_id,
                2,
                $html_content_welcome_email_to_laywer,
                $replay_to_mail,
                $send_email_result['status'],
                $send_email_result['mandrill_id'],
                1
            );
            // add activity logs
            $insert_task_activity = array(
                'leadid' => $lead_id,
                'staffid' => get_staff_user_id(),
                'full_name' => get_staff_full_name(),
                'description' => get_staff_full_name() . " sent an email to (" . $to_ins_received_initial_laywer_emails . ') <br>' . $ins_received_initial_email_to_laywer_editorid,
                'date' => date('Y-m-d H:i:s'),
            );
            leads_activity_log($this, $insert_task_activity);
            // update the last contact date 
            $this->leads_model->update_leads_last_contact_date($lead_id);
            $response = array(
                'success' => true
            );
        } else {
            $response = array(
                'success' => false
            );
        }
        $this->output
            ->set_content_type('application/json')
            ->set_output(json_encode($response));
    }
    // send the emai to laywer/lender
    public function ins_received_email_to_laywer($lead_id)
    {
        $ins_received_email_to_laywer_editorid = $this->input->post('ins_received_email_to_laywer_editorid', FALSE);
        $to_ins_received_laywer_emails = $this->input->post('to_ins_received_laywer_emails');
        $cc_ins_received_laywer_emails = $this->input->post('cc_ins_received_laywer_emails');
        $bcc_ins_received_laywer_emails = $this->input->post('bcc_ins_received_laywer_emails');
        $to_emails = array_map('trim', explode(',', $to_ins_received_laywer_emails));
        $cc_emails = array_map('trim', explode(',', $cc_ins_received_laywer_emails));
        $bcc_emails = array_map('trim', explode(',', $bcc_ins_received_laywer_emails));
        $get_mail_subject = get_mail_subject($this, $lead_id);
        if (!empty($ins_received_email_to_laywer_editorid)) {
            $_POST['case_url'] = '';
            $_POST['generic_email_title'] = '';
            $_POST['generic_email_content_title'] = 'Good ' . get_afternoon_and_morning();
            $_POST['generic_email_back_to_case_url'] = '';
            $_POST['generic_email_content'] = $ins_received_email_to_laywer_editorid;
            $_POST['general_attachment'] = '';
            $html_content_welcome_email_to_laywer = $this->load->view('admin/leads/Email_template/generic_email_template', $_POST, TRUE);

            $subject = $get_mail_subject;
            $assign_group = get_the_group_name_using_leadid($this, $lead_id);
            $replay_to_mail = get_all_staff_to_replay_email($this, get_staff_user_id(), $assign_group, $to_emails);
            $send_email_result = send_mailchimp_email($to_emails, $subject, $html_content_welcome_email_to_laywer, $replay_to_mail, $cc_emails, $bcc_emails, $lead_id);
            // add the record for outbox emails
            $outbox_id = $this->Outbox_model->save_outbox_email(
                $to_emails,
                $cc_emails,
                $bcc_emails,
                $subject,
                $ins_received_email_to_laywer_editorid,
                '',
                $lead_id,
                2,
                $html_content_welcome_email_to_laywer,
                $replay_to_mail,
                $send_email_result['status'],
                $send_email_result['mandrill_id'],
                1
            );
            // add activity logs
            $insert_task_activity = array(
                'leadid' => $lead_id,
                'staffid' => get_staff_user_id(),
                'full_name' => get_staff_full_name(),
                'description' => get_staff_full_name() . " sent an email to (" . $to_ins_received_laywer_emails . ') <br>' . $ins_received_email_to_laywer_editorid,
                'date' => date('Y-m-d H:i:s'),
            );
            $activity_log_last_id = leads_activity_log($this, $insert_task_activity);
            // update the last contact date 
            $this->leads_model->update_leads_last_contact_date($lead_id);
            $response = array(
                'success' => true,
                'activity_log_last_id' => is_numeric($activity_log_last_id) ? $activity_log_last_id : ''
            );
        } else {
            $response = array(
                'success' => false
            );
        }
        $this->output
            ->set_content_type('application/json')
            ->set_output(json_encode($response));
    }
    // send the email to the client for primarlily email
    public function preliminary_email_to_client($lead_id)
    {
        $preliminary_instruction_received_editorid = $this->input->post('preliminary_instruction_received_editorid', FALSE);
        $to_preliminary_instruction_received = $this->input->post('to_preliminary_instruction_received');
        $cc_preliminary_instruction_received = $this->input->post('cc_preliminary_instruction_received');
        $bcc_preliminary_instruction_received = $this->input->post('bcc_preliminary_instruction_received');
        $to_emails = array_map('trim', explode(',', $to_preliminary_instruction_received));
        $cc_emails = array_map('trim', explode(',', $cc_preliminary_instruction_received));
        $bcc_emails = array_map('trim', explode(',', $bcc_preliminary_instruction_received));
        $get_mail_subject = get_mail_subject($this, $lead_id);
        if (!empty($preliminary_instruction_received_editorid)) {
            $_POST['case_url'] = '';
            $_POST['generic_email_title'] = '';
            $_POST['generic_email_content_title'] = '';
            $_POST['generic_email_back_to_case_url'] = '';
            $_POST['generic_email_content'] = $preliminary_instruction_received_editorid;
            $_POST['general_attachment'] = '';
            $html_content_welcome_email_to_laywer = $this->load->view('admin/leads/Email_template/generic_email_template', $_POST, TRUE);

            $subject = $get_mail_subject;
            $assign_group = get_the_group_name_using_leadid($this, $lead_id);
            $replay_to_mail = get_all_staff_to_replay_email($this, get_staff_user_id(), $assign_group, $to_emails);
            $send_email_result = send_mailchimp_email($to_emails, $subject, $html_content_welcome_email_to_laywer, $replay_to_mail, $cc_emails, $bcc_emails, $lead_id);
            // add the record for outbox emails
            $outbox_id = $this->Outbox_model->save_outbox_email(
                $to_emails,
                $cc_emails,
                $bcc_emails,
                $subject,
                $preliminary_instruction_received_editorid,
                '',
                $lead_id,
                2,
                $html_content_welcome_email_to_laywer,
                $replay_to_mail,
                $send_email_result['status'],
                $send_email_result['mandrill_id'],
                1
            );
            //  send sms to the client
            $msg = 'Please check your email for preliminary information you may begin gathering to progress your transaction. PLEASE DO NOT REPLY TO THIS TEXT.';
            $all_client_phone_list = get_all_client_phonenumber_using_lead_id($this, $lead_id);
            $check_sms_send = $this->send_sms($all_client_phone_list, $msg, $msg, $lead_id, '', '');
            // add activity logs
            $insert_task_activity = array(
                'leadid' => $lead_id,
                'staffid' => get_staff_user_id(),
                'full_name' => get_staff_full_name(),
                'description' => get_staff_full_name() . " sent an email to (" . $to_preliminary_instruction_received . ') <br>' . $preliminary_instruction_received_editorid,
                'date' => date('Y-m-d H:i:s'),
            );
            $activity_log_last_id = leads_activity_log($this, $insert_task_activity);
            // update the last contact date 
            $this->leads_model->update_leads_last_contact_date($lead_id);
            $response = array(
                'success' => true,
                'activity_log_last_id' => is_numeric($activity_log_last_id) ? $activity_log_last_id : ''
            );
        } else {
            $response = array(
                'success' => false
            );
        }
        $this->output
            ->set_content_type('application/json')
            ->set_output(json_encode($response));
    }
    // Ds Document notification
    public function ds_doc_approved_notification($lead_id)
    {
        // Send Slack notification
        $group_name = get_the_group_name_using_leadid($this, $lead_id);
        $lead_name = get_lead_name_using_lead_id($this, $lead_id);
        $lead_name = leads_splitFullName($lead_name);
        $slack_message = " \n- DS Good \n- The file was reviewed. \n- Prepare the Docusign to go out.";
        $send_notification = $this->slack->sendnotification($slack_message, $lead_id, $group_name, $lead_name['lastname'] . ', ' . $lead_name['firstname'] . ' ' . $lead_name['middlename']);
        // add activity logs
        $insert_task_activity = array(
            'leadid' => $lead_id,
            'staffid' => get_staff_user_id(),
            'full_name' => get_staff_full_name(),
            'description' => get_staff_full_name() . " has sent a Slack notification: DS Good approved and shared with the team.",
            'date' => date('Y-m-d H:i:s'),
        );
        leads_activity_log($this, $insert_task_activity);
        if ($send_notification) {
            $response = array(
                'success' => true,
                'message' => 'Slack notification send properly.'
            );
        } else {
            $response = array(
                'success' => false,
                'message' => $send_notification
            );
        }
        $this->output
            ->set_content_type('application/json')
            ->set_output(json_encode($response));
    }
    // upload instruction bank doc in dropbox
    public function instruction_attachment()
    {
        $bank_id = $this->input->post('bank_id');
        $custom_bank_name = $this->input->post('custom_bank_name');
        $description = $this->input->post('description');
        $lead_id = $this->input->post('lead_id');
        $this->db->select('email,status,name,assign_group,file_opened_completed_at,id_verification_completed_at');
        $this->db->where('id', $lead_id);
        $result = $this->db->get(db_prefix() . 'leads')->row();
        $getemail = $result->email;
        $data = $this->Token_model->getToken();
        $get_id = array_column($data, 'token');
        $access_token = implode(',', $get_id);
        $data = $this->Contacts_model->getEmail($getemail);
        $get_id = array_column($data, 'id');
        $get_userid = array_column($data, 'userid');
        $get_firstname = array_column($data, 'firstname');
        $get_lastname = array_column($data, 'lastname');
        $dropbox_firstname = implode(',', $get_firstname);
        $dropbox_lastname = implode(',', $get_lastname);
        $get_id = implode(',', $get_id);
        $userid = implode(',', $get_userid);
        $leadData = $this->leads_model->get_lead_id($get_id);
        $user_id = $leadData->id;
        $user_name = $leadData->name;
        if ($_SERVER['REQUEST_METHOD'] === 'POST') {
            // Get form data
            // $files = $_FILES['bank_file'];

            // Validate form data
            $this->form_validation->set_rules('bank_id', 'Bank ID', 'required');
            // $this->form_validation->set_rules('description', 'Description', 'required');

            if ($this->form_validation->run() === TRUE) {
                $laywer_firm_id = $this->input->post('laywer_firm_id');
                $laywer_id = $this->input->post('lawyer_id');
                if (!empty($laywer_id)) {
                    $lawyer_ids_string = implode(',', $laywer_id);
                } else {
                    $lawyer_ids_string = '';
                }
                if (!empty($custom_bank_name)) {
                    $custom_bank_data = array(
                        'bank_name' => $custom_bank_name
                    );
                    $this->db->insert(db_prefix() . 'bank', $custom_bank_data);
                    $insert_id_bank_name = $this->db->insert_id();
                    $instruction_date = array(
                        'lead_id' => $lead_id,
                        'laywer_firm_id' => $laywer_firm_id,
                        'laywer_id' => $lawyer_ids_string,
                        'bank_name' => $insert_id_bank_name,
                        'description' => $description,
                        'stage_id' => 2,
                        'created_at' => date('Y-m-d H:i:s')
                    );
                } else {
                    $instruction_date = array(
                        'lead_id' => $lead_id,
                        'laywer_firm_id' => $laywer_firm_id,
                        'laywer_id' => $lawyer_ids_string,
                        'bank_name' => $bank_id,
                        'description' => $description,
                        'stage_id' => 2,
                        'created_at' => date('Y-m-d H:i:s')
                    );
                }
                $this->db->insert(db_prefix() . 'instruction', $instruction_date);
                $insert_id_of_instruction = $this->db->insert_id();

                if (!empty($_FILES['bank_file']['name'])) {
                    foreach ($_FILES['bank_file']['name'] as $key => $name) {
                        $tmp_file = $_FILES['bank_file']['tmp_name'][$key];
                        if (is_uploaded_file($tmp_file)) {
                            $file_name = $_FILES['bank_file']['name'][$key];
                            $data = $this->leads_model->upload_to_dropbox($access_token, $tmp_file, $file_name, $user_id, $dropbox_firstname, $dropbox_lastname);
                            if ($data['status'] != 200) {
                                $this->leads_model->add_errors_logs($lead_id, get_staff_user_id(), get_staff_full_name(), 'Instruction stage documents uplaod', $data, $data['status'], 'Staff');
                                echo json_encode(
                                    array(
                                        'success' => false,
                                        'response' => $data
                                    )
                                );
                                exit;
                            }
                            $instruction_file_data = array(
                                'instruction_id' => $insert_id_of_instruction,
                                'file_name' => $data['file_name'],
                                'file_type' => $data['file_type'],
                                'file_url' => $data['file_url'],
                                'downnload_file_url' => $data['download_file_url'],
                                'created_at' => date('Y-m-d H:i:s')
                            );
                            $this->db->insert(db_prefix() . 'instruction_file', $instruction_file_data);
                        }
                    }
                }
                $this->db->select('*');
                $this->db->from(db_prefix() . 'instruction');
                $this->db->join(db_prefix() . 'instruction_file', db_prefix() . 'instruction.id = ' . db_prefix() . 'instruction_file.instruction_id', 'left');
                $this->db->where(db_prefix() . 'instruction.stage_id', 2);
                $query = $this->db->get();
                $save = $query->result_array();
                // add the data in lead activity log
                $insert_task_activity = array(
                    'leadid' => $lead_id,
                    'staffid' => get_staff_user_id(),
                    'full_name' => get_staff_full_name(),
                    'activity_type' => '',
                    'description' => "Instruction are stored by " . get_staff_full_name(),
                    'date' => date('Y-m-d H:i:s'),
                );
                leads_activity_log($this, $insert_task_activity);
                if ($result->id_verification_completed_at == null && $result->file_opened_completed_at == null) {
                    // send slack notification when idv stage complete
                    $lead_name = leads_splitFullName($result->name);
                    $slack_message = "\n - ID Incomplete \n - Send the ID incomplete update e-mail to broker.";

                    $this->slack->sendnotification($slack_message, $lead_id, $result->assign_group, $lead_name['lastname'] . ', ' . $lead_name['firstname'] . ' ' . $lead_name['middlename']);
                }
                // pass and refesh code in front end side
                $leads_status_value = '#instructions_received';
                $complete_stage_button = 2;
                $response = array(
                    'success' => true,
                    'message' => 'Data saved successfully',
                    'data' => $save,
                    'leads_status' => $leads_status_value,
                    'complete_stage_button' => $complete_stage_button,
                    'id' => $lead_id,
                    'leadView' => $this->_get_lead_data($lead_id),
                );
                // send the slack notification when 
                // When ID is in,
                // IDV not in,
                // Instructions is in
                if ($result->file_opened_completed_at != null && (get_idv_pass_count($this, $lead_id) == 0 && get_idv_pass_NA_count($this, $lead_id) == 0) && get_instruction_count($this, $lead_id) >= 0) {
                    // Send Slack notification
                    $group_name = get_the_group_name_using_leadid($this, $lead_id);
                    $lead_name = get_lead_name_using_lead_id($this, $lead_id);
                    $lead_split_name = leads_splitFullName($lead_name);
                    $slack_message = "\n – Offer in, IDV outstanding \n- chase client.";
                    $this->slack->sendnotification($slack_message, $lead_id, $group_name, $lead_split_name['lastname'] . ', ' . $lead_split_name['firstname'] . ' ' . $lead_name['middlename']);
                }
                // update the flag for instruction filter
                update_ins_in_record($this, $lead_id);
            } else {
                $response['status'] = 'error';
                $response['message'] = validation_errors();
            }
            // update the last contact date 
            $this->leads_model->update_leads_last_contact_date($lead_id);
            $this->output
                ->set_content_type('application/json')
                ->set_output(json_encode($response));
        } else {
            show_404();
        }
    }
    // show insturction data
    public function show_instruction_data($lead_id)
    {
        $this->db->select(
            db_prefix() . 'instruction.id as instruction_id, ' .
                db_prefix() . 'instruction_file.id as instruction_file_id, ' .
                db_prefix() . 'instruction.*, ' .
                db_prefix() . 'instruction_file.*, ' .
                db_prefix() . 'bank.id as bank_id, ' .
                db_prefix() . 'bank.bank_name, ' .
                db_prefix() . 'laywer_firm.id as laywer_firm_id, ' .
                db_prefix() . 'laywer_firm.name as laywer_firm_name, ' .
                "GROUP_CONCAT(CONCAT(" . db_prefix() . "laywer.firstname, ' ', " . db_prefix() . "laywer.lastname) SEPARATOR ', ') as laywer_names"
        );

        $this->db->from(db_prefix() . 'instruction');

        $this->db->join(
            db_prefix() . 'instruction_file',
            db_prefix() . 'instruction.id = ' . db_prefix() . 'instruction_file.instruction_id',
            'INNER'
        );

        $this->db->join(
            db_prefix() . 'bank',
            db_prefix() . 'bank.id = ' . db_prefix() . 'instruction.bank_name',
            'INNER'
        );

        $this->db->join(
            db_prefix() . 'laywer_firm',
            db_prefix() . 'laywer_firm.id = ' . db_prefix() . 'instruction.laywer_firm_id',
            'LEFT'
        );

        $this->db->join(
            db_prefix() . 'laywer',
            'FIND_IN_SET(' . db_prefix() . 'laywer.id, ' . db_prefix() . 'instruction.laywer_id)',
            'LEFT'
        );

        $this->db->where(db_prefix() . 'instruction.lead_id', $lead_id);
        $this->db->where(db_prefix() . 'instruction.stage_id', 2);

        $this->db->group_by(db_prefix() . 'instruction.id, ' . db_prefix() . 'instruction_file.id');

        $query = $this->db->get();

        $save = $query->result_array();

        $response = array(
            'success' => true,
            'message' => 'Data fetched successfully',
            'data' => $save,
        );

        $this->output
            ->set_content_type('application/json')
            ->set_output(json_encode($response));
    }

    // show id_verification data
    public function show_id_verification_data($lead_id)
    {
        $this->db->select(
            'tblinstruction.id as instruction_id, ' .
                'tblinstruction.created_at as instruction_created_at, ' .
                'tblinstruction_file.id as instruction_file_id, ' .
                'tblinstruction.*, ' .
                'tblinstruction_file.*'
        );
        $this->db->from('tblinstruction');
        $this->db->join('tblinstruction_file', 'tblinstruction.id = tblinstruction_file.instruction_id', 'LEFT');
        $this->db->where('tblinstruction.lead_id', $lead_id);
        $this->db->where('tblinstruction.borrower_id', $lead_id);
        $this->db->where('tblinstruction.borrower_type', 'Client');
        $this->db->where('tblinstruction.stage_id', 8);
        $this->db->order_by('tblinstruction.id', 'DESC');
        $query = $this->db->get();
        $save = $query->result_array();

        $response = array(
            'success' => true,
            'message' => 'Data fetch successfully',
            'data' => $save,
        );
        $this->output
            ->set_content_type('application/json')
            ->set_output(json_encode($response));
    }
    // show idv other clients data 
    public function show_idv_borrower_record($lead_id)
    {
        $this->db->select(
            'tblinstruction.id as instruction_id, ' .
                'tblinstruction.created_at as instruction_created_at, ' .
                'tblinstruction_file.id as instruction_file_id, ' .
                'tblinstruction.*, ' .
                'tblinstruction_file.*, ' .
                'tblleads_borrow.*, '
        );
        $this->db->from('tblinstruction');
        $this->db->join('tblinstruction_file', 'tblinstruction.id = tblinstruction_file.instruction_id', 'LEFT');
        $this->db->join('tblleads_borrow', 'tblinstruction.borrower_id = tblleads_borrow.id AND tblinstruction.borrower_type = "Borrower"', 'LEFT');
        $this->db->where('tblinstruction.lead_id', $lead_id);
        $this->db->where('tblinstruction.borrower_type', 'Borrower');
        $this->db->where('tblinstruction.stage_id', 8);
        $this->db->order_by('tblinstruction.id', 'DESC');
        $query = $this->db->get();
        $save = $query->result_array();

        $response = array(
            'success' => true,
            'message' => 'Data fetched successfully',
            'data' => $save,
        );
        $this->output
            ->set_content_type('application/json')
            ->set_output(json_encode($response));
    }
    // Delete the co-borrow records
    // delete borrower checklist files details
    public function delete_borrower_checklist_file($lead_id, $leads_borrow_id)
    {
        $check = false;
        // get the all files from tbltask against lead_id
        $this->db->select('id');
        $this->db->where('lead_borrow_id', $leads_borrow_id);
        $this->db->where('rel_id', $lead_id);
        $this->db->where('rel_type', 'user-task');
        $deleted_task_array = $this->db->get(db_prefix() . 'tasks')->result_array();
        // delete line of code
        $this->db->select('email');
        $this->db->where('id', $lead_id);
        $result = $this->db->get(db_prefix() . 'leads')->row();
        $getemail = $result->email;
        $data = $this->Token_model->getToken();
        $get_id = array_column($data, 'token');
        $access_token = implode(',', $get_id);
        $data = $this->Contacts_model->getEmail($getemail);
        $get_id = array_column($data, 'id');
        $get_userid = array_column($data, 'userid');
        $get_firstname = array_column($data, 'firstname');
        $get_lastname = array_column($data, 'lastname');
        $dropbox_firstname = implode(',', $get_firstname);
        $dropbox_lastname = implode(',', $get_lastname);
        $get_id = implode(',', $get_id);
        $userid = implode(',', $get_userid);
        $leadData = $this->leads_model->get_lead_id($get_id);
        $user_id = $leadData->id;
        $user_name = $leadData->name;

        // Process each task
        foreach ($deleted_task_array as $task_data) {
            // Get all file ids associated with the task
            $this->db->select('id');
            $this->db->where('rel_id', $lead_id);
            $this->db->where('task_id', $task_data['id']);
            $this->db->where('rel_type', 'client-doc');
            $file_array = $this->db->get(db_prefix() . 'files')->result_array();
            if (!empty($file_array)) {
                // Delete files from Dropbox
                foreach ($file_array as $file_data) {
                    $this->db->select('file_name');
                    $this->db->where('id', $file_data['id']);
                    $delete_file_data = $this->db->get(db_prefix() . 'files')->row();
                    if ($delete_file_data) {
                        $cleanedString = $delete_file_data->file_name;
                        $imagePath = '/uploads/' . $user_id . '_' . $dropbox_firstname . "_" . $dropbox_lastname . '/' . $cleanedString;
                        $responsedelete = $this->leads_model->deleteFile($access_token, $imagePath);
                        if ($responsedelete) {
                            $check = true;
                            $this->db->where('id', $file_data['id']);
                            $this->db->delete(db_prefix() . 'files');
                        }
                    }
                }
            } else {
                $check = true;
            }
        }
        return $check;
    }
    public function co_borrow_delete()
    {
        $leads_borrow_id = $this->input->post('id');
        $lead_id = $this->input->post('lead_id');
        if ($leads_borrow_id) {
            $check_borrower_file = $this->delete_borrower_checklist_file($lead_id, $leads_borrow_id);
            if ($check_borrower_file) {
                $this->leads_model->delete_borrower_checklist($lead_id, $leads_borrow_id);
                $deleted = $this->leads_model->delete_borrow_record($leads_borrow_id);
            }
            if ($deleted) {
                $response['success'] = true;
                $response['message'] = 'Record deleted successfully.';
                $response['leads_status'] = '#co_borrow';
                $response['lead_id'] = $lead_id;
                $response['leadView'] = $this->_get_lead_data($lead_id);
            } else {
                $response['success'] = false;
                $response['message'] = 'Failed to delete record.';
            }
        } else {
            $response['success'] = false;
            $response['message'] = 'ID not provided.';
        }
        $this->output
            ->set_content_type('application/json')
            ->set_output(json_encode($response));
    }

    // delete id verificaiton images 
    public function delete_id_verification_image()
    {
        $instrucion_file_id = $this->input->post('id');
        $lead_id = $this->input->post('lead_id');
        $this->db->select('email');
        $this->db->where('id', $lead_id);
        $result = $this->db->get(db_prefix() . 'leads')->row();
        $getemail = $result->email;
        $data = $this->Token_model->getToken();
        $get_id = array_column($data, 'token');
        $access_token = implode(',', $get_id);
        $data = $this->Contacts_model->getEmail($getemail);
        $get_id = array_column($data, 'id');
        $get_userid = array_column($data, 'userid');
        $get_firstname = array_column($data, 'firstname');
        $get_lastname = array_column($data, 'lastname');
        $dropbox_firstname = implode(',', $get_firstname);
        $dropbox_lastname = implode(',', $get_lastname);
        $get_id = implode(',', $get_id);
        $userid = implode(',', $get_userid);
        $leadData = $this->leads_model->get_lead_id($get_id);
        $user_id = $leadData->id;
        $user_name = $leadData->name;
        // get the delete file name for remove in dropbox
        $this->db->select('file_name,instruction_id');
        $this->db->where('id', $instrucion_file_id);
        $delete_file_data = $this->db->get(db_prefix() . 'instruction_file')->row();
        $cleanedString = '';
        if ($delete_file_data) {
            $cleanedString = $delete_file_data->file_name;
            $instrucion_id = $delete_file_data->instruction_id;
        }
        // delete record from database
        $this->db->where('id', $instrucion_file_id);
        $success = $this->db->delete(db_prefix() . 'instruction_file');
        // $this->db->where('id', $instrucion_id);
        // $success = $this->db->delete(db_prefix() . 'instruction');
        // add the data in lead activity log
        $insert_task_activity = array(
            'leadid' => $lead_id,
            'staffid' => get_staff_user_id(),
            'full_name' => get_staff_full_name(),
            'activity_type' => '',
            'description' => "ID verification Doc are removed by " . get_staff_full_name(),
            'date' => date('Y-m-d H:i:s'),
        );
        leads_activity_log($this, $insert_task_activity);
        // delete record from dropbox
        $imagePath = '/uploads/' . $user_id . '_' . $dropbox_firstname . "_" . $dropbox_lastname . '/' . $cleanedString;

        $responsedelete = $this->leads_model->deleteFile($access_token, $imagePath);
        if ($success) {
            $response = array(
                'success' => true,
                'message' => 'ID verification Doc deleted successfully.'
            );
            $leads_status_value = '#id_verification';
            $complete_stage_button = 8;
            $response = array(
                'success' => true,
                'leads_status' => $leads_status_value,
                'complete_stage_button' => $complete_stage_button,
                'id' => $lead_id,
                'leadView' => $this->_get_lead_data($lead_id),
            );
        } else {
            $response = array(
                'success' => false,
                'message' => 'Failed to delete Id verification Doc.'
            );
        }
        $this->output
            ->set_content_type('application/json')
            ->set_output(json_encode($response));
    }
    // delete instruction images
    public function delete_instruction_image()
    {
        $instrucion_file_id = $this->input->post('id');
        $lead_id = $this->input->post('lead_id');
        $this->db->select('email');
        $this->db->where('id', $lead_id);
        $result = $this->db->get(db_prefix() . 'leads')->row();
        $getemail = $result->email;
        $data = $this->Token_model->getToken();
        $get_id = array_column($data, 'token');
        $access_token = implode(',', $get_id);
        $data = $this->Contacts_model->getEmail($getemail);
        $get_id = array_column($data, 'id');
        $get_userid = array_column($data, 'userid');
        $get_firstname = array_column($data, 'firstname');
        $get_lastname = array_column($data, 'lastname');
        $dropbox_firstname = implode(',', $get_firstname);
        $dropbox_lastname = implode(',', $get_lastname);
        $get_id = implode(',', $get_id);
        $userid = implode(',', $get_userid);
        $leadData = $this->leads_model->get_lead_id($get_id);
        $user_id = $leadData->id;
        $user_name = $leadData->name;
        // get the delete file name for remove in dropbox
        $this->db->select('file_name,instruction_id');
        $this->db->where('id', $instrucion_file_id);
        $delete_file_data = $this->db->get(db_prefix() . 'instruction_file')->row();
        $cleanedString = '';
        if ($delete_file_data) {
            $cleanedString = $delete_file_data->file_name;
            $instrucion_id = $delete_file_data->instruction_id;
        }
        // delete record from database
        $this->db->where('id', $instrucion_file_id);
        $success = $this->db->delete(db_prefix() . 'instruction_file');
        // add the data in lead activity log
        $insert_task_activity = array(
            'leadid' => $lead_id,
            'staffid' => get_staff_user_id(),
            'full_name' => get_staff_full_name(),
            'activity_type' => '',
            'description' => "Instruction image are removed by " . get_staff_full_name(),
            'date' => date('Y-m-d H:i:s'),
        );
        leads_activity_log($this, $insert_task_activity);
        // delete record from dropbox
        $imagePath = '/uploads/' . $user_id . '_' . $dropbox_firstname . "_" . $dropbox_lastname . '/' . $cleanedString;

        $responsedelete = $this->leads_model->deleteFile($access_token, $imagePath);
        if ($success) {
            $response = array(
                'success' => true,
                'message' => 'Instruction file deleted successfully.'
            );
            $leads_status_value = '#instructions_received';
            $complete_stage_button = 2;
            $response = array(
                'success' => true,
                'leads_status' => $leads_status_value,
                'complete_stage_button' => $complete_stage_button,
                'id' => $lead_id,
                'leadView' => $this->_get_lead_data($lead_id),
            );
        } else {
            $response = array(
                'success' => false,
                'message' => 'Failed to delete instruction file.'
            );
        }
        $this->output
            ->set_content_type('application/json')
            ->set_output(json_encode($response));
    }
    public function checklist_template($id = '')
    {
        // get the data of leads status
        $lead_status_data = get_ids_leads_status($this);
        $this->db->select('*');
        $this->db->order_by('id', 'desc');
        $checklist_templates = $this->db->get(db_prefix() . 'checklist_templates')->result_array();
        if ($id) {
            // get the checklist template data
            $this->db->select('id,order_no,type,case_status,title,doc_type,description,instruction');
            $this->db->where('id', $id);
            $checklist_templates_formdata = $this->db->get(db_prefix() . 'checklist_templates')->row();
            // add the checklist doc_type
            if ($checklist_templates_formdata->doc_type) {
                $doc_array = ['Png' => 1, 'Pdf' => 2, 'Jpeg' => 3, 'Zip' => 4, 'HEIC' => 5];
                $file_instructions = explode(',', $checklist_templates_formdata->doc_type);
                $matched_ids = [];

                foreach ($file_instructions as $instruction) {
                    $file_type = ucfirst(trim($instruction));
                    if (isset($doc_array[$file_type])) {
                        $matched_ids[] = $doc_array[$file_type];
                    }
                }
            }
            // Convert the array to a comma-separated string
            $instructionLines = explode("\n", $checklist_templates_formdata->instruction);
            $trimmedLines = [];

            foreach ($instructionLines as $line) {
                $trimmedLine = trim($line);

                if ($trimmedLine !== "") {
                    $trimmedLines[] = $trimmedLine;
                }
            }
            $valueProcessed = str_replace("\n\n", "\n", $checklist_templates_formdata->instruction);
            $cleanedText = str_replace(["\n", '<br>', '<br/>', '<br />'], '<br>', $checklist_templates_formdata->instruction);
            // checklist type 
            $checklist_type = $checklist_templates_formdata->type;
            //  add the file status 
            $this->load->view('admin/checklist/checklist_template', ['lead_status_data' => $lead_status_data, 'checklist_templates' => $checklist_templates, 'checklist_templates_formdata' => $checklist_templates_formdata, 'doc_id' => $matched_ids, 'instruction' => $cleanedText, 'checklist_type' => $checklist_type]);
        } else {
            $this->load->view('admin/checklist/checklist_template', ['lead_status_data' => $lead_status_data, 'checklist_templates' => $checklist_templates]);
        }
    }
    // add the checklist template 
    public function add_checklist_template($id = '')
    {
        $this->load->library('user_agent');
        $checklist_order = $this->input->post('checklist_order');
        $name = $this->input->post('name');
        $checklist_description = $this->input->post('checklist_description');
        $lead_status = $this->input->post('lead_status');
        $doc_type = $this->input->post('doc_type');
        if (is_array($doc_type) && !empty($doc_type)) {
            $doc_type_string = implode(',', $doc_type);
        }
        $checklist_instruction = $this->input->post('checklist_instruction');
        $checklist_instruction_new = str_replace(['<br />', '<br>', '<br/>'], "\n", nl2br($checklist_instruction));
        // Define validation rules

        $this->form_validation->set_rules('name', 'Checklist Title', 'required|min_length[3]|max_length[50]');
        $this->form_validation->set_rules('checklist_description', 'Checklist Description', 'required');
        $this->form_validation->set_rules('checklist_instruction', 'Checklist Instruction', 'required');
        $this->form_validation->set_rules('checklist_order', 'Checklist order', 'required');
        $this->form_validation->set_rules('lead_status', 'File status', 'required');
        $this->form_validation->set_rules('doc_type[]', 'Doc Type', 'required');
        // check the validation of checklist order
        if (!empty($id)) {
            // this check is se when update the template
            $this->db->select('id, order_no, case_status');
            $this->db->where_in('order_no', $checklist_order);
            $this->db->where('case_status', $lead_status);
            $this->db->where_not_in('id', $id);
            $query = $this->db->get(db_prefix() . 'checklist_templates');
        } else {
            // this check is run before add the template
            $this->db->select('id, order_no, case_status');
            $this->db->where('order_no', $checklist_order);
            $this->db->where('case_status', $lead_status);
            $query = $this->db->get(db_prefix() . 'checklist_templates');
        }
        if ($query->num_rows() > 0) {
            set_alert('danger', 'Checklist order No must be unique,please use another order no.');
            redirect($_SERVER['HTTP_REFERER']);
            exit;
        } else {
            // Run form validation
            if ($this->form_validation->run() == false) {
                $validation_errors = validation_errors();
                // Validation failed
                set_alert('danger', 'Please fill the form properly. Some fields are empty and not properly filled.');
            } else {
                $task_data = [
                    'order_no' => $checklist_order,
                    'case_status' => $lead_status,
                    'title' => $name,
                    'doc_type' => $doc_type_string,
                    'description' => $checklist_description,
                    'instruction' => $checklist_instruction_new,
                ];
                if (!empty($id)) {
                    $this->db->where('id', $id);
                    $save = $this->db->update(db_prefix() . 'checklist_templates', $task_data);
                    if ($save) {
                        set_alert('success', 'Checklist is update successfully.');
                    } else {
                        set_alert('danger', 'Failed to update checklist. Please try again.');
                    }
                } else {
                    $save = $this->db->insert(db_prefix() . 'checklist_templates', $task_data);
                    if ($save) {
                        set_alert('success', 'Checklist is created successfully.');
                    } else {
                        set_alert('danger', 'Failed to save checklist. Please try again.');
                    }
                }
            }
            redirect($_SERVER['HTTP_REFERER']);
        }
    }
    // add closeing stage daily Morning/evening tasks
    public function add_daily_task()
    {
        $task_type = $this->input->post('task_type');
        $task_value = $this->input->post('task_value');

        if (!empty($task_type) && !empty($task_value)) {

            $store_task = array(
                'name' => $task_value,
                'rel_id' => '0',
                'type' => 'bob-daily-' . $task_type . '-task',
                'dateadded' => date('Y-m-d H:i:s'),
            );

            $this->db->insert(db_prefix() . 'tasks', $store_task);
            $insert_id = $this->db->insert_id();
            $store_task['id'] = $insert_id;
            if ($this->db->affected_rows() > 0) {

                $response = array(
                    'success' => true,
                    'message' => 'Task added successfully.',
                    'data' => $store_task,
                );
            } else {
                $response = array(
                    'success' => false,
                    'message' => 'Failed to insert task.',
                );
            }
        } else {
            $response = array(
                'success' => false,
                'message' => 'Task type and value are required.',
            );
        }

        $this->output
            ->set_content_type('application/json')
            ->set_output(json_encode($response));
    }
    public function get_daily_tasks()
    {
        $this->output
            ->set_content_type('application/json')
            ->set_output(json_encode([
                'success' => true,
                'data' => $this->db
                    ->select('id, name, dateadded, type, checkbox_status, staff_ids, order_no')
                    ->order_by('order_no', 'ASC')
                    ->get_where(db_prefix() . 'tasks', "type LIKE 'bob-daily-%-task'")
                    ->result_array()
            ]));
    }

    // update the daily task status
    public function update_daily_task_status()
    {
        $task_id = $this->input->post('task_id');
        $checked = $this->input->post('checked');

        if (!empty($task_id)) {
            $update_record = [
                'checkbox_status' => $checked
            ];

            $this->db->where('id', $task_id);
            $this->db->update(db_prefix() . 'tasks', $update_record);

            if ($this->db->affected_rows() > 0) {
                $response = [
                    'success' => true,
                    'message' => 'Task status updated successfully.'
                ];
            } else {
                $response = [
                    'success' => false,
                    'message' => 'No changes were made.'
                ];
            }
        } else {
            $response = [
                'success' => false,
                'message' => 'Task ID is required.'
            ];
        }

        $this->output
            ->set_content_type('application/json')
            ->set_output(json_encode($response));
    }
    public function update_daily_task_order()
    {
        $morning_order = json_decode($this->input->post('morning_order'), true);
        $evening_order = json_decode($this->input->post('evening_order'), true);
        
        // Morning list update
        if (!empty($morning_order)) {
            foreach ($morning_order as $task) {
                if (!empty($task['id']) && isset($task['order_no'])) {
                    $this->db->where('id', (int)$task['id'])
                            ->update(db_prefix() . 'tasks', [
                                'order_no' => (int)$task['order_no'],
                                'type'     => 'bob-daily-morning-task'
                            ]);
                }
            }
        }

        // Evening list update
        if (!empty($evening_order)) {
            foreach ($evening_order as $task) {
                if (!empty($task['id']) && isset($task['order_no'])) {
                    $this->db->where('id', (int)$task['id'])
                            ->update(db_prefix() . 'tasks', [
                                'order_no' => (int)$task['order_no'],
                                'type'     => 'bob-daily-evening-task'
                            ]);
                }
            }
        }

        $this->output
            ->set_content_type('application/json')
            ->set_output(json_encode(['success' => true]));
    }





    // delete daily custom task
    public function delete_daily_custom_task()
    {
        $task_id = $this->input->post('task_id');

        if ($task_id) {
            $this->db->where('id', $task_id);
            $this->db->delete(db_prefix() . 'tasks');

            $success = $this->db->affected_rows() > 0;

            $response = [
                'success' => $success,
                'message' => $success ? 'Task deleted successfully.' : 'Task not found or already deleted.'
            ];
        } else {
            $response = [
                'success' => false,
                'message' => 'Task ID is missing.'
            ];
        }

        $this->output
            ->set_content_type('application/json')
            ->set_output(json_encode($response));
    }
    // update the staffids for daily chasers detilas
    public function custom_daily_chaser_assign_staff_to_task()
    {
        $task_id = $this->input->post('task_id');
        $staff_ids = $this->input->post('staff_ids');

        $staff_ids_string = is_array($staff_ids) ? implode(',', $staff_ids) : '';

        $update_record = [
            'staff_ids' => $staff_ids_string
        ];

        $this->db->where('id', $task_id);
        $this->db->update(db_prefix() . 'tasks', $update_record);

        if ($this->db->affected_rows() > 0) {
            $response = ['success' => true, 'message' => 'Staff assigned successfully.'];
        } else {
            $response = ['success' => false, 'message' => 'No changes made or invalid task ID.'];
        }

        $this->output
            ->set_content_type('application/json')
            ->set_output(json_encode($response));
    }
    // get the all staff record 
    public function get_all_ldteam_record()
    {
        $task_id = $this->input->post('task_id');
        $team_record = get_ld_team_staff_record($this);
        $selected_team_record = [];

        if (!empty($task_id)) {
            $this->db->select('staff_ids');
            $this->db->where('id', $task_id);
            $custom_chaser_task_record = $this->db->get(db_prefix() . 'tasks')->row();
            if ($custom_chaser_task_record && !empty($custom_chaser_task_record->staff_ids)) {
                $selected_team_record = explode(',', $custom_chaser_task_record->staff_ids);
            }
        }


        if (!empty($team_record)) {
            foreach ($team_record as &$record) {
                $record['image'] = get_staff_profile_url($record['staffid'], $record['profile_image']);
            }

            $response = array(
                'success' => true,
                'data' => $team_record,
                'selected_staff_ids' => $selected_team_record
            );
        } else {
            $response = array(
                'success' => false,
                'data' => null
            );
        }

        $this->output
            ->set_content_type('application/json')
            ->set_output(json_encode($response));
    }
    // Edit custom daily chaser record
    public function update_daily_custom_chaser_record()
    {
        $task_id = $this->input->post('task_id');
        $task_name = $this->input->post('task_name');
        if (!empty($task_id) && !empty($task_name)) {
            $update_record = [
                'name' => $task_name
            ];
            $this->db->where('id', $task_id);
            $this->db->update(db_prefix() . 'tasks', $update_record);

            if ($this->db->affected_rows() > 0) {
                $response = array(
                    'success' => true,
                    'message' => 'Task updated successfully.'
                );
            } else {
                $response = array(
                    'success' => false,
                    'message' => 'No changes were made or invalid task ID.'
                );
            }
        } else {
            $response = array(
                'success' => false,
                'message' => 'Task ID and Task name are required.'
            );
        }
        $this->output
            ->set_content_type('application/json')
            ->set_output(json_encode($response));
    }


    // delete the checklist template
    function delete_checklist_template()
    {
        $id = $this->input->post('checklistId');
        $this->db->where('id', $id);
        $this->db->delete(db_prefix() . 'checklist_templates');
        // Check if the deletion was successful
        if ($this->db->affected_rows() > 0) {
            $response = array(
                'status' => 'success',
                'message' => 'Tasks deleted successfully'
            );
        } else {
            $response = array(
                'status' => 'error',
                'message' => 'No tasks found for deletion'
            );
        }
        echo json_encode($response);
        exit();
    }
    // get the checklist value by id 
    public function get_checklist_template_data()
    {
        $order_no = $this->input->post('order_no');
        $current_stage_status = $this->input->post('current_stage_status');
        if ($current_stage_status == 4) {
            $this->db->select('id,title,doc_type,description,instruction');
            $this->db->where('addedfrom', $order_no);
            $this->db->where('type', 'ld_team');
            $this->db->where('case_status', $current_stage_status);
            $data = $this->db->get(db_prefix() . 'checklist_templates')->result_array();
        } else {
            $this->db->select('id,title,doc_type,description,instruction');
            $this->db->where('addedfrom', $order_no);
            $this->db->where('type', 'client');
            $this->db->where('case_status', $current_stage_status);
            $data = $this->db->get(db_prefix() . 'checklist_templates')->result_array();
        }
        if (!empty($data)) {
            $response = array(
                'status' => 'success',
                'data' => $data
            );
        } else {
            $response = array(
                'status' => 'error',
                'data' => null
            );
        }
        echo json_encode($response);
    }
    // get the checklist template data for file opened for broker
    public function get_checklist_template_data_file_opened_for_broker()
    {
        $order_no = $this->input->post('order_no');
        $current_stage_status = $this->input->post('current_stage_status');
        $this->db->select('id,title,doc_type,description,instruction');
        $this->db->where('addedfrom', $order_no);
        $this->db->where('type', 'broker');
        $this->db->where('case_status', 1);
        $data = $this->db->get(db_prefix() . 'checklist_templates')->result_array();
        if (!empty($data)) {
            $response = array(
                'status' => 'success',
                'data' => $data
            );
        } else {
            $response = array(
                'status' => 'error',
                'data' => null
            );
        }
        echo json_encode($response);
    }
    public function get_checklist_template_data_for_outstanding_ld_team()
    {
        $order_no = $this->input->post('order_no');
        $current_stage_status = $this->input->post('current_stage_status');
        $this->db->select('id,title,doc_type,description,instruction');
        $this->db->where('addedfrom', $order_no);
        $this->db->where('case_status', $current_stage_status);
        $this->db->where('type', 'ld_team');
        $data = $this->db->get(db_prefix() . 'checklist_templates')->result_array();
        if (!empty($data)) {
            $response = array(
                'status' => 'success',
                'data' => $data
            );
        } else {
            $response = array(
                'status' => 'error',
                'data' => null
            );
        }
        echo json_encode($response);
    }
    // checklist template add for the outstanding ld team
    public function checklist_template_add_in_task_table_for_ld_team_outstanding()
    {
        $checklist_template_ids = $this->input->get('id');
        $lead_id = $this->input->get('lead_id');
        $current_stage_id = $this->input->get('current_stage_id');
        foreach ($checklist_template_ids as $checklist_template_id) {
            // Get the data of checklist template
            $this->db->where('id', $checklist_template_id);
            $this->db->select('order_no, case_status, type, title, doc_type,Item_name, description, instruction, created_on');
            $checklist_template_data = $this->db->get(db_prefix() . 'checklist_templates')->row();
            // insert record in case checkboxes
            $task_data = [
                'title' => $checklist_template_data->title,
                'description' => $checklist_template_data->description,
                'created_at' => date('Y-m-d H:i:s'),
                'lead_id' => $lead_id,
                'leads_status' => $checklist_template_data->case_status,
                'type' => $checklist_template_data->type,
            ];
            $this->db->insert(db_prefix() . 'cases_checkboxes', $task_data);
            $inserted_id = $this->db->insert_id();
        }
        if (!empty($inserted_id)) {
            // set url properly
            switch ($current_stage_id) {
                case 1:
                    $leads_status_value = '#file_opened';
                    $complete_stage_button = 1;
                    break;
                case 2:
                    $leads_status_value = '#instructions_received';
                    $complete_stage_button = 2;
                    break;
                case 3:
                    $leads_status_value = '#outstanding_items';
                    $complete_stage_button = 3;
                    break;
                case 4:
                    $leads_status_value = '#request_for_funds';
                    $complete_stage_button = 4;
                    break;
                default:
                    $leads_status_value = '';
                    break;
            }
            $redirect_url = admin_url('cases/index/' . $lead_id . $leads_status_value);
            redirect($redirect_url, 'refresh');
        }
    }
    // Checklist template data add in Tbltask and tbl file instruction file
    public function checklist_template_add_in_task_table()
    {
        $checklist_template_ids = $this->input->get('id');
        $lead_id = $this->input->get('lead_id');
        $current_stage_id = $this->input->get('current_stage_id');
        // Loop through each checklist template ID
        foreach ($checklist_template_ids as $checklist_template_id) {
            // Get the data of checklist template
            $this->db->where('id', $checklist_template_id);
            $this->db->select('order_no, case_status, title, type, doc_type,Item_name, description, instruction, created_on');
            $checklist_template_data = $this->db->get(db_prefix() . 'checklist_templates')->row();
            if ($current_stage_id == 1 || $current_stage_id == 3) {
                // Insert task data
                $task_data = [
                    'name' => $checklist_template_data->title,
                    'description' => $checklist_template_data->description,
                    'status' => '2',
                    'dateadded' => date('Y-m-d H:i:s'),
                    'rel_id' => $lead_id,
                    'rel_type' => 'user-task',
                    'Item_name' => $checklist_template_data->Item_name,
                    'leads_status' => $checklist_template_data->case_status,
                    'type' => $checklist_template_data->type,
                ];
                $this->db->insert(db_prefix() . 'tasks', $task_data);
                $task_id = $this->db->insert_id();

                // Insert file instruction data
                $file_instruction_data = [
                    'lead_id' => $lead_id,
                    'task_id' => $task_id,
                    'instruction' => $checklist_template_data->instruction,
                    'doc_type' => $checklist_template_data->doc_type,
                    'created_at' => date('Y-m-d H:i:s'),
                    'updated_by' => '',
                ];
                $this->db->insert(db_prefix() . 'file_instruction', $file_instruction_data);
                $inserted_id = $this->db->insert_id();
            } else {
                $task_data = [
                    'title' => $checklist_template_data->title,
                    'description' => $checklist_template_data->description,
                    'created_at' => date('Y-m-d H:i:s'),
                    'lead_id' => $lead_id,
                    'leads_status' => $checklist_template_data->case_status,
                ];
                $this->db->insert(db_prefix() . 'cases_checkboxes', $task_data);
                $inserted_id = $this->db->insert_id();
            }
            // Convert instruction to new format
            $checklist_instruction_new = str_replace(['<br />', '<br>', '<br/>'], "\n", nl2br($checklist_template_data->instruction));
        }
        // Check if the data was inserted successfully
        if (!empty($inserted_id)) {
            // Add lead activtiy when checklist is created by admin

            if ($current_stage_id == 1 || $current_stage_id == 3) {
                // Loop through each checklist template ID
                foreach ($checklist_template_ids as $checklist_template_id) {
                    $this->db->where('id', $checklist_template_id);
                    $this->db->select('order_no, case_status, title, doc_type, description, instruction, created_on');
                    $checklist_template_data = $this->db->get(db_prefix() . 'checklist_templates')->row();
                    $add_activity_data = [
                        'leadid' => $lead_id,
                        'staffid' => get_staff_user_id(),
                        'full_name' => get_staff_full_name(),
                        'description' => 'Checklist - (' . $checklist_template_data->title . ') by template has been created successfully.',
                        'date' => date('Y-m-d H:i:s'),
                    ];
                    $this->db->insert(db_prefix() . 'lead_activity_log', $add_activity_data);
                    // Get the data of checklist template
                    $this->db->where('id', $checklist_template_id);
                    $this->db->select('order_no, case_status,type, title, doc_type, description, instruction, created_on');
                    $checklist_template_data2 = $this->db->get(db_prefix() . 'checklist_templates')->row();
                    $checklist_instruction_new2 = str_replace(['<br />', '<br>', '<br/>'], "\n", nl2br($checklist_template_data2->instruction));
                    // notificaation line of code 
                    $this->db->select('id,multiple_cases,client_id,phonenumber');
                    $this->db->where('id', $lead_id);
                    $lead_data_check = $this->db->get(db_prefix() . 'leads');
                    if ($lead_data_check->num_rows() > 0) {
                        $lead_data = $lead_data_check->row();
                        $client_id = get_client_id_using_contact_id($this, $lead_data->client_id, $lead_data->multiple_cases);
                        $contact_id = get_contact_id_using_client_id($this, $client_id);
                        $notification_type = get_notification_type(2);
                        $checklist_instruction_new2 = preg_replace('/^\s*(\S.*)$/m', '• $1', $checklist_instruction_new2);
                        if ($checklist_template_data2->type == 'client') {
                            // add_alerts_user($values);
                            $client_notification_type = $notification_type . '-created';
                            $client_notify_title = 'Checklist (' . $checklist_template_data2->title . ') created';
                            $client_notify_message = "This is Legal Direct. To progress your transaction, please return \n $checklist_instruction_new2  ";
                            send_notification_in_mobile('client', get_staff_user_id(), $contact_id, $client_id, $lead_id, $client_notify_title, $client_notify_message, $client_notification_type, $task_id);
                        }
                    }
                }
            }
            // set url properly
            switch ($current_stage_id) {
                case 1:
                    $leads_status_value = '#file_opened';
                    $complete_stage_button = 1;
                    break;
                case 2:
                    $leads_status_value = '#instructions_received';
                    $complete_stage_button = 2;
                    break;
                case 3:
                    $leads_status_value = '#outstanding_items';
                    $complete_stage_button = 3;
                    break;
                case 4:
                    $leads_status_value = '#request_for_funds';
                    $complete_stage_button = 4;
                    break;
                default:
                    $leads_status_value = '';
                    break;
            }
            $redirect_url = admin_url('cases/index/' . $lead_id . $leads_status_value);
            redirect($redirect_url, 'refresh');
        }
    }
    public function refresh_page_load()
    {
        $lead_id = $this->input->post('lead_id');
        $stage_id = $this->input->post('leads_status_current_id');
        // Initialize variables
        $leads_status_value = '';
        $complete_stage_button = '';
        switch ($stage_id) {
            case 1:
                $leads_status_value = '#file_opened';
                $complete_stage_button = 1;
                break;
            case 2:
                $leads_status_value = '#instructions_received';
                $complete_stage_button = 2;
                break;
            case 3:
                $leads_status_value = '#outstanding_items';
                $complete_stage_button = 3;
                break;
            case 4:
                $leads_status_value = '#request_for_funds';
                $complete_stage_button = 4;
                break;
            case 5:
                $leads_status_value = '#Closed';
                $complete_stage_button = 5;
                break;
            case 6:
                $leads_status_value = '#on_hold';
                $complete_stage_button = 6;
                break;
            case 7:
                $leads_status_value = '#lead_reminders';
                $complete_stage_button = 8;
                break;
            case 8:
                $leads_status_value = '#id_verification';
                $complete_stage_button = 8;
                break;
            default:
                // Handle default case
                break;
        }
        // Prepare response data
        $response = array(
            'success' => true,
            'message' => 'Data saved successfully',
            'leads_status' => $leads_status_value,
            'complete_stage_button' => $complete_stage_button,
            'id' => $lead_id,
            'leadView' => $this->_get_lead_data($lead_id),
        );

        // Set JSON response
        $this->output
            ->set_content_type('application/json')
            ->set_output(json_encode($response));
    }
    // summery refresh page
    public function summery_refresh_page_load()
    {
        $lead_id = $this->input->post('lead_id');
        $response = array(
            'success' => true,
            'message' => 'Data saved successfully',
            'leads_status' => '#summary',
            'id' => $lead_id,
            'leadView' => $this->_get_lead_data($lead_id),
        );

        // Set JSON response
        $this->output
            ->set_content_type('application/json')
            ->set_output(json_encode($response));
    }

    // Checklist Complete stage
    public function checklist_complete_stage()
    {
        $stage_id = $this->input->post('stage_id');
        $lead_id = $this->input->post('lead_id');
        $get_idv_pass_count = get_idv_pass_count($this, $lead_id);
        $get_idv_pass_NA_count = get_idv_pass_NA_count($this, $lead_id);
        $get_instruction_count = get_instruction_count($this, $lead_id);
        // update/insert broker fee agrremnt key before complete the outstanding stage
        $broker_fee_key = has_broker_fee_agreement_doc_or_note($this, $lead_id);
        $stage_name = '';
        // if (($get_idv_pass_count == 0 || $get_idv_pass_NA_count == 0) && ($stage_id == 7 || $stage_id == 2)) {
        // simple complete stages scanario for idv not Pass or N\A and instruction is in 
        if (
            (empty($get_idv_pass_count) || $get_idv_pass_count == 0) &&
            (empty($get_idv_pass_NA_count) || $get_idv_pass_NA_count == 0) &&
            $stage_id == 8
        ) {
            $response = [
                'success' => false,
                'idv_not_pass' => false,
            ];
            echo json_encode($response);
            return;
        }

        // if secure payout not have a expire date  thenn not complete stage
        if (get_expire_date_added_or_not_all_secure_items($this, $lead_id) === false && $stage_id == 3) {
            $response = [
                'success' => false,
                'payout_expire_date' => get_expire_date_added_or_not_all_secure_items($this, $lead_id),
            ];
            echo json_encode($response);
            return;
        }
        // if ($stage_id == 3) {
        //     if($broker_fee_key['has_doc'] == false){
        //         $response = [
        //             'success' => false,
        //             'file_doc_key' => $broker_fee_key['file_doc_key'],
        //             'ld_notes_key' => $broker_fee_key['ld_notes_key'],
        //             'leads_status' => 3
        //         ];
        //         echo json_encode($response);
        //         return;
        //     }
        // }  


        if ($stage_id == 1) {
            $stage_id = 8;
            $stage_name = 'File opened';
            $stage_description = 'Great news, your transaction has passed through another milestone.';
            $data = array(
                'status' => $stage_id,
                'file_opened_completed' => 1,
                'last_status_change' => date('Y-m-d H:i:s'),
                'file_opened_completed_at' => date('Y-m-d H:i:s'),
                'id_verification_started_at' => date('Y-m-d H:i:s'),
            );
        } elseif ($stage_id == 2) {
            $stage_id = 7;
            $stage_name = 'Instruction receive';
            $stage_description = 'Great news, your transaction has passed through another milestone.';
            $data = array(
                'status' => $stage_id,
                'ins_received_completed' => 1,
                'last_status_change' => date('Y-m-d H:i:s'),
                'ins_received_completed_at' => date('Y-m-d H:i:s'),
                'app_request_started_at' => date('Y-m-d H:i:s'),
            );
        } elseif ($stage_id == 3) {
            $stage_id = $stage_id + 1;
            $stage_name = 'Outstanding items';
            $stage_description = 'Great news, your transaction has passed through another milestone.';
            $data = array(
                'status' => $stage_id,
                'out_items_completed' => 1,
                'last_status_change' => date('Y-m-d H:i:s'),
                'outstanding_item_completed_at' => date('Y-m-d H:i:s'),
                'ledger_started_at' => date('Y-m-d H:i:s'),
            );
        } elseif ($stage_id == 4) {
            $request_for_funds_stage = true;
            $stage_id = $stage_id + 1;
            $stage_name = 'Request for funds';
            $stage_description = 'Great news, your transaction has passed through another milestone.';
            $data = array(
                'status' => $stage_id,
                'req_for_funds_completed' => 1,
                'last_status_change' => date('Y-m-d H:i:s'),
                'req_for_funds_completed_at' => date('Y-m-d H:i:s'),
            );
        } elseif ($stage_id == 5) {
            $closed_stage = true;
            $stage_name = 'Closing';
            $stage_description = 'Great news, your transaction has passed through another milestone.';
            $data = array(
                'status' => $stage_id,
                'last_status_change' => date('Y-m-d H:i:s'),
                // 'hold_completed_at' => date('Y-m-d H:i:s'),
            );
        } elseif ($stage_id == 6) {
            $stage_id = $stage_id;
            $stage_name = 'On Hold';
            $stage_description = 'Your case has gone to the hold stage.';
            $data = array(
                'status' => $stage_id,
                'last_status_change' => date('Y-m-d H:i:s'),
                'hold_completed_at' => date('Y-m-d H:i:s'),
            );
        } elseif ($stage_id == 7) {
            $stage_id = 3;
            $stage_name = 'Appointment Stage';
            $stage_description = 'Great news, your transaction has passed through another milestone.';
            $data = array(
                'status' => $stage_id,
                'app_request_completed' => 1,
                'last_status_change' => date('Y-m-d H:i:s'),
                'app_request_completed_at' => date('Y-m-d H:i:s'),
                'outstanding_item_started_at' => date('Y-m-d H:i:s'),
            );
        } elseif ($stage_id == 8) {
            if (($get_idv_pass_count > 0 || $get_idv_pass_NA_count > 0) && $get_instruction_count > 0) {
                $stage_id = 7;
            } else {
                $stage_id = 2;
            }
            $stage_name = 'ID verification';
            $stage_description = 'Great news, your transaction has passed through another milestone.';
            $data = array(
                'status' => $stage_id,
                'id_verification_completed' => 1,
                'last_status_change' => date('Y-m-d H:i:s'),
                'id_verification_completed_at' => date('Y-m-d H:i:s'),
                'ins_received_started_at' => date('Y-m-d H:i:s'),
            );
        }

        $this->db->where('id', $lead_id);
        $this->db->update(db_prefix() . 'leads', $data);
        if ($this->db->affected_rows() > 0) {
            // add Activity logs
            $insert_task_activity = array(
                'leadid' => $lead_id,
                'staffid' => get_staff_user_id(),
                'full_name' => get_staff_full_name(),
                'activity_type' => 'task-activity',
                'description' => $stage_description,
                'date' => date('Y-m-d H:i:s'),
            );
            leads_activity_log($this, $insert_task_activity);
            switch ($stage_id) {
                case 1:
                    $leads_status_value = '#file_opened';
                    $complete_stage_button = 1;
                    break;
                case 2:
                    $leads_status_value = '#instructions_received';
                    $complete_stage_button = 2;
                    break;
                case 3:
                    $leads_status_value = '#outstanding_items';
                    $complete_stage_button = 3;
                    break;
                case 4:
                    $leads_status_value = '#ledger';
                    $complete_stage_button = '';
                    break;
                case 5:
                    $leads_status_value = '#Closed';
                    $complete_stage_button = '';
                    break;
                case 7:
                    $leads_status_value = '#lead_reminders';
                    $complete_stage_button = 7;
                    break;
                case 8:
                    $leads_status_value = '#id_verification';
                    $complete_stage_button = 8;
                    break;
                default:
                    $leads_status_value = '';
                    $complete_stage_button = 4;
                    break;
            }
            $response = [
                'success' => true,
                'id' => $lead_id,
                'complete_stage_button' => $complete_stage_button,
                'leads_status' => $leads_status_value,
                'stage_id' => $stage_id,
                'stage_name' => $stage_name,
                'stage_description' => $stage_description,
                'request_for_funds_stage' => $request_for_funds_stage,
                'closed_stage' => $closed_stage,
                'get_idv_pass_count' => ($stage_id == 7 || $stage_id == 2) ? $get_idv_pass_count : '',
                'get_instruction_count' => ($stage_id == 7 || $stage_id == 2) ? $get_instruction_count : '',
                'get_idv_pass_NA_count' => ($stage_id == 7 || $stage_id == 2) ? $get_idv_pass_NA_count : '',
                'file_doc_key' => $broker_fee_key['file_doc_key'],
                'broker_fee_na_key' => $broker_fee_key['broker_fee_na_key'],
                'leadView' => $this->_get_lead_data($lead_id),
            ];
        } else {
            $response = [
                'success' => false,
            ];
        }
        $this->output
            ->set_content_type('application/json')
            ->set_output(json_encode($response));
    }
    // Checklist complete stage notification
    public function checklist_complete_stage_notify()
    {

        $lead_id = $this->input->post('lead_id');
        $stage_name = $this->input->post('stage_name');
        $stage_id = $this->input->post('stage_id');
        $request_for_funds_stage = $this->input->post('request_for_funds_stage');
        $closed_stage = $this->input->post('closed_stage');
        $get_mail_subject = get_mail_subject($this, $lead_id);
        $this->db->select('addedfrom');
        $this->db->where('id', $lead_id);
        $email_lead_data = $this->db->get(db_prefix() . 'leads')->row();
        $broker_data = get_multiple_broker_details_using_addedfrom($this, $email_lead_data->addedfrom);
        $_POST['stage_name'] = $stage_name;
        // slack details functino
        $group_name = get_the_group_name_using_leadid($this, $lead_id);
        $lead_name = get_lead_name_using_lead_id($this, $lead_id);
        $lead_split_name = leads_splitFullName($lead_name);

        $this->db->select('name');
        $this->db->where('rel_id', $lead_id);
        $this->db->where('rel_type', 'user-task');
        $task_data = $this->db->get(db_prefix() . 'tasks')->row();
        // notificaation line of code  and sms line of code 
        $this->db->select('id,multiple_cases,client_id,phonenumber,name,email,addedfrom,assign_group');
        $this->db->where('id', $lead_id);
        $lead_data_check = $this->db->get(db_prefix() . 'leads');
        if ($lead_data_check->num_rows() > 0) {
            $lead_data = $lead_data_check->row();
            $client_id = get_client_id_using_contact_id($this, $lead_data->client_id, $lead_data->multiple_cases);
            $contact_id = get_contact_id_using_client_id($this, $client_id);
            $notification_type = get_notification_type(2);
            $replay_to_mail = get_all_staff_to_replay_email($this, get_staff_user_id(), $lead_data->assign_group);
            // when idv stage complete send sms and notificatgion 
            // send notification if stage are not close
            $get_all_clients_emails_count = get_all_clients_email_counts_separately($this, $lead_id);
            // get the mail subject
            $get_mail_subject = get_mail_subject_for_case_stages($this, $lead_id, $stage_id);
            if ($stage_id != 5) {
                // send notificaitonto the staff
                $this->db->select('assign_group,assigned,email,name');
                $this->db->where('id', $lead_id);
                $lead_data_for_get_assign_group = $this->db->get(db_prefix() . 'leads')->row();
                // when id verification stage complete then send notification this otherwise else 
                // $replay_to_mail = get_all_staff_to_replay_email($this, get_staff_user_id(), $lead_data_for_get_assign_group->assign_group);
                if ($stage_id == 2) {
                    // send idv notification and email only when 2 client and 1 email at least exits
                    if ($get_all_clients_emails_count['borrower_count'] > 0 || $get_all_clients_emails_count['borrower_email_count'] > 0) {
                        $client_notifiation_type = $notification_type . '-created';
                        $client_notify_title = 'ID Verification process completed.';
                        $client_notify_message = '';
                        send_notification_in_mobile('client', get_staff_user_id(), $contact_id, $client_id, $lead_id, $client_notify_title, $client_notify_message, $client_notifiation_type, '');
                        // send mail to User when file opened/Id completed to the user
                        $_POST['get_afternoon_and_morning'] = get_afternoon_and_morning();

                        $_POST['attachment'] = get_file_attachment($this, $lead_id);
                        $_POST['client_name'] = get_all_lead_borrower_first_name($this, $lead_id);
                        $html_content_confirmation_id_verification = $this->load->view('admin/leads/Email_template/id_verification', $_POST, TRUE);
                        $all_client_email = get_all_client_email_using_lead_id($this, $lead_id);
                        $to_all_client_email = explode(',', $all_client_email);
                        $send_email_result = send_mailchimp_email($to_all_client_email, $get_mail_subject, $html_content_confirmation_id_verification, $replay_to_mail, '', '', $lead_id);
                        // add the record for outbox emails
                        $outbox_content = 'This is Legal Direct.Congratulations, your case has progressed through another milestone. Your ID has been verified. Once we have the mortgage documents from your new lender we shall set an appointment with you.';
                        $outbox_id = $this->Outbox_model->save_outbox_email(
                            $to_all_client_email,
                            '',
                            '',
                            $get_mail_subject,
                            $outbox_content,
                            '',
                            $lead_id,
                            $stage_id,
                            $html_content_confirmation_id_verification,
                            $replay_to_mail,
                            $send_email_result['status'],
                            $send_email_result['mandrill_id'],
                            1
                        );
                        // send the mail in secondary email
                        $get_secondary_emali = get_the_secondary_email($this, $lead_id);
                        if (!empty($get_secondary_emali)) {
                            send_mailchimp_email($get_secondary_emali, $get_mail_subject, $html_content_confirmation_id_verification, $replay_to_mail, '', '', $lead_id);
                        }
                        $insert_task_activity = array(
                            'leadid' => $lead_id,
                            'staffid' => get_staff_user_id(),
                            'full_name' => get_staff_full_name(),
                            'description' => get_staff_full_name() . ' Sent an email to ' . $lead_data->name . '<br> Good ' . get_afternoon_and_morning() . '<br>' . 'We have received all required ID and await lender instructions.',
                            'date' => date('Y-m-d H:i:s'),
                        );
                        leads_activity_log($this, $insert_task_activity);
                        // add the app message 
                        $app_message = 'Your ID has been verified. Once we have the mortgage documents from your new lender we shall set an appointment with you.';
                        store_app_message_for_client($this, $lead_id, $app_message, $stage_id);
                    }
                    // send slack notification when idv stage complete
                    $slack_message = "\n - Stage Complete: ID Complete \n- Send ID Complete update \n- Send preliminary e-mail";
                    $slack_resposne = $this->slack->sendnotification($slack_message, $lead_id, $lead_data->assign_group, $lead_split_name['lastname'] . ', ' . $lead_split_name['firstname'] . ' ' . $lead_split_name['middlename']);
                } else if ($stage_id == 4) {
                    // send notification to the bob
                    $get_bob_data = get_bb_data($this);
                    $this->leads_model->custom_lead_assigned_member_notification('staff', $lead_id, $get_bob_data->staffid, get_staff_user_id(), '', $lead_data->name . ',File' . $lead_data->id . '- Stage Complete:Final item received.');

                    $client_notification_type = $notification_type . '-created';
                    $client_notify_title = 'We received all the required documentation from you. We are now completing any outstanding conditions with your new lender.';
                    $client_notify_message = '';
                    send_notification_in_mobile('client', get_staff_user_id(), $contact_id, $client_id, $lead_id, $client_notify_title, $client_notify_message, $client_notification_type, '');
                    // add the app message 
                    $app_message = 'We received all the required documentation from you. We are now completing any outstanding conditions with your new lender.';
                    store_app_message_for_client($this, $lead_id, $app_message, $stage_id);
                    // // when outstanding stage complete send mail to the bob 
                    // $_POST['case_url'] = admin_url('cases/index/') . $lead_id;
                    // $_POST['generic_email_title'] = '';
                    // $_POST['generic_email_content_title'] = 'Good ' . get_afternoon_and_morning();
                    // $_POST['generic_email_back_to_case_url'] = 'Please <a href="' . htmlspecialchars($_POST['case_url'], ENT_QUOTES, 'UTF-8') . '">Click here</a> to access the file.';
                    // $_POST['generic_email_content'] = 'We received all the required documentation from you. We are now completing any outstanding conditions with your new lender.';
                    // $_POST['general_attachment'] = '';
                    // $html_content_welcome_email_to_bob = $this->load->view('admin/leads/Email_template/generic_email_template', $_POST, TRUE);
                    // $replay_to_mail = get_all_staff_to_replay_email($this, get_staff_user_id(), $lead_data_for_get_assign_group->assign_group);
                    // $cc_group_memebers = get_all_staff_name_email_by_group_for_cc($this, $lead_id, $lead_data_for_get_assign_group->assign_group);
                    // if (base_url() == 'https://dev.platform.legaldirect.ca/') {
                    //     send_mailchimp_email('ra.faheem7@gmail.com', $get_mail_subject, $html_content_welcome_email_to_bob, $replay_to_mail, '', '', $lead_id);
                    // } else {
                    //     send_mailchimp_email('bb@legaldirect.ca', $get_mail_subject, $html_content_welcome_email_to_bob, $replay_to_mail, $cc_group_memebers, '', $lead_id);
                    // }
                    // send the notification in crm
                    $admin_ids = get_all_admin_role_staff_ids($this);
                    $message_for_admins = 'On this file #' . $lead_id . ', all outstanding items have been completed, please expect the ledgers from the team shortly.';
                    foreach ($admin_ids as $admin_email) {
                        $this->leads_model->custom_lead_assigned_member_notification('staff', $lead_id, $admin_email['staffid'], get_staff_user_id(), '', $message_for_admins);
                    }
                    //  send email to the client when outstanding item stage complete
                    $client_names = get_all_lead_borrower_first_name($this, $lead_id);
                    $_POST['case_url'] = '';
                    $_POST['generic_email_title'] = '';
                    $_POST['generic_email_content_title'] = 'Dear ' . $client_names;
                    $_POST['generic_email_back_to_case_url'] = '';
                    $_POST['generic_email_content'] = 'We received all the required documentation from you. We are now completing any outstanding conditions with your new lender.';
                    $_POST['general_attachment'] = '';
                    $html_content_welcome_email_to_user = $this->load->view('admin/leads/Email_template/generic_email_template', $_POST, TRUE);

                    $all_client_email = get_all_client_email_using_lead_id($this, $lead_id);
                    $to_all_client_email = explode(',', $all_client_email);
                    $send_email_result = send_mailchimp_email($to_all_client_email, $get_mail_subject, $html_content_welcome_email_to_user, $replay_to_mail, '', '', $lead_id);
                    // add the record for outbox emails
                    $outbox_id = $this->Outbox_model->save_outbox_email(
                        $to_all_client_email,
                        '',
                        '',
                        $get_mail_subject,
                        $_POST['generic_email_content'],
                        '',
                        $lead_id,
                        $stage_id,
                        $html_content_welcome_email_to_user,
                        $replay_to_mail,
                        $send_email_result['status'],
                        $send_email_result['mandrill_id'],
                        1
                    );
                    // Send Slack notification
                    $slack_message = "\n - Stage Complete: OK? \n- Grab the physical file and print all relevant documents (e.g. payouts) \n- Prepare the ledgers and send to Bob \n- Bring the physical file to Bob.";
                    $send_notification = $this->slack->sendnotification($slack_message, $lead_id, $group_name, $lead_split_name['lastname'] . ', ' . $lead_split_name['firstname'] . ' ' . $lead_split_name['middlename']);
                } else if ($stage_id == 7) {
                    // $client_notification_type = $notification_type . '-created';
                    // $client_notify_title = 'Stage Complete';
                    // $client_notify_message = 'Great news, your transaction has passed through another milestone.';
                    // send_notification_in_mobile('client', get_staff_user_id(), $contact_id, $client_id, $lead_id, $client_notify_title, $client_notify_message, $client_notification_type, '');
                    // send mail to the bob when instruction received stage complete
                    $_POST['case_url'] = admin_url('cases/index/') . $lead_id;
                    $_POST['generic_email_title'] = '';
                    $_POST['generic_email_content_title'] = 'Good ' . get_afternoon_and_morning();
                    $_POST['generic_email_back_to_case_url'] = 'Please <a href="' . htmlspecialchars($_POST['case_url'], ENT_QUOTES, 'UTF-8') . '">Click here</a> to access the file.';
                    $_POST['generic_email_content'] = 'ID, IDV are complete and instructions are in. Appointment will now be sent out.';
                    $_POST['general_attachment'] = '';
                    $html_content_welcome_email_to_bob = $this->load->view('admin/leads/Email_template/generic_email_template', $_POST, TRUE);

                    if (base_url() == 'https://dev.platform.legaldirect.ca/') {
                        $send_email_result = send_mailchimp_email('ra.faheem7@gmail.com', $get_mail_subject, $html_content_welcome_email_to_bob, $replay_to_mail, '', '', $lead_id);
                        // add the record for outbox emails
                        $outbox_id = $this->Outbox_model->save_outbox_email(
                            'ra.faheem7@gmail.com',
                            '',
                            '',
                            $get_mail_subject,
                            $_POST['generic_email_content'],
                            '',
                            $lead_id,
                            $stage_id,
                            $html_content_welcome_email_to_bob,
                            $replay_to_mail,
                            $send_email_result['status'],
                            $send_email_result['mandrill_id'],
                            1
                        );
                    } else {
                        $send_email_result = send_mailchimp_email('bb@legaldirect.ca', $get_mail_subject, $html_content_welcome_email_to_bob, $replay_to_mail, '', '', $lead_id);
                        // add the record for outbox emails
                        $outbox_id = $this->Outbox_model->save_outbox_email(
                            'bb@legaldirect.ca',
                            '',
                            '',
                            $get_mail_subject,
                            $_POST['generic_email_content'],
                            '',
                            $lead_id,
                            $stage_id,
                            $html_content_welcome_email_to_bob,
                            $replay_to_mail,
                            $send_email_result['status'],
                            $send_email_result['mandrill_id'],
                            1
                        );
                    }
                    //  Send slack notification when instruction received stage complete
                    $slack_message = "\n - Stage Complete: ID & Instructions Received \n- Send appointment e-mail.";
                    $this->slack->sendnotification($slack_message, $lead_id, $lead_data->assign_group, $lead_split_name['lastname'] . ', ' . $lead_split_name['firstname'] . ' ' . $lead_split_name['middlename']);
                } else if ($stage_id == 8) {
                    // send this notification when outstanding item stage completed
                    $idv_sms_content = 'This is Legal Direct.Congratulations your case has progressed through another milestone, we have all your copy IDs. You will shortly receive an email or text message to complete the ID Verification process.Please DO NOT REPLY TO THIS TEXT.';
                    $idv_client_notification_contetn = 'IDs complete and authenticated';
                    $idv_notification_type = get_notification_type(1);

                    $client_notification_type = $idv_notification_type;
                    $client_notify_title = $idv_client_notification_contetn;
                    $client_notify_message = '';
                    send_notification_in_mobile('client', get_staff_user_id(), $contact_id, $client_id, $lead_id, $client_notify_title, $client_notify_message, $client_notification_type, '');
                    // add the app message 
                    $app_message = 'Thank you for sending the requisite IDs. As per the 2024 Law Society of Ontario regulations, for all virtual appointments, we are now required to electronically VERIFY your ID. Please check your email or texts to complete this process. For this step, you will need to have ready the PHOTO ID you provided already.';
                    store_app_message_for_client($this, $lead_id, $app_message, $stage_id);
                    // Slack notification send when file open stage complete
                    $slack_message = "\n - Send ID Verification.";
                    $this->slack->sendnotification($slack_message, $lead_id, $lead_data->assign_group, $lead_split_name['lastname'] . ', ' . $lead_split_name['firstname'] . ' ' . $lead_split_name['middlename']);
                }
                // send  notiication in crm to all the team group member and staff
                $this->db->select('assign_group,assigned,name');
                $this->db->where('id', $lead_id);
                $lead_data_for_get_assign_group = $this->db->get(db_prefix() . 'leads')->row();
                if (!empty($lead_data_for_get_assign_group->assign_group)) {
                    $current_staff_data = get_staff_ids_by_group($this, $lead_data_for_get_assign_group->assign_group);
                    $message = 'Case Stage (' . $stage_name . ') has been completed by ' . get_staff_full_name() . '. for case (ID: #' . $lead_id . ' & Name: ' . $lead_data_for_get_assign_group->name . ').';
                    foreach ($current_staff_data as $staff_notifiy_data) {
                        if (get_staff_user_id() != $staff_notifiy_data['staffid']) {

                            $ldteam_notify_type = $notification_type . '-created';
                            $ld_team_notify_title = $stage_name;
                            $ld_team_notify_message = 'Case Stage (' . $stage_name . ') has been completed by ' . get_staff_full_name() . '. for case (ID: #' . $lead_id . ' & Name: ' . $lead_data_for_get_assign_group->name . ').';
                            // send_notification_in_mobile('staff', $staff_notifiy_data['staffid'], $contact_id, $client_id, $lead_id, $ld_team_notify_title, $ld_team_notify_message, $ldteam_notify_type, '');
                            // send notification in crm
                            $this->leads_model->custom_lead_assigned_member_notification('staff', $lead_id, $staff_notifiy_data['staffid'], get_staff_user_id(), '', $message);
                        }
                    }
                }
                // get the all admin staff ids
                $admin_ids = get_all_admin_role_staff_ids($this);
                $message_for_admins = 'Case Stage (' . $stage_name . ') has been completed by ' . get_staff_full_name() . '. for case (ID: #' . $lead_id . ' & Name: ' . $lead_data_for_get_assign_group->name . ').';
                foreach ($admin_ids as $admin_email) {
                    if (get_staff_user_id() != $admin_email['staffid']) {

                        $admin_notify_type = $notification_type . '-created';
                        $admin_notify_title = $stage_name . ' Stage completed';
                        $admin_notify_message = 'Case Stage (' . $stage_name . ') has been completed by ' . get_staff_full_name() . '. for case (ID: #' . $lead_id . ' & Name: ' . $lead_data_for_get_assign_group->name . ').';
                        // send_notification_in_mobile('staff', $admin_email['staffid'], $contact_id, $client_id, $lead_id, $admin_notify_title, $admin_notify_message, $admin_notify_type, '');
                        // send notification in crm
                        $this->leads_model->custom_lead_assigned_member_notification('staff', $lead_id, $admin_email['staffid'], get_staff_user_id(), '', $message_for_admins);
                    }
                }
            }
            // send notificataion for request for funds
            if ($request_for_funds_stage) {
                // // send notificaitonto the staff
                // $this->db->select('assign_group,assigned,name');
                // $this->db->where('id', $lead_id);
                // $lead_data_for_get_assign_group = $this->db->get(db_prefix() . 'leads')->row();
                // $current_staff_data = get_staff_ids_by_group($this, $lead_data_for_get_assign_group->assign_group);
                // foreach ($current_staff_data as $staff_notifiy_data) {
                //     $ldteam_notify_type = $notification_type . '-created';
                //     $ld_team_notify_title = $stage_name;
                //     $ld_team_notify_message = 'Requested Closing from your new lender.';
                //     send_notification_in_mobile('staff', $staff_notifiy_data['staffid'], $contact_id, $client_id, $lead_id, $ld_team_notify_title, $ld_team_notify_message, $ldteam_notify_type, '');
                //     // send slack notification
                //     $slack_message = 'Requested Closing from your new lender.';
                //     // send notification in slack
                //     $this->slack->send_notification($staff_notifiy_data['email'], $slack_message);
                // }
                // // send notification to the crm
                // // send  notiication in crm to all the team group member and staff
                // $this->db->select('assign_group,assigned');
                // $this->db->where('id', $lead_id);
                // $lead_data_for_get_assign_group = $this->db->get(db_prefix() . 'leads')->row();
                // $current_staff_data = get_staff_ids_by_group($this, $lead_data_for_get_assign_group->assign_group);
                // foreach ($current_staff_data as $staff_notifiy_data) {
                //     if (get_staff_user_id() != $staff_notifiy_data['staffid']) {
                //         $this->leads_model->custom_lead_assigned_member_notification('staff', $lead_id, $staff_notifiy_data['staffid'], get_staff_user_id(), '', 'Case Stage (' . $stage_name . ') has been completed by ' . get_staff_full_name() . ' for case (ID: #' . $lead_id . ' & Name: ' . $lead_data_for_get_assign_group->name . ').');
                //     }
                // }
                // // get the all admin staff ids
                // $admin_ids = get_all_admin_role_staff_ids($this);
                // foreach ($admin_ids as $admin_email) {
                //     if (get_staff_user_id() != $admin_email['staffid']) {
                //         $admin_notify_type = $notification_type . '-created';
                //         $admin_notify_title = $stage_name . ' Stage completed';
                //         $admin_notify_message = 'Requested Closing from your new lender.';
                //         send_notification_in_mobile('staff', $admin_email['staffid'], $contact_id, $client_id, $lead_id, $admin_notify_title, $admin_notify_message, $admin_notify_type, '');
                //         // send slack notification
                //         $slack_message = 'Requested Closing from your new lender.';
                //         // send notification in slack individual person
                //         $this->slack->send_notification($admin_email['email'], $slack_message);
                //         // send notification in crm
                //         $this->leads_model->custom_lead_assigned_member_notification('staff', $lead_id, $admin_email['staffid'], get_staff_user_id(), '', 'Case Stage (' . $stage_name . ') has been completed by ' . get_staff_full_name() . ' for case (ID: #' . $lead_id . ' & Name: ' . $lead_data_for_get_assign_group->name . ').');
                //     }
                // }
                // $sms_message = 'We received all the required documentation from you. We are now completing any outstanding conditions with your new lender. DO NOT REPLY TO THIS TEXT.';
                // $all_client_phone_list = get_all_client_phonenumber_using_lead_id($this, $lead_id);
                // $this->send_sms($all_client_phone_list, $sms_message, $sms_message, $lead_id, '', '');
                // send notification for case closed
                $notification_type = get_notification_type(2);
                $client_notify_type = $notification_type . '-created';
                $client_notify_title = 'Requested Closing from your new lender';
                $client_notify_message = '';
                send_notification_in_mobile('client', get_staff_user_id(), $contact_id, $client_id, $lead_id, $client_notify_title, $client_notify_message, $client_notify_type, '');
                // add the app message 
                $app_message = 'We have requested closing funds from your new lender on your transaction. We shall let you know when yourfile has completed.';
                store_app_message_for_client($this, $lead_id, $app_message, 4);
                store_app_message_for_client($this, $lead_id, $app_message, 5);
                // send emailt to the client
                // $get_mail_subject = get_mail_subject_for_case_stages($this, $lead_id, $stage_id);
                // $_POST['case_url'] = '';
                // $_POST['generic_email_title'] = '';
                // $_POST['generic_email_back_to_case_url'] = '';
                // $_POST['generic_email_content_title'] = 'Dear ' . get_all_lead_borrower_first_name($this, $lead_id);
                // $_POST['generic_email_content'] = 'We received all the required documentation from you. We are now completing any outstanding conditions with your new lender.';
                // $_POST['general_attachment'] = '';
                // $html_content_welcome_email_to_user = $this->load->view('admin/leads/Email_template/generic_email_template', $_POST, TRUE);
                // $replay_to_mail = get_all_staff_to_replay_email($this, get_staff_user_id(), $lead_data_for_get_assign_group->assign_group);
                // $all_client_email = get_all_client_email_using_lead_id($this, $lead_id);
                // $to_all_client_email = explode(',', $all_client_email);
                // send_mailchimp_email($to_all_client_email, $get_mail_subject, $html_content_welcome_email_to_user, $replay_to_mail, '', '', $lead_id);

            }
            // send notification when outstanding stage complete
            if ($stage_id == 4) {
            }
            // send mail RFF_to_broker
            if ($stage_id == 3) {
                $this->db->select('firstname,lastname,email');
                $this->db->where('staffid', $lead_data->addedfrom);
                $get_staff_data = $this->db->get(db_prefix() . 'staff')->row();
                $_POST['get_afternoon_and_morning_Rff'] = get_afternoon_and_morning();
                // $subject = 'Expect documents to be closed';
                $subject = $get_mail_subject;
                // $replay_to_mail = $replay_to_mail = get_all_staff_to_replay_email($this, get_staff_user_id(), $lead_data_for_get_assign_group->assign_group);
                $this->db->where('lead_id', $lead_id);
                $this->db->where('leads_status', 3);
                $check_item_outstanding_ld_team = $this->db->get(db_prefix() . 'cases_checkboxes')->row();
                if (empty($check_item_outstanding_ld_team)) {
                    // get the checklist template ids for outstandin items and show preloaded for client
                    $this->db->select('id');
                    $this->db->where('type', 'ld_team');
                    $this->db->where('case_status', 3);
                    $this->db->order_by('order_no', 'asc');
                    $ld_query = $this->db->get(db_prefix() . 'checklist_templates');
                    $checklist_template_ids_for_ldteam = array_column($ld_query->result_array(), 'id');
                    preloaded_outstanding_item_for_ld_team($this, $checklist_template_ids_for_ldteam, $lead_id, 3, 'other_items');
                    // send sms when outstanding item preloaded 
                    // $sms_message_for_outstanding_item = 'This is Legal Direct. We are outstanding some items for your transaction. Please check our app “LEGAL DIRECTLY” to check the progress. Please DO NOT REPLY TO THIS TEXT.';
                    // $all_client_phone_list = get_all_client_phonenumber_using_lead_id($this, $lead_id);
                    // $this->send_sms($all_client_phone_list, $sms_message_for_outstanding_item, $sms_message_for_outstanding_item, $lead_id, $lead_data->name, $lead_data->email);
                }
                // outstanding secure payout item details
                $this->db->where('lead_id', $lead_id);
                $this->db->where('leads_status', 7);
                $check_item_outstanding_ld_team_payouts = $this->db->get(db_prefix() . 'cases_checkboxes')->row();
                if (empty($check_item_outstanding_ld_team_payouts)) {
                    // get the checklist template ids for outstandin items and show preloaded for client
                    $this->db->select('id');
                    $this->db->where('type', 'secure_charge');
                    $this->db->where('case_status', 7);
                    $this->db->order_by('order_no', 'asc');
                    $ld_query = $this->db->get(db_prefix() . 'checklist_templates');
                    $checklist_template_ids_for_ldteam_payouts = array_column($ld_query->result_array(), 'id');
                    preloaded_outstanding_item_for_ld_team($this, $checklist_template_ids_for_ldteam_payouts, $lead_id, 7, '');
                    // secure private charge loaded
                    $this->db->select('id');
                    $this->db->where('type', 'app_general');
                    $this->db->where('case_status', 7);
                    $this->db->order_by('order_no', 'asc');
                    $ld_query = $this->db->get(db_prefix() . 'checklist_templates');
                    $checklist_template_ids_for_ldteam_payouts = array_column($ld_query->result_array(), 'id');
                    preloaded_outstanding_item_for_ld_team($this, $checklist_template_ids_for_ldteam_payouts, $lead_id, 7, '');
                }
                // send notification and app message
                $idv_notification_type = get_notification_type(1);
                $client_notification_type = $notification_type . '-created';
                $client_notify_title = 'Appointment completed.';
                $client_notify_message = '';
                send_notification_in_mobile('client', get_staff_user_id(), $contact_id, $client_id, $lead_id, $client_notify_title, $client_notify_message, $client_notification_type, '');
                // add the app message 
                $app_message = 'Appointment completed. Please use the Outstanding Items dropdown menu below to provide items required to progress your case.';
                store_app_message_for_client($this, $lead_id, $app_message, $stage_id);
            }
            // when instruction received stage complete so send notifcation and mail to user appointment request
            if ($stage_id == 7) {
                // preloaded checklsit template create
                $this->db->where('rel_id', $lead_id);
                $this->db->where('rel_type', 'user-task');
                $this->db->where('leads_status', 7);
                $check_item_appointment_ld_team = $this->db->get(db_prefix() . 'tasks')->row();
                if (empty($check_item_appointment_ld_team)) {
                    $this->db->select('id');
                    $this->db->where('type', 'ld_team');
                    $this->db->where('case_status', 0);
                    $this->db->order_by('order_no', 'asc');
                    $query = $this->db->get(db_prefix() . 'checklist_templates');
                    $checklist_template_ids = array_column($query->result_array(), 'id');
                    preloaded_file_opened_checklist_template_add_in_task_table($this, $checklist_template_ids, $lead_id, 0);
                }
                // send mail to the user 
                $_POST['get_afternoon_and_morning'] = get_afternoon_and_morning();
                // $subject = 'Appointement Request';
                $subject = $get_mail_subject;
                // send notification and app message
                $idv_notification_type = get_notification_type(1);
                $client_notification_type = $notification_type . '-created';
                $client_notify_title = 'Lender instructions received.';
                $client_notify_message = '';
                send_notification_in_mobile('client', get_staff_user_id(), $contact_id, $client_id, $lead_id, $client_notify_title, $client_notify_message, $client_notification_type, '');
                // add the app message 
                $app_message = 'Lender instructions received and being reviewed.';
                store_app_message_for_client($this, $lead_id, $app_message, $stage_id);
                // send emailt to the client
                $get_mail_subject = get_mail_subject_for_case_stages($this, $lead_id, 2);
                $_POST['case_url'] = '';
                $_POST['generic_email_title'] = '';
                $_POST['generic_email_back_to_case_url'] = '';
                $_POST['generic_email_content_title'] = 'Dear ' . get_all_lead_borrower_first_name($this, $lead_id);
                $_POST['generic_email_content'] = 'We have received your lender instructions and are reviewing them. Once reviewed, we shall contact you again to set an appointment to go through the mortgage documents and the new lender’s requirements.';
                $_POST['general_attachment'] = '';
                $html_content_welcome_email_to_user = $this->load->view('admin/leads/Email_template/generic_email_template', $_POST, TRUE);

                $all_client_email = get_all_client_email_using_lead_id($this, $lead_id);
                $to_all_client_email = explode(',', $all_client_email);
                $send_email_result = send_mailchimp_email($to_all_client_email, $get_mail_subject, $html_content_welcome_email_to_user, $replay_to_mail, '', '', $lead_id);
                // add the record for outbox emails
                $outbox_id = $this->Outbox_model->save_outbox_email(
                    $to_all_client_email,
                    '',
                    '',
                    $get_mail_subject,
                    $_POST['generic_email_content'],
                    '',
                    $lead_id,
                    $stage_id,
                    $html_content_welcome_email_to_user,
                    $replay_to_mail,
                    $send_email_result['status'],
                    $send_email_result['mandrill_id'],
                    1
                );
            }
            // when closed stage complete
            if ($stage_id == 5) {
                // udpate the Broker/Client GTC request for funds datge
                update_action_date_for_GTC($this, $lead_id);
                $GTC_Check = get_gtc_check($this, $lead_id);
                if ($GTC_Check == 0) {
                    // update the gtc check key 
                    $this->leads_model->update_GTC_key($lead_id, 1);

                    $group_name = get_the_group_name_using_leadid($this, $lead_id);
                    $lead_name = get_lead_name_using_lead_id($this, $lead_id);
                    $lead_split_name = leads_splitFullName($lead_name);
                    $slack_message = "\n - Stage Complete: GTC from Client/Nuborrow \n - Request for Funds.";
                    $send_notification = $this->slack->sendnotification($slack_message, $lead_id, $group_name, $lead_split_name['lastname'] . ', ' . $lead_split_name['firstname'] . ' ' . $lead_split_name['middlename']);

                    // send mail to the bob
                    $_POST['case_url'] = admin_url('cases/index/') . $lead_id;
                    $_POST['generic_email_title'] = '';
                    $_POST['generic_email_content_title'] = 'Good ' . get_afternoon_and_morning();
                    $_POST['generic_email_back_to_case_url'] = 'Please <a href="' . htmlspecialchars($_POST['case_url'], ENT_QUOTES, 'UTF-8') . '">Click here</a> to access the file.';
                    $_POST['generic_email_content'] = 'Client/broker confirmed GTC.';
                    $_POST['general_attachment'] = '';
                    $html_content_welcome_email_to_bob = $this->load->view('admin/leads/Email_template/generic_email_template', $_POST, TRUE);
                    $GTC_subject = $get_mail_subject . ' Broker/Client confirmed GTC';
                    if (base_url() == 'https://dev.platform.legaldirect.ca/') {
                        $send_email_result = send_mailchimp_email('ra.faheem7@gmail.com', $GTC_subject, $html_content_welcome_email_to_bob, $replay_to_mail, '', '', $lead_id);
                        // add the record for outbox emails
                        $outbox_id = $this->Outbox_model->save_outbox_email(
                            'ra.faheem7@gmail.com',
                            '',
                            '',
                            $GTC_subject,
                            $_POST['generic_email_content'],
                            '',
                            $lead_id,
                            $stage_id,
                            $html_content_welcome_email_to_bob,
                            $replay_to_mail,
                            $send_email_result['status'],
                            $send_email_result['mandrill_id'],
                            1
                        );
                    } else {
                        $send_email_result = send_mailchimp_email('bb@legaldirect.ca', $GTC_subject, $html_content_welcome_email_to_bob, $replay_to_mail, '', '', $lead_id);
                        // add the record for outbox emails
                        $outbox_id = $this->Outbox_model->save_outbox_email(
                            'bb@legaldirect.ca',
                            '',
                            '',
                            $GTC_subject,
                            $_POST['generic_email_content'],
                            '',
                            $lead_id,
                            $stage_id,
                            $html_content_welcome_email_to_bob,
                            $replay_to_mail,
                            $send_email_result['status'],
                            $send_email_result['mandrill_id'],
                            1
                        );
                    }
                }
                // $closing_date_update = array(
                //     'closed_completed_at' => date('Y-m-d H:i:s'),
                //     'active_case' => 'Closed',
                // );
                // $this->db->where('id', $lead_id);
                // $this->db->update(db_prefix() . 'leads', $closing_date_update);
            }
            // broker line of code
            // Send email to broker for different stages
            if (!empty($broker_data)) {
                $_POST['case_url'] = get_the_redirect_email_case_url($lead_id, 'broker');
                $get_mail_subject = get_mail_subject_for_case_stages($this, $lead_id, $stage_id);
                switch ($stage_id):
                    case 8:
                        $html_content_confirmation_email_to_broker = $this->load->view('admin/leads/Email_template/broker/file_opened_stage_complete', $_POST, TRUE);
                        $new_broker_message_notify = 'We are delighted to inform you that the file has successfully moved through 
                    another milestone, we have all the necessary ID for the Client.As per Law Society rules, we shall now ask the Client to Verify their ID using 3rd 
                    party software.';
                        $insert_task_activity = array(
                            'leadid' => $lead_id,
                            'staffid' => get_staff_user_id(),
                            'full_name' => get_staff_full_name(),
                            'description' => get_staff_full_name() . ' Sent an email to ' . $_POST['broker_name'] . '<br> Good ' . get_afternoon_and_morning() . '<br>' . $new_broker_message_notify,
                            'date' => date('Y-m-d H:i:s'),
                        );
                        leads_activity_log($this, $insert_task_activity);
                        break;
                    case 2:
                        $html_content_confirmation_email_to_broker = $this->load->view('admin/leads/Email_template/broker/IDV_stage_complete', $_POST, TRUE);
                        $new_broker_message_notify = 'We are delighted to inform you that the file has successfully moved through another
                    milestone, the Client has completed the ID Verification process.Once we have received the new mortgage instructions from the lender or their 
                    lawyers we shall set an appointment with the Client.';
                        $insert_task_activity = array(
                            'leadid' => $lead_id,
                            'staffid' => get_staff_user_id(),
                            'full_name' => get_staff_full_name(),
                            'description' => get_staff_full_name() . ' Sent an email to ' . $_POST['broker_name'] . '<br> Good ' . get_afternoon_and_morning() . '<br>' . $new_broker_message_notify,
                            'date' => date('Y-m-d H:i:s'),
                        );
                        leads_activity_log($this, $insert_task_activity);
                        break;
                    case 3:
                        //     $this->db->select('name');
                        //     $this->db->where('rel_id', $lead_id);
                        //     $this->db->where('type', 'client');
                        //     $this->db->where('leads_status', 3);
                        //     $client_task_list = $this->db->get(db_prefix() . 'tasks')->result_array();
                        //     // ld-team task list 
                        //     $this->db->select('title');
                        //     $this->db->where('lead_id', $lead_id);
                        //     $this->db->where('leads_status', 3);
                        //     $ld_task_list = $this->db->get(db_prefix() . 'cases_checkboxes')->result_array();
                        //     $_POST['client_list'] = $client_task_list;
                        //     $_POST['ld_list'] = $ld_task_list;
                        //     $_POST['case_url'] = admin_url('cases/index/') . $lead_id;
                        //     $html_content_confirmation_email_to_broker = $this->load->view('admin/leads/Email_template/broker/Appointment_requested_stage_completed', $_POST, TRUE);
                        //     $new_broker_message_notify = 'We are delighted to inform you that the file has successfully moved through another
                        // milestone.Please check your email for all the details, including the shared IDs.';
                        //     $lead_logs_email_message = 'We require no further items from third parties.>In view of the above we anticipate the file should be ready to move towards closing
                        //     in the coming days.';
                        //     $insert_task_activity = array(
                        //         'leadid' => $lead_id,
                        //         'staffid' => get_staff_user_id(),
                        //         'full_name' => get_staff_full_name(),
                        //         'description' => get_staff_full_name() . ' Sent an email to ' . $_POST['broker_name'] . '<br> Good ' . get_afternoon_and_morning() . '<br>' . $lead_logs_email_message,
                        //         'date' => date('Y-m-d H:i:s'),
                        //     );
                        //     leads_activity_log($this, $insert_task_activity);
                        break;
                    case 7:
                        $new_broker_message_notify = 'Instruction Received stage Completed by ' . get_staff_full_name();
                        break;
                    case 4:
                        //     $html_content_confirmation_email_to_broker = $this->load->view('admin/leads/Email_template/broker/outstanding_stage_compeleted', $_POST, TRUE);
                        //     $new_broker_message_notify = 'We are delighted to inform you that the file has successfully moved through another
                        // milestone, we have all items required by the lender instructions and we have requested funds.We await a review of any mortgage conditions that remain outstanding and 
                        // thereafter the confirmation of funding.';
                        //     $insert_task_activity = array(
                        //         'leadid' => $lead_id,
                        //         'staffid' => get_staff_user_id(),
                        //         'full_name' => get_staff_full_name(),
                        //         'description' => get_staff_full_name() . ' Sent an email to ' . $_POST['broker_name'] . '<br> Good ' . get_afternoon_and_morning() . '<br>' . $new_broker_message_notify,
                        //         'date' => date('Y-m-d H:i:s'),
                        //     );
                        //     leads_activity_log($this, $insert_task_activity);
                        break;
                    case 5:
                        break;
                    default:
                        $new_broker_message_notify = 'We are delighted to inform you that the file has successfully moved through another
                    milestone.';
                endswitch;

                // foreach ($broker_data as $broker) {
                //     $_POST['broker_name'] = $broker['firstname'] . ' ' . $broker['lastname'];
                //     $broker_email = $broker['email'];
                //     // $role = get_current_staff_role($this, $broker['staffid']);
                //     // if (isset($_POST['addedfrom']) || $role == 2 || $role == 6) {
                //     if (!empty($html_content_confirmation_email_to_broker)) {
                //         $replay_to_mail = get_all_staff_to_replay_email($this, get_staff_user_id(), $lead_data_for_get_assign_group->assign_group);
                //         $send_email_result = send_mailchimp_email($broker_email, $get_mail_subject, $html_content_confirmation_email_to_broker, $replay_to_mail, '', '', $lead_id);
                //         // add the record for outbox emails
                //         $outbox_id = $this->Outbox_model->save_outbox_email(
                //             $broker_email,
                //             '',
                //             '',
                //             $get_mail_subject,
                //             $new_broker_message_notify,
                //             '',
                //             $lead_id,
                //             $stage_id,
                //             $html_content_confirmation_email_to_broker,
                //             $replay_to_mail,
                //             $send_email_result['status'],
                //             $send_email_result['mandrill_id'],
                //             1
                //         );
                //     }
                //     if (!empty($new_broker_message_notify)) {
                //         // send notification in crm
                //         $this->leads_model->custom_lead_assigned_member_notification('staff', $lead_id, $broker['staffid'], get_staff_user_id(), '', $new_broker_message_notify);
                //     }
                //     // }
                // }

                  // // get the admin email
                // $brokerage_id = get_brokerage_id_using_leadid($this, $lead_id);
                // // send the all admin notification and email to the admin broker
                // $admin_broker_ids = get_all_admin_broker_role_staff_ids($this, $brokerage_id);
                // foreach ($admin_broker_ids as $admin_broker_email) {
                //     if (get_staff_user_id() != $admin_broker_email['staffid'] && !in_array($admin_broker_email['staffid'], explode(',', $lead_data->addedfrom))) {
                //         $send_email_result = send_mailchimp_email($admin_broker_email['email'], $get_mail_subject, $html_content_confirmation_email_to_broker, $replay_to_mail, '', '', $lead_id);
                //         // add the record for outbox emails
                //         $outbox_id = $this->Outbox_model->save_outbox_email(
                //             $admin_broker_email['email'],
                //             '',
                //             '',
                //             $get_mail_subject,
                //             $new_broker_message_notify,
                //             '',
                //             $lead_id,
                //             $stage_id,
                //             $html_content_confirmation_email_to_broker,
                //             $replay_to_mail,
                //             $send_email_result['status'],
                //             $send_email_result['mandrill_id'],
                //             1
                //         );
                //     }
                //     // send notification in crm
                //     if (!empty($new_broker_message_notify)) {
                //         $this->leads_model->custom_lead_assigned_member_notification('staff', $lead_id, $admin_broker_email['staffid'], get_staff_user_id(), '', $new_broker_message_notify);
                //     }
                // }

                // Collect broker emails + names
                $broker_emails = array_column($broker_data, 'email');
                $broker_names  = array_map(function($b) {
                    return $b['firstname'] . ' ' . $b['lastname'];
                }, $broker_data);

                // Combine broker names into one string for form POST
                $_POST['broker_name'] = implode(', ', $broker_names);

                // Get brokerage ID
                $brokerage_id = get_brokerage_id_using_leadid($this, $lead_id);

                // Get all admin broker staff IDs + emails
                $admin_broker_ids = get_all_admin_broker_role_staff_ids($this, $brokerage_id);

                // Filter only allowed admin recipients
                $filtered_admins = array_filter($admin_broker_ids, function ($admin) use ($lead_data) {
                    return get_staff_user_id() != $admin['staffid'] &&
                        !in_array($admin['staffid'], explode(',', $lead_data->addedfrom));
                });

                // Extract admin emails & staff IDs
                $admin_emails = array_column($filtered_admins, 'email');
                $admin_staff_ids = array_column($filtered_admins, 'staffid');

                // Merge broker emails + admin broker emails into one array
                $all_recipients = array_unique(array_merge($broker_emails, $admin_emails));

                // Final comma-separated list for sending
                $recipients = implode(',', $all_recipients);

                // Prepare reply-to
                $replay_to_mail = get_all_staff_to_replay_email(
                    $this,
                    get_staff_user_id(),
                    $lead_data_for_get_assign_group->assign_group
                );

                // Send email to all recipients at once
                if (!empty($html_content_confirmation_email_to_broker) && !empty($recipients)) {
                    $send_email_result = send_mailchimp_email(
                        $recipients,
                        $get_mail_subject,
                        $html_content_confirmation_email_to_broker,
                        $replay_to_mail,
                        '',
                        '',
                        $lead_id
                    );

                    // Save one outbox record for all recipients
                    $outbox_id = $this->Outbox_model->save_outbox_email(
                        $recipients,
                        '',
                        '',
                        $get_mail_subject,
                        $new_broker_message_notify,
                        '',
                        $lead_id,
                        $stage_id,
                        $html_content_confirmation_email_to_broker,
                        $replay_to_mail,
                        $send_email_result['status'],
                        $send_email_result['mandrill_id'],
                        1
                    );
                }

                // Still send CRM notifications individually for brokers
                if (!empty($new_broker_message_notify)) {
                    foreach ($broker_data as $broker) {
                        $this->leads_model->custom_lead_assigned_member_notification(
                            'staff',
                            $lead_id,
                            $broker['staffid'],
                            get_staff_user_id(),
                            '',
                            $new_broker_message_notify
                        );
                    }

                    foreach ($admin_staff_ids as $staffid) {
                        $this->leads_model->custom_lead_assigned_member_notification(
                            'staff',
                            $lead_id,
                            $staffid,
                            get_staff_user_id(),
                            '',
                            $new_broker_message_notify
                        );
                    }
                }

            }
        }
        // update the last contact date 
        $this->leads_model->update_leads_last_contact_date($lead_id);
        // send sms to client 
        $sms_message_for_stages = send_sms_according_to_stage_compelte($stage_id);
        $all_client_phone_list = get_all_client_phonenumber_using_lead_id($this, $lead_id);
        if ($stage_id != 2 || ($get_all_clients_emails_count['borrower_count'] > 0 || $get_all_clients_emails_count['borrower_email_count'] > 0)) {
            $this->send_sms($all_client_phone_list, $sms_message_for_stages, $sms_message_for_stages, $lead_id, $lead_data->name, $lead_data->email);
        }

        $response = [
            'success' => true,
        ];
        $this->output
            ->set_content_type('application/json')
            ->set_output(json_encode($response));
    }
    // ID is in 
    // idv is not in
    // instruction is in 
    public function id_in_and_idv_not_in_and_ins_in()
    {
        $lead_id = $this->input->post('lead_id');
        $stage_id = $this->input->post('stage_id');

        // slack details functino
        $group_name = get_the_group_name_using_leadid($this, $lead_id);
        $lead_name = get_lead_name_using_lead_id($this, $lead_id);
        $lead_name = leads_splitFullName($lead_name);
        $this->db->select('name');
        $this->db->where('rel_id', $lead_id);
        $this->db->where('rel_type', 'user-task');
        $task_data = $this->db->get(db_prefix() . 'tasks')->row();
        // notificaation line of code  and sms line of code 
        $this->db->select('id,multiple_cases,client_id,phonenumber,name,email,addedfrom,assign_group');
        $this->db->where('id', $lead_id);
        $lead_data_check = $this->db->get(db_prefix() . 'leads');
        if ($lead_data_check->num_rows() > 0) {
            $lead_data = $lead_data_check->row();
            $client_id = get_client_id_using_contact_id($this, $lead_data->client_id, $lead_data->multiple_cases);
            $contact_id = get_contact_id_using_client_id($this, $client_id);
            $notification_type = get_notification_type(2);
            $replay_to_mail = get_all_staff_to_replay_email($this, get_staff_user_id(), $lead_data->assign_group);
            $get_mail_subject = get_mail_subject($this, $lead_id);
            // send notification if stage are not close
            $get_all_clients_emails_count = get_all_clients_email_counts_separately($this, $lead_id);
            // when idv stage complete notification triggers
            // if($get_all_clients_emails_count['borrower_count'] > 0 || $get_all_clients_emails_count['borrower_email_count'] > 0){
            //     $client_notifiation_type = $notification_type . '-created';
            //     $client_notify_title = 'ID Verification process completed.';
            //     $client_notify_message = '';
            //     send_notification_in_mobile('client', get_staff_user_id(), $contact_id, $client_id, $lead_id, $client_notify_title, $client_notify_message, $client_notifiation_type, '');
            //     // send mail to User when file opened/Id completed to the user
            //     $_POST['get_afternoon_and_morning'] = get_afternoon_and_morning();

            //     $_POST['attachment'] = get_file_attachment($this, $lead_id);
            //     $_POST['client_name'] = get_all_lead_borrower_first_name($this, $lead_id);
            //     $html_content_confirmation_id_verification = $this->load->view('admin/leads/Email_template/id_verification', $_POST, TRUE);
            //     $all_client_email = get_all_client_email_using_lead_id($this, $lead_id);
            //     $to_all_client_email = explode(',', $all_client_email);
            //     send_mailchimp_email($to_all_client_email, $get_mail_subject, $html_content_confirmation_id_verification, $replay_to_mail, '', '', $lead_id);
            //     // send the mail in secondary email
            //     $get_secondary_emali = get_the_secondary_email($this, $lead_id);
            //     if (!empty($get_secondary_emali)) {
            //         send_mailchimp_email($get_secondary_emali, $get_mail_subject, $html_content_confirmation_id_verification, $replay_to_mail, '', '', $lead_id);
            //     }
            //     $insert_task_activity = array(
            //         'leadid' => $lead_id,
            //         'staffid' => get_staff_user_id(),
            //         'full_name' => get_staff_full_name(),
            //         'description' => get_staff_full_name() . ' Sent an email to ' . $lead_data->name . '<br> Good ' . get_afternoon_and_morning() . '<br>' . 'We have received all required ID and await lender instructions.',
            //         'date' => date('Y-m-d H:i:s'),
            //     );
            //     leads_activity_log($this, $insert_task_activity);
            //     // add the app message 
            //     $app_message = 'Your ID has been verified. Once we have the mortgage documents from your new lender we shall set an appointment with you.';
            //     store_app_message_for_client($this, $lead_id, $app_message, $stage_id);
            //     // send slack notification when idv stage complete
            //     $slack_message = "\n - Stage Complete: ID Complete \n- Send ID Complete update \n- Send preliminary e-mail";
            //     $this->slack->sendnotification($slack_message, $lead_id, $lead_data->assign_group,  $lead_name['lastname'] . ', ' . $lead_name['firstname']);
            // // }

            // When instruction received stage complete
            $_POST['case_url'] = admin_url('cases/index/') . $lead_id;
            $_POST['generic_email_title'] = '';
            $_POST['generic_email_content_title'] = 'Good ' . get_afternoon_and_morning();
            $_POST['generic_email_back_to_case_url'] = 'Please <a href="' . htmlspecialchars($_POST['case_url'], ENT_QUOTES, 'UTF-8') . '">Click here</a> to access the file.';
            $_POST['generic_email_content'] = 'ID, IDV are complete and instructions are in. Appointment will now be sent out.';
            $_POST['general_attachment'] = '';
            $html_content_welcome_email_to_bob = $this->load->view('admin/leads/Email_template/generic_email_template', $_POST, TRUE);

            if (base_url() == 'https://dev.platform.legaldirect.ca/') {
                $send_email_result = send_mailchimp_email('ra.faheem7@gmail.com', $get_mail_subject, $html_content_welcome_email_to_bob, $replay_to_mail, '', '', $lead_id);
                // add the record for outbox emails
                $outbox_id = $this->Outbox_model->save_outbox_email(
                    'ra.faheem7@gmail.com',
                    '',
                    '',
                    $get_mail_subject,
                    $_POST['generic_email_content'],
                    '',
                    $lead_id,
                    $stage_id,
                    $html_content_welcome_email_to_bob,
                    $replay_to_mail,
                    $send_email_result['status'],
                    $send_email_result['mandrill_id'],
                    1
                );
            } else {
                $send_email_result = send_mailchimp_email('bb@legaldirect.ca', $get_mail_subject, $html_content_welcome_email_to_bob, $replay_to_mail, '', '', $lead_id);
                // add the record for outbox emails
                $outbox_id = $this->Outbox_model->save_outbox_email(
                    'bb@legaldirect.ca',
                    '',
                    '',
                    $get_mail_subject,
                    $_POST['generic_email_content'],
                    '',
                    $lead_id,
                    $stage_id,
                    $html_content_welcome_email_to_bob,
                    $replay_to_mail,
                    $send_email_result['status'],
                    $send_email_result['mandrill_id']
                );
            }
            //  Send slack notification when instruction received stage complete
            $slack_message = "\n - Stage Complete: ID & Instructions Received \n- Send appointment e-mail.";
            $this->slack->sendnotification($slack_message, $lead_id, $lead_data->assign_group, $lead_name['lastname'] . ', ' . $lead_name['firstname'] . ' ' . $lead_name['middlename']);

            // preloaded checklsit template create
            $this->db->where('rel_id', $lead_id);
            $this->db->where('rel_type', 'user-task');
            $this->db->where('leads_status', 7);
            $check_item_appointment_ld_team = $this->db->get(db_prefix() . 'tasks')->row();
            if (empty($check_item_appointment_ld_team)) {
                $this->db->select('id');
                $this->db->where('type', 'ld_team');
                $this->db->where('case_status', 0);
                $this->db->order_by('order_no', 'asc');
                $query = $this->db->get(db_prefix() . 'checklist_templates');
                $checklist_template_ids = array_column($query->result_array(), 'id');
                preloaded_file_opened_checklist_template_add_in_task_table($this, $checklist_template_ids, $lead_id, 0);
            }
            // send mail to the user 
            $_POST['get_afternoon_and_morning'] = get_afternoon_and_morning();
            // $subject = 'Appointement Request';
            $subject = $get_mail_subject;
            // send notification and app message
            $idv_notification_type = get_notification_type(1);
            $client_notification_type = $notification_type . '-created';
            $client_notify_title = 'Lender instructions received.';
            $client_notify_message = '';
            send_notification_in_mobile('client', get_staff_user_id(), $contact_id, $client_id, $lead_id, $client_notify_title, $client_notify_message, $client_notification_type, '');
            // add the app message 
            $app_message = 'Lender instructions received and being reviewed.';
            store_app_message_for_client($this, $lead_id, $app_message, $stage_id);
            // send emailt to the client
            $get_mail_subject = get_mail_subject_for_case_stages($this, $lead_id, 2);
            $_POST['case_url'] = '';
            $_POST['generic_email_title'] = '';
            $_POST['generic_email_back_to_case_url'] = '';
            $_POST['generic_email_content_title'] = 'Dear ' . get_all_lead_borrower_first_name($this, $lead_id);
            $_POST['generic_email_content'] = 'We have received your lender instructions and are reviewing them. Once reviewed, we shall contact you again to set an appointment to go through the mortgage documents and the new lender’s requirements.';
            $_POST['general_attachment'] = '';
            $html_content_welcome_email_to_user = $this->load->view('admin/leads/Email_template/generic_email_template', $_POST, TRUE);

            $all_client_email = get_all_client_email_using_lead_id($this, $lead_id);
            $to_all_client_email = explode(',', $all_client_email);
            $send_email_result = send_mailchimp_email($to_all_client_email, $get_mail_subject, $html_content_welcome_email_to_user, $replay_to_mail, '', '', $lead_id);
            // add the record for outbox emails
            $outbox_id = $this->Outbox_model->save_outbox_email(
                $to_all_client_email,
                '',
                '',
                $get_mail_subject,
                $_POST['generic_email_content'],
                '',
                $lead_id,
                $stage_id,
                $html_content_welcome_email_to_user,
                $replay_to_mail,
                $send_email_result['status'],
                $send_email_result['mandrill_id'],
                1
            );
            // update the last contact date 
            $this->leads_model->update_leads_last_contact_date($lead_id);
            // send sms to client 
            $sms_message_for_stages = send_sms_according_to_stage_compelte($stage_id);
            $all_client_phone_list = get_all_client_phonenumber_using_lead_id($this, $lead_id);
            if ($stage_id != 2 || ($get_all_clients_emails_count['borrower_count'] > 0 || $get_all_clients_emails_count['borrower_email_count'] > 0)) {
                $this->send_sms($all_client_phone_list, $sms_message_for_stages, $sms_message_for_stages, $lead_id, $lead_data->name, $lead_data->email);
            }
            $response = array(
                'success' => true
            );
        } else {
            $response = array(
                'success' => false
            );
        }
        $this->output
            ->set_content_type('application/json')
            ->set_output(json_encode($response));
    }
    // checklist ledger complete stage
    public function checklist_complete_stage_ledger()
    {
        $lead_id = $this->input->post('lead_id');
        // update the completed status and add date completed at
        $data = array(
            'ledger_completed' => 1,
            'ledger_completed_at' => date('Y-m-d H:i:s'),
        );
        $this->db->where('id', $lead_id);
        $this->db->update(db_prefix() . 'leads', $data);

        // add the activity
        $insert_task_activity = array(
            'leadid' => $lead_id,
            'staffid' => get_staff_user_id(),
            'full_name' => get_staff_full_name(),
            'activity_type' => 'task-activity',
            'description' => "Great news, your transaction has passed through another milestone.",
            'date' => date('Y-m-d H:i:s'),
        );
        leads_activity_log($this, $insert_task_activity);
        // notificaation line of code  and sms line of code 
        $stage_complete_description = 'Great news, your transaction has passed through another milestone.';
        $this->db->select('id,multiple_cases,client_id,phonenumber,name,email,addedfrom');
        $this->db->where('id', $lead_id);
        $lead_data_check = $this->db->get(db_prefix() . 'leads');
        if ($lead_data_check->num_rows() > 0) {
            $lead_data = $lead_data_check->row();
            $client_id = get_client_id_using_contact_id($this, $lead_data->client_id, $lead_data->multiple_cases);
            $contact_id = get_contact_id_using_client_id($this, $client_id);
            $notification_type = get_notification_type(1);
            // send  notiication in crm to all the team group member and staff
            $this->db->select('assign_group,assigned');
            $this->db->where('id', $lead_id);
            $lead_data_for_get_assign_group = $this->db->get(db_prefix() . 'leads')->row();
            $current_staff_data = get_staff_ids_by_group($this, $lead_data_for_get_assign_group->assign_group);
            foreach ($current_staff_data as $staff_notifiy_data) {
                if (get_staff_user_id() != $staff_notifiy_data['staffid']) {
                    $this->leads_model->custom_lead_assigned_member_notification('staff', $lead_id, $staff_notifiy_data['staffid'], get_staff_user_id(), '', $stage_complete_description);
                }
            }
            // get the all admin staff ids
            $admin_ids = get_all_admin_role_staff_ids($this);
            foreach ($admin_ids as $admin_email) {
                if (get_staff_user_id() != $admin_email['staffid']) {
                    //  send notification in crm
                    $this->leads_model->custom_lead_assigned_member_notification('staff', $lead_id, $admin_email['staffid'], get_staff_user_id(), '', $stage_complete_description);
                }
            }
        }
        // set the response
        if (!empty($lead_id)) {

            $leads_status_value = '#request_for_funds';
            $complete_stage_button = 4;
            $response = [
                'success' => true,
                'id' => $lead_id,
                'complete_stage_button' => $complete_stage_button,
                'leads_status' => $leads_status_value,
                'leadView' => $this->_get_lead_data($lead_id),
            ];
        } else {
            $response = [
                'success' => false,
            ];
        }
        $this->output
            ->set_content_type('application/json')
            ->set_output(json_encode($response));
    }
    // move to the archvie
    public function move_to_archive($lead_id)
    {
        // update the completed status and add date completed at
        $data = array(
            'status' => 9,
            // 'active_case' => 'Closed',
            'archive_date' => date('Y-m-d H:i:s'),
            'last_status_change' => date('Y-m-d H:i:s'),
        );
        $this->db->where('id', $lead_id);
        $this->db->update(db_prefix() . 'leads', $data);

        // add the activity
        $insert_task_activity = array(
            'leadid' => $lead_id,
            'staffid' => get_staff_user_id(),
            'full_name' => get_staff_full_name(),
            'activity_type' => 'task-activity',
            'description' => "Successfully Case #" . $lead_id . " has been archived.",
            'date' => date('Y-m-d H:i:s'),
        );
        leads_activity_log($this, $insert_task_activity);
        // notificaation line of code  and sms line of code 
        $stage_complete_description = "Successfully Case #" . $lead_id . " has been archived.";
        $this->db->select('id,multiple_cases,client_id,phonenumber,name,email,addedfrom');
        $this->db->where('id', $lead_id);
        $lead_data_check = $this->db->get(db_prefix() . 'leads');
        if ($lead_data_check->num_rows() > 0) {
            $lead_data = $lead_data_check->row();
            $client_id = get_client_id_using_contact_id($this, $lead_data->client_id, $lead_data->multiple_cases);
            $contact_id = get_contact_id_using_client_id($this, $client_id);
            $notification_type = get_notification_type(1);
            // send  notiication in crm to all the team group member and staff
            $this->db->select('assign_group,assigned');
            $this->db->where('id', $lead_id);
            $lead_data_for_get_assign_group = $this->db->get(db_prefix() . 'leads')->row();
            $current_staff_data = get_staff_ids_by_group($this, $lead_data_for_get_assign_group->assign_group);
            foreach ($current_staff_data as $staff_notifiy_data) {
                if (get_staff_user_id() != $staff_notifiy_data['staffid']) {
                    $this->leads_model->custom_lead_assigned_member_notification('staff', $lead_id, $staff_notifiy_data['staffid'], get_staff_user_id(), '', $stage_complete_description);
                }
            }
            // get the all admin staff ids
            $admin_ids = get_all_admin_role_staff_ids($this);
            foreach ($admin_ids as $admin_email) {
                if (get_staff_user_id() != $admin_email['staffid']) {
                    //  send notification in crm
                    $this->leads_model->custom_lead_assigned_member_notification('staff', $lead_id, $admin_email['staffid'], get_staff_user_id(), '', $stage_complete_description);
                }
            }
        }
        // set the response
        if (!empty($lead_id)) {
            $leads_status_value = '#Closed';
            $complete_stage_button = 5;
            $response = [
                'success' => true,
                'id' => $lead_id,
                'complete_stage_button' => $complete_stage_button,
                'leads_status' => $leads_status_value,
                'leadView' => $this->_get_lead_data($lead_id),
            ];
        } else {
            $response = [
                'success' => false,
            ];
        }
        $this->output
            ->set_content_type('application/json')
            ->set_output(json_encode($response));
    }
    // ledger undo stage
    public function checklist_undo_stage_ledger()
    {
        $lead_id = $this->input->post('lead_id');
        // add the activity
        $data = array(
            'ledger_completed' => 0,
            'status' => 3
        );
        $this->db->where('id', $lead_id);
        $this->db->update(db_prefix() . 'leads', $data);
        $insert_task_activity = array(
            'leadid' => $lead_id,
            'staffid' => get_staff_user_id(),
            'full_name' => get_staff_full_name(),
            'activity_type' => 'task-activity',
            'description' => 'Case Stage move Ledger to Outstanding Item stage.',
            'date' => date('Y-m-d H:i:s'),
        );
        leads_activity_log($this, $insert_task_activity);
        // set the response
        if (!empty($lead_id)) {
            $leads_status_value = '#outstanding_items';
            $complete_stage_button = 3;
            $response = [
                'success' => true,
                'id' => $lead_id,
                'complete_stage_button' => $complete_stage_button,
                'leads_status' => $leads_status_value,
                'leadView' => $this->_get_lead_data($lead_id),
            ];
        } else {
            $response = [
                'success' => false,
            ];
        }
        $this->output
            ->set_content_type('application/json')
            ->set_output(json_encode($response));
    }
    // Checklist undo stage code
    public function checklist_undo_stage()
    {
        $stage_id = $this->input->post('stage_id');
        $lead_id = $this->input->post('lead_id');
        // get the name of case to show in notificaiton
        $this->db->select('name,assign_group');
        $this->db->where('id', $lead_id);
        $leads_details = $this->db->get(db_prefix() . 'leads')->row();
        $case_name = $leads_details->name;
        $stage_name_from = '';
        if ($stage_id == 1) {
            $stage_name_from = 'File opened';
            $stage_description = 'Case Stage undo from ' . $stage_name_from . ' for case (ID: #' . $lead_id . ' & Name: ' . $case_name . ').';
            $data = array(
                'status' => $stage_id,
                'file_opened_completed' => null,
                'last_status_change' => date('Y-m-d H:i:s'),
            );
        } elseif ($stage_id == 2) {
            $stage_name_from = 'Instruction receive';
            $stage_name_to = 'ID Verification';
            $stage_description = 'Case Stage undo from ' . $stage_name_from . ' to ' . $stage_name_to . ' for case (ID: #' . $lead_id . ' & Name: ' . $case_name . ').';
            $stage_id = 8;
            $data = array(
                'status' => $stage_id,
                'ins_received_completed' => null,
                'last_status_change' => date('Y-m-d H:i:s'),
            );
        } elseif ($stage_id == 3) {
            $stage_name_from = 'Outstanding items';
            $stage_name_to = 'Appointment Stage';
            $stage_description = 'Case Stage undo from ' . $stage_name_from . ' to ' . $stage_name_to . ' for case (ID: #' . $lead_id . ' & Name: ' . $case_name . ').';
            $stage_id = 7;
            $data = array(
                'status' => $stage_id,
                'out_items_completed' => null,
                'last_status_change' => date('Y-m-d H:i:s'),
            );
        } elseif ($stage_id == 4) {
            $stage_name_from = 'Request for funds';
            $stage_name_to = 'Outstanding Item';
            $stage_description = 'Case Stage undo from ' . $stage_name_from . ' to ' . $stage_name_to . ' for case (ID: #' . $lead_id . ' & Name: ' . $case_name . ').';
            $data = array(
                'status' => $stage_id,
                'active_case' => 'Active',
                'req_for_funds_completed' => null,
                'ledger_completed' => 0,
                'last_status_change' => date('Y-m-d H:i:s'),
            );
        } elseif ($stage_id == 5) {
            $stage_name_from = 'Closing';
            $stage_name_to = 'Request for funds';
            $stage_description = 'Case Stage undo from ' . $stage_name_from . ' to ' . $stage_name_to . ' for case (ID: #' . $lead_id . ' & Name: ' . $case_name . ').';
            $data = array(
                'status' => $stage_id - 1,
                'active_case' => 'Active',
                'last_status_change' => date('Y-m-d H:i:s'),
                'close_completed' => null
            );
        } elseif ($stage_id == 6) {
            // get the previous status id before gone to on hold
            $before_onhold_status_id = get_stage_status_id_before_go_to_onhold($this, $lead_id);
            // get the previous status name
            $before_onhold_status_name = get_status_name_by_using_status_id($this, $before_onhold_status_id);
            // update record details
            $stage_name_from = 'On Hold';
            $stage_name_to = $before_onhold_status_name;
            $stage_description = 'Case Stage undo from ' . $stage_name_from . ' to ' . $stage_name_to . ' for case (ID: #' . $lead_id . ' & Name: ' . $case_name . ').';
            $stage_id = $before_onhold_status_id;
            $data = array(
                'status' => $stage_id,
                'active_case' => 'Active',
                'last_status_change' => date('Y-m-d H:i:s'),
            );
        } elseif ($stage_id == 7) {
            $stage_name_from = 'Appointment Stage';
            $stage_name_to = 'Instruction Received';
            $stage_description = 'Case Stage undo from ' . $stage_name_from . ' to ' . $stage_name_to . ' for case (ID: #' . $lead_id . ' & Name: ' . $case_name . ').';
            $stage_id = 2;
            $data = array(
                'status' => $stage_id,
                'app_request_completed' => null,
                'last_status_change' => date('Y-m-d H:i:s'),
            );
        } elseif ($stage_id == 8) {
            $stage_name_from = 'File Opened';
            $stage_name_to = 'ID verification';
            $stage_description = 'Case Stage undo from ' . $stage_name_to . ' to ' . $stage_name_from . ' for case (ID: #' . $lead_id . ' & Name: ' . $case_name . ').';
            $stage_id = 1;
            $data = array(
                'status' => $stage_id,
                'id_verification_completed' => null,
                'last_status_change' => date('Y-m-d H:i:s'),
            );
        }
        $this->db->where('id', $lead_id);
        $this->db->update(db_prefix() . 'leads', $data);
        $insert_task_activity = array(
            'leadid' => $lead_id,
            'staffid' => get_staff_user_id(),
            'full_name' => get_staff_full_name(),
            'description' => $stage_description,
            'date' => date('Y-m-d H:i:s'),
        );
        leads_activity_log($this, $insert_task_activity);
        if ($this->db->affected_rows() > 0) {
            // Send Email
            $this->db->select('addedfrom');
            $this->db->where('id', $lead_id);
            $email_lead_data = $this->db->get(db_prefix() . 'leads')->row();
            $_POST['broker_id'] = $email_lead_data->addedfrom;
            $_POST['stage_name'] = $stage_name_from;
            $role = get_current_staff_role($this, $_POST['broker_id']);

            if (isset($_POST['addedfrom']) || $role == 2 || $role == 6) {
                $staff_row = get_staff_data_by_id($this, $_POST['broker_id']);
                $subject = 'Case Stage undo from ' . $stage_name_from . ' to ' . $stage_name_to . '.';
                $html_content_confirmation_email_to_broker = $this->load->view('admin/leads/Email_template/confirmation', $_POST, TRUE);
                $replay_to_mail = get_all_staff_to_replay_email($this, get_staff_user_id(), $leads_details->assign_group);
            }
            $this->db->select('name');
            $this->db->where('rel_id', $lead_id);
            $this->db->where('rel_type', 'user-task');
            $task_data = $this->db->get(db_prefix() . 'tasks')->row();
            // notificaation line of code  and sms line of code 
            $this->db->select('id,multiple_cases,client_id,phonenumber,name,email,addedfrom');
            $this->db->where('id', $lead_id);
            $lead_data_check = $this->db->get(db_prefix() . 'leads');
            if ($lead_data_check->num_rows() > 0) {
                $lead_data = $lead_data_check->row();
                $client_id = get_client_id_using_contact_id($this, $lead_data->client_id, $lead_data->multiple_cases);
                $contact_id = get_contact_id_using_client_id($this, $client_id);
                $notification_type = get_notification_type(2);

                $client_notify_type = $notification_type . '-created';
                $client_notify_title = 'Case Stage undo from';
                $client_notify_message = 'Case Stage undo from ' . $stage_name_from . ' to ' . $stage_name_to . ' for case (ID: #' . $lead_id . ' & Name: ' . $case_name . ').';
                send_notification_in_mobile('client', get_staff_user_id(), $contact_id, $client_id, $lead_id, $client_notify_title, $client_notify_message, $client_notify_type, '');
            }
            if ($stage_id == 3) {
                $puls_stage_id = 7;
            } else if ($stage_id == 7) {
                $puls_stage_id = 7;
            } else if ($stage_id == 2) {
                $puls_stage_id = 2;
            } else if ($stage_id == 1) {
                $puls_stage_id = 1;
            } else if ($stage_id == 8) {
                $puls_stage_id = 8;
            } else if ($stage_id == 4) {
                $puls_stage_id = 9;
            } else {
                $puls_stage_id = $stage_id - 1;
            }
            switch ($puls_stage_id) {
                case 1:
                    $leads_status_value = '#file_opened';
                    $complete_stage_button = 1;
                    break;
                case 2:
                    $leads_status_value = '#instructions_received';
                    $complete_stage_button = 2;
                    break;
                case 3:
                    $leads_status_value = '#outstanding_items';
                    $complete_stage_button = 3;
                    break;
                case 4:
                    $leads_status_value = '#request_for_funds';
                    $complete_stage_button = 4;
                    break;
                case 5:
                    $leads_status_value = '#closed';
                    $complete_stage_button = 5;
                    break;
                case 6:
                    $leads_status_value = '#on_hold';
                    $complete_stage_button = 6;
                    break;
                case 7:
                    $leads_status_value = '#lead_reminders';
                    $complete_stage_button = 7;
                    break;
                case 8:
                    $leads_status_value = '#id_verification';
                    $complete_stage_button = 8;
                    break;
                case 9:
                    $leads_status_value = '#ledger';
                    $complete_stage_button = 9;
                    break;
            }
            $response = [
                'success' => true,
                'id' => $lead_id,
                'complete_stage_button' => $complete_stage_button,
                'leads_status' => $leads_status_value,
                'leadView' => $this->_get_lead_data($lead_id),
                'stage_id' => $stage_id,
                'leads_status_value' => $leads_status_value
            ];
            // send  notiication in crm to all the team group member and staff
            // $this->db->select('assign_group,assigned');
            // $this->db->where('id', $lead_id);
            // $lead_data_for_get_assign_group = $this->db->get(db_prefix() . 'leads')->row();
            // $current_staff_data = get_staff_ids_by_group($this, $lead_data_for_get_assign_group->assign_group);
            // foreach ($current_staff_data as $staff_notifiy_data) {
            //     if (get_staff_user_id() != $staff_notifiy_data['staffid']) {
            //         $ld_team_notify_type = $notification_type . '-created';
            //         $ld_team_notify_title = 'Case Stage Move';
            //         $ld_team_notify_message = 'Case Stage move ' . $stage_name_from . ' to ' . $stage_name_to . ' for case (ID: #' . $lead_id . ' & Name: ' . $case_name . ').';
            //         send_notification_in_mobile('staff', $staff_notifiy_data['staffid'], $contact_id, $client_id, $lead_id, $ld_team_notify_title, $ld_team_notify_message, $ld_team_notify_type, '');
            //         // send slack notification
            //         $slack_message = 'Case Stage move ' . $stage_name_from . ' to ' . $stage_name_to . ' for case (ID: #' . $lead_id . ' & Name: ' . $case_name . ').';
            //         // send notification in the crm
            //         $this->leads_model->custom_lead_assigned_member_notification('staff', $lead_id, $staff_notifiy_data['staffid'], get_staff_user_id(), '', get_staff_full_name() . '  move Case Stage ' . $stage_name_from . ' to ' . $stage_name_to . ' for case (ID: #' . $lead_id . ' & Name: ' . $case_name . ').');
            //     }
            // }
            // // get the all admin staff ids
            // $admin_ids = get_all_admin_role_staff_ids($this);
            // foreach ($admin_ids as $admin_email) {
            //     if (get_staff_user_id() != $admin_email['staffid']) {
            //         $admin_notify_type = $notification_type . '-created';
            //         $admin_notify_title = 'Case Stage Move';
            //         $admin_notify_message = 'Case Stage move ' . $stage_name_from . ' to ' . $stage_name_to . ' for case (ID: #' . $lead_id . ' & Name: ' . $case_name . ').';
            //         send_notification_in_mobile('staff', $admin_email['staffid'], $contact_id, $client_id, $lead_id, $admin_notify_title, $admin_notify_message, $admin_notify_type, '');

            //         // send slack notification
            //         $slack_message = 'Case Stage move ' . $stage_name_from . ' to ' . $stage_name_to . ' for case (ID: #' . $lead_id . ' & Name: ' . $case_name . ').';

            //         // send notification in the crm
            //         $this->leads_model->custom_lead_assigned_member_notification('staff', $lead_id, $admin_email['staffid'], get_staff_user_id(), '', get_staff_full_name() . '  move Case Stage ' . $stage_name_from . ' to ' . $stage_name_to . ' for case (ID: #' . $lead_id . ' & Name: ' . $case_name . ').');
            //     }
            // }
        } else {
            $response = [
                'success' => false,
            ];
        }
        // echo json_encode($response);
        $this->output
            ->set_content_type('application/json')
            ->set_output(json_encode($response));
    }

    // view the checklist load and use in borrower ajax load 
    public function get_checklist_view($lead_id, $borrower_id)
    {
        $data['lead_id'] = $lead_id;
        $data['checklist_id'] = $borrower_id;
        $data['lead_status_current_id'] = $borrower_id;
        $data['lead_borrower_id'] = $borrower_id;

        $this->db->select('assign_group');
        $this->db->where('id', $lead_id);
        $lead_data = $this->db->get(db_prefix() . 'leads')->row();
        $staff_group_name = get_group_name_of_staff($this, get_staff_user_id());
        // case crud permission
        $data['samegroup'] = case_crud_permissions_by_role($this, $lead_data->assign_group, $staff_group_name);

        $this->load->view('admin/leads/checklist_all_borrower', $data);
    }
    // get teh task record by task id
    public function get_task_record_by_task_id()
    {
        $task_id = $this->input->get('task_id');
        $this->db->select('ld_notes, leads_status,name,rel_id,type');
        $this->db->where('id', $task_id);
        $task_data = $this->db->get(db_prefix() . 'tasks')->row();

        if (!empty($task_data)) {
            $response = array(
                'success' => true,
                'ld_notes' => str_replace(["\n", '<br>', '<br/>', '<br />'], '<br>', $task_data->ld_notes),
                'leads_status' => $task_data->leads_status,
                'name' => $task_data->name,
                'type' => $task_data->type,
            );
        } else {
            $this->leads_model->add_errors_logs($task_data->rel_id, get_staff_user_id(), get_staff_full_name(), 'Retrieve the Task ID when uploading a document linked to the checklist.', 'Task id is missing #' . $task_id, 400, 'Staff');
            $response = array(
                'success' => false,
                'ld_notes' => null,
                'leads_status' => null,
            );
        }

        $this->output
            ->set_content_type('application/json')
            ->set_output(json_encode($response));
    }
    public function get_outstanding_ld_task_notes($lead_id)
    {
        $stateId = $this->input->get('stateId');
        $this->db->select('description, leads_status,title,type');
        $this->db->where('id', $stateId);
        $task_data = $this->db->get(db_prefix() . 'cases_checkboxes')->row();

        if (!empty($task_data)) {
            $response = array(
                'success' => true,
                'description' => str_replace(["\n", '<br>', '<br/>', '<br />'], '<br>', $task_data->description),
                'leads_status' => $task_data->leads_status,
                'title' => $task_data->title,
                'type' => $task_data->type
            );
        } else {
            $this->leads_model->add_errors_logs($lead_id, get_staff_user_id(), get_staff_full_name(), 'Retrieve the Task ID againts outstanding stage.', 'Task id is missing againts this functino get_outstanding_ld_task_notes($lead_id)', 400, 'Staff');
            $response = array(
                'success' => false,
                'description' => null,
                'leads_status' => null,
            );
        }

        $this->output
            ->set_content_type('application/json')
            ->set_output(json_encode($response));
    }
    // add the checklist 
    public function checklist($lead_id = '')
    {
        $checklist_stage_id = $this->input->post('checklist_stage_id');
        $lead_borrower_id = $this->input->post('lead_borrower_id');
        if ($lead_borrower_id) {
            $checklist_stage_id = $lead_borrower_id;
        }
        // checklist_type is use to check if broker then not send sms and norifcation
        $checklist_type = $this->input->post('checklist_type');
        $checklist_file = $this->input->post('checklist_file' . $checklist_stage_id);
        // Define validation rules
        $this->form_validation->set_rules('name' . $checklist_stage_id, 'Checklist Title', 'required|min_length[3]|max_length[50]');

        // Define input names for reference
        $input_names = [
            'name' . $checklist_stage_id => 'Title',
        ];
        // print_r($input_names);
        // Run form validation
        if ($this->form_validation->run() == false) {
            // Validation failed
            $errors = [];

            foreach ($input_names as $field => $label) {
                $error = form_error($field);

                if (!empty($error)) {
                    $errors[$field] = $error;
                }
            }

            $response = array(
                'success' => false,
                'errors' => $errors,
            );
            echo json_encode($response);
            exit;
        }
        $name_key = 'name' . $checklist_stage_id;
        $checklist_description_key = 'checklist_description' . $checklist_stage_id;
        $checklist_instruction_key = 'checklist_instruction' . $checklist_stage_id;
        $ld_notes_key = 'ld_notes' . $checklist_stage_id;
        $name = $this->input->post($name_key);
        $status = 2;
        $doc_type = $this->input->post('doc_type');
        $checklist_description = $this->input->post($checklist_description_key);
        // $checklist_instruction = $this->input->post($checklist_instruction_key);
        $ld_notes = $this->input->post($ld_notes_key);
        $checklist_item_type = $this->input->post('Item_name');
        $checklist_type = $this->input->post('outstanding_type');
        // $checklist_instruction = str_replace(['<br />', '<br>', '<br/>'], "\n", nl2br($checklist_instruction));
        $ld_notes = str_replace(['<br />', '<br>', '<br/>'], "\n", nl2br($ld_notes));
        if (is_array($checklist_item_type) && !empty($checklist_item_type)) {
            $Item_name_string = implode(',', $checklist_item_type);
        }
        // add the instruction manually in the custom checklist item
        $checklist_instruction = '';
        if ($checklist_stage_id == 1) {
            $checklist_instruction = 'Please ensure the IDs show ALL edges, are CLEAR, have no flash spots, and are valid (NOT expired).' . "\n\r";
        } elseif ($checklist_stage_id == 3) {
            $checklist_instruction = 'Please use the buttons below to upload your item ensuring there are no flash spots, the picture is clear and the item is valid.' . "\n\r";
        } else {
            $checklist_instruction = 'Please ensure the IDs show ALL edges, are CLEAR, have no flash spots, and are valid (NOT expired).' . "\n\r";
        }
        if ($lead_borrower_id) {
            $task_data = [
                'name' => ucfirst($name),
                'description' => $checklist_description,
                'ld_notes' => $ld_notes,
                'Item_name' => $Item_name_string,
                'status' => $status,
                'dateadded' => date('Y-m-d H:i:s'),
                'rel_id' => $lead_id,
                'lead_borrow_id' => $lead_borrower_id ?? 0,
                'rel_type' => 'user-task',
                'leads_status' => 1,
                'type' => $checklist_type,
            ];
        } else {
            if ($checklist_stage_id == 1) {
                $task_data = [
                    'name' => ucfirst($name),
                    'description' => $checklist_description,
                    'ld_notes' => $ld_notes,
                    'Item_name' => $Item_name_string,
                    'status' => $status,
                    'dateadded' => date('Y-m-d H:i:s'),
                    'rel_id' => $lead_id,
                    'rel_type' => 'user-task',
                    'leads_status' => $checklist_stage_id,
                    'lead_borrow_id' => $lead_borrower_id ?? 0,
                    'type' => $checklist_type,
                ];
            } else {
                $task_data = [
                    'name' => ucfirst($name),
                    'description' => $checklist_description,
                    'ld_notes' => $ld_notes,
                    'Item_name' => null,
                    'status' => $status,
                    'dateadded' => date('Y-m-d H:i:s'),
                    'rel_id' => $lead_id,
                    'rel_type' => 'user-task',
                    'leads_status' => $checklist_stage_id,
                    'lead_borrow_id' => $lead_borrower_id ?? 0,
                    'type' => $checklist_type,
                ];
            }
        }


        $this->db->insert(db_prefix() . 'tasks', $task_data);
        $task_id = $this->db->insert_id();
        // insert the images against taskid 
        if ($lead_borrower_id) {
            $this->upload_doc_for_checklist_all_stages($lead_id, $task_id, $lead_borrower_id);
        } else {
            $this->upload_doc_for_checklist_all_stages($lead_id, $task_id, $checklist_stage_id);
        }

        $doc_type_string = implode(',', $doc_type);
        // Insert file instruction data
        $file_instruction_data = [
            'lead_id' => $lead_id,
            'task_id' => $task_id,
            'instruction' => $checklist_instruction,
            'doc_type' => $doc_type_string,
            'created_at' => date('Y-m-d H:i:s'),
            'updated_by' => '',
        ];

        $this->db->insert(db_prefix() . 'file_instruction', $file_instruction_data);

        // Check if the data was inserted successfully
        if ($this->db->affected_rows() > 0) {
            // Add lead activtiy when checklist is created by admin
            $add_activity_data = [
                'leadid' => $lead_id,
                'staffid' => get_staff_user_id(),
                'full_name' => get_staff_full_name(),
                'description' => 'Checklist (' . ucfirst($name) . ') has been created successfully.',
                'date' => date('Y-m-d H:i:s'),
            ];
            $this->db->insert(db_prefix() . 'lead_activity_log', $add_activity_data);
            $this->db->select('*');
            $this->db->where('rel_id', $lead_id);
            $this->db->where('id', $task_id);
            $this->db->where('rel_type', 'user-task');
            $query_tasks = $this->db->get(db_prefix() . 'tasks');
            $task_data = $query_tasks->row();

            $save = [];

            if (!empty($task_data)) {
                $this->db->select('*');
                $this->db->where('task_id', $task_data->id);
                $this->db->where('rel_id', $lead_id);
                $this->db->where('rel_type', 'client-doc');
                $query_files = $this->db->get(db_prefix() . 'files');
                $file_data = $query_files->result_array();

                // Check if file_data is not empty
                if (!empty($file_data)) {
                    foreach ($file_data as &$file) {
                        $file_type_string = $file['filetype'];
                        $first_part = explode('/', $file_type_string)[1];
                        $directLink = str_replace('raw=1', 'dl=1', $file['file_url']);
                        $file['dl_file_url'] = $directLink;
                        $file['check_filetype'] = $first_part;
                    }
                }

                $new_task_date = time_ago($task_data->dateadded);
                $dt_new_task_date = _dt($task_data->dateadded);
                // get the all details of file insturtion
                $this->db->select('doc_type, instruction');
                $this->db->where('task_id', $task_data->id);
                $file_instruction_data = $this->db->get(db_prefix() . 'file_instruction')->row();
                $save[] = [
                    'id' => $task_data->id,
                    'name' => $task_data->name,
                    'description' => $task_data->description,
                    'doc_type' => $file_instruction_data->doc_type,
                    'instruction' => $file_instruction_data->instruction,
                    'dateadded' => (string) $task_data->dateadded,
                    'new_dateadded' => $new_task_date,
                    'dt_new_dateadded' => (string) $dt_new_task_date,
                    'status' => $task_data->status,
                    'file_data' => $file_data,
                    'checklist_stage_status' => $task_data->leads_status,
                ];
            }
            // notification push code 
            $this->db->where('leadid', $lead_id);
            $this->db->where('activity_type', 'file_opened_mail_send');
            $count = $this->db->count_all_results(db_prefix() . 'lead_activity_log');
            if ($count > 0) {
                // get first email send count
                $this->db->select('multiple_cases,client_id,phonenumber,name,email,addedfrom,app_email_requested');
                $this->db->where('id', $lead_id);
                $lead_data_check = $this->db->get(db_prefix() . 'leads');
                if ($lead_data_check->num_rows() > 0) {
                    $lead_data = $lead_data_check->row();
                    $client_id = get_client_id_using_contact_id($this, $lead_data->client_id, $lead_data->multiple_cases);
                    $contact_id = get_contact_id_using_client_id($this, $client_id);
                    $notification_type = get_notification_type(2);
                    $checklist_instruction = preg_replace('/^\s*(\S.*)$/m', '• $1', $checklist_instruction);
                    // not send notification and sms if broker checklsit created
                    if ($checklist_type != 'broker') {
                        $client_notify_type = $notification_type . '-created';
                        $client_notify_title = 'Checklist created';
                        $notify_message_wording = '';
                        if ($checklist_stage_id == 1) {
                            $notify_message_wording = "file opened";
                        } elseif ($checklist_stage_id == 3) {
                            $notify_message_wording = "outstanding";
                        }
                        $client_notify_message = "Please provide the " . $notify_message_wording . " items to progress your transaction.";
                        send_notification_in_mobile('client', get_staff_user_id(), $contact_id, $client_id, $lead_id, $client_notify_title, $client_notify_message, $client_notify_type, $task_id, '', 'client');
                        $msg = "Hi $lead_data->name,
                        This is Legal Direct. To progress your transaction, please return:
                        • $name
                        
                        PLEASE DO NOT REPLY TO THIS TEXT.";
                        $all_client_phone_list = get_all_client_phonenumber_using_lead_id($this, $lead_id);
                        if ($checklist_stage_id == 1) {
                            $this->send_sms($all_client_phone_list, $msg, $msg, $lead_id, $lead_data->name, $lead_data->email);
                            // Send client app message
                            $app_message = 'Please use the drop down menu below ' . $notify_message_wording . ' for items needed to progress your transaction.';
                            store_app_message_for_client($this, $lead_id, $app_message, 3);
                        } else if ($checklist_stage_id == 3 && $lead_data->app_email_requested > 0) {
                            $this->send_sms($all_client_phone_list, $msg, $msg, $lead_id, $lead_data->name, $lead_data->email);
                            // Send client app message
                            $app_message = 'Please use the drop down menu below ' . $notify_message_wording . ' for items needed to progress your transaction.';
                            store_app_message_for_client($this, $lead_id, $app_message, 3);
                        }
                    } elseif ($checklist_type == 'broker') {
                        $broker_data = get_multiple_broker_details_using_addedfrom($this, $lead_data->addedfrom);
                        foreach ($broker_data as $broker) {
                            $this->leads_model->custom_lead_assigned_member_notification('staff', $lead_id, $broker['staffid'], get_staff_user_id(), '', get_staff_full_name() . ' added a new item (' . $task_data->name . ').');
                        }
                        // send the all admin notification and email to the admin broker
                        $brokerage_id = get_brokerage_id_using_leadid($this, $lead_id);
                        $admin_broker_ids = get_all_admin_broker_role_staff_ids($this, $brokerage_id);
                        foreach ($admin_broker_ids as $admin_broker_email) {
                            if (get_staff_user_id() != $admin_broker_email['staffid'] && !in_array($admin_broker_email['staffid'], explode(',', $lead_data->addedfrom))) {
                                $this->leads_model->custom_lead_assigned_member_notification('staff', $lead_id, $admin_broker_email['staffid'], get_staff_user_id(), '', get_staff_full_name() . ' added a new item (' . $task_data->name . ').');
                            }
                        }
                    }
                }
            }
            // update the last contact date 
            $this->leads_model->update_leads_last_contact_date($lead_id);
            switch ($checklist_stage_id) {
                case 1:
                    $leads_status_value = '#file_opened';
                    $complete_stage_button = 1;
                    break;
                case 2:
                    $leads_status_value = '#instructions_received';
                    $complete_stage_button = 2;
                    break;
                case 3:
                    $leads_status_value = '#outstanding_items';
                    $complete_stage_button = 3;
                    break;
                case 4:
                    $leads_status_value = '#request_for_funds';
                    $complete_stage_button = 4;
                    break;
                default:
                    $leads_status_value = '#file_opened';
                    $complete_stage_button = 1;
                    break;
            }

            $response = array(
                'success' => true,
                'data' => $save,
                'leads_status' => $leads_status_value,
                'complete_stage_button' => $complete_stage_button,
                'id' => $lead_id,
                'leadView' => $this->_get_lead_data($lead_id),
            );

            // Send JSON response
            $this->output
                ->set_content_type('application/json')
                ->set_output(json_encode($response));
        } else {
            $this->leads_model->add_errors_logs($lead_id, get_staff_user_id(), get_staff_full_name(), 'Custom checklist create issue in stage ' . $checklist_stage_id, 'Custom Checklist is not created properly.', 400, 'Staff');
            echo json_encode(['success' => false, 'message' => 'Error inserting data']);
        }
    }
    // 
    // update Checklist 
    public function updatechecklist($lead_id, $task_id)
    {
        $this->load->library('form_validation');

        // Define validation rules
        $this->form_validation->set_rules('name', 'Checklist Title', 'required|min_length[3]|max_length[50]');

        // Define input names for reference
        $input_names = [
            'name' => 'Title',
        ];

        // Run form validation
        if ($this->form_validation->run() == false) {
            // Validation failed
            $errors = [];

            foreach ($input_names as $field => $label) {
                $error = form_error($field);

                if (!empty($error)) {
                    $errors[$field] = $error;
                }
            }

            $response = array(
                'success' => false,
                'errors' => $errors,
            );
            echo json_encode($response);
            exit;
        }
        $name = $this->input->post('name');
        $doc_type = $this->input->post('doc_type');
        $Item_name = $this->input->post('Item_name');
        $checklist_description = $this->input->post('checklist_description');
        $checklist_instruction = $this->input->post('checklist_instruction');
        $checklist_ld_notes = $this->input->post('ld_notes');
        $checklist_instruction = str_replace(['<br />', '<br>', '<br/>'], "\n", nl2br($checklist_instruction));
        $checklist_ld_notes = str_replace(['<br />', '<br>', '<br/>'], "\n", nl2br($checklist_ld_notes));

        // convert item  name array to string
        if (is_array($Item_name) && !empty($Item_name)) {
            $Item_name_string = implode(',', $Item_name);
        }

        // Insert task data
        $task_data = [
            'name' => ucfirst($name),
            'ld_notes' => $checklist_ld_notes,
            'description' => $checklist_description,
            'Item_name' => $Item_name_string
        ];

        $this->db->where('rel_id', $lead_id);
        $this->db->where('rel_type', 'user-task');
        $this->db->where('id', $task_id);
        $this->db->update(db_prefix() . 'tasks', $task_data);
        $doc_type_string = implode(',', $doc_type);
        // Insert file instruction data
        $file_instruction_data = [
            'instruction' => $checklist_instruction,
            'doc_type' => $doc_type_string,
            'updated_at' => date('Y-m-d H:i:s'),
            'updated_by' => get_staff_full_name(),
        ];
        // Update file instruction data
        $this->db->where('lead_id', $lead_id);
        $this->db->where('task_id', $task_id);
        $this->db->update(db_prefix() . 'file_instruction', $file_instruction_data);
        // Check if the data was inserted successfully
        if ($this->db->affected_rows() > 0) {
            // Add lead activtiy when checklist is created by admin
            $add_activity_data = [
                'leadid' => $lead_id,
                'staffid' => get_staff_user_id(),
                'full_name' => get_staff_full_name(),
                'description' => 'Checklist updated by ' . get_staff_full_name() . '.',
                'date' => date('Y-m-d H:i:s'),
            ];
            // Update Lead activity
            $this->db->where('leadid', $lead_id);
            $this->db->where('task_id', $task_id);
            $this->db->where('activity_type', 'task-activity');
            $this->db->update(db_prefix() . 'lead_activity_log', $add_activity_data);
            // get the task
            $this->db->select('*');
            $this->db->where('rel_id', $lead_id);
            $this->db->where('id', $task_id);
            $this->db->where('rel_type', 'user-task');
            $query_tasks = $this->db->get(db_prefix() . 'tasks');
            $task_data = $query_tasks->row();
            // get file instruction
            $this->db->where('lead_id', $lead_id);
            $this->db->where('task_id', $task_id);
            $file_instruction_data = $this->db->get(db_prefix() . 'file_instruction')->row();
            $save = [];

            if (!empty($task_data)) {
                $this->db->select('*');
                $this->db->where('task_id', $task_data->id);
                $this->db->where('rel_id', $lead_id);
                $this->db->where('rel_type', 'client-doc');
                $query_files = $this->db->get(db_prefix() . 'files');
                $file_data = $query_files->result_array();

                // Check if file_data is not empty
                if (!empty($file_data)) {
                    foreach ($file_data as &$file) {
                        $file_type_string = $file['filetype'];
                        $first_part = explode('/', $file_type_string)[1];
                        $directLink = str_replace('raw=1', 'dl=1', $file['file_url']);
                        $file['dl_file_url'] = $directLink;
                        $file['check_filetype'] = $first_part;
                    }
                }

                $new_task_date = time_ago($task_data->dateadded);
                $dt_new_task_date = _dt($task_data->dateadded);
                // get the all details of file insturtion
                $this->db->select('doc_type, instruction');
                $this->db->where('task_id', $task_data->id);
                $file_instruction_data = $this->db->get(db_prefix() . 'file_instruction')->row();
                $save[] = [
                    'id' => $task_data->id,
                    'lead_id' => $task_data->rel_id,
                    'leads_status' => $task_data->leads_status,
                    'name' => $task_data->name,
                    'ld_notes' => $task_data->ld_notes,
                    'description' => $task_data->description,
                    'doc_type' => $file_instruction_data->doc_type,
                    'instruction' => $file_instruction_data->instruction,
                    'dateadded' => (string) $task_data->dateadded,
                    'new_dateadded' => $new_task_date,
                    'dt_new_dateadded' => (string) $dt_new_task_date,
                    'status' => $task_data->status,
                    'file_data' => $file_data,
                ];
                // notification push code 
                $this->db->select('multiple_cases,client_id,phonenumber,name,email');
                $this->db->where('id', $lead_id);
                $lead_data_check = $this->db->get(db_prefix() . 'leads');
                if ($lead_data_check->num_rows() > 0) {
                    $lead_data = $lead_data_check->row();
                    $client_id = get_client_id_using_contact_id($this, $lead_data->client_id, $lead_data->multiple_cases);
                    $contact_id = get_contact_id_using_client_id($this, $client_id);
                    $notification_type = get_notification_type(2);
                    $client_notify_type = $notification_type . '-updated';
                    $client_notify_title = 'Checklist updated';
                    $client_notify_message = 'This is Legal Direct. To progress your transaction, please return ' . $checklist_instruction . '.';
                    send_notification_in_mobile('client', get_staff_user_id(), $contact_id, $client_id, $lead_id, $client_notify_title, $client_notify_message, $client_notify_type, $task_id);

                    $msg = 'Hi ' . $lead_data->name . '
                    This is Legal Direct. To progress your transaction, please return ' . $checklist_instruction . ' PLEASE DO NOT REPLY TO THIS TEXT.';

                    $all_client_phone_list = get_all_client_phonenumber_using_lead_id($this, $lead_id);
                    $this->send_sms($all_client_phone_list, $msg, $msg, $lead_id, $lead_data->name, $lead_data->email);
                }
            }
            $response = array(
                'success' => true,
                'data' => $save,
            );
            $this->output
                ->set_content_type('application/json')
                ->set_output(json_encode($response));
        } else {
            $this->leads_model->add_errors_logs($lead_id, get_staff_user_id(), get_staff_full_name(), 'Custom checklist updated issue.', 'Custom checklist updated issue for id ' . $task_id, 400, 'Staff');
            echo json_encode(['success' => false, 'message' => 'Checklist is not update.']);
        }
    }
    // File opened client review email code
    public function file_opened_client_review_email_send($lead_id)
    {
        $file_opened_client_email_review_tincymac = $this->input->post('file_opened_client_email_review_tincymac', FALSE);
        $to_fileopen_client_reviewmail = $this->input->post('to_fileopen_client_reviewmail');
        $cc_fileopen_client_reviewmail = $this->input->post('cc_fileopen_client_reviewmail');
        $bcc_fileopen_client_reviewmail = $this->input->post('bcc_fileopen_client_reviewmail');
        // map the emaili
        $to_emails = array_map('trim', explode(',', $to_fileopen_client_reviewmail));
        $cc_emails = array_map('trim', explode(',', $cc_fileopen_client_reviewmail));
        $bcc_emails = array_map('trim', explode(',', $bcc_fileopen_client_reviewmail));
        $this->db->select('email,name,phonenumber,assign_group');
        $this->db->where('id', $lead_id);
        $lead_data = $this->db->get(db_prefix() . 'leads')->row();

        // send the account details email to the client
        $get_mail_subject = get_mail_subject_for_case_stages($this, $lead_id, 1);
        $subject = $get_mail_subject;
        $replay_to_mail = get_all_staff_to_replay_email($this, get_staff_user_id(), $lead_data->assign_group, $to_emails);
        if (!empty($file_opened_client_email_review_tincymac)) {
            $_POST['file_opened_client_email_review_tincymac'] = $file_opened_client_email_review_tincymac;
            $html_content_welcome_email_to_user = $this->load->view('admin/leads/Email_template/client/file_opened_review_checklist', $_POST, TRUE);
            $send_email_result = send_mailchimp_email($to_emails, $get_mail_subject, $html_content_welcome_email_to_user, $replay_to_mail, $cc_emails, $bcc_emails, $lead_id);
            // add the record for outbox emails
            $outbox_id = $this->Outbox_model->save_outbox_email(
                $to_emails,
                $cc_emails,
                $bcc_emails,
                $get_mail_subject,
                $file_opened_client_email_review_tincymac,
                '',
                $lead_id,
                1,
                $html_content_welcome_email_to_user,
                $replay_to_mail,
                $send_email_result['status'],
                $send_email_result['mandrill_id'],
                1
            );
            // add the activiy logs
            $insert_task_activity = array(
                'leadid' => $lead_id,
                'staffid' => get_staff_user_id(),
                'full_name' => get_staff_full_name(),
                'description' => get_staff_full_name() . ' Sent an email to (' . $lead_data->name . ') <br>' . $file_opened_client_email_review_tincymac,
                'date' => date('Y-m-d H:i:s'),
                'activity_type' => 'file_opened_mail_send'
            );
            $activity_log_last_id = leads_activity_log($this, $insert_task_activity);
            // add the app message 
            $app_message = 'Congratulations, your case has been opened. The first step is the ID requirement. Please check your email and the File Opened drop down menu below, click on any red items to upload your ID.';
            store_app_message_for_client($this, $lead_id, $app_message, 1);
            // update the last contact date 
            $this->leads_model->update_leads_last_contact_date($lead_id);
            $response = array(
                'success' => true,
                'activity_log_last_id' => is_numeric($activity_log_last_id) ? $activity_log_last_id : ''
            );
        } else {
            $response = array(
                'success' => false
            );
        }
        $this->output
            ->set_content_type('application/json')
            ->set_output(json_encode($response));
    }
    // send login emails 
    public function send_login_email_to_client($lead_id)
    {
        $this->db->select('email,name,phonenumber,assign_group');
        $this->db->where('id', $lead_id);
        $lead_data = $this->db->get(db_prefix() . 'leads')->row();
        // send the account details email to the client
        $get_mail_subject = get_mail_subject_for_case_stages($this, $lead_id, 1);
        $subject = $get_mail_subject;
        $replay_to_mail = get_all_staff_to_replay_email($this, get_staff_user_id(), $lead_data->assign_group);
        // send account activiation email to client if check
        $change_password_flag = get_app_side_change_password_flag($this, $lead_data->email);
        if ($change_password_flag == 'false') {
            if (base_url() == 'https://dev.platform.legaldirect.ca/') {
                $get_all_clients_emails_count = get_all_clients_email_counts_separately($this, $lead_id);
                $new_password = generateRandomPassword($lead_id, $lead_data->name);
                update_client_password_using_email($this, $lead_data->email, $new_password);
                $_POST['password'] = $new_password;
                $_POST['email'] = $lead_data->email;
                $_POST['name'] = $lead_data->name;
                $_POST['borrower_email_count'] = $get_all_clients_emails_count['borrower_email_count'];
                $_POST['borrower_count'] = $get_all_clients_emails_count['borrower_count'];
                $login_subject = $subject;
                $html_content_account_activiation = $this->load->view('admin/leads/Email_template/account_activation', $_POST, TRUE);
                $send_email_result = send_mailchimp_email($lead_data->email, $login_subject, $html_content_account_activiation, $replay_to_mail, '', '', $lead_id);

                // add the record for outbox emails
                $outbox_content = 'Welcome to Legal Direct’s new market leading software “LEGAL DIRECTLY”!. We are pleased to provide you with your initial login details: Email: XXXXXXX, Password: XXXXXX, Please use these credentials to log in to the Legal Direct User App. If this is a transaction for 2 or more borrowers only the primary borrower will receive this email.Upon your first login, you will be prompted to change your password for added security.Heres how to proceed:Download the Legal Direct User App from your app store.Use the provided username and temporary password to log in.Follow the on-screen prompts to set a new, secure password.Remember to keep your password confidential and unique for your accounts protection. If you have any questions or need assistance, please donnot hesitate to contact our team at (905) 787-2296.Thank you for choosing Legal Direct.';
                $outbox_id = $this->Outbox_model->save_outbox_email(
                    $lead_data->email,
                    '',
                    '',
                    $login_subject,
                    $_POST['generic_email_content'],
                    '',
                    $lead_id,
                    1,
                    $html_content_account_activiation,
                    $replay_to_mail,
                    $send_email_result['status'],
                    $send_email_result['mandrill_id'],
                    0
                );
                // send sms to the client
                $sms_msg = 'Hi ' . $lead_data->name . ' This is Legal Direct. Your new case #' . $lead_id . ' has been created successfully. Please check your email and login to our app LEGAL DIRECTLY for next steps. Please DO NOT REPLY TO THIS TEXT.';
                $all_client_phone_list = get_all_client_phonenumber_using_lead_id($this, $lead_id);
                if (!empty($all_client_phone_list)) {
                    $this->send_sms($all_client_phone_list, $sms_msg, $sms_msg, $lead_id, $lead_data->name, $lead_data->email);
                }
                // send the notification to user in mobile side
                // notification send code
                $this->db->select('multiple_cases,client_id,phonenumber,name,email,addedfrom');
                $this->db->where('id', $lead_id);
                $lead_data_check = $this->db->get(db_prefix() . 'leads');
                if ($lead_data_check->num_rows() > 0) {
                    $lead_data = $lead_data_check->row();
                    $case_name = $lead_data->name;
                    $client_id = get_client_id_using_contact_id($this, $lead_data->client_id, $lead_data->multiple_cases);
                    $contact_id = get_contact_id_using_client_id($this, $client_id);
                    $notification_type = get_notification_type(1);
                    $client_notify_title = 'File Opened';
                    $sms_msg = 'Hi ' . $lead_data->name . ' This is Legal Direct. Your new case #' . $lead_id . ' has been created successfully. Please check your email and login to our app LEGAL DIRECTLY for next steps.';
                    $client_notify_message = $sms_msg;
                    send_notification_in_mobile('client', get_staff_user_id(), $contact_id, $client_id, $lead_id, $client_notify_title, $client_notify_message, $notification_type, '');
                }
                // add activity logs
                $insert_task_activity = array(
                    'leadid' => $lead_id,
                    'staffid' => get_staff_user_id(),
                    'full_name' => get_staff_full_name(),
                    'description' => get_staff_full_name() . 'sent login email to the client.',
                    'date' => date('Y-m-d H:i:s'),
                );
                $activity_log_last_id = leads_activity_log($this, $insert_task_activity);

                $response = array(
                    'success' => true,
                    'activity_log_last_id' => is_numeric($activity_log_last_id) ? $activity_log_last_id : '',
                    'message' => 'Email sent successfully.'
                );
            }
        } else {
            $response = array(
                'success' => false,
                'message' => 'User is already update password. '
            );
        }
        $this->output
            ->set_content_type('application/json')
            ->set_output(json_encode($response));
    }
    // send the outstanding ids email to all clients
    public function file_opened_outstanding_ids_client_review_email_send($lead_id)
    {
        $file_opened_client_email_review_outstanding_tincymac = $this->input->post('file_opened_client_email_review_outstanding_tincymac', FALSE);
        $to_fileopen_outstanding_ids_client_reviewmail = $this->input->post('to_fileopen_outstanding_ids_client_reviewmail');
        $cc_fileopen_outstanding_ids_client_reviewmail = $this->input->post('cc_fileopen_outstanding_ids_client_reviewmail');
        $bcc_fileopen_outstanding_ids_client_reviewmail = $this->input->post('bcc_fileopen_outstanding_ids_client_reviewmail');
        // map the emaili
        $to_emails = array_map('trim', explode(',', $to_fileopen_outstanding_ids_client_reviewmail));
        $cc_emails = array_map('trim', explode(',', $cc_fileopen_outstanding_ids_client_reviewmail));
        $bcc_emails = array_map('trim', explode(',', $bcc_fileopen_outstanding_ids_client_reviewmail));
        $this->db->select('email,name,phonenumber,client_id,multiple_cases,assign_group');
        $this->db->where('id', $lead_id);
        $lead_data = $this->db->get(db_prefix() . 'leads')->row();
        if (!empty($file_opened_client_email_review_outstanding_tincymac)) {
            $get_mail_subject = get_mail_subject_for_case_stages($this, $lead_id, 1);
            $_POST['case_url'] = '';
            $_POST['generic_email_title'] = '';
            $_POST['generic_email_back_to_case_url'] = $file_opened_client_email_review_outstanding_tincymac;
            $_POST['generic_email_content'] = '';
            $_POST['general_attachment'] = '';
            $html_content_welcome_email_to_user = $this->load->view('admin/leads/Email_template/generic_email_template', $_POST, TRUE);
            $replay_to_mail = get_all_staff_to_replay_email($this, get_staff_user_id(), $lead_data->assign_group, $to_emails);
            $send_email_result = send_mailchimp_email($to_emails, $get_mail_subject, $html_content_welcome_email_to_user, $replay_to_mail, $cc_emails, $bcc_emails, $lead_id);
            // add the record for outbox emails
            $outbox_id = $this->Outbox_model->save_outbox_email(
                $to_emails,
                '',
                '',
                $get_mail_subject,
                $file_opened_client_email_review_outstanding_tincymac,
                '',
                $lead_id,
                1,
                $html_content_welcome_email_to_user,
                $replay_to_mail,
                $send_email_result['status'],
                $send_email_result['mandrill_id'],
                1
            );
            // add the activiy logs
            $insert_task_activity = array(
                'leadid' => $lead_id,
                'staffid' => get_staff_user_id(),
                'full_name' => get_staff_full_name(),
                'description' => get_staff_full_name() . ' Sent an email to ' . $lead_data->name . '<br>' . $file_opened_client_email_review_outstanding_tincymac,
                'date' => date('Y-m-d H:i:s'),
            );
            $activity_log_last_id = leads_activity_log($this, $insert_task_activity);
            // send notification in app side 
            $client_id = get_client_id_using_contact_id($this, $lead_data->client_id, $lead_data->multiple_cases);
            $contact_id = get_contact_id_using_client_id($this, $client_id);
            $notification_type = get_notification_type(1);
            $client_notify_title = 'IDs outstanding';
            $client_notify_message = '';
            send_notification_in_mobile('client', get_staff_user_id(), $contact_id, $client_id, $lead_id, $client_notify_title, $client_notify_message, $notification_type, '');
            // add the app home screen message
            $app_message = 'IDs outstanding.';
            store_app_message_for_client($this, $lead_id, $app_message, 1);
            // send sms to all clients
            $msg = 'Hi ' . $lead_data->name . ', This is Legal Direct.Please check your email and the Legal Directly app and provide the outstanding IDs to progress your file.PLEASE DO NOT REPLY TO THIS TEXT.';
            $all_client_phone_list = get_all_client_phonenumber_using_lead_id($this, $lead_id);
            $this->send_sms($all_client_phone_list, $msg, $msg, $lead_id, $lead_data->name, $lead_data->email);
            // update the last contact date 
            $this->leads_model->update_leads_last_contact_date($lead_id);
            $response = array(
                'success' => true,
                'activity_log_last_id' => is_numeric($activity_log_last_id) ? $activity_log_last_id : ''
            );
        } else {
            $response = array(
                'success' => false
            );
        }
        $this->output
            ->set_content_type('application/json')
            ->set_output(json_encode($response));
    }
    // get the all borrower checklist details
    public function get_file_opened_borrower_checklist_items($lead_id)
    {
        $this->db->select('id,name,lead_borrow_id,rejection_reason');
        $this->db->where('rel_id', $lead_id);
        $this->db->where('rel_type', 'user-task');
        $this->db->where('type', 'client');
        $this->db->where_in('status', [2, 3]);
        $this->db->where('leads_status', 1);
        $borrower_data = $this->db->get(db_prefix() . 'tasks')->result_array();

        // Add the borrower details  
        foreach ($borrower_data as &$record) {
            if (!empty($record['lead_borrow_id'])) {
                $record['client_name'] = get_borrwer_name_by_id($this, $record['lead_borrow_id']);
            } else {
                $record['client_name'] = get_lead_name_using_lead_id($this, $lead_id);
            }
        }
        if (!empty($borrower_data)) {
            $response = array(
                'success' => true,
                'borrower_data' => $borrower_data
            );
        } else {
            $response = array(
                'success' => false,
                'borrower_data' => null
            );
        }
        $this->output
            ->set_content_type('application/json')
            ->set_output(json_encode($response));
    }
    // get the all checklist item details for oustanding and appointmetn stage for email review
    public function outstanding_item_checklist_review_mail($lead_id)
    {
        $this->db->select('id,name,lead_borrow_id,rejection_reason');
        $this->db->where('rel_id', $lead_id);
        $this->db->where('rel_type', 'user-task');
        $this->db->where('type', 'client');
        $this->db->where_in('status', [2, 3]);
        $this->db->where('leads_status', 3);
        $borrower_data = $this->db->get(db_prefix() . 'tasks')->result_array();
        if (!empty($borrower_data)) {
            $response = array(
                'success' => true,
                'borrower_data' => $borrower_data
            );
        } else {
            $response = array(
                'success' => false,
                'borrower_data' => null
            );
        }
        $this->output
            ->set_content_type('application/json')
            ->set_output(json_encode($response));
    }
    // get the all checklist for ld team
    public function get_ld_team_outstanding_checklist_email_review($lead_id)
    {
        $this->db->select('id,title');
        $this->db->where('lead_id', $lead_id);
        $this->db->where('leads_status', 3);
        $task_data = $this->db->get(db_prefix() . 'cases_checkboxes')->result_array();
        $task_items = '';
        if (!empty($task_data)) {
            foreach ($task_data as $task) {
                $task_items .= '<li>' . htmlspecialchars($task['title']) . '</li>';
            }
            $response = array(
                'success' => true,
                'task_data' => $task_items
            );
        } else {
            $response = array(
                'success' => false,
                'task_data' => null
            );
        }
        $this->output
            ->set_content_type('application/json')
            ->set_output(json_encode($response));
    }
    // get the all ledgers
    // get all lenders details
    public function get_latest_lender_details($lead_id)
    {
        // Get lender IDs for the given lead
        $this->db->select('lender_ids');
        $this->db->where('id', $lead_id);
        $get_lenders_ids = $this->db->get(db_prefix() . 'leads')->row();
        if (!empty($get_lenders_ids->lender_ids)) {
            $this->db->select('id, bank_name, lender_address, lender_phoneno');
            $this->db->where_in('id', explode(',', $get_lenders_ids->lender_ids));
            $get_lender_data = $this->db->get(db_prefix() . 'bank')->result_array();
            foreach ($get_lender_data as &$record) {
                $this->db->select('loan_amount');
                $this->db->where('lead_id', $lead_id);
                $this->db->where('bank_id', $record['id']);
                $get_data = $this->db->get(db_prefix() . 'leads_bank_details')->row();
                $record['loan_amount'] = isset($get_data->loan_amount) ? $get_data->loan_amount : '-';
            }
            // get the item using lead_id
            $check_Insurance_Binder = 0;
            $check_Void_cheque = 0;
            $Property_tax_statement = 0;
            $this->db->select('name, status');
            $this->db->where('leads_status', '3');
            $this->db->where('type', 'client');
            $this->db->where('rel_id', $lead_id);
            $this->db->where('rel_type', 'user-task');
            $lead_tasks = $this->db->get(db_prefix() . 'tasks')->result_array();
            if (!empty($lead_tasks)) {
                foreach ($lead_tasks as $task) {
                    if (($task['status'] == 2 || $task['status'] == 3)) {
                        if ($task['name'] == 'Void cheque(s)') {
                            $check_Void_cheque = 1;
                        }
                        if ($task['name'] == 'PROPERTY INSURANCE' || $task['name'] == 'Property insurance') {
                            $check_Insurance_Binder = 1;
                        }
                        if ($task['name'] == 'Property tax statement') {
                            $Property_tax_statement = 1;
                        }
                    }
                }
            }
            if (!empty($get_lender_data)) {
                $response = array(
                    'success' => true,
                    'ledger_data' => $get_lender_data,
                    'check_Void_cheque' => $check_Void_cheque,
                    'check_Insurance_Binder' => $check_Insurance_Binder,
                    'Property_tax_statement' => $Property_tax_statement
                );
            } else {
                $response = array(
                    'success' => false,
                    'ledger_data' => null
                );
            }
        } else {
            $response = array(
                'success' => false,
                'ledger_data' => null
            );
        }
        $this->output
            ->set_content_type('application/json')
            ->set_output(json_encode($response));
    }
    // get the last time of ledgers
    public function get_the_last_approved_ledger_time($lead_id)
    {
        $this->db->select('bb_change_status_time');
        $this->db->where('lead_id', $lead_id);
        $this->db->where('type', 'ld_team');
        $this->db->where('bb_status', 'Approved');
        $this->db->order_by('id', 'desc');
        $this->db->limit(1);
        $get_the_data = $this->db->get(db_prefix() . 'leads_ledger')->row();
        if (!empty($get_the_data)) {
            $response = array(
                'success' => true,
                'ledger_approve_time' => $get_the_data->bb_change_status_time,
            );
        } else {
            $response = array(
                'success' => true,
                'ledger_approve_time' => null,
            );
        }
        $this->output
            ->set_content_type('application/json')
            ->set_output(json_encode($response));
    }
    public function get_leads_ledger_for_ldteam($lead_id)
    {
        // get the ledger data
        $this->db->select('id,lead_id,ledger_number,type,file_name,filetype,file_url,bb_status,bb_comment,bb_change_status_time,created_at');
        $this->db->where('lead_id', $lead_id);
        $this->db->where_in('type', ['ld_team', 'broker']);
        $ledger_data = $this->db->get(db_prefix() . 'leads_ledger')->result_array();

        // Fetch logs for each ledger
        $ledger_logs = [];
        if (!empty($ledger_data)) {
            foreach ($ledger_data as $ledger) {
                $this->db->select('id, status, comment, notes, created_at');
                $this->db->where('lead_ledger_id', $ledger['id']);
                $this->db->where('lead_id', $lead_id);
                $logs = $this->db->get(db_prefix() . 'leads_ledger_logs')->result_array();
                $ledger_logs[$ledger['id']] = $logs;
            }

            $response = array(
                'success' => true,
                'ledger_data' => $ledger_data,
                'ledger_logs' => $ledger_logs
            );
        } else {
            $response = array(
                'success' => false,
                'ledger_data' => null,
                'ledger_logs' => null
            );
        }

        $this->output
            ->set_content_type('application/json')
            ->set_output(json_encode($response));
    }
    // update the leadger logs 
    public function update_leader_logs($lead_id)
    {
        $leadger_log_id = $this->input->post('leadger_log_id');
        $leadger_log_comment = $this->input->post('leadger_log_comment');

        if (!empty($leadger_log_id) && !empty($leadger_log_comment)) {
            $update_log_data = array(
                'comment' => $leadger_log_comment,
            );
            // update the leadger logs
            $this->db->where('id', $leadger_log_id);
            $this->db->update(db_prefix() . 'leads_ledger_logs', $update_log_data);
            if ($this->db->affected_rows() > 0) {
                // add the activity of ledges change status
                $insert_task_activity = array(
                    'leadid' => $lead_id,
                    'staffid' => get_staff_user_id(),
                    'full_name' => get_staff_full_name(),
                    'description' => 'Ledger log has been updated by ' . get_staff_full_name(),
                    'date' => date('Y-m-d H:i:s'),
                );
                leads_activity_log($this, $insert_task_activity);

                $response = array(
                    'success' => true,
                    'message' => 'Ledger log has been updated successfully.',
                    'ledger_log_id' => $leadger_log_id,
                    'ledger_log_comment' => $leadger_log_comment
                );
            } else {
                $response = array(
                    'success' => false,
                    'message' => 'Ledger log is not updated.'
                );
            }
        } else {
            $response = array(
                'success' => false,
                'message' => 'Missing the log_id or comments'
            );
        }
        $this->output
            ->set_content_type('application/json')
            ->set_output(json_encode($response));
    }
    // get the final ledgers details
    public function get_leads_final_ledger_for_ldteam($lead_id)
    {
        // get the ledger data
        $this->db->select('id, lead_id, ledger_number, type, file_name, filetype, file_url, bb_status, bb_comment, bb_change_status_time, created_at');
        $this->db->where('lead_id', $lead_id);
        $this->db->where('type', 'final-closed-ledger-sent');
        $ledger_data = $this->db->get(db_prefix() . 'leads_ledger')->result_array();

        // Fetch logs for each ledger
        $ledger_logs = [];
        if (!empty($ledger_data)) {
            foreach ($ledger_data as $ledger) {
                $this->db->select('status, comment, created_at');
                $this->db->where('lead_id', $lead_id);
                $this->db->where('lead_ledger_number', $ledger['ledger_number']);
                $this->db->where('leads_ledger_type', 'final-closed-ledger-sent');
                $logs = $this->db->get(db_prefix() . 'leads_ledger_logs')->result_array();
                $ledger_logs[$ledger['id']] = $logs;
            }

            $response = [
                'success' => true,
                'ledger_data' => $ledger_data,
                'ledger_logs' => $ledger_logs,
            ];
        } else {
            $response = [
                'success' => false,
                'ledger_data' => null,
                'ledger_logs' => null,
            ];
        }
        $this->output
            ->set_content_type('application/json')
            ->set_output(json_encode($response));
    }
    // change the status for bb ledgers
    public function ledger_status_change_by_bb($lead_id)
    {
        $ledger_id = $this->input->post('ledger_id');
        $ledger_number = $this->input->post('ledger_number');
        $status = $this->input->post('status');
        $bb_comment = $this->input->post('bb_comment');
        // get the lead data
        $this->db->select('assign_group,name');
        $this->db->where('id', $lead_id);
        $lead_data = $this->db->get(db_prefix() . 'leads')->row();
        $data = array(
            'bb_status' => $status,
            'bb_comment' => $bb_comment,
            'bb_change_status_time' => date('Y-m-d H:i:s'),
            'bb_approval_button' => 1
        );
        $ledger_log_data = array(
            'lead_id' => $lead_id,
            'lead_ledger_id' => $ledger_id,
            'lead_ledger_number' => $ledger_number,
            'status' => 'Ledgers has been ' . $status . ' by ' . get_staff_full_name(),
            'comment' => $bb_comment,
            'created_at' => date('Y-m-d H:i:s'),
        );
        if (!empty($ledger_number) && !empty($status)) {
            $this->db->where('ledger_number', $ledger_number);
            $this->db->where('lead_id', $lead_id);
            $this->db->update(db_prefix() . 'leads_ledger', $data);
            // add the status logs in the ledger_logs 
            $this->db->insert(db_prefix() . 'leads_ledger_logs', $ledger_log_data);
            // add the activity of ledges change status
            $insert_task_activity = array(
                'leadid' => $lead_id,
                'staffid' => get_staff_user_id(),
                'full_name' => get_staff_full_name(),
                'description' => 'Ledgers has been ' . $status . ' by ' . get_staff_full_name(),
                'date' => date('Y-m-d H:i:s'),
            );
            leads_activity_log($this, $insert_task_activity);
            // if current staff is not a broker
            $role = get_current_staff_role($this, get_staff_user_id());
            if ($role != 2 && $role != 6) {
                // send email and notification to the all admins and team
                $mail_content_accr_to_status = "The ledger you have sent has been reviewed by BB and his response is $status";

                if ($status === 'Approved') {
                    $mail_content_accr_to_status .= ".";
                } elseif ($status === 'Rejected' && !empty($bb_comment)) {
                    $mail_content_accr_to_status .= " for the following reason: $bb_comment.";
                }
                $get_mail_subject = 'Ledger Review ' . get_mail_subject($this, $lead_id);
                $_POST['case_url'] = admin_url('cases/index/') . $lead_id;
                $_POST['generic_email_title'] = '';
                $_POST['generic_email_back_to_case_url'] = $mail_content_accr_to_status . ' Please <a href="' . htmlspecialchars($_POST['case_url'], ENT_QUOTES, 'UTF-8') . '">Click here</a> to see his response.';
                $_POST['generic_email_content'] = 'Good ' . get_afternoon_and_morning() . '<br>';
                $html_content_welcome_email_to_user = $this->load->view('admin/leads/Email_template/generic_email_template', $_POST, TRUE);
                $replay_to_mail = get_all_staff_to_replay_email($this, get_staff_user_id(), $lead_data->assign_group);

                $current_staff_data = get_staff_ids_by_group($this, $lead_data->assign_group);
                $ledger_message = 'Ledgers has been ' . $status . ' by ' . get_staff_full_name() . ' for case (#' . $lead_id . ', Name:' . $lead_data->name . ').';
                $slack_message = $ledger_message;
                foreach ($current_staff_data as $staff_notifiy_data) {
                    if (get_staff_user_id() != $staff_notifiy_data['staffid']) {
                        // send_mailchimp_email($staff_notifiy_data['email'], $get_mail_subject, $html_content_welcome_email_to_user, $replay_to_mail, '', '', $lead_id);
                        // send notification in crm
                        $this->leads_model->custom_lead_assigned_member_notification('staff', $lead_id, $staff_notifiy_data['staffid'], get_staff_user_id(), '', $ledger_message);
                    }
                }
                // get the all admin staff ids
                $admin_ids = get_all_admin_role_staff_ids($this);
                foreach ($admin_ids as $admin_email) {
                    if (get_staff_user_id() != $admin_email['staffid']) {
                        // send_mailchimp_email($admin_email['email'], $get_mail_subject, $html_content_welcome_email_to_user, $replay_to_mail, '', '', $lead_id);
                        // send notification in crm
                        $this->leads_model->custom_lead_assigned_member_notification('staff', $lead_id, $admin_email['staffid'], get_staff_user_id(), '', $ledger_message);
                    }
                }

                $group_name = get_the_group_name_using_leadid($this, $lead_id);
                $lead_name = get_lead_name_using_lead_id($this, $lead_id);
                $lead_split_name = leads_splitFullName($lead_name);
                if ($status == 'Approved') {
                    $data = array(
                        'ledger_completed' => 1,
                        'ledger_completed_at' => date('Y-m-d H:i:s'),
                    );
                    $this->db->where('id', $lead_id);
                    $this->db->update(db_prefix() . 'leads', $data);
                    // Send Slack notification
                    $review_text = $ledger_number > 1 ? 'REVISED ledgers' : 'ledgers';
                    $slack_message = "\n - Please note, Bob has reviewed the {$review_text} and approved them. Combine the ledgers and send out for review." .
                        "\n - Attach relevant payouts if required." .
                        "\n - " . $bb_comment;

                    $lead_full_name = $lead_split_name['lastname'] . ', ' . $lead_split_name['firstname'] . ' ' . $lead_split_name['middlename'];
                    $this->slack->sendnotification($slack_message, $lead_id, $group_name, $lead_full_name);
                }
            }
            if ($status == 'Rejected') {
                // send slack notification when first time
                $review_text = $ledger_number > 1 ? 'REVISED ledgers' : 'ledgers';
                $slack_message = "\n -Please note, Bob has reviewed the {$review_text} and REJECTED them. Please correct and resend when ready." .
                    "\n - " . $bb_comment;

                $lead_full_name = $lead_split_name['lastname'] . ', ' . $lead_split_name['firstname'] . ' ' . $lead_split_name['middlename'];

                $this->slack->sendnotification($slack_message, $lead_id, $group_name, $lead_full_name);
                // $slack_message = "\n - Ledgers Rejected \n - Note: " . $bb_comment;
                // $send_notification = $this->slack->sendnotification($slack_message, $lead_id, $group_name, $lead_split_name['lastname'] . ', ' . $lead_split_name['firstname'] . ' ' . $lead_split_name['middlename']);
            }
            $response = array(
                'success' => true,
                'leads_status' => '#ledger',
                'id' => $lead_id,
                'leadView' => $this->_get_lead_data($lead_id),
            );
        } else {
            $response = array(
                'success' => false
            );
        }
        $this->output
            ->set_content_type('application/json')
            ->set_output(json_encode($response));
    }
    // file opened review email code 
    public function file_opened_review_email_send($lead_id)
    {
        $file_opened_client_emailContent = $this->input->post('file_opened_client_emailContent', FALSE);
        $to_fileopenreviewmail = $this->input->post('to_fileopenreviewmail');
        $cc_fileopenreviewmail = $this->input->post('cc_fileopenreviewmail');
        $bcc_fileopenreviewmail = $this->input->post('bcc_fileopenreviewmail');
        $to_emails = array_map('trim', explode(',', $to_fileopenreviewmail));
        $cc_emails = array_map('trim', explode(',', $cc_fileopenreviewmail));
        $bcc_emails = array_map('trim', explode(',', $bcc_fileopenreviewmail));
        $get_mail_subject = get_mail_subject($this, $lead_id);
        if (!empty($file_opened_client_emailContent)) {
            // get the lead data
            $this->db->select('addedfrom,assign_group');
            $this->db->where('id', $lead_id);
            $get_lead_data = $this->db->get(db_prefix() . 'leads')->row();
            // get the staff data
            $broker_data = get_multiple_broker_details_using_addedfrom($this, $get_lead_data->addedfrom);
            $_POST['file_opened_client_emailContent'] = $file_opened_client_emailContent;
            $_POST['case_url'] = get_the_redirect_email_case_url($lead_id, 'broker');
            $html_content_welcome_email_to_user = $this->load->view('admin/leads/Email_template/broker/file_opened_review_mail', $_POST, TRUE);

            $subject = $get_mail_subject;
            $replay_to_mail = get_all_staff_to_replay_email($this, get_staff_user_id(), $get_lead_data->assign_group);
            $send_email_result = send_mailchimp_email($to_emails, $subject, $html_content_welcome_email_to_user, $replay_to_mail, $cc_emails, $bcc_emails, $lead_id);
            // add the record for outbox emails
            $outbox_id = $this->Outbox_model->save_outbox_email(
                $to_emails,
                '',
                '',
                $subject,
                $file_opened_client_emailContent,
                '',
                $lead_id,
                1,
                $html_content_welcome_email_to_user,
                $replay_to_mail,
                $send_email_result['status'],
                $send_email_result['mandrill_id'],
                1
            );
            if (!empty($broker_data)) {
                foreach ($broker_data as $broker) {
                    $_POST['broker_name'] = $broker['firstname'] . ' ' . $broker['lastname'];
                    $broker_email = $broker['email'];
                    $this->leads_model->custom_lead_assigned_member_notification('staff', $lead_id, $broker['staffid'], get_staff_user_id(), '', 'New insturction are coming from the ' . get_staff_full_name() . '. Please check your email for required documents. Thank you!');
                }
                // send the all admin notification and email to the admin broker
                $brokerage_id = get_brokerage_id_using_leadid($this, $lead_id);
                $admin_broker_ids = get_all_admin_broker_role_staff_ids($this, $brokerage_id);
                foreach ($admin_broker_ids as $admin_broker_email) {
                    if (get_staff_user_id() != $admin_broker_email['staffid'] && !in_array($admin_broker_email['staffid'], explode(',', $get_lead_data->addedfrom))) {
                        $_POST['broker_name'] = $admin_broker_email['firstname'] . ' ' . $admin_broker_email['lastname'];
                        $broker_email = $admin_broker_email['email'];
                        $this->leads_model->custom_lead_assigned_member_notification('staff', $lead_id, $admin_broker_email['staffid'], get_staff_user_id(), '', 'New insturction are coming from the ' . get_staff_full_name() . '. Please check your email for required documents. Thank you!');
                    }
                }
            }

            $insert_task_activity = array(
                'leadid' => $lead_id,
                'staffid' => get_staff_user_id(),
                'full_name' => get_staff_full_name(),
                'description' => get_staff_full_name() . ' Sent an email to (' . $to_fileopenreviewmail . ' ) <br>' . $file_opened_client_emailContent,
                'date' => date('Y-m-d H:i:s'),
            );
            $activity_log_last_id = leads_activity_log($this, $insert_task_activity);
            // update the last contact date 
            $this->leads_model->update_leads_last_contact_date($lead_id);
            $response = array(
                'success' => true,
                'activity_log_last_id' => is_numeric($activity_log_last_id) ? $activity_log_last_id : ''
            );
        } else {
            $response = array(
                'success' => false
            );
        }
        $this->output
            ->set_content_type('application/json')
            ->set_output(json_encode($response));
    }
    // send review mail to the client 
    public function file_opened_review_email_send_to_client($lead_id)
    {

        $item_ids = $this->input->post('task_id');
        $type = $this->input->post('type');
        // get the lead email
        $this->db->select('email,name,assign_group');
        $this->db->where('id', $lead_id);
        $lead_data = $this->db->get(db_prefix() . 'leads')->row();

        $this->db->select('lead_borrow_id, name');
        $this->db->where_in('id', $item_ids);
        $task_query = $this->db->get(db_prefix() . 'tasks')->result_array();

        $response_records = array();

        $client_data = array();
        $client_data['client'] = 'Client 1';
        $client_data['borrower_checklist_name'] = '';

        $tasks_with_borrower_id = array();

        foreach ($task_query as $record) {
            if (empty($record['lead_borrow_id'])) {
                $client_data['borrower_checklist_name'] .= $record['name'] . '<br>';
            } else {
                $tasks_with_borrower_id[] = $record;
            }
        }

        // If there are tasks without a lead_borrow_id, add them as Client 1
        if (!empty($client_data['borrower_checklist_name'])) {
            $response_records[] = $client_data;
        }

        $borrower_ids = array_unique(array_column($tasks_with_borrower_id, 'lead_borrow_id'));

        $client_number = 2;

        foreach ($borrower_ids as $borrower_id) {
            $client_data = array();
            $client_data['client'] = 'Client ' . $client_number;
            $client_data['borrower_checklist_name'] = '';

            foreach ($tasks_with_borrower_id as $record) {
                if ($borrower_id == $record['lead_borrow_id']) {
                    $client_data['borrower_checklist_name'] .= $record['name'] . '<br>';
                }
            }

            $response_records[] = $client_data;
            $client_number++;
        }
        if (!empty($response_records)) {
            // if checkboxes check in view appened the record not send mail even broker button not hit
            if ($type != "view" || empty($type)) {
                // send mail to the client 
                $_POST['get_afternoon_and_morning'] = get_afternoon_and_morning();
                $get_mail_subject = get_mail_subject($this, $lead_id);
                $_POST['response_records'] = $response_records;
                $html_content_welcome_email_to_user = $this->load->view('admin/leads/Email_template/client/file_opened_review_checklist', $_POST, TRUE);
                $replay_to_mail = get_all_staff_to_replay_email($this, get_staff_user_id(), $lead_data->assign_group);
                $all_client_email = get_all_client_email_using_lead_id($this, $lead_id);
                $to_all_client_email = explode(',', $all_client_email);
                $send_email_result = send_mailchimp_email($to_all_client_email, $get_mail_subject, $html_content_welcome_email_to_user, $replay_to_mail, '', '', $lead_id);
                // add the record for outbox emails
                $outbox_id = $this->Outbox_model->save_outbox_email(
                    $to_all_client_email,
                    '',
                    '',
                    $get_mail_subject,
                    $_POST['file_opened_client_email_review_tincymac'],
                    '',
                    $lead_id,
                    1,
                    $html_content_welcome_email_to_user,
                    $replay_to_mail,
                    $send_email_result['status'],
                    $send_email_result['mandrill_id'],
                    1
                );
            }
            $response = array(
                'success' => true,
                'response_records' => $response_records
            );
        } else {
            $response = array(
                'success' => false
            );
        }
        $this->output
            ->set_content_type('application/json')
            ->set_output(json_encode($response));
    }
    // add the details of appointmetn request stage
    public function appointment_details_add($lead_id)
    {
        $appointment_purpose_funds = $this->input->post('appointment_purpose_funds');
        $appointment_id_seen = $this->input->post('appointment_id_seen');
        $appointment_notes = $this->input->post('appointment_notes');
        $vc_confirmation = $this->input->post('vc_confirmation');
        // add details of appointment 
        $insert_data = array(
            'lead_id' => $lead_id,
            'type' => 'appointment_details',
            'appointment_purpose_funds' => str_replace(['<br />', '<br>', '<br/>'], "\n", nl2br($appointment_purpose_funds)),
            'appointment_id_seen' => str_replace(['<br />', '<br>', '<br/>'], "\n", nl2br($appointment_id_seen)),
            'appointment_notes' => str_replace(['<br />', '<br>', '<br/>'], "\n", nl2br($appointment_notes)),
            'vc_confirmation' => str_replace(['<br />', '<br>', '<br/>'], "\n", nl2br($vc_confirmation)),
            'appointment_details_created_at' => date('Y-m-d H:i:s'),
            'action_by' => get_staff_full_name() . ' add the appointment details',
        );
        $this->db->insert(db_prefix() . 'cases_checkboxes', $insert_data);
        if ($this->db->affected_rows()) {
            $add_activity_data = [
                'leadid' => $lead_id,
                'staffid' => get_staff_user_id(),
                'full_name' => get_staff_full_name(),
                'description' => 'Appointment details have been entered by ' . get_staff_full_name() . '.',
                'date' => date('Y-m-d H:i:s'),
            ];
            $this->db->insert(db_prefix() . 'lead_activity_log', $add_activity_data);
            // perform checklist complete stage for appointment request and send notification same like as checklist_complete_stage for id 7
            $stage_id = 3;
            $stage_name = 'Appointment Stage';
            $stage_description = 'Great news, your transaction has passed through another milestone.';
            $data = array(
                'status' => $stage_id,
                'app_request_completed' => 1,
                'last_status_change' => date('Y-m-d H:i:s'),
                'app_request_completed_at' => date('Y-m-d H:i:s'),
                'outstanding_item_started_at' => date('Y-m-d H:i:s'),
            );
            $this->db->where('id', $lead_id);
            $this->db->update(db_prefix() . 'leads', $data);
            // creating a checklist items for outstanding preloaded when appointment request stage complete
            $this->db->where('lead_id', $lead_id);
            $this->db->where('leads_status', 3);
            $check_item_outstanding_ld_team = $this->db->get(db_prefix() . 'cases_checkboxes')->row();
            if (empty($check_item_outstanding_ld_team)) {
                // get the checklist template ids for outstandin items and show preloaded for client
                $this->db->select('id');
                $this->db->where('type', 'ld_team');
                $this->db->where('case_status', 3);
                $this->db->order_by('order_no', 'asc');
                $ld_query = $this->db->get(db_prefix() . 'checklist_templates');
                $checklist_template_ids_for_ldteam = array_column($ld_query->result_array(), 'id');
                preloaded_outstanding_item_for_ld_team($this, $checklist_template_ids_for_ldteam, $lead_id, 3, 'other_items');
            }
            // outstanding secure payout item details
            $this->db->where('lead_id', $lead_id);
            $this->db->where('leads_status', 7);
            $check_item_outstanding_ld_team_payouts = $this->db->get(db_prefix() . 'cases_checkboxes')->row();
            if (empty($check_item_outstanding_ld_team_payouts)) {
                // get the checklist template ids for outstandin items and show preloaded for client
                $this->db->select('id');
                $this->db->where('type', 'secure_charge');
                $this->db->where('case_status', 7);
                $this->db->order_by('order_no', 'asc');
                $ld_query = $this->db->get(db_prefix() . 'checklist_templates');
                $checklist_template_ids_for_ldteam_payouts = array_column($ld_query->result_array(), 'id');
                preloaded_outstanding_item_for_ld_team($this, $checklist_template_ids_for_ldteam_payouts, $lead_id, 7, '');
                // secure private charge loaded
                $this->db->select('id');
                $this->db->where('type', 'app_general');
                $this->db->where('case_status', 7);
                $this->db->order_by('order_no', 'asc');
                $ld_query = $this->db->get(db_prefix() . 'checklist_templates');
                $checklist_template_ids_for_ldteam_payouts = array_column($ld_query->result_array(), 'id');
                preloaded_outstanding_item_for_ld_team($this, $checklist_template_ids_for_ldteam_payouts, $lead_id, 7, '');
            }
            // update the purpose of funds notes details
            $purpose_funds_items_notes = [
                'description' => $appointment_purpose_funds
            ];
            $this->db->where('title', 'PURPOSE OF FUNDS');
            $this->db->where('lead_id', $lead_id);
            $this->db->update(db_prefix() . 'cases_checkboxes', $purpose_funds_items_notes);
            // get the lead data
            $this->db->select('id,name,email,client_id,multiple_cases');
            $this->db->where('id', $lead_id);
            $lead_data = $this->db->get(db_prefix() . 'leads')->row();
            $client_id = get_client_id_using_contact_id($this, $lead_data->client_id, $lead_data->multiple_cases);
            $contact_id = get_contact_id_using_client_id($this, $client_id);
            // send notification and app message
            $idv_notification_type = get_notification_type(4);
            $client_notification_type = $idv_notification_type;
            $client_notify_title = 'Appointment completed.';
            $client_notify_message = '';
            send_notification_in_mobile('client', get_staff_user_id(), $contact_id, $client_id, $lead_id, $client_notify_title, $client_notify_message, $client_notification_type, '');
            // add the app message 
            $app_message = 'Appointment completed. Please use the Outstanding Items dropdown menu below to provide items required to progress your case.';
            store_app_message_for_client($this, $lead_id, $app_message, $stage_id);
            //  send sms to the client
            $msg = 'This is Legal Direct. Please provide any outstanding items as discussed during your recent meeting via email or using the Legal Directly app. PLEASE DO NOT REPLY TO THIS TEXT.';
            $all_client_phone_list = get_all_client_phonenumber_using_lead_id($this, $lead_id);
            $this->send_sms($all_client_phone_list, $msg, $msg, $lead_id, $lead_data->name, $lead_data->email);
            // Send Slack notification
            $group_name = get_the_group_name_using_leadid($this, $lead_id);
            $lead_name = get_lead_name_using_lead_id($this, $lead_id);
            $lead_split_name = leads_splitFullName($lead_name);
            $slack_message = "\n - Stage Complete: Appointment Complete \n- Upload.";
            $this->slack->sendnotification($slack_message, $lead_id, $group_name, $lead_split_name['lastname'] . ', ' . $lead_split_name['firstname'] . ' ' . $lead_split_name['middlename']);
            $response = array(
                'success' => true,
                'id' => $lead_id,
                'leads_status' => '#outstanding_items',
                'leadView' => $this->_get_lead_data($lead_id),
            );
        } else {
            $response = array(
                'success' => false,
            );
        }
        $this->output
            ->set_content_type('application/json')
            ->set_output(json_encode($response));
    }
    // get the appointment add details
    public function get_appointment_details($lead_id)
    {
        // Select the necessary columns from the table
        if (!empty($lead_id)) {
            $this->db->select('appointment_purpose_funds, appointment_id_seen, appointment_notes, appointment_details_created_at,action_by,vc_confirmation');
            $this->db->where('type', 'appointment_details');
            $this->db->where('lead_id', $lead_id);
            $data = $this->db->get(db_prefix() . 'cases_checkboxes')->result_array();
            if (!empty($data)) {
                $response = array(
                    'success' => true,
                    'data' => $data
                );
            } else {
                $response = array(
                    'success' => false,
                    'message' => 'No appointment details found.'
                );
            }
        } else {
            $response = array(
                'success' => false,
                'message' => 'No appointment details found.'
            );
        }
        $this->output
            ->set_content_type('application/json')
            ->set_output(json_encode($response));
    }
    // send review mail for appointment
    public function appointment_review_broker_email($lead_id)
    {
        $appointment_broker_email_review_tincymac = $this->input->post('appointment_broker_email_review_tincymac', FALSE);
        $to_appointment_broker_reviewmail = $this->input->post('to_appointment_broker_reviewmail');
        $cc_appointment_broker_reviewmail = $this->input->post('cc_appointment_broker_reviewmail');
        $bcc_appointment_broker_reviewmail = $this->input->post('bcc_appointment_broker_reviewmail');
        $to_emails = array_map('trim', explode(',', $to_appointment_broker_reviewmail));
        $cc_emails = array_map('trim', explode(',', $cc_appointment_broker_reviewmail));
        $bcc_emails = array_map('trim', explode(',', $bcc_appointment_broker_reviewmail));
        $get_mail_subject = get_mail_subject($this, $lead_id);
        $this->db->select('addedfrom,assign_group');
        $this->db->where('id', $lead_id);
        $get_lead_data = $this->db->get(db_prefix() . 'leads')->row();
        // get the staff data
        $get_staff_record = get_multiple_broker_details_using_addedfrom($this, $get_lead_data->addedfrom);
        $_POST['appointment_broker_email_review_tincymac'] = $appointment_broker_email_review_tincymac;
        $_POST['case_url'] = get_the_redirect_email_case_url($lead_id, 'broker');
        $html_content_welcome_email_to_user = $this->load->view('admin/leads/Email_template/broker/appointment_item_review_mail', $_POST, TRUE);
        if (!empty($appointment_broker_email_review_tincymac)) {
            $subject = $get_mail_subject;
            $replay_to_mail = get_all_staff_to_replay_email($this, get_staff_user_id(), $get_lead_data->assign_group);
            $send_email_result = send_mailchimp_email($to_emails, $subject, $html_content_welcome_email_to_user, $replay_to_mail, $cc_emails, $bcc_emails, $lead_id);
            // add the record for outbox emails
            $outbox_id = $this->Outbox_model->save_outbox_email(
                $to_emails,
                $cc_emails,
                $bcc_emails,
                $subject,
                $_POST['appointment_broker_email_review_tincymac'],
                '',
                $lead_id,
                7,
                $html_content_welcome_email_to_user,
                $replay_to_mail,
                $send_email_result['status'],
                $send_email_result['mandrill_id'],
                1
            );
            if (!empty($get_staff_record)) {
                foreach ($get_staff_record as $broker) {
                    $_POST['broker_name'] = $broker['firstname'] . ' ' . $broker['lastname'];
                    $broker_email = $broker['email'];
                    // send notification in crm
                    $this->leads_model->custom_lead_assigned_member_notification('staff', $lead_id, $broker['staffid'], get_staff_user_id(), '', 'New insturction are coming from the ' . get_staff_full_name() . '. Please check your email for required documents. Thank you!');
                    // add the emali in activity logs
                    $insert_task_activity = array(
                        'leadid' => $lead_id,
                        'staffid' => get_staff_user_id(),
                        'full_name' => get_staff_full_name(),
                        'description' => get_staff_full_name() . " sent an email to " . $_POST['broker_name'] . ' <br>' . $appointment_broker_email_review_tincymac,
                        'date' => date('Y-m-d H:i:s'),
                    );
                    leads_activity_log($this, $insert_task_activity);
                }
                // send the all admin notification and email to the admin broker
                $brokerage_id = get_brokerage_id_using_leadid($this, $lead_id);
                $admin_broker_ids = get_all_admin_broker_role_staff_ids($this, $brokerage_id);
                foreach ($admin_broker_ids as $admin_broker_email) {
                    if (get_staff_user_id() != $admin_broker_email['staffid'] && !in_array($admin_broker_email['staffid'], explode(',', $get_lead_data->addedfrom))) {
                        $_POST['broker_name'] = $admin_broker_email['firstname'] . ' ' . $admin_broker_email['lastname'];
                        $broker_email = $admin_broker_email['email'];
                        // send notification in crm
                        $this->leads_model->custom_lead_assigned_member_notification('staff', $lead_id, $admin_broker_email['staffid'], get_staff_user_id(), '', 'New insturction are coming from the ' . get_staff_full_name() . '. Please check your email for required documents. Thank you!');
                    }
                }
            }
            // update the last contact date 
            $this->leads_model->update_leads_last_contact_date($lead_id);
            $response = array(
                'success' => true,
            );
        } else {
            $response = array(
                'success' => false,
            );
        }
        $this->output
            ->set_content_type('application/json')
            ->set_output(json_encode($response));
    }
    // Send after appointment email send to the client
    public function after_appointment_email_send_to_client($lead_id)
    {
        $emailContent = $this->input->post('after_appointment_emailContent', FALSE);
        $to_after_appointment_reviewmail = $this->input->post('to_after_appointment_reviewmail');
        $cc_after_appointment_reviewmail = $this->input->post('cc_after_appointment_reviewmail');
        $bcc_after_appointment_reviewmail = $this->input->post('bcc_after_appointment_reviewmail');
        $to_emails = array_map('trim', explode(',', $to_after_appointment_reviewmail));
        $cc_emails = array_map('trim', explode(',', $cc_after_appointment_reviewmail));
        $bcc_emails = array_map('trim', explode(',', $bcc_after_appointment_reviewmail));
        // get the leads data
        $this->db->select('email,name,addedfrom,assign_group');
        $this->db->where('id', $lead_id);
        $get_lead_data = $this->db->get(db_prefix() . 'leads')->row();
        // send mail to the client
        if (!empty($emailContent)) {
            $get_mail_subject = get_mail_subject($this, $lead_id);
            $_POST['case_url'] = admin_url('cases/index/') . $lead_id;
            $_POST['generic_email_title'] = '';
            $_POST['generic_email_back_to_case_url'] = 'Please <a href="' . htmlspecialchars($_POST['case_url'], ENT_QUOTES, 'UTF-8') . '">Click here</a> to access the file.';
            $_POST['generic_email_content'] = $emailContent;
            $html_content_welcome_email_to_user = $this->load->view('admin/leads/Email_template/generic_email_template', $_POST, TRUE);
            $subject = $get_mail_subject;
            $replay_to_mail = get_all_staff_to_replay_email($this, get_staff_user_id(), $get_lead_data->assign_group, $to_emails);
            $send_email_result = send_mailchimp_email($to_emails, $subject, $html_content_welcome_email_to_user, $replay_to_mail, $cc_emails, $bcc_emails);
            // add the record for outbox emails
            $outbox_id = $this->Outbox_model->save_outbox_email(
                $to_emails,
                $cc_emails,
                $bcc_emails,
                $subject,
                $_POST['generic_email_content'],
                '',
                $lead_id,
                7,
                $html_content_welcome_email_to_user,
                $replay_to_mail,
                $send_email_result['status'],
                $send_email_result['mandrill_id'],
                1
            );
            $insert_task_activity = array(
                'leadid' => $lead_id,
                'staffid' => get_staff_user_id(),
                'full_name' => get_staff_full_name(),
                'description' => get_staff_full_name() . ' Sent an email to ' . $get_lead_data->name . ' Please click on the view button to review email' . $emailContent,
                'date' => date('Y-m-d H:i:s'),
            );
            leads_activity_log($this, $insert_task_activity);
            // update the last contact date 
            $this->leads_model->update_leads_last_contact_date($lead_id);
            $response = array(
                'success' => true
            );
        } else {
            $response = array(
                'success' => false
            );
        }
        $this->output
            ->set_content_type('application/json')
            ->set_output(json_encode($response));
    }
    // Send client Review mail for appointment
    public function client_appointment_review_email_send($lead_id)
    {
        $emailContent = $this->input->post('appointment_client_emailContent', FALSE);
        $to_client_appointment_reviewmail = $this->input->post('to_client_appointment_reviewmail');
        $cc_client_appointment_reviewmail = $this->input->post('cc_client_appointment_reviewmail');
        $bcc_client_appointment_reviewmail = $this->input->post('bcc_client_appointment_reviewmail');
        $to_emails = array_map('trim', explode(',', $to_client_appointment_reviewmail));
        $cc_emails = array_map('trim', explode(',', $cc_client_appointment_reviewmail));
        $bcc_emails = array_map('trim', explode(',', $bcc_client_appointment_reviewmail));
        // send mail to the client
        $this->appt_client_email_sent('', $lead_id, $to_emails, $cc_emails, $bcc_emails, $emailContent, '', '');
        // if (!empty($emailContent)) {
        //     $get_mail_subject = get_mail_subject_for_case_stages($this, $lead_id, 7);
        //     $_POST['email_content'] = $emailContent;
        //     $html_content_welcome_email_to_user = $this->load->view('admin/leads/Email_template/client/client_appointment_item_review_mail', $_POST, TRUE);

        //     $subject = $get_mail_subject;
        //     $replay_to_mail = get_all_staff_to_replay_email($this, get_staff_user_id(), $get_lead_data->assign_group, $to_emails);
        //     send_mailchimp_email($to_emails, $subject, $html_content_welcome_email_to_user, $replay_to_mail, $cc_emails, $bcc_emails, $lead_id);
        //     // update the record of leads 
        //     $update_lead_array = array(
        //         'app_email_requested' => 1
        //     );
        //     $this->db->where('id', $lead_id);
        //     $this->db->update(db_prefix() . 'leads', $update_lead_array);
        //     // send the email to broker and add the activity of of the broker mail
        //     $staff_row = get_multiple_broker_details_using_addedfrom($this, $get_lead_data->addedfrom);
        //     $appointment_date = get_latest_set_case_appointment($this, $lead_id);
        //     $broker_replay_to_mail = get_all_staff_to_replay_email($this, get_staff_user_id(), $get_lead_data->assign_group);
        //     $_POST['start_date'] = $appointment_date['start_date'];
        //     $_POST['end_date'] = $appointment_date['end_date'];
        //     if (!empty($staff_row)) {
        //         $broker_message = 'We are delighted to inform you that the file has successfully moved through another
        //         milestone, the mortgage offer has been received and we are liaising with the Client over a suitable appointment date.We shall update you again upon conclusion of that meeting.';
        //         foreach ($staff_row as $broker) {
        //             $_POST['broker_name'] = $broker['firstname'] . ' ' . $broker['lastname'];
        //             $_POST['case_url'] = admin_url('cases/index/') . $lead_id;
        //             $broker_email = $broker['email'];
        //             $html_content_confirmation_email_to_broker = $this->load->view('admin/leads/Email_template/broker/instruction_received_stage_complete', $_POST, TRUE);
        //             send_mailchimp_email($broker_email, $subject, $html_content_confirmation_email_to_broker, $broker_replay_to_mail, '', '', $lead_id);

        //         }
        //         // send the all admin notification and email to the admin broker
        //         $brokerage_id = get_brokerage_id_using_leadid($this, $lead_id);
        //         $admin_broker_ids = get_all_admin_broker_role_staff_ids($this, $brokerage_id);
        //         foreach ($admin_broker_ids as $admin_broker_email) {
        //             if (get_staff_user_id() != $admin_broker_email['staffid'] && !in_array($admin_broker_email['staffid'], explode(',', $get_lead_data->addedfrom))) {
        //                 $_POST['broker_name'] = $admin_broker_email['firstname'] . ' ' . $admin_broker_email['lastname'];
        //                 $_POST['case_url'] = admin_url('cases/index/') . $lead_id;
        //                 $broker_email = $admin_broker_email['email'];
        //                 $html_content_confirmation_email_to_broker = $this->load->view('admin/leads/Email_template/broker/instruction_received_stage_complete', $_POST, TRUE);
        //                 send_mailchimp_email($broker_email, $subject, $html_content_confirmation_email_to_broker, $broker_replay_to_mail, '', '', $lead_id);
        //             }
        //         }
        //         $insert_task_activity = array(
        //             'leadid' => $lead_id,
        //             'staffid' => get_staff_user_id(),
        //             'full_name' => get_staff_full_name(),
        //             'description' => get_staff_full_name() . ' Sent an email to Brokers <br> Good ' . get_afternoon_and_morning() . '<br>' . $broker_message,
        //             'date' => date('Y-m-d H:i:s'),
        //         );
        //         leads_activity_log($this, $insert_task_activity);
        //     }

        //     // add the email in activity logs
        //     $insert_task_activity = array(
        //         'leadid' => $lead_id,
        //         'staffid' => get_staff_user_id(),
        //         'full_name' => get_staff_full_name(),
        //         'description' => get_staff_full_name() . " sent an email to " . $get_lead_data->name . ' <br>' . $emailContent,
        //         'date' => date('Y-m-d H:i:s'),
        //     );
        //     $activity_log_last_id = leads_activity_log($this, $insert_task_activity);
        //     // send notification to ld and admin
        //     $this->db->select('assign_group,assigned,name');
        //     $this->db->where('id', $lead_id);
        //     $lead_data_for_get_assign_group = $this->db->get(db_prefix() . 'leads')->row();
        //     $current_staff_data = get_staff_ids_by_group($this, $lead_data_for_get_assign_group->assign_group);
        //     $closed_message = 'Thank you for completing the ID process. Please check your email for the mortgage documents signing appointment.';
        //     $crm_message = 'Appointment to be sent out for case #' . $lead_id . '.';
        //     // notification line of code
        //     $client_id = get_client_id_using_contact_id($this, $get_lead_data->client_id, $get_lead_data->multiple_cases);
        //     $contact_id = get_contact_id_using_client_id($this, $client_id);
        //     $notification_type = get_notification_type(4);
        //     $client_notify_type = $notification_type;
        //     $client_notify_message = '';
        //     $client_notify_title = 'Mortgage Offer received and Appointment Set ' . $get_date['start_date'] . '.';
        //     send_notification_in_mobile('client', get_staff_user_id(), $contact_id, $client_id, $lead_id, $client_notify_title, $client_notify_message, $client_notify_type, '');

        //     // send sms to the client 
        //     $msg = '
        //     This is Legal Direct. Just a quick reminder that your meeting appointment is set for ' . $get_date['start_date'] . ' to ' . $get_date['end_date'] . '. PLEASE DO NOT REPLY TO THIS TEXT.';
        //     $all_client_phone_list = get_all_client_phonenumber_using_lead_id($this, $lead_id);
        //     $this->send_sms($all_client_phone_list, $msg, $msg, $lead_id, $get_lead_data->name, $get_lead_data->email);
        //     // add the app message 
        //     $app_message = 'Thank you for completing the ID process. Please check your email for the mortgage documents signing appointment.';
        //     store_app_message_for_client($this, $lead_id, $app_message, 7);
        //     // update the last contact date 
        //     $this->leads_model->update_leads_last_contact_date($lead_id);
        //     $response = array(
        //         'success' => true,
        //         'activity_log_last_id' => is_numeric($activity_log_last_id) ? $activity_log_last_id : ''
        //     );
        // } else {
        //     $response = array(
        //         'success' => false
        //     );
        // }
        // $this->output
        //     ->set_content_type('application/json')
        //     ->set_output(json_encode($response));
    }
    private function appt_client_email_sent($draft_id = null, $lead_id, $to_emails, $cc_emails, $bcc_emails, $emailContent, $leads_status = null, $type = null)
    {
        $get_date = get_latest_set_case_appointment($this, $lead_id);
        // get the leads data
        $this->db->select('id,multiple_cases,client_id,phonenumber,name,email,addedfrom,assign_group');
        $this->db->where('id', $lead_id);
        $get_lead_data = $this->db->get(db_prefix() . 'leads')->row();
        // send mail to the client
        if (!empty($emailContent)) {
            $get_mail_subject = get_mail_subject_for_case_stages($this, $lead_id, 7);
            $_POST['email_content'] = $emailContent;
            $html_content_welcome_email_to_user = $this->load->view('admin/leads/Email_template/client/client_appointment_item_review_mail', $_POST, TRUE);

            $subject = $get_mail_subject;
            $replay_to_mail = get_all_staff_to_replay_email($this, get_staff_user_id(), $get_lead_data->assign_group, $to_emails);
            $send_email_result = send_mailchimp_email($to_emails, $subject, $html_content_welcome_email_to_user, $replay_to_mail, $cc_emails, $bcc_emails, $lead_id);
            // add the record for outbox emails
            $outbox_id = $this->Outbox_model->save_outbox_email(
                $to_emails,
                $cc_emails,
                $bcc_emails,
                $subject,
                $_POST['email_content'],
                '',
                $lead_id,
                7,
                $html_content_welcome_email_to_user,
                $replay_to_mail,
                $send_email_result['status'],
                $send_email_result['mandrill_id'],
                1
            );
            // update the record of leads 
            $update_lead_array = array(
                'app_email_requested' => 1
            );
            $this->db->where('id', $lead_id);
            $this->db->update(db_prefix() . 'leads', $update_lead_array);
            // send the email to broker and add the activity of of the broker mail
            $staff_row = get_multiple_broker_details_using_addedfrom($this, $get_lead_data->addedfrom);
            $all_broker_emails = array_column($staff_row, 'email');
            // Get all admin broker emails
            $brokerage_id = get_brokerage_id_using_leadid($this, $lead_id);
            $admin_broker_ids = get_all_admin_broker_role_staff_ids($this, $brokerage_id);
            $all_admin_broker_emails = array_column($admin_broker_ids, 'email');
            
            // Merge both broker and admin broker emails, remove duplicates
            $all_recipients = array_unique(array_merge($all_broker_emails, $all_admin_broker_emails));


            $appointment_date = get_latest_set_case_appointment($this, $lead_id);
            $broker_replay_to_mail = get_all_staff_to_replay_email($this, get_staff_user_id(), $get_lead_data->assign_group);
            $_POST['start_date'] = $appointment_date['start_date'];
            $_POST['end_date'] = $appointment_date['end_date'];
            if (!empty($staff_row)) {
                $_POST['case_url'] = get_the_redirect_email_case_url($lead_id, 'broker');
                $broker_message = 'We are delighted to inform you that the file has successfully moved through another
                milestone, the mortgage offer has been received and we are liaising with the Client over a suitable appointment date.We shall update you again upon conclusion of that meeting.';
                // foreach ($staff_row as $broker) {
                // $_POST['broker_name'] = $broker['firstname'] . ' ' . $broker['lastname'];
                // $broker_email = $broker['email'];
                // $all_broker_emails = array_column($staff_row, 'email');
                // $html_content_confirmation_email_to_broker = $this->load->view('admin/leads/Email_template/broker/instruction_received_stage_complete', $_POST, TRUE);

                // $send_email_result = send_mailchimp_email($all_broker_emails, $subject, $html_content_confirmation_email_to_broker, $broker_replay_to_mail, '', '', $lead_id);
                // // add the record for outbox emails
                // $outbox_id = $this->Outbox_model->save_outbox_email(
                //     $all_broker_emails,
                //     '',
                //     '',
                //     $subject,
                //     $_POST['email_content'],
                //     '',
                //     $lead_id,
                //     7,
                //     $html_content_confirmation_email_to_broker,
                //     $replay_to_mail,
                //     $send_email_result['status'],
                //     $send_email_result['mandrill_id'],
                //     1
                // );

                // // }
                // // send the all admin notification and email to the admin broker
                // $brokerage_id = get_brokerage_id_using_leadid($this, $lead_id);
                // $admin_broker_ids = get_all_admin_broker_role_staff_ids($this, $brokerage_id);
                // // foreach ($admin_broker_ids as $admin_broker_email) {
                // //     if (get_staff_user_id() != $admin_broker_email['staffid'] && !in_array($admin_broker_email['staffid'], explode(',', $get_lead_data->addedfrom))) {
                // // $_POST['broker_name'] = $admin_broker_email['firstname'] . ' ' . $admin_broker_email['lastname'];
                // // $broker_email = $admin_broker_email['email'];
                // $all_admin_broker_emails = array_column($admin_broker_ids, 'email');
                // $html_content_confirmation_email_to_broker = $this->load->view('admin/leads/Email_template/broker/instruction_received_stage_complete', $_POST, TRUE);

                // $send_email_result = send_mailchimp_email($all_admin_broker_emails, $subject, $html_content_confirmation_email_to_broker, $broker_replay_to_mail, '', '', $lead_id);
                // // add the record for outbox emails
                // $outbox_id = $this->Outbox_model->save_outbox_email(
                //     $all_admin_broker_emails,
                //     '',
                //     '',
                //     $subject,
                //     $_POST['email_content'],
                //     '',
                //     $lead_id,
                //     7,
                //     $html_content_confirmation_email_to_broker,
                //     $replay_to_mail,
                //     $send_email_result['status'],
                //     $send_email_result['mandrill_id'],
                //     1
                // );
                //     }
                // }
                // Prepare email content
                $html_content_confirmation_email_to_broker = $this->load->view(
                    'admin/leads/Email_template/broker/instruction_received_stage_complete',
                    $_POST,
                    TRUE
                );

                // Send one email to all recipients
                $send_email_result = send_mailchimp_email(
                    implode(',', $all_recipients),
                    $subject,
                    $html_content_confirmation_email_to_broker,
                    $broker_replay_to_mail,
                    '',
                    '',
                    $lead_id
                );

                // Save one record in outbox for all recipients
                $outbox_id = $this->Outbox_model->save_outbox_email(
                    implode(',', $all_recipients),
                    '',
                    '',
                    $subject,
                    $broker_message,
                    '',
                    $lead_id,
                    7,
                    $html_content_confirmation_email_to_broker,
                    $replay_to_mail,
                    $send_email_result['status'],
                    $send_email_result['mandrill_id'],
                    1
                );

                $insert_task_activity = array(
                    'leadid' => $lead_id,
                    'staffid' => get_staff_user_id(),
                    'full_name' => get_staff_full_name(),
                    'description' => get_staff_full_name() . ' Sent an email to Brokers <br> Good ' . get_afternoon_and_morning() . '<br>' . $broker_message,
                    'date' => date('Y-m-d H:i:s'),
                );
                leads_activity_log($this, $insert_task_activity);
            }

            // add the email in activity logs
            $insert_task_activity = array(
                'leadid' => $lead_id,
                'staffid' => get_staff_user_id(),
                'full_name' => get_staff_full_name(),
                'description' => get_staff_full_name() . " sent an email to " . $get_lead_data->name . ' <br>' . $emailContent,
                'date' => date('Y-m-d H:i:s'),
            );
            $activity_log_last_id = leads_activity_log($this, $insert_task_activity);
            // send notification to ld and admin
            $this->db->select('assign_group,assigned,name');
            $this->db->where('id', $lead_id);
            $lead_data_for_get_assign_group = $this->db->get(db_prefix() . 'leads')->row();
            $current_staff_data = get_staff_ids_by_group($this, $lead_data_for_get_assign_group->assign_group);
            $closed_message = 'Thank you for completing the ID process. Please check your email for the mortgage documents signing appointment.';
            $crm_message = 'Appointment to be sent out for case #' . $lead_id . '.';
            // notification line of code
            $client_id = get_client_id_using_contact_id($this, $get_lead_data->client_id, $get_lead_data->multiple_cases);
            $contact_id = get_contact_id_using_client_id($this, $client_id);
            $notification_type = get_notification_type(4);
            $client_notify_type = $notification_type;
            $client_notify_message = '';
            $client_notify_title = 'Mortgage Offer received and Appointment Set ' . $get_date['start_date'] . '.';
            send_notification_in_mobile('client', get_staff_user_id(), $contact_id, $client_id, $lead_id, $client_notify_title, $client_notify_message, $client_notify_type, '');

            // send sms to the client 
            $msg = '
            This is Legal Direct. Just a quick reminder that your meeting appointment is set for ' . $get_date['start_date'] . ' to ' . $get_date['end_date'] . '. PLEASE DO NOT REPLY TO THIS TEXT.';
            $all_client_phone_list = get_all_client_phonenumber_using_lead_id($this, $lead_id);
            $this->send_sms($all_client_phone_list, $msg, $msg, $lead_id, $get_lead_data->name, $get_lead_data->email);
            // add the app message 
            $app_message = 'Thank you for completing the ID process. Please check your email for the mortgage documents signing appointment.';
            store_app_message_for_client($this, $lead_id, $app_message, 7);
            // update the last contact date 
            $this->leads_model->update_leads_last_contact_date($lead_id);
            $response = array(
                'success' => true,
                'activity_log_last_id' => is_numeric($activity_log_last_id) ? $activity_log_last_id : ''
            );
        } else {
            $response = array(
                'success' => false
            );
        }
        $this->output
            ->set_content_type('application/json')
            ->set_output(json_encode($response));
    }
    // send the reconfirm email to the broker 
    public function broker_appointment_review_email_send($lead_id)
    {
        $emailContent = $this->input->post('appointment_confirm_broker_emailContent', FALSE);
        $to_broker_appointment_reviewmail = $this->input->post('to_broker_appointment_reviewmail');
        $cc_broker_appointment_reviewmail = $this->input->post('cc_broker_appointment_reviewmail');
        $bcc_broker_appointment_reviewmail = $this->input->post('bcc_broker_appointment_reviewmail');
        $to_emails = array_map('trim', explode(',', $to_broker_appointment_reviewmail));
        $cc_emails = array_map('trim', explode(',', $cc_broker_appointment_reviewmail));
        $bcc_emails = array_map('trim', explode(',', $bcc_broker_appointment_reviewmail));
        // get the leads data
        $this->db->select('email,name,addedfrom,assign_group');
        $this->db->where('id', $lead_id);
        $get_lead_data = $this->db->get(db_prefix() . 'leads')->row();
        // send mail to the client
        if (!empty($emailContent)) {
            $get_mail_subject = get_mail_subject($this, $lead_id);
            $_POST['case_url'] = get_the_redirect_email_case_url($lead_id, 'broker');
            $_POST['generic_email_title'] = '';
            $_POST['generic_email_back_to_case_url'] = 'Please <a href="' . htmlspecialchars($_POST['case_url'], ENT_QUOTES, 'UTF-8') . '">Click here</a> to access the file.';
            $_POST['generic_email_content'] = $emailContent;
            $html_content_welcome_email_to_user = $this->load->view('admin/leads/Email_template/generic_email_template', $_POST, TRUE);
            $subject = $get_mail_subject;
            $replay_to_mail = get_all_staff_to_replay_email($this, get_staff_user_id(), $get_lead_data->assign_group);
            $send_email_result = send_mailchimp_email($to_emails, $subject, $html_content_welcome_email_to_user, $replay_to_mail, $cc_emails, $bcc_emails, $lead_id);
            // add the record for outbox emails
            $outbox_id = $this->Outbox_model->save_outbox_email(
                $to_emails,
                $cc_emails,
                $bcc_emails,
                $subject,
                $_POST['generic_email_content'],
                '',
                $lead_id,
                7,
                $html_content_welcome_email_to_user,
                $replay_to_mail,
                $send_email_result['status'],
                $send_email_result['mandrill_id'],
                1
            );
            $insert_task_activity = array(
                'leadid' => $lead_id,
                'staffid' => get_staff_user_id(),
                'full_name' => get_staff_full_name(),
                'description' => get_staff_full_name() . ' Sent an email to ' . $get_lead_data->name . ' Please click on the view button to review email' . $emailContent,
                'date' => date('Y-m-d H:i:s'),
            );
            leads_activity_log($this, $insert_task_activity);
            // send notification to ld and admin
            $this->db->select('assign_group,assigned,name');
            $this->db->where('id', $lead_id);
            $lead_data_for_get_assign_group = $this->db->get(db_prefix() . 'leads')->row();
            $current_staff_data = get_staff_ids_by_group($this, $lead_data_for_get_assign_group->assign_group);
            $closed_message = get_staff_full_name() . ' set the Appointment for case (id:#' . $lead_id . 'name: ' . $lead_data_for_get_assign_group->name . ').';
            foreach ($current_staff_data as $staff_notifiy_data) {
                if (get_staff_user_id() != $staff_notifiy_data['staffid']) {
                    // send notificaiton in crm for group members
                    $this->leads_model->custom_lead_assigned_member_notification('staff', $lead_id, $staff_notifiy_data['staffid'], get_staff_user_id(), '', $closed_message);
                }
            }
            // get the all admin staff ids
            $admin_ids = get_all_admin_role_staff_ids($this);
            foreach ($admin_ids as $admin_email) {
                if (get_staff_user_id() != $admin_email['staffid']) {
                    // send notification in crm
                    $this->leads_model->custom_lead_assigned_member_notification('staff', $lead_id, $admin_email['staffid'], get_staff_user_id(), '', $closed_message);
                }
            }
            // send the all admin notification and email to the admin broker
            $brokerage_id = get_brokerage_id_using_leadid($this, $lead_id);
            $admin_broker_ids = get_all_admin_broker_role_staff_ids($this, $brokerage_id);
            foreach ($admin_broker_ids as $admin_broker_email) {
                if (get_staff_user_id() != $admin_broker_email['staffid'] && !in_array($admin_broker_email['staffid'], explode(',', $get_lead_data->addedfrom))) {
                    $this->leads_model->custom_lead_assigned_member_notification('staff', $lead_id, $admin_broker_email['staffid'], get_staff_user_id(), '', $closed_message);
                }
            }
            // update the last contact date 
            $this->leads_model->update_leads_last_contact_date($lead_id);
            $response = array(
                'success' => true
            );
        } else {
            $response = array(
                'success' => false
            );
        }
        $this->output
            ->set_content_type('application/json')
            ->set_output(json_encode($response));
    }
    // save appt draft emails
    public function save_appt_client_email_draft($lead_id)
    {
        $to = $this->input->post('to');
        $cc = $this->input->post('cc');
        $bcc = $this->input->post('bcc');
        $content = $this->input->post('content');
        $leads_status = $this->input->post('leads_status');
        $type = $this->input->post('type');
        $editor_id = 'appointment_client_emailContent';

        $this->leads_model->save_appt_client_email_draft_model(
            $lead_id,
            $to,
            $cc,
            $bcc,
            $content,
            $leads_status,
            $type,
            $editor_id
        );

        $response = array(
            'success' => true,
            'lead_id' => $lead_id,
            'leadView' => $this->_get_lead_data($lead_id),
        );
        $this->output
            ->set_content_type('application/json')
            ->set_output(json_encode($response));
    }
    // update draft emails
    public function update_email_draft($lead_id)
    {
        $postData = $this->input->post();
        $success = $this->leads_model->update_email_draft($lead_id, $postData);
        if ($success) {
            echo json_encode([
                'success' => true,
                'message' => 'Draft updated successfully.'
            ]);
        } else {
            echo json_encode([
                'success' => false,
                'message' => 'Failed to update draft. Please try again.'
            ]);
        }
    }
    // sent draft emails code 
    public function draft_email_sent($lead_id)
    {
        $draft_id = $this->input->post('draft_id');
        $to = $this->input->post('to');
        $cc = $this->input->post('cc');
        $bcc = $this->input->post('bcc');
        $emailContent = $this->input->post('content', FALSE);

        $to_emails = array_map('trim', explode(',', $to));
        $cc_emails = array_map('trim', explode(',', $cc));
        $bcc_emails = array_map('trim', explode(',', $bcc));
        // delete the draft
        $this->leads_model->delete_draft_record($draft_id);

        $this->appt_client_email_sent($draft_id, $lead_id, $to_emails, $cc_emails, $bcc_emails, $emailContent, '', '');
    }
    // Delete Draft emails
    public function delete_draft_email($lead_id)
    {
        $draft_id = $this->input->post('draft_id');
        if (empty($draft_id)) {
            echo json_encode(['success' => false, 'message' => 'Invalid draft ID']);
            return;
        }
        $deleted = $this->leads_model->delete_draft_record($draft_id);

        echo json_encode(['success' => $deleted]);
    }


    // lender appt mail send to the broker
    public function lender_appointment_review_email_send($lead_id)
    {
        $emailContent = $this->input->post('appointment_confirm_lender_emailContent', FALSE);
        $to_lender_appointment_reviewmail = $this->input->post('to_lender_appointment_reviewmail');
        $cc_lender_appointment_reviewmail = $this->input->post('cc_lender_appointment_reviewmail');
        $bcc_lender_appointment_reviewmail = $this->input->post('bcc_lender_appointment_reviewmail');
        $to_emails = array_map('trim', explode(',', $to_lender_appointment_reviewmail));
        $cc_emails = array_map('trim', explode(',', $cc_lender_appointment_reviewmail));
        $bcc_emails = array_map('trim', explode(',', $bcc_lender_appointment_reviewmail));
        // get the leads data
        $this->db->select('email,name,addedfrom,assign_group');
        $this->db->where('id', $lead_id);
        $get_lead_data = $this->db->get(db_prefix() . 'leads')->row();
        // send mail to the client
        if (!empty($emailContent)) {
            $get_mail_subject = get_mail_subject($this, $lead_id);
            $_POST['case_url'] = admin_url('cases/index/') . $lead_id;
            $_POST['generic_email_title'] = '';
            $_POST['generic_email_back_to_case_url'] = 'Please <a href="' . htmlspecialchars($_POST['case_url'], ENT_QUOTES, 'UTF-8') . '">Click here</a> to access the file.';
            $_POST['generic_email_content'] = $emailContent;
            $html_content_welcome_email_to_user = $this->load->view('admin/leads/Email_template/generic_email_template', $_POST, TRUE);
            $subject = $get_mail_subject;
            $replay_to_mail = get_all_staff_to_replay_email($this, get_staff_user_id(), $get_lead_data->assign_group);
            $send_email_result = send_mailchimp_email($to_emails, $subject, $html_content_welcome_email_to_user, $replay_to_mail, $cc_emails, $bcc_emails, $lead_id);
            // add the record for outbox emails
            $outbox_id = $this->Outbox_model->save_outbox_email(
                $to_emails,
                $cc_emails,
                $bcc_emails,
                $subject,
                $_POST['generic_email_content'],
                '',
                $lead_id,
                7,
                $html_content_welcome_email_to_user,
                $replay_to_mail,
                $send_email_result['status'],
                $send_email_result['mandrill_id'],
                1
            );
            $insert_task_activity = array(
                'leadid' => $lead_id,
                'staffid' => get_staff_user_id(),
                'full_name' => get_staff_full_name(),
                'description' => get_staff_full_name() . ' Sent an email to ' . $get_lead_data->name . ' Please click on the view button to review email' . $emailContent,
                'date' => date('Y-m-d H:i:s'),
            );
            leads_activity_log($this, $insert_task_activity);
            // send notification to ld and admin
            $this->db->select('assign_group,assigned,name');
            $this->db->where('id', $lead_id);
            $lead_data_for_get_assign_group = $this->db->get(db_prefix() . 'leads')->row();
            $current_staff_data = get_staff_ids_by_group($this, $lead_data_for_get_assign_group->assign_group);
            $closed_message = get_staff_full_name() . ' set the Appointment for case (id:#' . $lead_id . 'name: ' . $lead_data_for_get_assign_group->name . ').';
            foreach ($current_staff_data as $staff_notifiy_data) {
                if (get_staff_user_id() != $staff_notifiy_data['staffid']) {
                    // send notificaiton in crm for group members
                    $this->leads_model->custom_lead_assigned_member_notification('staff', $lead_id, $staff_notifiy_data['staffid'], get_staff_user_id(), '', $closed_message);
                }
            }
            // get the all admin staff ids
            $admin_ids = get_all_admin_role_staff_ids($this);
            foreach ($admin_ids as $admin_email) {
                if (get_staff_user_id() != $admin_email['staffid']) {
                    // send notification in crm
                    $this->leads_model->custom_lead_assigned_member_notification('staff', $lead_id, $admin_email['staffid'], get_staff_user_id(), '', $closed_message);
                }
            }
            // send the all admin notification and email to the admin broker
            $brokerage_id = get_brokerage_id_using_leadid($this, $lead_id);
            $admin_broker_ids = get_all_admin_broker_role_staff_ids($this, $brokerage_id);
            foreach ($admin_broker_ids as $admin_broker_email) {
                if (get_staff_user_id() != $admin_broker_email['staffid'] && !in_array($admin_broker_email['staffid'], explode(',', $get_lead_data->addedfrom))) {
                    $this->leads_model->custom_lead_assigned_member_notification('staff', $lead_id, $admin_broker_email['staffid'], get_staff_user_id(), '', $closed_message);
                }
            }
            // check record exit again lead id for lender appt confirmation email
            $lender_apt_confirmation = $this->leads_model->check_lender_appt_confirmation_email($lead_id);
            if (empty($lender_apt_confirmation) && $lender_apt_confirmation == false) {
                // Insert the lender appt confirmation email status
                $this->leads_model->insert_lender_appt_confirmation_email_status($lead_id);
            }
            // check record exit again lead_id for lender appt confirmation then update recrod
            if (!empty($lender_apt_confirmation) && $lender_apt_confirmation == true) {
                // Insert the lender appt confirmation email status
                $this->leads_model->update_lender_appt_confirmation_email_status($lead_id);
            }
            // update the last contact date 
            $this->leads_model->update_leads_last_contact_date($lead_id);
            $response = array(
                'success' => true
            );
        } else {
            $response = array(
                'success' => false
            );
        }
        $this->output
            ->set_content_type('application/json')
            ->set_output(json_encode($response));
    }
    // outsanding item review mail to broker
    public function broker_outstanding_email_review($lead_id)
    {
        $broker_outstanding_review_email_tincymac = $this->input->post('broker_outstanding_review_email_tincymac', FALSE);
        $to_outstanding_broker_reviewmail = $this->input->post('to_outstanding_broker_reviewmail');
        $cc_outstanding_broker_reviewmail = $this->input->post('cc_outstanding_broker_reviewmail');
        $bcc_outstanding_broker_reviewmail = $this->input->post('bcc_outstanding_broker_reviewmail');
        $to_emails = array_map('trim', explode(',', $to_outstanding_broker_reviewmail));
        $cc_emails = array_map('trim', explode(',', $cc_outstanding_broker_reviewmail));
        $bcc_emails = array_map('trim', explode(',', $bcc_outstanding_broker_reviewmail));
        $get_mail_subject = get_mail_subject($this, $lead_id);
        if (!empty($broker_outstanding_review_email_tincymac)) {
            // get the lead data
            $this->db->select('addedfrom,assign_group');
            $this->db->where('id', $lead_id);
            $get_lead_data = $this->db->get(db_prefix() . 'leads')->row();
            // get the staff data
            $get_staff_record = get_multiple_broker_details_using_addedfrom($this, $get_lead_data->addedfrom);
            $_POST['broker_outstanding_review_email_tincymac'] = $broker_outstanding_review_email_tincymac;
            $_POST['case_url'] = get_the_redirect_email_case_url($lead_id, 'broker');
            $html_content_welcome_email_to_user = $this->load->view('admin/leads/Email_template/broker/outstanding_item_review_mail', $_POST, TRUE);

            $subject = $get_mail_subject;
            $replay_to_mail = get_all_staff_to_replay_email($this, get_staff_user_id(), $get_lead_data->assign_group);
            $send_email_result = send_mailchimp_email($to_emails, $subject, $html_content_welcome_email_to_user, $replay_to_mail, $cc_emails, $bcc_emails, $lead_id);
            // add the record for outbox emails
            $outbox_id = $this->Outbox_model->save_outbox_email(
                $to_emails,
                $cc_emails,
                $bcc_emails,
                $subject,
                $_POST['broker_outstanding_review_email_tincymac'],
                '',
                $lead_id,
                3,
                $html_content_welcome_email_to_user,
                $replay_to_mail,
                $send_email_result['status'],
                $send_email_result['mandrill_id'],
                1
            );
            if (!empty($get_staff_record)) {
                foreach ($get_staff_record as $broker) {
                    $_POST['broker_name'] = $broker['firstname'] . ' ' . $broker['lastname'];
                    $broker_email = $broker['email'];
                    // Send crm notification to broker
                    $notification_text = get_staff_full_name() . " sent a email you for case (" . $get_mail_subject . ').';
                    $this->leads_model->custom_lead_assigned_member_notification('staff', $lead_id, $broker['staffid'], get_staff_user_id(), '', $notification_text);
                }
                // send the all admin notification and email to the admin broker
                $brokerage_id = get_brokerage_id_using_leadid($this, $lead_id);
                $admin_broker_ids = get_all_admin_broker_role_staff_ids($this, $brokerage_id);
                foreach ($admin_broker_ids as $admin_broker_email) {
                    if (get_staff_user_id() != $admin_broker_email['staffid'] && !in_array($admin_broker_email['staffid'], explode(',', $get_lead_data->addedfrom))) {
                        $notification_text = get_staff_full_name() . " sent a email you for case (" . $get_mail_subject . ').';
                        $this->leads_model->custom_lead_assigned_member_notification('staff', $lead_id, $admin_broker_email['staffid'], get_staff_user_id(), '', $notification_text);
                    }
                }
            }


            $insert_task_activity = array(
                'leadid' => $lead_id,
                'staffid' => get_staff_user_id(),
                'full_name' => get_staff_full_name(),
                'description' => get_staff_full_name() . " sent an email to ( " . $to_outstanding_broker_reviewmail . ') <br>' . $broker_outstanding_review_email_tincymac,
                'date' => date('Y-m-d H:i:s'),
            );
            $activity_log_last_id = leads_activity_log($this, $insert_task_activity);
            // update the last contact date 
            $this->leads_model->update_leads_last_contact_date($lead_id);
            $response = array(
                'success' => true,
                'activity_log_last_id' => is_numeric($activity_log_last_id) ? $activity_log_last_id : ''
            );
        } else {
            $response = array(
                'success' => false
            );
        }
        $this->output
            ->set_content_type('application/json')
            ->set_output(json_encode($response));
    }
    // client outstandig email review code
    public function client_outstanding_email_review($lead_id)
    {
        $client_outstanding_review_email_tincymac = $this->input->post('client_outstanding_review_email_tincymac', FALSE);
        $to_outstanding_client_reviewmail = $this->input->post('to_outstanding_client_reviewmail');
        $cc_outstanding_client_reviewmail = $this->input->post('cc_outstanding_client_reviewmail');
        $bcc_outstanding_client_reviewmail = $this->input->post('bcc_outstanding_client_reviewmail');
        $to_emails = array_map('trim', explode(',', $to_outstanding_client_reviewmail));
        $cc_emails = array_map('trim', explode(',', $cc_outstanding_client_reviewmail));
        $bcc_emails = array_map('trim', explode(',', $bcc_outstanding_client_reviewmail));
        $get_mail_subject = get_mail_subject_for_case_stages($this, $lead_id, 3);
        if (!empty($client_outstanding_review_email_tincymac)) {
            // get the lead data
            $this->db->select('email,name,phonenumber,status,assign_group');
            $this->db->where('id', $lead_id);
            $get_lead_data = $this->db->get(db_prefix() . 'leads')->row();
            // get the staff data
            $get_staff_record = get_staff_data_by_id($this, $get_lead_data->addedfrom);
            $_POST['client_outstanding_review_email_tincymac'] = $client_outstanding_review_email_tincymac;
            $html_content_welcome_email_to_user = $this->load->view('admin/leads/Email_template/client/outstanding_item_review_email', $_POST, TRUE);

            $subject = $get_mail_subject;
            $replay_to_mail = get_all_staff_to_replay_email($this, get_staff_user_id(), $get_lead_data->assign_group, $to_emails);
            $send_email_result = send_mailchimp_email($to_emails, $subject, $html_content_welcome_email_to_user, $replay_to_mail, $cc_emails, $bcc_emails, $lead_id);
            // add the record for outbox emails
            $outbox_id = $this->Outbox_model->save_outbox_email(
                $to_emails,
                $cc_emails,
                $bcc_emails,
                $subject,
                $_POST['client_outstanding_review_email_tincymac'],
                '',
                $lead_id,
                3,
                $html_content_welcome_email_to_user,
                $replay_to_mail,
                $send_email_result['status'],
                $send_email_result['mandrill_id'],
                1
            );
            // Send crm notification to broker
            $this->leads_model->custom_lead_assigned_member_notification('staff', $lead_id, $get_lead_data->addedfrom, get_staff_user_id(), '', $get_mail_subject);
            // send sms to the client
            $this->db->select('id,name,lead_borrow_id');
            $this->db->where('rel_id', $lead_id);
            $this->db->where('rel_type', 'user-task');
            $this->db->where('type', 'client');
            $this->db->where_in('status', [1, 2, 3, 5]);
            $this->db->where('leads_status', 3);
            $borrower_data = $this->db->get(db_prefix() . 'tasks')->result_array();
            // Prepare task names for the SMS
            $task_names = [];
            foreach ($borrower_data as $task) {
                $task_names[] = $task['name'];
            }
            // Join task names with a newline separator
            $task_names_bulleted = array_map(function ($task) {
                return '• ' . $task;
            }, $task_names);
            $task_names_str = implode("\n", $task_names_bulleted);
            $sms_msg = 'Hi ' . $get_lead_data->name . ' This is Legal Direct.To progress your transaction, please return via email or the app ' . "\n\n" . $task_names_str . "\n\n" . ' Please DO NOT REPLY TO THIS TEXT.';
            $all_client_phone_list = get_all_client_phonenumber_using_lead_id($this, $lead_id);
            $this->send_sms($all_client_phone_list, $sms_msg, $sms_msg, $lead_id, $get_lead_data->name, $get_lead_data->email);
            // send the notification to user in mobile side
            // notification send code
            $this->db->select('multiple_cases,client_id,phonenumber,name,email,addedfrom');
            $this->db->where('id', $lead_id);
            $lead_data_check = $this->db->get(db_prefix() . 'leads');
            if ($lead_data_check->num_rows() > 0) {
                $lead_data = $lead_data_check->row();
                $case_name = $lead_data->name;

                $client_id = get_client_id_using_contact_id($this, $lead_data->client_id, $lead_data->multiple_cases);
                $contact_id = get_contact_id_using_client_id($this, $client_id);
                $notification_type = get_notification_type(1);

                $client_notify_title = 'Appointment completed.Send any outstanding items discussed.';
                $client_notify_message = '';
                send_notification_in_mobile('client', get_staff_user_id(), $contact_id, $client_id, $lead_id, $client_notify_title, $client_notify_message, $notification_type, '');
            }
            // add the app message 
            $app_message = 'Thank you for attending your appointment. Please send any outstanding items discussed at that meeting.';
            store_app_message_for_client($this, $lead_id, $app_message, $get_lead_data->status);
            // add the emali in activity logs
            $insert_task_activity = array(
                'leadid' => $lead_id,
                'staffid' => get_staff_user_id(),
                'full_name' => get_staff_full_name(),
                'description' => get_staff_full_name() . " sent an email to " . $get_lead_data->name . ' <br>' . $client_outstanding_review_email_tincymac,
                'date' => date('Y-m-d H:i:s'),
            );
            $activity_log_last_id = leads_activity_log($this, $insert_task_activity);
            // update the last contact date 
            $this->leads_model->update_leads_last_contact_date($lead_id);
            $response = array(
                'success' => true,
                'activity_log_last_id' => is_numeric($activity_log_last_id) ? $activity_log_last_id : ''
            );
        } else {
            $response = array(
                'success' => false
            );
        }
        $this->output
            ->set_content_type('application/json')
            ->set_output(json_encode($response));
    }
    // sms send to the outstanding client review   
    public function client_outstanding_sms_review($lead_id)
    {
        $outstanding_client_sms = $this->input->post('outstanding_client_sms');
        $get_mail_subject = get_mail_subject($this, $lead_id);
        if (!empty($outstanding_client_sms)) {
            // get the lead data
            $this->db->select('email,name,phonenumber,client_id,multiple_cases');
            $this->db->where('id', $lead_id);
            $get_lead_data = $this->db->get(db_prefix() . 'leads')->row();
            // send sms to the client
            // $msg = 'Hi '. $get_lead_data->name . '. This is Legal Direct.To progress your transaction,please ' . $outstanding_client_sms . '. PLEASE DO NOT REPLY TO THIS TEXT.';
            $msg = $outstanding_client_sms . '. PLEASE DO NOT REPLY TO THIS TEXT.';
            $all_client_phone_list = get_all_client_phonenumber_using_lead_id($this, $lead_id);
            $check_sms_send = $this->send_sms($all_client_phone_list, $msg, $msg, $lead_id, $get_lead_data->name, $get_lead_data->email, true);
            //  send notification and app message set in app
            $client_id = get_client_id_using_contact_id($this, $get_lead_data->client_id, $get_lead_data->multiple_cases);
            $contact_id = get_contact_id_using_client_id($this, $client_id);

            $notification_type = get_notification_type(4);
            $client_notify_type = $notification_type;
            $client_notify_title = 'Please use the drop-down menu below to provide the outstanding items to progress your transaction.';
            $client_notify_message = '';
            send_notification_in_mobile('client', get_staff_user_id(), $contact_id, $client_id, $lead_id, $client_notify_title, $client_notify_message, $client_notify_type, '');
            //  Store app message in app side
            $app_message = 'Please provide the outstanding items to progress your transaction.';
            store_app_message_for_client($this, $lead_id, $app_message, 3);
            // add the emali in activity logs
            $insert_task_activity = array(
                'leadid' => $lead_id,
                'staffid' => get_staff_user_id(),
                'full_name' => get_staff_full_name(),
                'description' => get_staff_full_name() . " sent sms to " . $get_lead_data->name . ' <br>' . $outstanding_client_sms,
                'date' => date('Y-m-d H:i:s'),
            );
            $activity_log_last_id = leads_activity_log($this, $insert_task_activity);
            if ($check_sms_send) {
                $response = array(
                    'success' => true,
                    'activity_log_last_id' => is_numeric($activity_log_last_id) ? $activity_log_last_id : ''
                );
            } else {
                $response = array(
                    'success' => false
                );
            }
        } else {
            $response = array(
                'success' => false
            );
        }
        $this->output
            ->set_content_type('application/json')
            ->set_output(json_encode($response));
    }
    public function file_opened_checkbox_status($lead_id)
    {
        $checkbox_id = $this->input->post('id');
        $get_mail_subject = get_mail_subject($this, $lead_id);
        $this->db->select('id,checkbox_status');
        $this->db->where('id', $checkbox_id);
        $checkbox_status_row = $this->db->get(db_prefix() . 'tasks')->row();
        $checkbox_status = $checkbox_status_row->checkbox_status;
        // get the files data
        $this->db->where('task_id', $checkbox_status_row->id);
        $this->db->where('rel_id', $lead_id);
        $this->db->where('rel_type', 'client-doc');
        $query_files = $this->db->get(db_prefix() . 'files')->row();
        if (!empty($query_files) && get_current_staff_role($this, get_staff_user_id()) != 2 && get_current_staff_role($this, get_staff_user_id()) != 6) {
            if ($checkbox_status == 1) {
                $checked_status = 0;
                $checked = true;
                $status = 'Pending Review';
                $data = array(
                    'checkbox_status' => $checked_status,
                    'status' => 1,
                );
            } else {
                $checked_status = 1;
                $checked = true;
                $status = 'Approved';
                $data = array(
                    'checkbox_status' => $checked_status,
                    'status' => 4,
                );
            }
            $this->db->where('id', $checkbox_id);
            $this->db->update(db_prefix() . 'tasks', $data);
            // notification send code
            $this->db->select('multiple_cases,client_id,phonenumber,name,email,addedfrom,assign_group');
            $this->db->where('id', $lead_id);
            $lead_data_check = $this->db->get(db_prefix() . 'leads');
            if ($lead_data_check->num_rows() > 0) {
                $lead_data = $lead_data_check->row();
                $case_name = $lead_data->name;

                $client_id = get_client_id_using_contact_id($this, $lead_data->client_id, $lead_data->multiple_cases);
                $contact_id = get_contact_id_using_client_id($this, $client_id);
                // get the title of checklist/task  and send notification
                $this->db->select('name,type');
                $this->db->where('id', $checkbox_id);
                $task_query_file = $this->db->get(db_prefix() . 'tasks')->row();
                $get_task_name = $task_query_file->name;
                $get_task_type = $task_query_file->type;
                $notification_type = get_notification_type(2);
                if ($get_task_type != 'broker') {

                    $client_notify_type = $notification_type . '-' . strtolower($status);
                    $client_notify_title = 'Checklist item status updated';
                    $client_notify_message = 'Checklist item (' . $get_task_name . ') has been ' . strtolower($status) . ' for Case(ID: #' . $lead_id . ' & Name: ' . $case_name . ').';
                    send_notification_in_mobile('client', get_staff_user_id(), $contact_id, $client_id, $lead_id, $client_notify_title, $client_notify_message, $client_notify_type, $checkbox_id);

                    // send notification to the ld-team and admin
                    // send  notiication in crm to all the team group member and staff
                    $title = 'Checklist item status updated';
                    $new_case_message = 'Checklist item (' . $get_task_name . ') has been ' . strtolower($status) . ' for Case(ID: #' . $lead_id . ' & Name: ' . $case_name . ').';
                    $this->db->select('assign_group,assigned');
                    $this->db->where('id', $lead_id);
                    $lead_data_for_get_assign_group = $this->db->get(db_prefix() . 'leads')->row();
                    $current_staff_data = get_staff_ids_by_group($this, $lead_data_for_get_assign_group->assign_group);

                    if ($checkbox_status == 0) {
                        $_POST['email_details_texting'] = 'Checklist item (' . $get_task_name . ') has been ' . strtolower($status) . ' by ' . get_staff_full_name() . '.';
                        $broker_data = get_staff_email_by_staffid($this, $lead_data->addedfrom);
                        $_POST['broker_name'] = $broker_data->firstname . ' ' . $broker_data->lastname;
                        // $subject = 'Checkilst Item Status';
                        $subject = $get_mail_subject;
                        $replay_to_mail = get_all_staff_to_replay_email($this, get_staff_user_id(), $lead_data->assign_group);
                        $html_content_confirmation_email_to_broker = $this->load->view('admin/leads/Email_template/broker/checklist_status_update', $_POST, TRUE);
                        $send_email_result = send_mailchimp_email($broker_data->email, $subject, $html_content_confirmation_email_to_broker, $replay_to_mail, '', '', $lead_id);
                        // add the record for outbox emails
                        $outbox_id = $this->Outbox_model->save_outbox_email(
                            $broker_data->email,
                            '',
                            '',
                            $subject,
                            $_POST['email_details_texting'],
                            '',
                            $lead_id,
                            1,
                            $html_content_confirmation_email_to_broker,
                            $replay_to_mail,
                            $send_email_result['status'],
                            $send_email_result['mandrill_id'],
                            1
                        );
                    }
                    // add data in activity logs
                    $description = 'Checklist item (' . $get_task_name . ') has been ' . strtolower($status) . ' by ' . get_staff_full_name() . ' for Case(ID: #' . $lead_id . ' & Name: ' . $case_name . ').';
                    $insert_task_activity = array(
                        'leadid' => $lead_id,
                        'task_id' => $checkbox_id,
                        'staffid' => get_staff_user_id(),
                        'full_name' => get_staff_full_name(),
                        'activity_type' => 'task-activity',
                        'description' => $description,
                        'additional_data' => $status,
                        'date' => date('Y-m-d H:i:s'),
                    );
                    leads_activity_log($this, $insert_task_activity);
                } else {
                    // add data in activity logs for broker
                    $description = 'Checklist item (' . $get_task_name . ') has been submmit by ' . get_staff_full_name() . ' for Case(ID: #' . $lead_id . ' & Name: ' . $case_name . ').';
                    $insert_task_activity = array(
                        'leadid' => $lead_id,
                        'task_id' => $checkbox_id,
                        'staffid' => get_staff_user_id(),
                        'full_name' => get_staff_full_name(),
                        'activity_type' => 'task-activity',
                        'description' => $description,
                        'additional_data' => $status,
                        'date' => date('Y-m-d H:i:s'),
                    );
                    leads_activity_log($this, $insert_task_activity);
                }
            }
        } elseif ((!empty($query_files) && get_current_staff_role($this, get_staff_user_id()) == 2) || get_current_staff_role($this, get_staff_user_id()) == 6) {
            $checked_status = 3;
            $checked = true;
        } else {
            $checked_status = 0;
            $checked = false;
        }
        $leads_status_value = "#file_opened";
        $complete_stage_button = 1;
        echo json_encode([
            'success' => true,
            'id' => $lead_id,
            'task_id' => $checkbox_status_row->id,
            'leadView' => $this->_get_lead_data($lead_id),
            'checked' => $checked,
            'checked_status' => $checked_status,
            'leads_status' => $leads_status_value,
            'complete_stage_button' => $complete_stage_button,
        ]);
    }
    public function outstanding_item_checkbox_status($lead_id)
    {
        $checkbox_id = $this->input->post('id');
        $get_mail_subject = get_mail_subject($this, $lead_id);
        $this->db->select('id,checkbox_status');
        $this->db->where('id', $checkbox_id);
        $checkbox_status_row = $this->db->get(db_prefix() . 'tasks')->row();
        $checkbox_status = $checkbox_status_row->checkbox_status;
        // get the files data
        $this->db->where('task_id', $checkbox_status_row->id);
        $this->db->where('rel_id', $lead_id);
        $this->db->where('rel_type', 'client-doc');
        $query_files = $this->db->get(db_prefix() . 'files')->row();
        if (!empty($query_files)) {
            if ($checkbox_status == 1) {
                $checked_status = 0;
                $checked = true;
                $status = 'Pending Review';
                $data = array(
                    'checkbox_status' => $checked_status,
                    'status' => 1,
                );
            } else {
                $checked_status = 1;
                $checked = true;
                $status = 'Approved';
                $data = array(
                    'checkbox_status' => $checked_status,
                    'status' => 4,
                );
            }
            $this->db->where('id', $checkbox_id);
            $this->db->update(db_prefix() . 'tasks', $data);
            // notification send code
            $this->db->select('multiple_cases,client_id,phonenumber,name,email,addedfrom');
            $this->db->where('id', $lead_id);
            $lead_data_check = $this->db->get(db_prefix() . 'leads');
            if ($lead_data_check->num_rows() > 0) {
                $lead_data = $lead_data_check->row();
                $case_name = $lead_data->name;

                $this->db->select('name');
                $this->db->where('id', $checkbox_id);
                $task_query_file = $this->db->get(db_prefix() . 'tasks')->row();
                $get_task_name = $task_query_file->name;
                $client_id = get_client_id_using_contact_id($this, $lead_data->client_id, $lead_data->multiple_cases);
                $contact_id = get_contact_id_using_client_id($this, $client_id);
                $notification_type = get_notification_type(2);

                $client_notify_type = $notification_type . '-' . strtolower($status);
                $client_notify_title = 'Checklist item status updated';
                $client_notify_message = 'Checklist item (' . $get_task_name . ') has been ' . strtolower($status) . ' for case (ID: #' . $lead_id . ' & Name:' . $case_name . ').';
                send_notification_in_mobile('client', get_staff_user_id(), $contact_id, $client_id, $lead_id, $client_notify_title, $client_notify_message, $client_notify_type, $checkbox_id);

                // send  notiication in crm to all the team group member and staff
                $title = 'Checklist item status updated';
                $new_case_message = 'Checklist item (' . $get_task_name . ') has been ' . strtolower($status) . ' for case (ID: #' . $lead_id . ' & Name:' . $case_name . ').';
                $this->db->select('assign_group,assigned');
                $this->db->where('id', $lead_id);
                $lead_data_for_get_assign_group = $this->db->get(db_prefix() . 'leads')->row();
                $current_staff_data = get_staff_ids_by_group($this, $lead_data_for_get_assign_group->assign_group);

                if ($checkbox_status == 0) {
                    $_POST['email_details_texting'] = 'Checklist item (' . $get_task_name . ') has been ' . strtolower($status) . ' by ' . get_staff_full_name() . '.';
                    $broker_data = get_staff_email_by_staffid($this, $lead_data->addedfrom);
                    $_POST['broker_name'] = $broker_data->firstname . ' ' . $broker_data->lastname;
                    // $subject = 'Checkilst Item Status';
                    $subject = $get_mail_subject;
                    $replay_to_mail = get_all_staff_to_replay_email($this, get_staff_user_id(), $lead_data_for_get_assign_group->assign_group);
                    $html_content_confirmation_email_to_broker = $this->load->view('admin/leads/Email_template/broker/checklist_status_update', $_POST, TRUE);
                    $send_email_result = send_mailchimp_email($broker_data->email, $subject, $html_content_confirmation_email_to_broker, $replay_to_mail, '', '', $lead_id);
                    // add the record for outbox emails
                    $outbox_id = $this->Outbox_model->save_outbox_email(
                        $broker_data->email,
                        '',
                        '',
                        $subject,
                        $_POST['email_details_texting'],
                        '',
                        $lead_id,
                        3,
                        $html_content_confirmation_email_to_broker,
                        $replay_to_mail,
                        $send_email_result['status'],
                        $send_email_result['mandrill_id'],
                        1
                    );
                }
                $insert_task_activity = array(
                    'leadid' => $lead_id,
                    'task_id' => $checkbox_id,
                    'staffid' => get_staff_user_id(),
                    'full_name' => get_staff_full_name(),
                    'activity_type' => 'task-activity',
                    'description' => 'Checklist item (' . $get_task_name . ') has been ' . strtolower($status) . ' by ' . get_staff_full_name() . '.',
                    'additional_data' => $status,
                    'date' => date('Y-m-d H:i:s'),
                );
                leads_activity_log($this, $insert_task_activity);
            }
        } else {
            $checked_status = 0;
            $checked = false;
        }
        $leads_status_value = "#outstanding_items";
        $complete_stage_button = 3;
        echo json_encode([
            'success' => true,
            'id' => $lead_id,
            'task_id' => $checkbox_status_row->id,
            'leadView' => $this->_get_lead_data($lead_id),
            'checked' => $checked,
            'checked_status' => $checked_status,
            'leads_status' => $leads_status_value,
            'complete_stage_button' => $complete_stage_button,
        ]);
    }
    // change the status of ledger doc 
    public function approve_ledger_item($lead_id)
    {
        $ledger_number = $this->input->post('fileId');
        $file_status = $this->input->post('status');
        $rejectionReason = $this->input->post('rejectionReason');

        // Check if file ID and status are provided
        if (!$ledger_number || !$file_status) {
            $response = array(
                'success' => false,
                'message' => 'File ID and status are required.'
            );
            echo json_encode($response);
            return;
        }

        $data = array(
            'broker_status' => $file_status,
            'broker_comment' => $rejectionReason,
            'broker_change_status_time' => date('Y-m-d H:i:s'),
        );

        // Update the database
        $this->db->where('ledger_number', $ledger_number);
        $this->db->where('lead_id', $lead_id);
        // $this->db->where('type', 'broker');
        $this->db->update(db_prefix() . 'leads_ledger', $data);
        // select the latest ledgers id
        $this->db->select('id');
        $this->db->where('lead_id', $lead_id);
        $this->db->where('ledger_number', $ledger_number);
        $this->db->limit(1);
        $get_ledger_id = $this->db->get(db_prefix() . 'leads_ledger')->row();
        // add record in leads ledgers logs
        $ledger_logs_array = array(
            'lead_id' => $lead_id,
            'lead_ledger_id' => $get_ledger_id->id,
            'lead_ledger_number' => $ledger_number,
            'status' => $file_status . ' by ' . get_staff_full_name(),
            'comment' => $rejectionReason,
            'created_at' => date('Y-m-d H:i:s'),
        );
        $this->db->insert(db_prefix() . 'leads_ledger_logs', $ledger_logs_array);

        // Check if the update was successful
        if ($this->db->affected_rows() > 0) {
            $insert_task_activity = array(
                'leadid' => $lead_id,
                'staffid' => get_staff_user_id(),
                'full_name' => get_staff_full_name(),
                'description' => 'Ledger documents ' . $file_status . ' by ' . get_staff_full_name(),
                'date' => date('Y-m-d H:i:s'),
            );
            leads_activity_log($this, $insert_task_activity);
            // notification send code
            $this->db->select('multiple_cases,client_id,phonenumber,name,email,addedfrom,assign_group');
            $this->db->where('id', $lead_id);
            $lead_data_check = $this->db->get(db_prefix() . 'leads');
            if ($lead_data_check->num_rows() > 0) {
                $lead_data = $lead_data_check->row();
                $case_name = $lead_data->name;
                // slack details function 
                $group_name = get_the_group_name_using_leadid($this, $lead_id);
                $lead_name = get_lead_name_using_lead_id($this, $lead_id);
                $lead_split_name = leads_splitFullName($lead_name);

                $client_id = get_client_id_using_contact_id($this, $lead_data->client_id, $lead_data->multiple_cases);
                // send notification to the ld-team and admin
                // send  notiication in crm to all the team group member and staff
                $_POST['lead_name'] = $case_name;
                $_POST['get_afternoon_and_morning'] = get_afternoon_and_morning();
                $_POST['file_status'] = $file_status;
                $get_mail_subject = get_mail_subject($this, $lead_id);
                $_POST['lead_id'] = $lead_id;
                $_POST['case_url'] = admin_url('cases/index/') . $lead_id;
                $_POST['ledger_comment'] = $rejectionReason;
                $new_case_message = 'Ledger Document ' . $file_status . ' by ' . get_staff_full_name() . ', ' . $get_mail_subject;
                $this->db->select('assign_group,assigned');
                $this->db->where('id', $lead_id);
                $lead_data_for_get_assign_group = $this->db->get(db_prefix() . 'leads')->row();
                $current_staff_data = get_staff_ids_by_group($this, $lead_data_for_get_assign_group->assign_group);
                foreach ($current_staff_data as $staff_notifiy_data) {
                    if (get_staff_user_id() != $staff_notifiy_data['staffid']) {
                        // $subject = $new_case_message;
                        // $replay_to_mail = get_all_staff_to_replay_email($this, get_staff_user_id(), $lead_data_for_get_assign_group->assign_group);
                        // $html_content_confirmation_email_to_broker = $this->load->view('admin/leads/Email_template/admin/Ledger_doc_approved_rejected', $_POST, TRUE);
                        // send_mailchimp_email($staff_notifiy_data['email'], $subject, $html_content_confirmation_email_to_broker, $replay_to_mail, '', '', $lead_id);
                        // send notificaiton in crm
                        $this->leads_model->custom_lead_assigned_member_notification('staff', $lead_id, $staff_notifiy_data['staffid'], get_staff_user_id(), '', $new_case_message);
                    }
                }
                // get the all admin staff ids
                $admin_ids = get_all_admin_role_staff_ids($this);
                foreach ($admin_ids as $admin_email) {
                    if (get_staff_user_id() != $admin_email['staffid']) {
                        // send slack notification
                        // $slack_message = $new_case_message;
                        // $subject = $new_case_message;
                        // $replay_to_mail = get_all_staff_to_replay_email($this, get_staff_user_id(), $lead_data_for_get_assign_group->assign_group);
                        // $html_content_confirmation_email_to_broker = $this->load->view('admin/leads/Email_template/admin/Ledger_doc_approved_rejected', $_POST, TRUE);
                        // send_mailchimp_email($admin_email['email'], $subject, $html_content_confirmation_email_to_broker, $replay_to_mail, '', '', $lead_id);
                        // send notification in crm
                        $this->leads_model->custom_lead_assigned_member_notification('staff', $lead_id, $admin_email['staffid'], get_staff_user_id(), '', $new_case_message);
                    }
                }
                if ($file_status == 'Approved') {
                    $broker_ledger_mail_content = 'Good ' . get_afternoon_and_morning() . '<br>' . ' <p>Please note on the file of #' . $_POST['lead_id'] . ', the broker has approved the ledger.</p> <br><p>To progress the file <a href="' . $_POST['case_url'] . '">Click here</a>.</p>';
                } elseif ($file_status == 'Rejected') {
                    $broker_ledger_mail_content = 'Good ' . get_afternoon_and_morning() . '<br>' . ' <p>Please note on the file of #' . $_POST['lead_id'] . ', the broker has rejected the ledger.</p><br><p>To progress the file <a href="' . $_POST['case_url'] . '">Click here</a>.</p>';
                }
                $insert_task_activity = array(
                    'leadid' => $lead_id,
                    'staffid' => get_staff_user_id(),
                    'full_name' => get_staff_full_name(),
                    'description' => get_staff_full_name() . " sent an email to " . ' BOB & all group members ( ' . $lead_data->assign_group . ' ) <br>' . $broker_ledger_mail_content,
                    'date' => date('Y-m-d H:i:s'),
                );
                leads_activity_log($this, $insert_task_activity);
                // send slack notification when broker approve ledgers
                $staffRole = get_current_staff_role($this, get_staff_user_id());
                $reason = '';
                if (!empty($rejectionReason)) {
                    $reason = "\n - " . $rejectionReason;
                }
                // get check of gtc
                $GTC_Check = get_gtc_check($this, $lead_id);
                // update the gtc check key 
                $this->leads_model->update_GTC_key($lead_id, 1);
                if (in_array($staffRole, [2, 6]) && $file_status == 'Approved') {
                    if ($GTC_Check == 0) {
                        // Send Slack notification for GTC
                        $slack_message = "\n - Stage Complete: GTC from Client/Nuborrow \n - Request for Funds.";
                        $send_notification = $this->slack->sendnotification($slack_message, $lead_id, $group_name, $lead_split_name['lastname'] . ', ' . $lead_split_name['firstname'] . ' ' . $lead_split_name['middlename']);
                    }
                    // send slack notificiton when broker approve/reject ledger
                    $slack_message = "\n - Broker has reviewed ledgers and the status is: Approved" . $reason;
                    $send_notification = $this->slack->sendnotification($slack_message, $lead_id, $group_name, $lead_split_name['lastname'] . ', ' . $lead_split_name['firstname'] . ' ' . $lead_split_name['middlename']);
                }
                // send slack notification when broker reject ledgers
                if (in_array($staffRole, [2, 6]) && $file_status == 'Rejected') {
                    // send slack notificiton when broker approve/reject ledger
                    $slack_message = "\n - Broker has reviewed ledgers and the status is: Rejected" . $reason;
                    $send_notification = $this->slack->sendnotification($slack_message, $lead_id, $group_name, $lead_split_name['lastname'] . ', ' . $lead_split_name['firstname'] . ' ' . $lead_split_name['middlename']);
                }
            }
            $response = array(
                'success' => true,
                'id' => $lead_id,
                'leadView' => $this->_get_lead_data($lead_id),
                'message' => 'File status updated successfully.',
            );
        } else {
            $response = array(
                'success' => false,
                'id' => $lead_id,
                'leadView' => $this->_get_lead_data($lead_id),
                'message' => 'Failed to update file status.',
            );
        }

        $this->output
            ->set_content_type('application/json')
            ->set_output(json_encode($response));
    }

    // upload doc for ledger
    public function upload_doc_for_ledger()
    {
        $leads_status_value = '#ledger';
        $complete_stage_button = 4;
        $last_inserted_file_id = '';
        $lead_id = $this->input->post('lead_id');
        $type = $this->input->post('type');
        $ledger_comment = $this->input->post('ledger_comment');
        $ledger_notes = $this->input->post('ledger_notes');
        $send_approved_ledger_to_broker_tinymce = $this->input->post('send_approved_ledger_to_broker_tinymce', FALSE);
        $to_broker_ledgers_reviewmail = $this->input->post('to_broker_ledgers_reviewmail');
        $cc_broker_ledgers_reviewmail = $this->input->post('cc_broker_ledgers_reviewmail');
        $bcc_broker_ledgers_reviewmail = $this->input->post('bcc_broker_ledgers_reviewmail');
        $ledger_type = '';
        $ledger_type = ($type === 'broker') ? $type : 'ld_team';
        // get the last ledger count
        $ledger_number_count = get_the_ledger_number_count($this, $lead_id, $ledger_type);
        // get the leads data
        $this->db->select('email,assign_group');
        $this->db->where('id', $lead_id);
        $result = $this->db->get(db_prefix() . 'leads')->row();
        $getemail = $result->email;
        $check_assign_group = $result->assign_group;
        $data = $this->Token_model->getToken();
        $get_id = array_column($data, 'token');
        $access_token = implode(',', $get_id);
        $data = $this->Contacts_model->getEmail($getemail);
        $get_id = array_column($data, 'id');
        $get_userid = array_column($data, 'userid');
        $get_firstname = array_column($data, 'firstname');
        $get_lastname = array_column($data, 'lastname');
        $dropbox_firstname = implode(',', $get_firstname);
        $dropbox_lastname = implode(',', $get_lastname);
        $get_id = implode(',', $get_id);
        $userid = implode(',', $get_userid);
        $leadData = $this->leads_model->get_lead_id($get_id);
        $user_id = $leadData->id;
        $user_name = $leadData->name;
        $uploaded_files_data = array();
        // check upload ledger docs for ld or broker
        if ($ledger_type == 'broker') {
            // conver string to array 
            $to_emails = array_map('trim', explode(',', $to_broker_ledgers_reviewmail));
            $cc_emails = array_map('trim', explode(',', $cc_broker_ledgers_reviewmail));
            $bcc_emails = array_map('trim', explode(',', $bcc_broker_ledgers_reviewmail));
            // get latest ledger number count
            $get_latest_approved_ledger_number = get_latest_distinct_ledger_number($this, $lead_id);
            $ld_ledger_data = get_the_ldteam_latest_ledger_approved_id(
                $this,
                $lead_id,
                $get_latest_approved_ledger_number->ledger_number
            );
            // apply check if ledgers approved according to the lead id
            $this->db->from(db_prefix() . 'leads_ledger');
            $this->db->where('lead_id', $lead_id);
            $this->db->where('bb_status', 'Approved');
            $count = $this->db->count_all_results();
            if ($count > 0) {
                if (isset($_FILES['ledger_userfile']) && !empty($_FILES['ledger_userfile']['name'][0])) {
                    foreach ($_FILES['ledger_userfile']['name'] as $key => $name) {
                        $tmp_file = $_FILES['ledger_userfile']['tmp_name'][$key];
                        if (is_uploaded_file($tmp_file)) {
                            $file_name = $_FILES['ledger_userfile']['name'][$key];
                            $data = $this->leads_model->upload_to_dropbox($access_token, $tmp_file, $file_name, $user_id, $dropbox_firstname, $dropbox_lastname);
                            if ($data['status'] != 200) {
                                $this->leads_model->add_errors_logs($lead_id, get_staff_user_id(), get_staff_full_name(), 'Upload ledger for broker approval', $data, $data['status'], 'Staff');
                                echo json_encode(
                                    array(
                                        'success' => false,
                                        'response' => $data
                                    )
                                );
                                exit;
                            }
                            $file_data = array(
                                'lead_id' => $lead_id,
                                'ledger_number' => $ld_ledger_data->ledger_number,
                                'type' => $ledger_type,
                                'file_name' => $data['file_name'],
                                'filetype' => $data['file_type'],
                                'file_url' => $data['file_url'],
                                'download_file_url' => $data['download_file_url'],
                                'bb_comment' => $ledger_comment,
                                'bb_status' => 'Approved',
                                'created_at' => date('Y-m-d H:i:s'),
                            );
                            $uploaded_files_data[] = $file_data;
                            $this->db->insert(db_prefix() . 'leads_ledger', $file_data);
                            $last_inserted_file_id = $this->db->insert_id();
                        }
                    }
                    $insert_task_activity = array(
                        'leadid' => $lead_id,
                        'staffid' => get_staff_user_id(),
                        'full_name' => get_staff_full_name(),
                        'description' => get_staff_full_name() . " upload the ledger documents.",
                        'date' => date('Y-m-d H:i:s'),
                    );
                    leads_activity_log($this, $insert_task_activity);
                } else {
                    $last_inserted_file_id = 1;
                }
                $ledger_logs_array = array(
                    'lead_id' => $lead_id,
                    'lead_ledger_id' => $ld_ledger_data->id,
                    'lead_ledger_number' => $ld_ledger_data->ledger_number,
                    'status' => 'Sent Ledgers to Broker for approval.',
                    'comment' => $ledger_comment,
                    'created_at' => date('Y-m-d H:i:s'),
                );
                $this->db->insert(db_prefix() . 'leads_ledger_logs', $ledger_logs_array);
                // send email line of code 
                $get_mail_subject = get_mail_subject($this, $lead_id);
                $this->db->select('addedfrom');
                $this->db->where('id', $lead_id);
                $get_record = $this->db->get(db_prefix() . 'leads')->row();
                $broker_data = get_multiple_broker_details_using_addedfrom($this, $get_record->addedfrom);
                // get the task id using lead id for get a files_url
                $this->db->select('id, ledger_number');
                $this->db->where('lead_id', $lead_id);
                $this->db->where('type', 'ld_team');
                $this->db->order_by('id', 'desc');
                $this->db->where('bb_status', 'Approved');
                $this->db->limit(1);
                $query = $this->db->get(db_prefix() . 'leads_ledger');
                $ledger_number_row = $query->row();
                $_POST['close_attachment'] = $uploaded_files_data;
                $subject = 'Review Ledgers ' . $get_mail_subject;
                $_POST['case_url'] = get_the_redirect_email_case_url($lead_id, 'broker');
                $_POST['send_approved_ledger_to_broker_tinymce'] = $send_approved_ledger_to_broker_tinymce;
                $_POST['ledger_comment'] = $ledger_comment;
                $replay_to_mail = get_all_staff_to_replay_email($this, get_staff_user_id(), $check_assign_group);
                $html_content_confirmation_email_to_broker = $this->load->view('admin/leads/Email_template/broker/draft_ledger_attachement', $_POST, TRUE);
                $send_email_result = send_mailchimp_email($to_emails, $subject, $html_content_confirmation_email_to_broker, $replay_to_mail, $cc_emails, $bcc_emails, $lead_id);
                // add the record for outbox emails
                $outbox_id = $this->Outbox_model->save_outbox_email(
                    $to_emails,
                    $cc_emails,
                    $bcc_emails,
                    $subject,
                    $_POST['send_approved_ledger_to_broker_tinymce'],
                    $_POST['close_attachment'],
                    $lead_id,
                    10,
                    $html_content_confirmation_email_to_broker,
                    $replay_to_mail,
                    $send_email_result['status'],
                    $send_email_result['mandrill_id'],
                    1
                );
                if (!empty($broker_data)) {
                    foreach ($broker_data as $broker) {
                        $_POST['broker_name'] = $broker['firstname'] . ' ' . $broker['lastname'];
                        $broker_email = $broker['email'];
                        // add the emali in activity logs
                        $broker_ledger_mail_content = 'Dear Colleague,<br>
                                We are now moving to closing, please see attached ledgers and kindly update
                                    your records.<br>If you wish to access this file, Please <a href="' . $_POST['case_url'] . '">Click here</a>';
                        $insert_task_activity = array(
                            'leadid' => $lead_id,
                            'staffid' => get_staff_user_id(),
                            'full_name' => get_staff_full_name(),
                            'description' => get_staff_full_name() . " sent an email to " . $_POST['broker_name'] . ' <br>' . $broker_ledger_mail_content,
                            'date' => date('Y-m-d H:i:s'),
                        );
                        leads_activity_log($this, $insert_task_activity);
                        $this->leads_model->custom_lead_assigned_member_notification('staff', $lead_id, $broker['staffid'], get_staff_user_id(), '', 'The latest ledgers have been sent. Please check your email for the details.');
                    }
                    // send the all admin notification and email to the admin broker
                    $brokerage_id = get_brokerage_id_using_leadid($this, $lead_id);
                    $admin_broker_ids = get_all_admin_broker_role_staff_ids($this, $brokerage_id);
                    foreach ($admin_broker_ids as $admin_broker_email) {
                        if (get_staff_user_id() != $admin_broker_email['staffid'] && !in_array($admin_broker_email['staffid'], explode(',', $get_record->addedfrom))) {
                            $notification_text = get_staff_full_name() . " sent a email you for case (" . $get_mail_subject . ').';
                            $this->leads_model->custom_lead_assigned_member_notification('staff', $lead_id, $admin_broker_email['staffid'], get_staff_user_id(), '', $notification_text);
                        }
                    }
                }
                // notification send code
                $this->db->select('multiple_cases,client_id,phonenumber,name,email,addedfrom,assign_group');
                $this->db->where('id', $lead_id);
                $lead_data_check = $this->db->get(db_prefix() . 'leads');
                if ($lead_data_check->num_rows() > 0) {
                    $lead_data = $lead_data_check->row();
                    $case_name = $lead_data->name;
                    $client_id = get_client_id_using_contact_id($this, $lead_data->client_id, $lead_data->multiple_cases);
                    // send notification to the ld-team and admin
                    // send  notiication in crm to all the team group member and staff
                    $get_mail_subject = get_mail_subject($this, $lead_id);
                    $_POST['lead_id'] = $lead_id;
                    $_POST['case_url'] = admin_url('cases/index/') . $lead_id;
                    $new_case_message = 'Please check the ledgers for case (#' . $lead_id . ', Name: ' . $case_name . ').';
                    $this->db->select('assign_group,assigned');
                    $this->db->where('id', $lead_id);
                    $lead_data_for_get_assign_group = $this->db->get(db_prefix() . 'leads')->row();
                    $current_staff_data = get_staff_ids_by_group($this, $lead_data_for_get_assign_group->assign_group);
                    foreach ($current_staff_data as $staff_notifiy_data) {
                        if (get_staff_user_id() != $staff_notifiy_data['staffid']) {
                            // $subject = 'Attachment Draft Ledger';
                            $subject = $new_case_message;
                            // send notificaiton in crm
                            $this->leads_model->custom_lead_assigned_member_notification('staff', $lead_id, $staff_notifiy_data['staffid'], get_staff_user_id(), '', $new_case_message);
                        }
                    }
                    // send notificaion to the broker
                    $this->leads_model->custom_lead_assigned_member_notification('staff', $lead_id, $lead_data->addedfrom, get_staff_user_id(), '', $new_case_message);
                }
            } else {
                $response = array(
                    'success' => false,
                    'message' => 'Please Approved any one ledgers.',
                    'leads_status' => $leads_status_value,
                    'complete_stage_button' => $complete_stage_button,
                    'id' => $lead_id,
                    'leadView' => $this->_get_lead_data($lead_id),
                );
            }
        } else {
            if (!empty($_FILES)) {
                foreach ($_FILES['ledger_userfile']['name'] as $key => $name) {
                    $tmp_file = $_FILES['ledger_userfile']['tmp_name'][$key];
                    if (is_uploaded_file($tmp_file)) {
                        $file_name = $_FILES['ledger_userfile']['name'][$key];
                        $data = $this->leads_model->upload_to_dropbox($access_token, $tmp_file, $file_name, $user_id, $dropbox_firstname, $dropbox_lastname);
                        if ($data['status'] != 200) {
                            $this->leads_model->add_errors_logs($lead_id, get_staff_user_id(), get_staff_full_name(), 'BB for approval ledgers', $data, $data['status'], 'Staff');
                            echo json_encode(
                                array(
                                    'success' => false,
                                    'response' => $data
                                )
                            );
                            exit;
                        }
                        $file_data = array(
                            'lead_id' => $lead_id,
                            'ledger_number' => $ledger_number_count,
                            'type' => $ledger_type,
                            'file_name' => $data['file_name'],
                            'filetype' => $data['file_type'],
                            'file_url' => $data['file_url'],
                            'download_file_url' => $data['download_file_url'],
                            'bb_comment' => $ledger_comment,
                            'created_at' => date('Y-m-d H:i:s'),
                        );
                        $uploaded_files_data[] = $file_data;
                        $this->db->insert(db_prefix() . 'leads_ledger', $file_data);
                        $last_inserted_file_id = $this->db->insert_id();
                    }
                }
            }
            // insert the record in leads ledger logs
            $this->db->select('id,ledger_number');
            $this->db->where('lead_id', $lead_id);
            $this->db->where('ledger_number', $ledger_number_count);
            $this->db->where('type', $ledger_type);
            $this->db->order_by('id', 'asc');
            $this->db->limit(1);
            $query = $this->db->get(db_prefix() . 'leads_ledger');
            $ledger_number_row = $query->row();
            $ledger_logs_array = array(
                'lead_id' => $lead_id,
                'lead_ledger_id' => $ledger_number_row->id,
                'lead_ledger_number' => $ledger_number_row->ledger_number,
                'status' => 'Sent ' . (($ledger_number_count > 1) ? 'Revised' : 'Review') . ' Ledgers to BB for approval.',
                'comment' => $ledger_comment,
                'notes' => $ledger_notes,
                'created_at' => date('Y-m-d H:i:s'),
            );
            $this->db->insert(db_prefix() . 'leads_ledger_logs', $ledger_logs_array);
            // send ledger mail to the broker with attachment
            $get_mail_subject = get_mail_subject($this, $lead_id);
            $this->db->select('addedfrom');
            $this->db->where('id', $lead_id);
            $get_record = $this->db->get(db_prefix() . 'leads')->row();
            $_POST['broker_name'] = get_staff_name_by_id($this, $get_record->addedfrom);
            $broker_email = get_staff_email_by_id($this, $get_record->addedfrom);
            // get the task id using lead id for get a files_url
            $ledger_document = get_specific_legder_doc($this, $lead_id, $ledger_number_count, 'ld_team');
            $_POST['close_attachment'] = $ledger_document;
            if (!empty($ledger_document)) {
                $_POST['case_url'] = admin_url('cases/index/') . $lead_id;
                $_POST['ledger_number_count'] = $ledger_number_count;
                // $subject = 'Attachment Draft Ledger';
                $subject = 'Review Ledgers ' . $get_mail_subject;
                $replay_to_mail = get_all_staff_to_replay_email($this, get_staff_user_id(), $check_assign_group);
                $html_content_confirmation_email_to_broker = $this->load->view('admin/leads/Email_template/ledger_bb_for_approval', $_POST, TRUE);
                // creating a seperate email for tester and bob for different server
                $get_test_staff_data = get_staff_data_by_id($this, get_staff_user_id());
                if (base_url() == 'https://dev.platform.legaldirect.ca/') {
                    $send_email_result = send_mailchimp_email('ra.faheem7@gmail.com', $subject, $html_content_confirmation_email_to_broker, $replay_to_mail, '', '', $lead_id);
                    // add the record for outbox emails
                    $outbox_content = "Dear Bob, Please review the " . ($ledger_number_count > 1 ? 'REVISED ' : '') . "Ledgers Documents.";
                    $outbox_id = $this->Outbox_model->save_outbox_email(
                        'ra.faheem7@gmail.com',
                        '',
                        '',
                        $subject,
                        $outbox_content,
                        $_POST['close_attachment'],
                        $lead_id,
                        10,
                        $html_content_confirmation_email_to_broker,
                        $replay_to_mail,
                        $send_email_result['status'],
                        $send_email_result['mandrill_id'],
                        1
                    );
                } else {
                    $send_email_result = send_mailchimp_email('bb@legaldirect.ca', $subject, $html_content_confirmation_email_to_broker, $replay_to_mail, '', 'dy@legaldirect.ca', $lead_id);
                    // add the record for outbox emails
                    $outbox_content = "Dear Bob, Please review the " . ($ledger_number_count > 1 ? 'REVISED ' : '') . "Ledgers Documents.";
                    $outbox_id = $this->Outbox_model->save_outbox_email(
                        'bb@legaldirect.ca',
                        '',
                        'dy@legaldirect.ca',
                        $subject,
                        $outbox_content,
                        $_POST['close_attachment'],
                        $lead_id,
                        10,
                        $html_content_confirmation_email_to_broker,
                        $replay_to_mail,
                        $send_email_result['status'],
                        $send_email_result['mandrill_id'],
                        1
                    );
                }
                // add the doc upload text in activity logs
                $insert_task_activity = array(
                    'leadid' => $lead_id,
                    'staffid' => get_staff_user_id(),
                    'full_name' => get_staff_full_name(),
                    'description' => get_staff_full_name() . " upload the ledgers documents.",
                    'date' => date('Y-m-d H:i:s'),
                );
                leads_activity_log($this, $insert_task_activity);
                // add the emali in activity logs
                $broker_ledger_mail_content = 'Dear Colleague,<br>Please review the Ledgers Documents. <br>
                If you wish to access this file, Please <a href="' . $_POST['case_url'] . '">Click here</a>';
                $insert_task_activity = array(
                    'leadid' => $lead_id,
                    'staffid' => get_staff_user_id(),
                    'full_name' => get_staff_full_name(),
                    'description' => get_staff_full_name() . " sent an email to " . ' BOB ' . ' <br>' . $broker_ledger_mail_content,
                    'date' => date('Y-m-d H:i:s'),
                );
                leads_activity_log($this, $insert_task_activity);
                // notification send code
                $this->db->select('multiple_cases,client_id,phonenumber,name,email,addedfrom,assign_group');
                $this->db->where('id', $lead_id);
                $lead_data_check = $this->db->get(db_prefix() . 'leads');
                if ($lead_data_check->num_rows() > 0) {
                    $lead_data = $lead_data_check->row();
                    $case_name = $lead_data->name;
                    $client_id = get_client_id_using_contact_id($this, $lead_data->client_id, $lead_data->multiple_cases);
                    $lead_split_name = leads_splitFullName($lead_data->name);
                    // send notification to the ld-team and admin
                    // send  notiication in crm to all the team group member and staff
                    $get_mail_subject = get_mail_subject($this, $lead_id);
                    $_POST['lead_id'] = $lead_id;
                    $_POST['case_url'] = admin_url('cases/index/') . $lead_id;
                    $new_case_message = 'Ledger Document uploaded by ' . get_staff_full_name();
                    $slack_message = 'Ledger Document uploaded by ' . htmlspecialchars(get_staff_full_name());

                    $this->db->select('assign_group,assigned');
                    $this->db->where('id', $lead_id);
                    $lead_data_for_get_assign_group = $this->db->get(db_prefix() . 'leads')->row();
                    $current_staff_data = get_staff_ids_by_group($this, $lead_data_for_get_assign_group->assign_group);
                    foreach ($current_staff_data as $staff_notifiy_data) {
                        if (get_staff_user_id() != $staff_notifiy_data['staffid']) {
                            // $subject = 'Attachment Draft Ledger';
                            $subject = $new_case_message;
                            // send notificaiton in crm
                            $this->leads_model->custom_lead_assigned_member_notification('staff', $lead_id, $staff_notifiy_data['staffid'], get_staff_user_id(), '', $new_case_message);
                        }
                    }
                    // get the all admin staff ids
                    $admin_ids = get_all_admin_role_staff_ids($this);
                    foreach ($admin_ids as $admin_email) {
                        if (get_staff_user_id() != $admin_email['staffid']) {
                            // send notificaiton in crm
                            $this->leads_model->custom_lead_assigned_member_notification('staff', $lead_id, $admin_email['staffid'], get_staff_user_id(), '', $new_case_message);
                        }
                    }
                }
            }
        }
        // update the last contact date 
        $this->leads_model->update_leads_last_contact_date($lead_id);
        if (!empty($last_inserted_file_id)) {
            $response = array(
                'success' => true,
                'message' => 'Data saved successfully',
                'leads_status' => $leads_status_value,
                'complete_stage_button' => $complete_stage_button,
                'id' => $lead_id,
                'leadView' => $this->_get_lead_data($lead_id),
            );
        } else {
            $response = array(
                'success' => false,
                'message' => 'Data is not save in our record.',
                'leads_status' => $leads_status_value,
                'complete_stage_button' => $complete_stage_button,
                'id' => $lead_id,
                'leadView' => $this->_get_lead_data($lead_id),
            );
        }
        $this->output
            ->set_content_type('application/json')
            ->set_output(json_encode($response));
    }
    // bb to approve closing day ledgers
    public function bb_to_approve_closing_day_ledger()
    {
        $leads_status_value = '#Closed';
        $complete_stage_button = 5;
        $last_inserted_file_id = '';
        $lead_id = $this->input->post('lead_id');
        $bb_to_approve_closing_day_ledger_notes = $this->input->post('bb_to_approve_closing_day_ledger_notes');
        // get the last ledger count
        $ledger_number_count = get_the_ledger_number_count($this, $lead_id, 'final-closed-ledger-sent');
        // get the leads data
        $this->db->select('email,assign_group');
        $this->db->where('id', $lead_id);
        $result = $this->db->get(db_prefix() . 'leads')->row();
        $getemail = $result->email;
        $check_assign_group = $result->assign_group;
        $data = $this->Token_model->getToken();
        $get_id = array_column($data, 'token');
        $access_token = implode(',', $get_id);
        $data = $this->Contacts_model->getEmail($getemail);
        $get_id = array_column($data, 'id');
        $get_userid = array_column($data, 'userid');
        $get_firstname = array_column($data, 'firstname');
        $get_lastname = array_column($data, 'lastname');
        $dropbox_firstname = implode(',', $get_firstname);
        $dropbox_lastname = implode(',', $get_lastname);
        $get_id = implode(',', $get_id);
        $userid = implode(',', $get_userid);
        $leadData = $this->leads_model->get_lead_id($get_id);
        $user_id = $leadData->id;
        $user_name = $leadData->name;
        // upload doc 
        if (isset($_FILES['bb_to_approve_closing_day_ledger_userfile']) && !empty($_FILES['bb_to_approve_closing_day_ledger_userfile']['name'][0])) {
            foreach ($_FILES['bb_to_approve_closing_day_ledger_userfile']['name'] as $key => $name) {
                $tmp_file = $_FILES['bb_to_approve_closing_day_ledger_userfile']['tmp_name'][$key];
                if (is_uploaded_file($tmp_file)) {
                    $file_name = $_FILES['bb_to_approve_closing_day_ledger_userfile']['name'][$key];
                    $data = $this->leads_model->upload_to_dropbox($access_token, $tmp_file, $file_name, $user_id, $dropbox_firstname, $dropbox_lastname);
                    if ($data['status'] != 200) {
                        $this->leads_model->add_errors_logs($lead_id, get_staff_user_id(), get_staff_full_name(), 'BB to approve closing day ledgers.', $data, $data['status'], 'Staff');
                        echo json_encode(
                            array(
                                'success' => false,
                                'response' => $data
                            )
                        );
                        exit;
                    }
                    $file_data = array(
                        'lead_id' => $lead_id,
                        'ledger_number' => $ledger_number_count,
                        'type' => 'final-closed-ledger-sent',
                        'file_name' => $data['file_name'],
                        'filetype' => $data['file_type'],
                        'file_url' => $data['file_url'],
                        'download_file_url' => $data['download_file_url'],
                        'created_at' => date('Y-m-d H:i:s'),
                    );
                    $uploaded_files_data[] = $file_data;
                    $this->db->insert(db_prefix() . 'leads_ledger', $file_data);
                    $last_inserted_file_id = $this->db->insert_id();
                }
            }
            // add the record in tbl leads ledger logs
            $ledger_logs_array = array(
                'lead_id' => $lead_id,
                'lead_ledger_number' => $ledger_number_count,
                'leads_ledger_type' => 'final-closed-ledger-sent',
                'status' => 'Sent Final Ledgers to BB for approval.',
                'comment' => $bb_to_approve_closing_day_ledger_notes,
                'created_at' => date('Y-m-d H:i:s'),
            );
            $this->db->insert(db_prefix() . 'leads_ledger_logs', $ledger_logs_array);
            // add the activity lgos
            $insert_task_activity = array(
                'leadid' => $lead_id,
                'staffid' => get_staff_user_id(),
                'full_name' => get_staff_full_name(),
                'description' => get_staff_full_name() . " Upload BB to approve closing day leders and send mail to the BOB." . '<br>' . 'Please review final ledgers for closing due today,please press here if you wish to access the file.',
                'date' => date('Y-m-d H:i:s'),
            );
            leads_activity_log($this, $insert_task_activity);
        }
        $get_mail_subject = 'Review Final Ledgers ' . get_mail_subject($this, $lead_id);
        if (!empty($last_inserted_file_id)) {
            $_POST['case_url'] = admin_url('cases/index/') . $lead_id;
            $_POST['generic_email_title'] = 'Review Final Ledgers';
            $_POST['generic_email_content_title'] = 'Dear BOB,';
            $_POST['generic_email_back_to_case_url'] = 'Please <a href="' . htmlspecialchars($_POST['case_url'], ENT_QUOTES, 'UTF-8') . '">Click here</a> to access the file and allocate it to the relevant team.';
            $_POST['generic_email_content'] = 'Please review final ledgers for closing due today.';
            $_POST['general_attachment'] = get_specific_legder_doc($this, $lead_id, $ledger_number_count, 'final-closed-ledger-sent');
            $html_content_welcome_email_to_user = $this->load->view('admin/leads/Email_template/generic_email_template', $_POST, TRUE);
            $replay_to_mail = get_all_staff_to_replay_email($this, get_staff_user_id(), $check_assign_group);
            // get the group name 
            $leads_group = get_the_group_name_using_leadid($this, $lead_id);
            $cc_group_member = get_all_staff_name_email_by_group_for_cc($this, $lead_id, $leads_group);
            // creating a seperate email for tester and bob for different server
            $get_test_staff_data = get_staff_data_by_id($this, get_staff_user_id());
            if (base_url() == 'https://dev.platform.legaldirect.ca/') {
                $send_email_result = send_mailchimp_email('ra.faheem7@gmail.com', $get_mail_subject, $html_content_welcome_email_to_user, $replay_to_mail, $cc_group_member, '', $lead_id);
                // add the record for outbox emails
                $outbox_id = $this->Outbox_model->save_outbox_email(
                    'ra.faheem7@gmail.com',
                    $cc_group_member,
                    '',
                    $get_mail_subject,
                    $_POST['generic_email_content'],
                    $_POST['general_attachment'],
                    $lead_id,
                    5,
                    $html_content_welcome_email_to_user,
                    $replay_to_mail,
                    $send_email_result['status'],
                    $send_email_result['mandrill_id'],
                    1
                );
            } else {
                $send_email_result = send_mailchimp_email('bb@legaldirect.ca', $get_mail_subject, $html_content_welcome_email_to_user, $replay_to_mail, $cc_group_member, '', $lead_id);
                // add the record for outbox emails
                $outbox_id = $this->Outbox_model->save_outbox_email(
                    'bb@legaldirect.ca',
                    $cc_group_member,
                    '',
                    $get_mail_subject,
                    $_POST['generic_email_content'],
                    $_POST['general_attachment'],
                    $lead_id,
                    5,
                    $html_content_welcome_email_to_user,
                    $replay_to_mail,
                    $send_email_result['status'],
                    $send_email_result['mandrill_id'],
                    1
                );
            }
            $response = array(
                'success' => true,
                'message' => 'Data saved successfully',
                'leads_status' => $leads_status_value,
                'complete_stage_button' => $complete_stage_button,
                'id' => $lead_id,
                'leadView' => $this->_get_lead_data($lead_id),
            );
        } else {
            $response = array(
                'success' => false,
            );
        }
        $this->output
            ->set_content_type('application/json')
            ->set_output(json_encode($response));
    }
    // bb response to closing day ledgers
    public function bb_response_to_closing_day_ledger()
    {
        $leads_status_value = '#Closed';
        $complete_stage_button = 5;
        $last_inserted_file_id = '';
        $lead_id = $this->input->post('lead_id');
        $bb_response_to_closing_day_ledger_notes = $this->input->post('bb_response_to_closing_day_ledger_notes');
        // get the last ledger count
        $ledger_number_count = get_the_ledger_number_count($this, $lead_id, 'final-closed-ledger-sent');
        // get the leads data
        $this->db->select('email,assign_group,name');
        $this->db->where('id', $lead_id);
        $result = $this->db->get(db_prefix() . 'leads')->row();
        $getemail = $result->email;
        $case_name = $result->name;
        $check_assign_group = $result->assign_group;
        $data = $this->Token_model->getToken();
        $get_id = array_column($data, 'token');
        $access_token = implode(',', $get_id);
        $data = $this->Contacts_model->getEmail($getemail);
        $get_id = array_column($data, 'id');
        $get_userid = array_column($data, 'userid');
        $get_firstname = array_column($data, 'firstname');
        $get_lastname = array_column($data, 'lastname');
        $dropbox_firstname = implode(',', $get_firstname);
        $dropbox_lastname = implode(',', $get_lastname);
        $get_id = implode(',', $get_id);
        $userid = implode(',', $get_userid);
        $leadData = $this->leads_model->get_lead_id($get_id);
        $user_id = $leadData->id;
        $user_name = $leadData->name;
        // upload doc 
        if (isset($_FILES['bb_response_to_closing_day_ledger_userfile']) && !empty($_FILES['bb_response_to_closing_day_ledger_userfile']['name'][0])) {
            foreach ($_FILES['bb_response_to_closing_day_ledger_userfile']['name'] as $key => $name) {
                $tmp_file = $_FILES['bb_response_to_closing_day_ledger_userfile']['tmp_name'][$key];
                if (is_uploaded_file($tmp_file)) {
                    $file_name = $_FILES['bb_response_to_closing_day_ledger_userfile']['name'][$key];
                    $data = $this->leads_model->upload_to_dropbox($access_token, $tmp_file, $file_name, $user_id, $dropbox_firstname, $dropbox_lastname);
                    if ($data['status'] != 200) {
                        $this->leads_model->add_errors_logs($lead_id, get_staff_user_id(), get_staff_full_name(), 'BB response to Closing ledgers', $data, $data['status'], 'Staff');
                        echo json_encode(
                            array(
                                'success' => false,
                                'response' => $data
                            )
                        );
                        exit;
                    }
                    $file_data = array(
                        'lead_id' => $lead_id,
                        'ledger_number' => $ledger_number_count,
                        'type' => 'final-closed-ledger-sent',
                        'file_name' => $data['file_name'],
                        'filetype' => $data['file_type'],
                        'file_url' => $data['file_url'],
                        'download_file_url' => $data['download_file_url'],
                        'created_at' => date('Y-m-d H:i:s'),
                    );
                    $uploaded_files_data[] = $file_data;
                    $this->db->insert(db_prefix() . 'leads_ledger', $file_data);
                    $last_inserted_file_id = $this->db->insert_id();
                }
            }
            // add the record in tbl leads ledger logs
            $ledger_logs_array = array(
                'lead_id' => $lead_id,
                'lead_ledger_number' => $ledger_number_count,
                'leads_ledger_type' => 'final-closed-ledger-sent',
                'status' => 'BB response to the closing daily Ledgers.',
                'comment' => $bb_response_to_closing_day_ledger_notes,
                'created_at' => date('Y-m-d H:i:s'),
            );
            $this->db->insert(db_prefix() . 'leads_ledger_logs', $ledger_logs_array);
            // add the activity lgos
            $insert_task_activity = array(
                'leadid' => $lead_id,
                'staffid' => get_staff_user_id(),
                'full_name' => get_staff_full_name(),
                'description' => get_staff_full_name() . " upload the bb response daily closing ledger documents and sent an email to Team." . '<br>' . 'Please see my response to ledgers for closing due today.',
                'date' => date('Y-m-d H:i:s'),
            );
            leads_activity_log($this, $insert_task_activity);
        }
        $get_mail_subject = 'Review Final Ledger ' . get_mail_subject($this, $lead_id);
        if (!empty($last_inserted_file_id)) {
            $_POST['case_url'] = admin_url('cases/index/') . $lead_id;
            $_POST['generic_email_title'] = '';
            $_POST['generic_email_back_to_case_url'] = 'Please <a href="' . htmlspecialchars($_POST['case_url'], ENT_QUOTES, 'UTF-8') . '">Click here</a> to access the file and allocate it to the relevant team.';
            $_POST['generic_email_content'] = 'Please see my response to ledgers for closing due today.';
            $_POST['general_attachment'] = get_specific_legder_doc($this, $lead_id, $ledger_number_count, 'final-closed-ledger-sent');
            $html_content_welcome_email_to_user = $this->load->view('admin/leads/Email_template/generic_email_template', $_POST, TRUE);
            $replay_to_mail = get_all_staff_to_replay_email($this, get_staff_user_id(), $check_assign_group);
            // get the group name 
            $leads_group = get_the_group_name_using_leadid($this, $lead_id);
            $cc_group_member = get_all_staff_name_email_by_group_for_cc($this, $lead_id, $leads_group);
            // creating a seperate email for tester and bob for different server
            $get_test_staff_data = get_staff_data_by_id($this, get_staff_user_id());
            if (base_url() == 'https://dev.platform.legaldirect.ca/') {
                $send_email_result = send_mailchimp_email($cc_group_member, $get_mail_subject, $html_content_welcome_email_to_user, 'bb@legaldirect.ca', '', '', $lead_id);
                // add the record for outbox emails
                $outbox_id = $this->Outbox_model->save_outbox_email(
                    $cc_group_member,
                    '',
                    '',
                    $get_mail_subject,
                    $_POST['generic_email_content'],
                    $_POST['general_attachment'],
                    $lead_id,
                    5,
                    $html_content_welcome_email_to_user,
                    'bb@legaldirect.ca',
                    $send_email_result['status'],
                    $send_email_result['mandrill_id'],
                    1
                );
            } else {
                $send_email_result = send_mailchimp_email('bb@legaldirect.ca', $get_mail_subject, $html_content_welcome_email_to_user, $replay_to_mail, $cc_group_member, '', $lead_id);
                // add the record for outbox emails
                $outbox_id = $this->Outbox_model->save_outbox_email(
                    $cc_group_member,
                    '',
                    '',
                    $get_mail_subject,
                    $_POST['generic_email_content'],
                    $_POST['general_attachment'],
                    $lead_id,
                    5,
                    $html_content_welcome_email_to_user,
                    'bb@legaldirect.ca',
                    $send_email_result['status'],
                    $send_email_result['mandrill_id'],
                    1
                );
            }
            $response = array(
                'success' => true,
                'message' => 'Data saved successfully',
                'leads_status' => $leads_status_value,
                'complete_stage_button' => $complete_stage_button,
                'id' => $lead_id,
                'leadView' => $this->_get_lead_data($lead_id),
            );
        } else {
            $response = array(
                'success' => false,
            );
        }
        $this->output
            ->set_content_type('application/json')
            ->set_output(json_encode($response));
    }
    // upload doc for final ledgers to button ()
    public function final_closing_ledger_send_to_bb()
    {
        $leads_status_value = '#Closed';
        $complete_stage_button = 5;
        $last_inserted_file_id = '';
        $lead_id = $this->input->post('lead_id');
        $final_closing_ledger_send_to_bb_notes = $this->input->post('final_closing_ledger_send_to_bb_notes');
        // get the last ledger count
        $ledger_number_count = get_the_ledger_number_count($this, $lead_id, 'final-closed-ledger-sent');
        // get the leads data
        $this->db->select('email,assign_group');
        $this->db->where('id', $lead_id);
        $result = $this->db->get(db_prefix() . 'leads')->row();
        $getemail = $result->email;
        $check_assign_group = $result->assign_group;
        $data = $this->Token_model->getToken();
        $get_id = array_column($data, 'token');
        $access_token = implode(',', $get_id);
        $data = $this->Contacts_model->getEmail($getemail);
        $get_id = array_column($data, 'id');
        $get_userid = array_column($data, 'userid');
        $get_firstname = array_column($data, 'firstname');
        $get_lastname = array_column($data, 'lastname');
        $dropbox_firstname = implode(',', $get_firstname);
        $dropbox_lastname = implode(',', $get_lastname);
        $get_id = implode(',', $get_id);
        $userid = implode(',', $get_userid);
        $leadData = $this->leads_model->get_lead_id($get_id);
        $user_id = $leadData->id;
        $user_name = $leadData->name;
        // upload doc 
        if (isset($_FILES['final_closing_ledger_userfile']) && !empty($_FILES['final_closing_ledger_userfile']['name'][0])) {
            foreach ($_FILES['final_closing_ledger_userfile']['name'] as $key => $name) {
                $tmp_file = $_FILES['final_closing_ledger_userfile']['tmp_name'][$key];
                if (is_uploaded_file($tmp_file)) {
                    $file_name = $_FILES['final_closing_ledger_userfile']['name'][$key];
                    $data = $this->leads_model->upload_to_dropbox($access_token, $tmp_file, $file_name, $user_id, $dropbox_firstname, $dropbox_lastname);
                    if ($data['status'] != 200) {
                        $this->leads_model->add_errors_logs($lead_id, get_staff_user_id(), get_staff_full_name(), 'Final closing ledgers upload doc', $data, $data['status'], 'Staff');
                        echo json_encode(
                            array(
                                'success' => false,
                                'response' => $data
                            )
                        );
                        exit;
                    }
                    $file_data = array(
                        'lead_id' => $lead_id,
                        'ledger_number' => $ledger_number_count,
                        'type' => 'final-closed-ledger-sent',
                        'file_name' => $data['file_name'],
                        'filetype' => $data['file_type'],
                        'file_url' => $data['file_url'],
                        'download_file_url' => $data['download_file_url'],
                        'created_at' => date('Y-m-d H:i:s'),
                    );
                    $uploaded_files_data[] = $file_data;
                    $this->db->insert(db_prefix() . 'leads_ledger', $file_data);
                    $last_inserted_file_id = $this->db->insert_id();
                }
            }
            // add the record in tbl leads ledger logs
            $ledger_logs_array = array(
                'lead_id' => $lead_id,
                'lead_ledger_number' => $ledger_number_count,
                'leads_ledger_type' => 'final-closed-ledger-sent',
                'status' => 'Sent Closing daily Ledgers to BB for approval.',
                'comment' => $final_closing_ledger_send_to_bb_notes,
                'created_at' => date('Y-m-d H:i:s'),
            );
            $this->db->insert(db_prefix() . 'leads_ledger_logs', $ledger_logs_array);
            // add the activity lgos
            $insert_task_activity = array(
                'leadid' => $lead_id,
                'staffid' => get_staff_user_id(),
                'full_name' => get_staff_full_name(),
                'description' => get_staff_full_name() . " upload the final ledger documents and sent an email to BOB." . '<br>' . 'Please find attached relevant final ledgers/attachments/wire confirmation,please let us know if we may confirm closing.',
                'date' => date('Y-m-d H:i:s'),
            );
            leads_activity_log($this, $insert_task_activity);
        }
        $get_mail_subject = 'Please proceed with banking file, #' . get_mail_subject($this, $lead_id);
        if (!empty($last_inserted_file_id)) {
            $_POST['case_url'] = admin_url('cases/index/') . $lead_id;
            $_POST['generic_email_title'] = '';
            $_POST['generic_email_back_to_case_url'] = 'Please <a href="' . htmlspecialchars($_POST['case_url'], ENT_QUOTES, 'UTF-8') . '">Click here</a> to access the file and allocate it to the relevant team.';
            $_POST['generic_email_content'] = 'Please review the closing documents and let us know if we may confirm closing.';
            $_POST['general_attachment'] = get_specific_legder_doc($this, $lead_id, $ledger_number_count, 'final-closed-ledger-sent');
            $html_content_welcome_email_to_user = $this->load->view('admin/leads/Email_template/generic_email_template', $_POST, TRUE);
            $replay_to_mail = get_all_staff_to_replay_email($this, get_staff_user_id(), $check_assign_group);
            // get the group name 
            $leads_group = get_the_group_name_using_leadid($this, $lead_id);
            $cc_group_member = get_all_staff_name_email_by_group_for_cc($this, $lead_id, $leads_group);
            // creating a seperate email for tester and bob for different server
            $get_test_staff_data = get_staff_data_by_id($this, get_staff_user_id());
            if (base_url() == 'https://dev.platform.legaldirect.ca/') {
                $send_email_result = send_mailchimp_email('ra.faheem7@gmail.com', $get_mail_subject, $html_content_welcome_email_to_user, $replay_to_mail, $cc_group_member, '', $lead_id);
                // add the record for outbox emails
                $outbox_id = $this->Outbox_model->save_outbox_email(
                    'ra.faheem7@gmail.com',
                    $cc_group_member,
                    '',
                    $get_mail_subject,
                    $_POST['generic_email_content'],
                    $_POST['general_attachment'],
                    $lead_id,
                    5,
                    $html_content_welcome_email_to_user,
                    $replay_to_mail,
                    $send_email_result['status'],
                    $send_email_result['mandrill_id'],
                    1
                );
            } else {
                $send_email_result = send_mailchimp_email('bb@legaldirect.ca', $get_mail_subject, $html_content_welcome_email_to_user, $replay_to_mail, $cc_group_member, 'en@legaldirect.ca,nb@legaldirect.ca', $lead_id);
                // add the record for outbox emails
                $outbox_id = $this->Outbox_model->save_outbox_email(
                    'bb@legaldirect.ca',
                    $cc_group_member,
                    'en@legaldirect.ca,nb@legaldirect.ca',
                    $get_mail_subject,
                    $_POST['generic_email_content'],
                    $_POST['general_attachment'],
                    $lead_id,
                    5,
                    $html_content_welcome_email_to_user,
                    $replay_to_mail,
                    $send_email_result['status'],
                    $send_email_result['mandrill_id'],
                    1
                );
            }
            $response = array(
                'success' => true,
                'message' => 'Data saved successfully',
                'leads_status' => $leads_status_value,
                'complete_stage_button' => $complete_stage_button,
                'id' => $lead_id,
                'leadView' => $this->_get_lead_data($lead_id),
            );
        } else {
            $response = array(
                'success' => false,
            );
        }
        $this->output
            ->set_content_type('application/json')
            ->set_output(json_encode($response));
    }
    // BB response to final ledgers
    public function final_closing_bb_response_final_ledger()
    {
        $leads_status_value = '#Closed';
        $complete_stage_button = 5;
        $last_inserted_file_id = '';
        $lead_id = $this->input->post('lead_id');
        $final_closing_ledger_send_to_bb_notes = $this->input->post('final_closing_ledger_send_to_bb_notes');
        $confirm_closing = $this->input->post('confirm_closing');
        if ($confirm_closing == 'Funds in') {
            $confirm_closing_status = $confirm_closing . ' Please: Confirm closing. Cheques Please.';
        } else {
            $confirm_closing_status = $confirm_closing . ' Please note: Private Discharge Process. Cheques please.';
        }
        // get the last ledger count
        $ledger_number_count = get_the_ledger_number_count($this, $lead_id, 'final-closed-ledger-sent');
        // get the leads data
        $this->db->select('email,assign_group,name');
        $this->db->where('id', $lead_id);
        $result = $this->db->get(db_prefix() . 'leads')->row();
        $getemail = $result->email;
        $check_assign_group = $result->assign_group;
        $case_name = $result->name;
        $data = $this->Token_model->getToken();
        $get_id = array_column($data, 'token');
        $access_token = implode(',', $get_id);
        $data = $this->Contacts_model->getEmail($getemail);
        $get_id = array_column($data, 'id');
        $get_userid = array_column($data, 'userid');
        $get_firstname = array_column($data, 'firstname');
        $get_lastname = array_column($data, 'lastname');
        $dropbox_firstname = implode(',', $get_firstname);
        $dropbox_lastname = implode(',', $get_lastname);
        $get_id = implode(',', $get_id);
        $userid = implode(',', $get_userid);
        $leadData = $this->leads_model->get_lead_id($get_id);
        $user_id = $leadData->id;
        $user_name = $leadData->name;
        // upload doc 
        if (isset($_FILES['final_closing_ledger_userfile']) && !empty($_FILES['final_closing_ledger_userfile']['name'][0])) {
            foreach ($_FILES['final_closing_ledger_userfile']['name'] as $key => $name) {
                $tmp_file = $_FILES['final_closing_ledger_userfile']['tmp_name'][$key];
                if (is_uploaded_file($tmp_file)) {
                    $file_name = $_FILES['final_closing_ledger_userfile']['name'][$key];
                    $data = $this->leads_model->upload_to_dropbox($access_token, $tmp_file, $file_name, $user_id, $dropbox_firstname, $dropbox_lastname);
                    if ($data['status'] != 200) {
                        $this->leads_model->add_errors_logs($lead_id, get_staff_user_id(), get_staff_full_name(), 'Final closing bb for response ledger', $data, $data['status'], 'Staff');
                        echo json_encode(
                            array(
                                'success' => false,
                                'response' => $data
                            )
                        );
                        exit;
                    }
                    $file_data = array(
                        'lead_id' => $lead_id,
                        'ledger_number' => $ledger_number_count,
                        'type' => 'final-closed-ledger-sent',
                        'file_name' => $data['file_name'],
                        'filetype' => $data['file_type'],
                        'file_url' => $data['file_url'],
                        'download_file_url' => $data['download_file_url'],
                        'created_at' => date('Y-m-d H:i:s'),
                    );
                    $uploaded_files_data[] = $file_data;
                    $this->db->insert(db_prefix() . 'leads_ledger', $file_data);
                    $last_inserted_file_id = $this->db->insert_id();
                }
            }
        } else {
            $file_data = array(
                'lead_id' => $lead_id,
                'ledger_number' => $ledger_number_count,
                'type' => 'final-closed-ledger-sent',
                'created_at' => date('Y-m-d H:i:s'),
            );
            $this->db->insert(db_prefix() . 'leads_ledger', $file_data);
            $last_inserted_file_id = $this->db->insert_id();
        }
        if (!empty($last_inserted_file_id)) {
            // add the record in tbl leads ledger logs
            $ledger_logs_array = array(
                'lead_id' => $lead_id,
                'lead_ledger_number' => $ledger_number_count,
                'leads_ledger_type' => 'final-closed-ledger-sent',
                'status' => $confirm_closing_status,
                'comment' => $final_closing_ledger_send_to_bb_notes,
                'created_at' => date('Y-m-d H:i:s'),
            );
            $this->db->insert(db_prefix() . 'leads_ledger_logs', $ledger_logs_array);
            // add the activity lgos
            $insert_task_activity = array(
                'leadid' => $lead_id,
                'staffid' => get_staff_user_id(),
                'full_name' => get_staff_full_name(),
                'description' => get_staff_full_name() . "Please: Confirm closing. Cheques Please.",
                'date' => date('Y-m-d H:i:s'),
            );
            leads_activity_log($this, $insert_task_activity);
            $_POST['case_url'] = admin_url('cases/index/') . $lead_id;
            $_POST['generic_email_title'] = '';
            $_POST['generic_email_back_to_case_url'] = 'Please <a href="' . htmlspecialchars($_POST['case_url'], ENT_QUOTES, 'UTF-8') . '">Click here</a> to access the file and allocate it to the relevant team.';
            if ($confirm_closing == 'Funds in') {
                $_POST['generic_email_content'] = 'Please: Confirm closing. Cheques Please.';
            } else {
                $_POST['generic_email_content'] = 'Please note: Private Discharge Process. Cheques please.';
            }
            $_POST['general_attachment'] = get_specific_legder_doc($this, $lead_id, $ledger_number_count, 'final-closed-ledger-sent');
            $html_content_welcome_email_to_user = $this->load->view('admin/leads/Email_template/generic_email_template', $_POST, TRUE);
            $subject = 'Review Final Ledgers' . get_mail_subject($this, $lead_id);
            $replay_to_mail = get_all_staff_to_replay_email($this, get_staff_user_id(), $check_assign_group);
            // get the group name 
            $leads_group = get_the_group_name_using_leadid($this, $lead_id);
            $cc_group_member = get_all_staff_name_email_by_group_for_cc($this, $lead_id, $leads_group);
            $send_email_result = send_mailchimp_email($cc_group_member, $subject, $html_content_welcome_email_to_user, $replay_to_mail, '', '', $lead_id);
            // add the record for outbox emails
            $outbox_id = $this->Outbox_model->save_outbox_email(
                $cc_group_member,
                '',
                '',
                $subject,
                $_POST['generic_email_content'],
                $_POST['general_attachment'],
                $lead_id,
                5,
                $html_content_welcome_email_to_user,
                $replay_to_mail,
                $send_email_result['status'],
                $send_email_result['mandrill_id'],
                1
            );
            $response = array(
                'success' => true,
                'message' => 'Data saved successfully',
                'leads_status' => $leads_status_value,
                'complete_stage_button' => $complete_stage_button,
                'id' => $lead_id,
                'leadView' => $this->_get_lead_data($lead_id),
            );
        } else {
            $response = array(
                'success' => false,
            );
        }
        $this->output
            ->set_content_type('application/json')
            ->set_output(json_encode($response));
    }
    // Confirm closing email send 
    public function confirm_final_closing_internally()
    {
        $archive_check = $this->input->post('archive_check');
        $lead_id = $this->input->post('lead_id');
        $to_confirm_closing_ledgers = $this->input->post('to_confirm_closing_ledgers');
        $cc_confirm_closing_ledgers = $this->input->post('cc_confirm_closing_ledgers');
        $bcc_confirm_closing_ledgers = $this->input->post('bcc_confirm_closing_ledgers');
        $send_tinymace_final_ledger_cofirm_final_close_email = $this->input->post('send_tinymace_final_ledger_cofirm_final_close_email', FALSE);
        // conver string to array 
        $to_emails = array_map('trim', explode(',', $to_confirm_closing_ledgers));
        $cc_emails = array_map('trim', explode(',', $cc_confirm_closing_ledgers));
        $bcc_emails = array_map('trim', explode(',', $bcc_confirm_closing_ledgers));
        // send email code 
        $_POST['case_url'] = admin_url('cases/index/') . $lead_id;
        $_POST['generic_email_title'] = '';
        $_POST['generic_email_back_to_case_url'] = 'Please <a href="' . htmlspecialchars($_POST['case_url'], ENT_QUOTES, 'UTF-8') . '">Click here</a> to access the file and allocate it to the relevant team.';
        $_POST['generic_email_content'] = $send_tinymace_final_ledger_cofirm_final_close_email;
        $html_content_welcome_email_to_user = $this->load->view('admin/leads/Email_template/generic_email_template', $_POST, TRUE);
        $subject = get_mail_subject($this, $lead_id);
        $check_assign_group = get_the_group_name_using_leadid($this, $lead_id);
        $replay_to_mail = get_all_staff_to_replay_email($this, get_staff_user_id(), $check_assign_group);
        // get the group name 
        $send_email_result = send_mailchimp_email($to_emails, $subject, $html_content_welcome_email_to_user, $replay_to_mail, $cc_emails, $bcc_emails, $lead_id);
        // add the record for outbox emails
        $outbox_id = $this->Outbox_model->save_outbox_email(
            $to_emails,
            $$cc_emails,
            $bcc_emails,
            $subject,
            $_POST['generic_email_content'],
            '',
            $lead_id,
            5,
            $html_content_welcome_email_to_user,
            $replay_to_mail,
            $send_email_result['status'],
            $send_email_result['mandrill_id'],
            1
        );
        // get the last ledger count
        $ledger_number_count = get_the_ledger_number_count($this, $lead_id, 'final-closed-ledger-sent');
        if ($send_email_result) {
            $file_data = array(
                'lead_id' => $lead_id,
                'ledger_number' => $ledger_number_count,
                'type' => 'final-closed-ledger-sent',
                'created_at' => date('Y-m-d H:i:s'),
            );
            $this->db->insert(db_prefix() . 'leads_ledger', $file_data);
            $last_inserted_file_id = $this->db->insert_id();
            if (!empty($last_inserted_file_id)) {
                // add the record in tbl leads ledger logs
                $ledger_logs_array = array(
                    'lead_id' => $lead_id,
                    'lead_ledger_number' => $ledger_number_count,
                    'leads_ledger_type' => 'final-closed-ledger-sent',
                    'status' => 'Ledgers Closing Confirmation: ' . get_staff_full_name() . ' sent an email for finalization.',
                    'comment' => $send_tinymace_final_ledger_cofirm_final_close_email,
                    'created_at' => date('Y-m-d H:i:s'),
                );
                $this->db->insert(db_prefix() . 'leads_ledger_logs', $ledger_logs_array);
                // add the activity lgos
                $insert_task_activity = array(
                    'leadid' => $lead_id,
                    'staffid' => get_staff_user_id(),
                    'full_name' => get_staff_full_name(),
                    'description' => 'Ledgers Closing Confirmation: ' . get_staff_full_name() . ' sent an email for finalization.',
                    'date' => date('Y-m-d H:i:s'),
                );
                leads_activity_log($this, $insert_task_activity);
                // update the leads Record and case closed
                $stage_description = 'Case Closed.';
                $update_leads_status = ($archive_check === 'on') ? 9 : 5;
                $data = array(
                    'status' => $update_leads_status,
                    'archive_date' => ($archive_check === 'on') ? date('Y-m-d H:i:s') : '',
                    // 'active_case' => 'Closed',
                    'last_status_change' => date('Y-m-d H:i:s'),
                );
                $this->db->where('id', $lead_id);
                $this->db->update(db_prefix() . 'leads', $data);
            }
            // slack notification send 
            $group_name = get_the_group_name_using_leadid($this, $lead_id);
            $case_name = get_lead_name_using_lead_id($this, $lead_id);
            $lead_split_name = leads_splitFullName($case_name);
            $slack_message = "\n - Confirm \n - Send Final Report.";
            $send_notification = $this->slack->sendnotification($slack_message, $lead_id, $group_name, $lead_split_name['lastname'] . ', ' . $lead_split_name['firstname'] . ' ' . $lead_split_name['middlename']);
            $response = array(
                'success' => true,
            );
        } else {
            $response = array(
                'success' => false,
            );
        }
        $this->output
            ->set_content_type('application/json')
            ->set_output(json_encode($response));
    }
    // upload doc for checklist
    public function upload_doc_for_checklist_all_stages($lead_id, $task_id, $checklist_stage_id)
    {
        $this->db->select('email,assign_group');
        $this->db->where('id', $lead_id);
        $result = $this->db->get(db_prefix() . 'leads')->row();
        $getemail = $result->email;
        $check_assign_group = $result->assign_group;
        $data = $this->Token_model->getToken();
        $get_id = array_column($data, 'token');
        $access_token = implode(',', $get_id);
        $data = $this->Contacts_model->getEmail($getemail);
        $get_id = array_column($data, 'id');
        $get_userid = array_column($data, 'userid');
        $get_firstname = array_column($data, 'firstname');
        $get_lastname = array_column($data, 'lastname');
        $dropbox_firstname = implode(',', $get_firstname);
        $dropbox_lastname = implode(',', $get_lastname);
        $get_id = implode(',', $get_id);
        $userid = implode(',', $get_userid);
        $leadData = $this->leads_model->get_lead_id($get_id);
        $user_id = $leadData->id;
        $user_name = $leadData->name;
        foreach ($_FILES['checklist_file' . $checklist_stage_id]['name'] as $key => $name) {
            $tmp_file = $_FILES['checklist_file' . $checklist_stage_id]['tmp_name'][$key];
            if (is_uploaded_file($tmp_file)) {
                $file_name = $_FILES['checklist_file' . $checklist_stage_id]['name'][$key];
                $data = $this->leads_model->upload_to_dropbox($access_token, $tmp_file, $file_name, $user_id, $dropbox_firstname, $dropbox_lastname);
                $this->leads_model->add_errors_logs($lead_id, get_staff_user_id(), get_staff_full_name(), 'document upload againts stage {' . $checklist_stage_id . '}', $data, $data['status'], 'Staff');
                if ($data['status'] != 200) {
                    echo json_encode(
                        array(
                            'success' => false,
                            'response' => $data
                        )
                    );
                    exit;
                }
                $file_data = array(
                    'task_id' => $task_id,
                    'rel_id' => $lead_id,
                    'rel_type' => 'client-doc',
                    'file_name' => $data['file_name'],
                    'filetype' => $data['file_type'],
                    'file_url' => $data['file_url'],
                    'download_file_url' => $data['download_file_url'],
                    'doc_status' => 'Submitted',
                    'dateadded' => date('Y-m-d H:i:s'),
                    'item_type_id' => null,
                );
                $this->db->insert(db_prefix() . 'files', $file_data);
                $last_inserted_file_id = $this->db->insert_id();
            }
        }
        // update key to show the Review ledgers in kanban card
        $role = get_current_staff_role($this, get_staff_user_id());
        $brokerActionTimePassed = after_one_day_of_case_broker_client_items_trigger($this, $lead_id);
        if (($role == 2 || $role == 6) && $brokerActionTimePassed == true) {
            update_key_of_upload_docs($this, $lead_id, 1);
        }
        // update the last contact date 
        $this->leads_model->update_leads_last_contact_date($lead_id);
    }
    public function upload_doc_for_fileopened($lead_id)
    {
        $task_id = $this->input->post('task_id');
        $ld_notes = $this->input->post('ld_notes');
        $checklist_ld_notes = str_replace(['<br />', '<br>', '<br/>'], "\n", nl2br($ld_notes));
        $get_mail_subject = get_mail_subject($this, $lead_id);
        $this->db->select('email,assign_group,addedfrom,name');
        $this->db->where('id', $lead_id);
        $result = $this->db->get(db_prefix() . 'leads')->row();
        $getemail = $result->email;
        $check_assign_group = $result->assign_group;
        $data = $this->Token_model->getToken();
        $get_id = array_column($data, 'token');
        $access_token = implode(',', $get_id);
        $data = $this->Contacts_model->getEmail($getemail);
        $get_id = array_column($data, 'id');
        $get_userid = array_column($data, 'userid');
        $get_firstname = array_column($data, 'firstname');
        $get_lastname = array_column($data, 'lastname');
        $dropbox_firstname = implode(',', $get_firstname);
        $dropbox_lastname = implode(',', $get_lastname);
        $get_id = implode(',', $get_id);
        $userid = implode(',', $get_userid);
        $leadData = $this->leads_model->get_lead_id($get_id);
        $user_id = $leadData->id;
        $user_name = $leadData->name;
        $file_data_response = array();
        foreach ($_FILES['userfile']['name'] as $key => $name) {
            $tmp_file = $_FILES['userfile']['tmp_name'][$key];
            if (is_uploaded_file($tmp_file)) {
                $file_name = $_FILES['userfile']['name'][$key];
                $data = $this->leads_model->upload_to_dropbox($access_token, $tmp_file, $file_name, $user_id, $dropbox_firstname, $dropbox_lastname);
                if ($data['status'] != 200) {
                    $this->leads_model->add_errors_logs($lead_id, get_staff_user_id(), get_staff_full_name(), 'Upload doc for file opened', $data, $data['status'], 'Staff');
                    echo json_encode(
                        array(
                            'success' => false,
                            'response' => $data
                        )
                    );
                    exit;
                }
                $file_data = array(
                    'task_id' => $task_id,
                    'rel_id' => $lead_id,
                    'rel_type' => 'client-doc',
                    'file_name' => $data['file_name'],
                    'filetype' => $data['file_type'],
                    'file_url' => $data['file_url'],
                    'download_file_url' => $data['download_file_url'],
                    'doc_status' => 'Submitted',
                    'dateadded' => date('Y-m-d H:i:s'),
                    'item_type_id' => null,
                );
                $this->db->insert(db_prefix() . 'files', $file_data);
                $file_data_response[] = $file_data;
            }
        }
        // update key to show the Review ledgers in kanban card
        $role = get_current_staff_role($this, get_staff_user_id());
        $brokerActionTimePassed = after_one_day_of_case_broker_client_items_trigger($this, $lead_id);
        if (($role == 2 || $role == 6) && $brokerActionTimePassed == true) {
            update_key_of_upload_docs($this, $lead_id, 1);
        }

        $get_task_data = get_task_name_by_task_id($this, $task_id);
        $additional_data = 'Pending Review';
        if ($get_task_data->type == 'broker') {
            // if (preg_match('/\b(photo id\s*\d*|paper id\s*\d*)\b/i', $get_task_data->name)) {
            //     $task_data = array(
            //         'status' => 1,
            //         'checkbox_status' => 1,
            //     );
            // } else {
                $task_data = array(
                    'status' => 5,
                    'checkbox_status' => 1,
                );
            // }
            $additional_data = 'uploaded';
        } else {
            $task_data = array(
                'status' => 1,
                'checkbox_status' => 1,
                'ld_notes' => $checklist_ld_notes,
            );
        }
        $this->db->where('id', $task_id);
        $this->db->update(db_prefix() . 'tasks', $task_data);
        // get the task name
        $message_submitted = 'Document of checklist Item (' . $get_task_data->name . ') has been submitted by ' . get_staff_full_name() . '.';
        // add the data in lead activity log
        $insert_task_activity = array(
            'leadid' => $lead_id,
            'task_id' => $task_id,
            'staffid' => get_staff_user_id(),
            'full_name' => get_staff_full_name(),
            'activity_type' => 'task-activity',
            'additional_data' => $additional_data,
            'description' => $message_submitted,
            'date' => date('Y-m-d H:i:s'),
        );
        leads_activity_log($this, $insert_task_activity);
        // send mail line of code and file 
        $subject = 'Case ' . get_mail_subject($this, $lead_id) . ' New Real Estate Transaction.';
        $_POST['broker_name'] = get_staff_full_name();
        $_POST['get_afternoon_and_morning'] = get_afternoon_and_morning();
        $_POST['lead_id'] = $lead_id;
        $_POST['case_url'] = admin_url('cases/index/') . $lead_id;
        $_POST['task_name'] = $get_task_data->name;
        // Mail is send to the admin
        $replay_to_mail = get_all_staff_to_replay_email($this, get_staff_user_id(), $check_assign_group);
        $html_content_confirmation_email_to_broker = $this->load->view('admin/leads/Email_template/upload_doc_by_broker', $_POST, TRUE);
        // send notification or emails only when broker do or atleast one day to create a case
        if (($role == 2 || $role == 6) && $brokerActionTimePassed == false) {
        } else if ((($role != 2 && $role != 6)) || (($role == 2 || $role == 6) && $brokerActionTimePassed == true)) {
            // send notification to the admin when broker upload atleast one doc then admin is able to assign the case otherwise not
            // if (empty($check_assign_group)) {
            // get client and contact id line of code
            $this->db->select('id,multiple_cases,client_id,phonenumber,name,email,addedfrom,assign_group');
            $this->db->where('id', $lead_id);
            $lead_data_check = $this->db->get(db_prefix() . 'leads');
            if ($lead_data_check->num_rows() > 0) {
                $lead_data = $lead_data_check->row();
                $client_id = get_client_id_using_contact_id($this, $lead_data->client_id, $lead_data->multiple_cases);
                $contact_id = get_contact_id_using_client_id($this, $client_id);
                $admin_ids = get_all_admin_role_staff_ids($this);
                $notification_type = get_notification_type(2);
                if (!empty($lead_data->assign_group)) {
                    $new_case_message_broker = 'Document of checklist Item (' . $get_task_data->name . ') has been submitted by ' . get_staff_full_name() . '.';
                } else {
                    $new_case_message_broker = "The document has been uploaded by " . get_staff_full_name() . ". Please navigate to the case (" . $lead_id . ") profile editing section and assign the appropriate group. Once the group is assigned, the case will become active.";
                }
                $notification_type = get_notification_type(2);
                foreach ($admin_ids as $admin_email) {
                    $staff_row = get_staff_data_by_id($this, $admin_email['staffid']);
                    if (get_staff_user_id() != $admin_email['staffid']) {
                        // send email to different admis when broker upload doc
                        if (get_current_staff_role($this, get_staff_user_id()) == 2 || get_current_staff_role($this, get_staff_user_id()) == 6) {
                            $send_email_result = send_mailchimp_email($staff_row->email, $subject, $html_content_confirmation_email_to_broker, $replay_to_mail, '', '', $lead_id);
                            // add the record for outbox emails
                            $outbox_content = "Good " . $_POST['get_afternoon_and_morning'] . "\n\n" .
                                "Please note the broker has uploaded " . $_POST['lead_id'] . ", ID " . $_POST['task_name'] . ". Kindly review the file by clicking this link: " . $_POST['case_url'] . "\n\n" .
                                "Thank you.";
                            $outbox_id = $this->Outbox_model->save_outbox_email(
                                $staff_row->email,
                                '',
                                '',
                                $subject,
                                $outbox_content,
                                '',
                                $lead_id,
                                1,
                                $html_content_confirmation_email_to_broker,
                                $replay_to_mail,
                                $send_email_result['status'],
                                $send_email_result['mandrill_id'],
                                1
                            );
                        }
                        if ($get_task_data->type == 'broker') {
                            $user_type = 'appointment';
                        } else {
                            $user_type = $notification_type . '-submitted';
                        }
                        $admin_notify_type = $user_type;
                        $admin_notify_title = 'Submitted document';
                        $admin_notify_message = $new_case_message_broker;

                        // send notification in crm
                        $this->leads_model->custom_lead_assigned_member_notification('staff', $lead_id, $admin_email['staffid'], get_staff_user_id(), '', $new_case_message_broker);
                    }
                }
                // }
            }
            // send notification when case group assigned
            // if (!empty($check_assign_group)) {
            //     // get client and contact id line of code
            //     $this->db->select('id,multiple_cases,client_id,phonenumber,name,email,addedfrom,assign_group');
            //     $this->db->where('id', $lead_id);
            //     $lead_data_check = $this->db->get(db_prefix() . 'leads');
            //     if ($lead_data_check->num_rows() > 0) {
            //         $lead_data = $lead_data_check->row();
            //         $client_id = get_client_id_using_contact_id($this, $lead_data->client_id, $lead_data->multiple_cases);
            //         $contact_id = get_contact_id_using_client_id($this, $client_id);
            //         $admin_ids = get_all_admin_role_staff_ids($this);
            //         $notification_type = get_notification_type(2);
            //         $new_case_message_broker = "The document has been uploaded by " . get_staff_full_name() . ".";
            //         $notification_type = get_notification_type(2);
            //         $current_staff_data = get_staff_ids_by_group($this, $lead_data->assign_group);
            //         if ($get_task_record->type == 'broker') {
            //             $user_type = 'appointment';
            //         } else {
            //             $user_type = $notification_type . '-submitted';
            //         }
            //         // send mail and notification to ld team only when broker or client upload doc
            //         if ($role == 2 || $role == 6) {
            //             foreach ($current_staff_data as $staff_notifiy_data) {
            //                 // send mail to the admin when broker document upload
            //                 if (in_array($role, [2, 6]) && $get_task_record->type !== 'broker') {
            //                     send_mailchimp_email($staff_notifiy_data['email'], $subject, $html_content_confirmation_email_to_broker, $replay_to_mail, '', '', $lead_id);
            //                 }
            //                 // send mobile side notification
            //                 if (get_staff_user_id() != $staff_notifiy_data['staffid']) {
            //                     $ldteam_notify_type = $user_type;
            //                     $ld_team_notify_title = 'Submitted document';
            //                     $ld_team_notify_message = $message_submitted;

            //                     // send notification in crm 
            //                     $this->leads_model->custom_lead_assigned_member_notification('staff', $lead_id, $staff_notifiy_data['staffid'], get_staff_user_id(), '', $message_submitted);
            //                 }
            //             }
            //             foreach ($admin_ids as $admin_email) {
            //                 if (get_staff_user_id() != $admin_email['staffid']) {
            //                     // send mail to the admin when broker document upload
            //                     $staffRole = get_current_staff_role($this, get_staff_user_id());
            //                     if (in_array($staffRole, [2, 6]) && $get_task_record->type !== 'broker') {
            //                         $staff_row = get_staff_data_by_id($this, $admin_email['staffid']);
            //                         send_mailchimp_email($staff_row->email, $subject, $html_content_confirmation_email_to_broker, $replay_to_mail, '', '', $lead_id);
            //                     }
            //                     $admin_notify_type = $user_type;
            //                     $admin_notify_title = 'Submitted document';
            //                     $admin_notify_message = $message_submitted;

            //                     // send notification in crm
            //                     $this->leads_model->custom_lead_assigned_member_notification('staff', $lead_id, $admin_email['staffid'], get_staff_user_id(), '', $message_submitted);
            //                 }
            //             }
            //         }
            //     }
            // }
            // if ($get_task_record->type == 'broker') {
            if ($role == 2 || $role == 6 && ($get_task_data->type == 'broker' || $get_task_data->type == 'client')) {
                $broker_message = 'Document of checklist Item (' . $get_task_data->name . ') has been submitted by ' . get_staff_full_name() . '.';
                // send notification to the all related broker
                $brokerdata = get_multiple_broker_details_using_addedfrom($this, $result->addedfrom);
                foreach ($brokerdata as $broker_email) {
                    if (get_staff_user_id() != $broker_email['staffid']) {
                        $this->leads_model->custom_lead_assigned_member_notification('staff', $lead_id, $broker_email['staffid'], get_staff_user_id(), '', $broker_message);
                    }
                }
                // send notification to the admin broker
                $brokerage_id = get_brokerage_id_using_leadid($this, $lead_id);
                $admin_broker_ids = get_all_admin_broker_role_staff_ids($this, $brokerage_id);
                foreach ($admin_broker_ids as $admin_broker_email) {
                    if (get_staff_user_id() != $admin_broker_email['staffid'] && !in_array($admin_broker_email['staffid'], explode(',', $result->addedfrom))) {
                        $this->leads_model->custom_lead_assigned_member_notification('staff', $lead_id, $admin_broker_email['staffid'], get_staff_user_id(), '', $broker_message);
                    }
                }
                // Send Slack notification
                $group_name = get_the_group_name_using_leadid($this, $lead_id);
                $lead_name = get_lead_name_using_lead_id($this, $lead_id);
                $lead_split_name = leads_splitFullName($lead_name);
                $slack_message = " \n - Document Uploaded by broker \n - (" . $get_task_data->name . ') has been uploaded.';
                $send_notification = $this->slack->sendnotification($slack_message, $lead_id, $group_name, $lead_split_name['lastname'] . ', ' . $lead_split_name['firstname'] . ' ' . $lead_split_name['middlename']);
            }
        }
        // update the last contact date 
        $this->leads_model->update_leads_last_contact_date($lead_id);
        $leads_status_id = using_task_id_get_lead_status_id($this, $task_id);
        switch ($leads_status_id) {
            case 1:
                $leads_status_value = '#file_opened';
                $complete_stage_button = 1;
                break;
            case 3:
                $leads_status_value = '#outstanding_items';
                $complete_stage_button = 3;
                break;
            case 4:
                $leads_status_value = '#request_for_funds';
                $complete_stage_button = 4;
                break;
            default:
                $leads_status_value = '';
                $complete_stage_button = '';
                break;
        }

        $response = array(
            'success' => true,
            'message' => 'Data saved successfully',
            'task_id' => $task_id,
            'task_type' => $get_task_data->type,
            'leads_status' => $leads_status_value,
            'complete_stage_button' => $complete_stage_button,
            'id' => $lead_id,
            'leadView' => $this->_get_lead_data($lead_id),
            'files' => $file_data_response,
            'brokerActionTimePassed' => $brokerActionTimePassed,
        );
        $this->output
            ->set_content_type('application/json')
            ->set_output(json_encode($response));
    }
    // outstanding item modal
    public function upload_doc_for_outstanding_item($lead_id)
    {
        $task_id = $this->input->post('task_id');
        $this->db->select('email,assign_group');
        $this->db->where('id', $lead_id);
        $result = $this->db->get(db_prefix() . 'leads')->row();
        $getemail = $result->email;
        $check_assign_group = $result->assign_group;
        $data = $this->Token_model->getToken();
        $get_id = array_column($data, 'token');
        $access_token = implode(',', $get_id);
        $data = $this->Contacts_model->getEmail($getemail);
        $get_id = array_column($data, 'id');
        $get_userid = array_column($data, 'userid');
        $get_firstname = array_column($data, 'firstname');
        $get_lastname = array_column($data, 'lastname');
        $dropbox_firstname = implode(',', $get_firstname);
        $dropbox_lastname = implode(',', $get_lastname);
        $get_id = implode(',', $get_id);
        $userid = implode(',', $get_userid);
        $leadData = $this->leads_model->get_lead_id($get_id);
        $user_id = $leadData->id;
        $user_name = $leadData->name;
        foreach ($_FILES['outstanding_item_userfile']['name'] as $key => $name) {
            $tmp_file = $_FILES['outstanding_item_userfile']['tmp_name'][$key];
            if (is_uploaded_file($tmp_file)) {
                $file_name = $_FILES['outstanding_item_userfile']['name'][$key];
                $data = $this->leads_model->upload_to_dropbox($access_token, $tmp_file, $file_name, $user_id, $dropbox_firstname, $dropbox_lastname);
                if ($data['status'] != 200) {
                    $this->leads_model->add_errors_logs($lead_id, get_staff_user_id(), get_staff_full_name(), 'Upload doc for Outstanding stage', $data, $data['status'], 'Staff');
                    echo json_encode(
                        array(
                            'success' => false,
                            'response' => $data
                        )
                    );
                    exit;
                }
                $file_data = array(
                    'task_id' => $task_id,
                    'rel_id' => $lead_id,
                    'rel_type' => 'client-doc',
                    'file_name' => $data['file_name'],
                    'filetype' => $data['file_type'],
                    'file_url' => $data['file_url'],
                    'download_file_url' => $data['download_file_url'],
                    'doc_status' => 'Submitted',
                    'dateadded' => date('Y-m-d H:i:s')
                );
                $this->db->insert(db_prefix() . 'files', $file_data);
            }
        }
        $task_data = array(
            'status' => 1
        );
        $this->db->where('id', $task_id);
        $this->db->update(db_prefix() . 'tasks', $task_data);
        // update key to show the Review ledgers in kanban card
        $role = get_current_staff_role($this, get_staff_user_id());
        $brokerActionTimePassed = after_one_day_of_case_broker_client_items_trigger($this, $lead_id);
        if (($role == 2 || $role == 6) && $brokerActionTimePassed == true) {
            update_key_of_upload_docs($this, $lead_id, 1);
        }
        // get the task name
        $get_task_data = get_task_name_by_task_id($this, $task_id);
        $message_submitted = 'Document of checklist Item (' . $get_task_data->name . ') has been submitted by ' . get_staff_full_name() . '.';
        // add the data in lead activity log
        $insert_task_activity = array(
            'leadid' => $lead_id,
            'task_id' => $task_id,
            'staffid' => get_staff_user_id(),
            'full_name' => get_staff_full_name(),
            'activity_type' => 'task-activity',
            'additional_data' => 'Pending Review',
            'description' => $message_submitted,
            'date' => date('Y-m-d H:i:s'),
        );
        leads_activity_log($this, $insert_task_activity);
        // send notification or emails only when broker do or atleast one day to create a case
        if (($role == 2 || $role == 6) && $brokerActionTimePassed == false) {
        } elseif ((($role != 2 && $role != 6)) || (($role == 2 || $role == 6) && $brokerActionTimePassed == true)) {
            if (!empty($check_assign_group)) {
                // get client and contact id line of code
                $this->db->select('id,multiple_cases,client_id,phonenumber,name,email,addedfrom,assign_group');
                $this->db->where('id', $lead_id);
                $lead_data_check = $this->db->get(db_prefix() . 'leads');
                if ($lead_data_check->num_rows() > 0) {
                    $lead_data = $lead_data_check->row();
                    $client_id = get_client_id_using_contact_id($this, $lead_data->client_id, $lead_data->multiple_cases);
                    $contact_id = get_contact_id_using_client_id($this, $client_id);
                    $admin_ids = get_all_admin_role_staff_ids($this);
                    $notification_type = get_notification_type(2);
                    $new_case_message_broker = "The document has been uploaded by " . get_staff_full_name() . ".";
                    $current_staff_data = get_staff_ids_by_group($this, $lead_data->assign_group);
                    foreach ($current_staff_data as $staff_notifiy_data) {
                        // Get notification type
                        $notification_type = get_notification_type(2);
                        $ldteam_notify_type = $notification_type . '-submitted';
                        $ld_team_notify_title = 'Submitted document';
                        $ld_team_notify_message = $message_submitted;

                        // send notification in crm 
                        $this->leads_model->custom_lead_assigned_member_notification('client', $lead_id, $staff_notifiy_data['staffid'], get_staff_user_id(), '', $message_submitted);
                    }
                    foreach ($admin_ids as $admin_email) {
                        if (get_staff_user_id() != $admin_email['staffid']) {
                            $admin_notify_type = $notification_type . '-submitted';
                            $admin_notify_title = 'Submitted document';
                            $admin_notify_message = $message_submitted;
                            // send notification in crm
                            $this->leads_model->custom_lead_assigned_member_notification('staff', $lead_id, $admin_email['staffid'], get_staff_user_id(), '', $message_submitted);
                        }
                    }
                }
                $leads_status_id = using_task_id_get_lead_status_id($this, $task_id);
                switch ($leads_status_id) {
                    case 1:
                        $leads_status_value = '#file_opened';
                        $complete_stage_button = 1;
                        break;
                    case 3:
                        $leads_status_value = '#outstanding_items';
                        $complete_stage_button = 3;
                        break;
                    case 4:
                        $leads_status_value = '#request_for_funds';
                        $complete_stage_button = 4;
                        break;
                    // Add more cases as needed
                    default:
                        // Default case if none of the above matches
                        $leads_status_value = '';
                        $complete_stage_button = '';
                        break;
                }
                $response = array(
                    'success' => true,
                    'message' => 'Data saved successfully',
                    'leads_status' => $leads_status_value,
                    'complete_stage_button' => $complete_stage_button,
                    'id' => $lead_id,
                    'leadView' => $this->_get_lead_data($lead_id),
                );
                $this->output
                    ->set_content_type('application/json')
                    ->set_output(json_encode($response));
            }
        }
        // update the last contact date 
        $this->leads_model->update_leads_last_contact_date($lead_id);
        $leads_status_id = using_task_id_get_lead_status_id($this, $task_id);
        switch ($leads_status_id) {
            case 1:
                $leads_status_value = '#file_opened';
                $complete_stage_button = 1;
                break;
            case 3:
                $leads_status_value = '#outstanding_items';
                $complete_stage_button = 3;
                break;
            case 4:
                $leads_status_value = '#request_for_funds';
                $complete_stage_button = 4;
                break;
            // Add more cases as needed
            default:
                // Default case if none of the above matches
                $leads_status_value = '';
                $complete_stage_button = '';
                break;
        }
        $response = array(
            'success' => true,
            'message' => 'Data saved successfully',
            'leads_status' => $leads_status_value,
            'complete_stage_button' => $complete_stage_button,
            'id' => $lead_id,
            'leadView' => $this->_get_lead_data($lead_id),
            'brokerActionTimePassed' => $brokerActionTimePassed,
        );
        $this->output
            ->set_content_type('application/json')
            ->set_output(json_encode($response));
    }
    // LD outstanding item upload doc code
    public function upload_doc_for_ld_outstanding_item($lead_id)
    {
        $cases_checkbox_id = $this->input->post('cases_checkbox_id');
        $get_ld_notes = $this->input->post('ld_payout_other_notes');
        $lender_id = $this->input->post('lender_name');
        $payout_expire_date = $this->input->post('payout_expire_date');
        $type = $this->input->post('type');
        // get the lenders name
        $lender_name = get_lender_name_by_lender_id($this, $lender_id);
        // get the lead data
        $this->db->select('email,assign_group');
        $this->db->where('id', $lead_id);
        $result = $this->db->get(db_prefix() . 'leads')->row();
        $getemail = $result->email;
        $check_assign_group = $result->assign_group;
        $data = $this->Token_model->getToken();
        $get_id = array_column($data, 'token');
        $access_token = implode(',', $get_id);
        $data = $this->Contacts_model->getEmail($getemail);
        $get_id = array_column($data, 'id');
        $get_userid = array_column($data, 'userid');
        $get_firstname = array_column($data, 'firstname');
        $get_lastname = array_column($data, 'lastname');
        $dropbox_firstname = implode(',', $get_firstname);
        $dropbox_lastname = implode(',', $get_lastname);
        $get_id = implode(',', $get_id);
        $userid = implode(',', $get_userid);
        $leadData = $this->leads_model->get_lead_id($get_id);
        $user_id = $leadData->id;
        $user_name = $leadData->name;
        // update the record cases checkboxes
        if (!empty($get_ld_notes)) {
            $cases_checkboxes_update = array(
                'description' => str_replace(['<br />', '<br>', '<br/>'], "\n", nl2br($get_ld_notes)),
                'payout_expire_date' => to_sql_date($payout_expire_date, true),
            );
            $this->db->where('id', $cases_checkbox_id);
            $this->db->update(db_prefix() . 'cases_checkboxes', $cases_checkboxes_update);
        }
        foreach ($_FILES['ld_outstanding_item_userfile']['name'] as $key => $name) {
            $tmp_file = $_FILES['ld_outstanding_item_userfile']['tmp_name'][$key];
            if (is_uploaded_file($tmp_file)) {
                $file_name = $_FILES['ld_outstanding_item_userfile']['name'][$key];
                $data = $this->leads_model->upload_to_dropbox($access_token, $tmp_file, $file_name, $user_id, $dropbox_firstname, $dropbox_lastname);
                if ($data['status'] != 200) {
                    $this->leads_model->add_errors_logs($lead_id, get_staff_user_id(), get_staff_full_name(), 'Upload doc for LD outsanding stage', $data, $data['status'], 'Staff');
                    echo json_encode(
                        array(
                            'success' => false,
                            'response' => $data
                        )
                    );
                    exit;
                }
                $file_data = array(
                    'cases_checkbox_id' => $cases_checkbox_id,
                    'rel_id' => $lead_id,
                    'rel_type' => 'client-doc-outstanding-item',
                    'file_name' => $data['file_name'],
                    'filetype' => $data['file_type'],
                    'file_url' => $data['file_url'],
                    'download_file_url' => $data['download_file_url'],
                    'doc_status' => '',
                    'lender_name' => $lender_name,
                    'payout_expire_date' => to_sql_date($payout_expire_date, true),
                    'dateadded' => date('Y-m-d H:i:s')
                );
                $this->db->insert(db_prefix() . 'cases_checkbox_files', $file_data);
                $last_casescheckboxfile_inserted_id = $this->db->insert_id();
            }
        }
        // get the checkboxes data details
        $this->db->select('title');
        $this->db->where('id', $cases_checkbox_id);
        $get_checkbox_data = $this->db->get(db_prefix() . 'cases_checkboxes')->row();
        $checkbox_title = $get_checkbox_data->title;
        // add the data in lead activity log
        $insert_task_activity = array(
            'leadid' => $lead_id,
            'task_id' => null,
            'staffid' => get_staff_user_id(),
            'full_name' => get_staff_full_name(),
            'activity_type' => 'task-activity',
            'additional_data' => 'Pending Review',
            'description' => 'Document for checklist item (' . $checkbox_title . ') uploaded by ' . get_staff_full_name(),
            'date' => date('Y-m-d H:i:s'),
        );
        leads_activity_log($this, $insert_task_activity);
        // update the last contact date 
        $this->leads_model->update_leads_last_contact_date($lead_id);
        // get client and contact id line of code
        $leads_status_value = '#outstanding_items';
        $complete_stage_button = 3;
        $response = array(
            'success' => true,
            'message' => 'Data saved successfully',
            'cases_checkbox_id' => $cases_checkbox_id,
            'leads_status' => $leads_status_value,
            'complete_stage_button' => $complete_stage_button,
            'id' => $lead_id,
            'leadView' => $this->_get_lead_data($lead_id),
        );
        $this->output
            ->set_content_type('application/json')
            ->set_output(json_encode($response));
    }
    //LD request for funds upload doc
    public function upload_doc_for_request_for_funds($lead_id)
    {
        $last_casescheckboxfile_inserted_id = array();
        $cases_checkbox_id = $this->input->post('cases_checkbox_id');
        $req_action_date = $this->input->post('action_date');
        $req_comments = $this->input->post('req_comments');
        $request_for_funds_review_email_tincymac = $this->input->post('request_for_funds_review_email_tincymac', FALSE);
        $request_for_funds_stage_complete_question = $this->input->post('req_complete_stage_question');
        $to_client_req_for_funds_send_report_reviewmail = $this->input->post('to_client_req_for_funds_send_report_reviewmail');
        $cc_req_for_funds_send_report_reviewmail = $this->input->post('cc_req_for_funds_send_report_reviewmail');
        $bcc_req_for_funds_send_report_reviewmail = $this->input->post('bcc_req_for_funds_send_report_reviewmail');
        $to_emails = array_map('trim', explode(',', $to_client_req_for_funds_send_report_reviewmail));
        $cc_emails = array_map('trim', explode(',', $cc_req_for_funds_send_report_reviewmail));
        $bcc_emails = array_map('trim', explode(',', $bcc_req_for_funds_send_report_reviewmail));
        $type = $this->input->post('type');
        $this->db->select('email,assign_group');
        $this->db->where('id', $lead_id);
        $result = $this->db->get(db_prefix() . 'leads')->row();
        $getemail = $result->email;
        $check_assign_group = $result->assign_group;
        $data = $this->Token_model->getToken();
        $get_id = array_column($data, 'token');
        $access_token = implode(',', $get_id);
        $data = $this->Contacts_model->getEmail($getemail);
        $get_id = array_column($data, 'id');
        $get_userid = array_column($data, 'userid');
        $get_firstname = array_column($data, 'firstname');
        $get_lastname = array_column($data, 'lastname');
        $dropbox_firstname = implode(',', $get_firstname);
        $dropbox_lastname = implode(',', $get_lastname);
        $get_id = implode(',', $get_id);
        $userid = implode(',', $get_userid);
        $leadData = $this->leads_model->get_lead_id($get_id);
        $user_id = $leadData->id;
        $user_name = $leadData->name;
        foreach ($_FILES['request_for_funds_userfile']['name'] as $key => $name) {
            $tmp_file = $_FILES['request_for_funds_userfile']['tmp_name'][$key];
            if (is_uploaded_file($tmp_file)) {
                $file_name = $_FILES['request_for_funds_userfile']['name'][$key];
                $data = $this->leads_model->upload_to_dropbox($access_token, $tmp_file, $file_name, $user_id, $dropbox_firstname, $dropbox_lastname);
                if ($data['status'] != 200) {
                    $this->leads_model->add_errors_logs($lead_id, get_staff_user_id(), get_staff_full_name(), 'Upload doc for Request for funds stage', $data, $data['status'], 'Staff');
                    echo json_encode(
                        array(
                            'success' => false,
                            'response' => $data
                        )
                    );
                    exit;
                }
                if ($request_for_funds_stage_complete_question == 'yes' || $request_for_funds_stage_complete_question == 'Yes') {
                    $holdback_file_data = array(
                        'rel_id' => $lead_id,
                        'rel_type' => 'holdback_doc',
                        'file_name' => $data['file_name'],
                        'filetype' => $data['file_type'],
                        'file_url' => $data['file_url'],
                        'download_file_url' => $data['download_file_url'],
                        'dateadded' => date('Y-m-d H:i:s')
                    );
                    $this->db->insert(db_prefix() . 'files', $holdback_file_data);
                    $hold_back_last_inserted_id = $this->db->insert_id();
                    $holdback_files_inserted_ids[] = $hold_back_last_inserted_id;
                }
                $file_data = array(
                    'cases_checkbox_id' => $cases_checkbox_id,
                    'rel_id' => $lead_id,
                    'rel_type' => 'client-doc-request-for-funds',
                    'file_name' => $data['file_name'],
                    'filetype' => $data['file_type'],
                    'file_url' => $data['file_url'],
                    'doc_status' => '',
                    'dateadded' => date('Y-m-d H:i:s')
                );
                $this->db->insert(db_prefix() . 'cases_checkbox_files', $file_data);
                $last_inserted_id = $this->db->insert_id();
                $last_casescheckboxfile_inserted_ids[] = $last_inserted_id;
            }
        }
        // update teh action dates 
        if (!empty($req_action_date) || !empty($req_comments)) {
            // if task is GTC then send slack notification
            $checklist_checkboxes_data = get_cases_checkbox_by_id($this, $cases_checkbox_id);
            // send notification if gtc already sent
            $GTC_Check = get_gtc_check($this, $lead_id);
            if ($GTC_Check == 0) {
                // update the gtc check key 
                $this->leads_model->update_GTC_key($lead_id, 1);
                if ($checklist_checkboxes_data->title == 'Broker/Client GTC') {
                    // Send Slack notification
                    $group_name = get_the_group_name_using_leadid($this, $lead_id);
                    $lead_name = get_lead_name_using_lead_id($this, $lead_id);
                    $lead_split_name = leads_splitFullName($lead_name);
                    $slack_message = "\n - Stage Complete: GTC from Client/Nuborrow \n - Request for Funds.";
                    $send_notification = $this->slack->sendnotification($slack_message, $lead_id, $group_name, $lead_split_name['lastname'] . ', ' . $lead_split_name['firstname'] . ' ' . $lead_split_name['middlename']);
                }
            }
            $req_for_funds_action_update = array(
                'req_for_funds_action_at' => $req_action_date,
                'req_comments' => $req_comments
            );
            $this->db->where('id', $cases_checkbox_id);
            $this->db->update(db_prefix() . 'cases_checkboxes', $req_for_funds_action_update);
        }
        if (!empty($last_casescheckboxfile_inserted_ids)) {
            $this->db->select('file_url, filetype');
            $this->db->where_in('id', $last_casescheckboxfile_inserted_ids);
            $get_file_data = $this->db->get(db_prefix() . 'cases_checkbox_files')->result_array();
            $_POST['close_attachment'] = $get_file_data;
        }
        // send report mail to the client in request for fudns stage
        if (!empty($type) && $type == 'send-report') {
            $closing_date_update = array(
                'active_case' => 'Closed',
                'closed_completed_at' => date('Y-m-d H:i:s'),
                'close_completed' => 1,
                'last_status_change' => date('Y-m-d H:i:s'),
            );
            $this->db->where('id', $lead_id);
            $this->db->update(db_prefix() . 'leads', $closing_date_update);
            // add the app message 
            $app_message = 'Congratulations, your transaction has now closed.Please check your email for a copy of the documents you signed for your records and details of payments made on your behalf. We thank you for your kind instructions, co-operation and hope to work with you again soon.';
            store_app_message_for_client($this, $lead_id, $app_message, 5);

            $get_mail_subject = get_mail_subject($this, $lead_id);
            $this->db->select('name,email,addedfrom');
            $this->db->where('id', $lead_id);
            $get_data = $this->db->get(db_prefix() . 'leads')->row();
            $subject = $get_mail_subject;
            $_POST['user_name'] = $get_data->name;
            $replay_to_mail = get_all_staff_to_replay_email($this, get_staff_user_id(), $check_assign_group);
            // send mail to the broker
            $broker_data = get_multiple_broker_details_using_addedfrom($this, $get_data->addedfrom);
            $_POST['case_url'] = get_the_redirect_email_case_url($lead_id, 'broker');
            $html_content_confirmation_email_to_broker = $this->load->view('admin/leads/Email_template/broker/request_funds_stage_complete', $_POST, TRUE);
            if (!empty($broker_data)) {
                $broker_message = 'We are delighted to inform you that the file has successfully moved through another
                milestone and closed. The Client has been sent a copy of the documents and ledger.Thank you for your kind instructions and we look forward to working with you again 
                shortly.';
                // foreach ($broker_data as $broker) {
                //     $_POST['broker_name'] = $broker['firstname'] . ' ' . $broker['lastname'];
                //     $broker_email = $broker['email'];
                $all_broker_emails = array_column($broker_data, 'email');
                $send_email_result = send_mailchimp_email($all_broker_emails, $subject, $html_content_confirmation_email_to_broker, $replay_to_mail, '', '', $lead_id);
                // add the record for outbox emails
                $this->Outbox_model->save_outbox_email(
                    $all_broker_emails,
                    '',
                    '',
                    $subject,
                    $broker_message,
                    '',
                    $lead_id,
                    5,
                    $html_content_confirmation_email_to_broker,
                    $replay_to_mail,
                    $send_email_result['status'],
                    $send_email_result['mandrill_id'],
                    1
                );

                // }
                // send the all admin notification and email to the admin broker
                $brokerage_id = get_brokerage_id_using_leadid($this, $lead_id);
                $admin_broker_ids = get_all_admin_broker_role_staff_ids($this, $brokerage_id);
                $all_admin_broker_emails = array_column($admin_broker_ids, 'email');
                // foreach ($admin_broker_ids as $admin_broker_email) {
                //     if (get_staff_user_id() != $admin_broker_email['staffid'] && !in_array($admin_broker_email['staffid'], explode(',', $get_data->addedfrom))) {
                //         $_POST['broker_name'] = $admin_broker_email['firstname'] . ' ' . $admin_broker_email['lastname'];
                //         $broker_email = $admin_broker_email['email'];
                $send_email_result = send_mailchimp_email($all_admin_broker_emails, $subject, $html_content_confirmation_email_to_broker, $replay_to_mail, '', '', $lead_id);
                // add the record for outbox emails
                $this->Outbox_model->save_outbox_email(
                    $all_admin_broker_emails,
                    '',
                    '',
                    $subject,
                    $broker_message,
                    '',
                    $lead_id,
                    5,
                    $html_content_confirmation_email_to_broker,
                    $replay_to_mail,
                    $send_email_result['status'],
                    $send_email_result['mandrill_id'],
                    1
                );
                //     }
                // }
                $insert_task_activity = array(
                    'leadid' => $lead_id,
                    'lead_status' => 5,
                    'activity_type' => 'closed-emails',
                    'staffid' => get_staff_user_id(),
                    'full_name' => get_staff_full_name(),
                    'description' => get_staff_full_name() . ' Sent an email to Broker. Good ' . get_afternoon_and_morning() . '<br>' . $broker_message,
                    'date' => date('Y-m-d H:i:s'),
                );
                leads_activity_log($this, $insert_task_activity);
            }
            // send the maiil to the send report client
            // if (!empty($request_for_funds_review_email_tincymac)) {
            if (!empty($to_emails)) {
                // get the lead data
                $this->db->select('name,email,phonenumber,addedfrom');
                $this->db->where('id', $lead_id);
                $get_lead_data = $this->db->get(db_prefix() . 'leads')->row();
                // notification line of code
                $this->db->select('id,multiple_cases,client_id,phonenumber,name,email,addedfrom,assign_group');
                $this->db->where('id', $lead_id);
                $lead_data_check = $this->db->get(db_prefix() . 'leads');
                if ($lead_data_check->num_rows() > 0) {
                    $lead_data = $lead_data_check->row();
                    $client_id = get_client_id_using_contact_id($this, $lead_data->client_id, $lead_data->multiple_cases);
                    $contact_id = get_contact_id_using_client_id($this, $client_id);
                    $subject = get_mail_subject_for_case_stages($this, $lead_id, 5) . ' Transaction Completed';
                    $replay_to_mail = get_all_staff_to_replay_email($this, get_staff_user_id(), $lead_data->assign_group, $to_emails);
                    $_POST['request_for_funds_review_email_tincymac'] = $request_for_funds_review_email_tincymac;
                    $html_content_confirmation_email_to_broker = $this->load->view('admin/leads/Email_template/case_closed', $_POST, TRUE);
                    $send_email_result = send_mailchimp_email($to_emails, $subject, $html_content_confirmation_email_to_broker, $replay_to_mail, $cc_emails, $bcc_emails, $lead_id);

                    // add the record for outbox emails
                    $this->Outbox_model->save_outbox_email(
                        $to_emails,
                        $cc_emails,
                        $bcc_emails,
                        $subject,
                        $request_for_funds_review_email_tincymac,
                        '',
                        $lead_id,
                        5,
                        $html_content_confirmation_email_to_broker,
                        $replay_to_mail,
                        $send_email_result['status'],
                        $send_email_result['mandrill_id'],
                        1
                    );
                    // send the mail in secondary email
                    $get_secondary_emali = get_the_secondary_email($this, $lead_id);
                    if (!empty($get_secondary_emali)) {
                        send_mailchimp_email($get_secondary_emali, $subject, $html_content_confirmation_email_to_broker, $replay_to_mail, $cc_emails, $bcc_emails, $lead_id);
                    }
                    // add the emali in activity logs
                    $broker_ledger_mail_content = '<p style="margin:0px;">Dear Colleague,</p>
                    <p>We are now moving to closing, please see attached ledgers and kindly update
                        your records.
                    </p>
                   <p>If you wish to access this file, Please <a href="' . $_POST['case_url'] . '">Click here</a></p>';
                    $insert_task_activity = array(
                        'leadid' => $lead_id,
                        'lead_status' => 5,
                        'activity_type' => 'closed-emails',
                        'staffid' => get_staff_user_id(),
                        'full_name' => get_staff_full_name(),
                        'description' => get_staff_full_name() . " sent an email to " . $get_lead_data->name . ' <br>' . $request_for_funds_review_email_tincymac,
                        'date' => date('Y-m-d H:i:s'),
                    );
                    leads_activity_log($this, $insert_task_activity);
                    // send notification for case closed
                    $notification_type = get_notification_type(2);
                    $client_notify_type = $notification_type . '-created';
                    $client_notify_title = 'Case Closed';
                    $client_notify_message = 'Congratulations, your transaction has now closed. Please check your email for a copy of the documents you signed for your records and details of payments made on your behalf. We thank you for your kind instructions, co-operation and hope to work with you again soon.';
                    send_notification_in_mobile('client', get_staff_user_id(), $contact_id, $client_id, $lead_id, $client_notify_title, '', $client_notify_type, '');

                    $client_case_closed_sms = 'This is Legal Direct. Congratulations your transaction has now closed. Please check your email for confirmation. Thank you for your kind instructions. Please DO NOT REPLY TO THIS TEXT.';
                    $all_client_phone_list = get_all_client_phonenumber_using_lead_id($this, $lead_id);
                    $this->send_sms($all_client_phone_list, $client_case_closed_sms, $client_case_closed_sms, $lead_id, $get_lead_data->name, $get_lead_data->email);
                    // send  notiication in crm to all the team group member and staff when case closed
                    $closed_message = 'Congratulations, your transaction has now closed. Please check your email for a copy of the documents you signed for your records and details of payments made on your behalf. We thank you for your kind instructions, co-operation and hope to work with you again soon.';
                    $this->db->select('assign_group,assigned');
                    $this->db->where('id', $lead_id);
                    $lead_data_for_get_assign_group = $this->db->get(db_prefix() . 'leads')->row();
                    $current_staff_data = get_staff_ids_by_group($this, $lead_data_for_get_assign_group->assign_group);
                    foreach ($current_staff_data as $staff_notifiy_data) {
                        if (get_staff_user_id() != $staff_notifiy_data['staffid']) {

                            $ldteam_notify_type = $notification_type . '-created';
                            $ld_team_notify_title = 'Case Closed';
                            $ld_team_notify_message = 'Congratulations, your transaction has now closed. Please check your email for a copy of the documents you signed for your records and details of payments made on your behalf. We thank you for your kind instructions, co-operation and hope to work with you again soon.';
                            // send notificaiton in crm for group members
                            $this->leads_model->custom_lead_assigned_member_notification('staff', $lead_id, $staff_notifiy_data['staffid'], get_staff_user_id(), '', $closed_message);
                        }
                    }
                    // get the all admin staff ids
                    $admin_ids = get_all_admin_role_staff_ids($this);
                    foreach ($admin_ids as $admin_email) {
                        if (get_staff_user_id() != $admin_email['staffid']) {

                            $admin_notify_type = $notification_type . '-created';
                            $admin_notify_title = 'Case Closed';
                            $admin_notify_message = $closed_message;
                            // send notification in crm
                            $this->leads_model->custom_lead_assigned_member_notification('staff', $lead_id, $admin_email['staffid'], get_staff_user_id(), '', $closed_message);
                        }
                    }
                }
            }
            // store the holdback details
            if ($request_for_funds_stage_complete_question == 'yes' || $request_for_funds_stage_complete_question == 'Yes') {
                $last_casescheckboxfile_inserted_ids_string = implode(',', $holdback_files_inserted_ids);
                $data = array(
                    'lead_id' => $lead_id,
                    'file_id' => $last_casescheckboxfile_inserted_ids_string,
                    'name' => 'Send Report to Client/copy to broker/ holdback information',
                    'comment' => $request_for_funds_review_email_tincymac,
                    'type' => 'holdback',
                    'additional_data' => $request_for_funds_stage_complete_question,
                    'created_at' => date('Y-m-d H:i:s'),
                );
                $this->leads_model->add_holdback_info($data);
            }
        }
        // get the checkboxes data details
        $this->db->select('title');
        $this->db->where('id', $cases_checkbox_id);
        $get_checkbox_data = $this->db->get(db_prefix() . 'cases_checkboxes')->row();
        $checkbox_title = $get_checkbox_data->title;
        // add the data in lead activity log
        $insert_task_activity = array(
            'leadid' => $lead_id,
            'task_id' => null,
            'staffid' => get_staff_user_id(),
            'full_name' => get_staff_full_name(),
            'activity_type' => 'task-activity',
            'additional_data' => 'Pending Review',
            'description' => 'Document for checklist item (' . $checkbox_title . ') uploaded by ' . get_staff_full_name(),
            'date' => date('Y-m-d H:i:s'),
        );
        leads_activity_log($this, $insert_task_activity);
        // update the last contact date 
        $this->leads_model->update_leads_last_contact_date($lead_id);
        // get client and contact id line of code
        $leads_status_value = '#request_for_funds';
        $complete_stage_button = 4;
        $response = array(
            'success' => true,
            'message' => 'Data saved successfully',
            'leads_status' => $leads_status_value,
            'cases_checkbox_id' => $cases_checkbox_id,
            'complete_stage_button' => $complete_stage_button,
            'id' => $lead_id,
            'leadView' => $this->_get_lead_data($lead_id),
        );
        $this->output
            ->set_content_type('application/json')
            ->set_output(json_encode($response));
    }
    // uplaod doc for case closed
    public function upload_doc_for_case_closed($lead_id)
    {
        $case_closed_notes = $this->input->post('case_closed_notes');
        $last_file_inserted_id = array();
        $this->db->select('email,assign_group');
        $this->db->where('id', $lead_id);
        $result = $this->db->get(db_prefix() . 'leads')->row();
        $getemail = $result->email;
        $check_assign_group = $result->assign_group;
        $data = $this->Token_model->getToken();
        $get_id = array_column($data, 'token');
        $access_token = implode(',', $get_id);
        $data = $this->Contacts_model->getEmail($getemail);
        $get_id = array_column($data, 'id');
        $get_userid = array_column($data, 'userid');
        $get_firstname = array_column($data, 'firstname');
        $get_lastname = array_column($data, 'lastname');
        $dropbox_firstname = implode(',', $get_firstname);
        $dropbox_lastname = implode(',', $get_lastname);
        $get_id = implode(',', $get_id);
        $userid = implode(',', $get_userid);
        $leadData = $this->leads_model->get_lead_id($get_id);
        $user_id = $leadData->id;
        $user_name = $leadData->name;
        // add record in tblcases checkboxes
        $insert_data = array(
            'lead_id' => $lead_id,
            'type' => 'case_closed_doc',
            'description' => str_replace(['<br />', '<br>', '<br/>'], "\n", nl2br($case_closed_notes)),
            'created_at' => date('Y-m-d H:i:s'),
        );
        $this->db->insert(db_prefix() . 'cases_checkboxes', $insert_data);
        $cases_checkboxes_inserted_ids = $this->db->insert_id();
        foreach ($_FILES['case_closed_userfile']['name'] as $key => $name) {
            $tmp_file = $_FILES['case_closed_userfile']['tmp_name'][$key];
            if (is_uploaded_file($tmp_file)) {
                $file_name = $_FILES['case_closed_userfile']['name'][$key];
                $data = $this->leads_model->upload_to_dropbox($access_token, $tmp_file, $file_name, $user_id, $dropbox_firstname, $dropbox_lastname);
                if ($data['status'] != 200) {
                    $this->leads_model->add_errors_logs($lead_id, get_staff_user_id(), get_staff_full_name(), 'Upload doc for Case closed', $data, $data['status'], 'Staff');
                    echo json_encode(
                        array(
                            'success' => false,
                            'response' => $data
                        )
                    );
                    exit;
                }
                $file_data = array(
                    'cases_checkbox_id' => $cases_checkboxes_inserted_ids,
                    'rel_id' => $lead_id,
                    'rel_type' => 'case_closed_doc',
                    'file_name' => $data['file_name'],
                    'filetype' => $data['file_type'],
                    'file_url' => $data['file_url'],
                    'download_file_url' => $data['download_file_url'],
                    'dateadded' => date('Y-m-d H:i:s'),
                );
                $this->db->insert(db_prefix() . 'cases_checkbox_files', $file_data);
                $last_file_inserted_id[] = $this->db->insert_id();
            }
        }
        if (!empty($last_file_inserted_id)) {
            // add the activitly
            $insert_task_activity = array(
                'leadid' => $lead_id,
                'staffid' => get_staff_user_id(),
                'full_name' => get_staff_full_name(),
                'description' => "Case closed document has been upload by " . get_staff_full_name(),
                'date' => date('Y-m-d H:i:s'),
            );
            leads_activity_log($this, $insert_task_activity);
            $leads_status_value = '#Closed';
            $response = array(
                'success' => true,
                'message' => 'Data saved successfully',
                'leads_status' => $leads_status_value,
                'id' => $lead_id,
                'leadView' => $this->_get_lead_data($lead_id),
            );
        } else {
            $response = array(
                'success' => false,
            );
        }
        $this->output
            ->set_content_type('application/json')
            ->set_output(json_encode($response));
    }
    // get the request for funds emails activity
    public function get_activity_emails()
    {
        $lead_id = $this->input->post('lead_id');
        $lead_status = $this->input->post('lead_status');
        $activity_type = $this->input->post('activity_type');

        // $this->db->select('*');
        // $this->db->from(db_prefix() . 'lead_activity_log');
        // $this->db->where('leadid', $lead_id);
        // $this->db->where('lead_status', $lead_status);
        // if (!empty($activity_type)) {
        //     $this->db->where('activity_type', $activity_type);
        // }
        // $query = $this->db->get();
        // $data = $query->result_array();
        $data = get_final_report_activity_details($this, $lead_id, $lead_status, $activity_type);

        if (!empty($data)) {
            $response = array(
                'success' => true,
                'data' => $data,
            );
        } else {
            $response = array(
                'success' => false,
                'data' => null,
            );
        }
        $this->output
            ->set_content_type('application/json')
            ->set_output(json_encode($response));
    }

    // get the all case closed documents
    public function get_all_details_for_case_closed($lead_id)
    {
        $this->db->select('id, description, created_at');
        $this->db->where('lead_id', $lead_id);
        $this->db->where('type', 'case_closed_doc');
        $get_case_closed_data = $this->db->get(db_prefix() . 'cases_checkboxes')->result_array();

        if (!empty($get_case_closed_data)) {
            foreach ($get_case_closed_data as &$data) {
                $this->db->select('id, file_name, filetype, file_url, dateadded');
                $this->db->where('cases_checkbox_id', $data['id']);
                $this->db->where('rel_type', 'case_closed_doc');
                $get_files_data = $this->db->get(db_prefix() . 'cases_checkbox_files')->result_array();
                $data['file_data'] = $get_files_data;
            }
            $response = array(
                'success' => true,
                'case_closed_data' => $get_case_closed_data,
            );
        } else {
            $response = array(
                'success' => false,
            );
        }
        $this->output
            ->set_content_type('application/json')
            ->set_output(json_encode($response));
    }
    // add the holdback details
    public function add_holdback_details()
    {
        $lead_id = $this->input->post('lead_id');
        $hold_back_details_comments = $this->input->post('hold_back_details_comments');
        // get the request for funds task id 
        $this->db->select('id');
        $this->db->where('lead_id', $lead_id);
        $this->db->where('title', 'Send Report to Client/copy to broker/ holdback information');
        $get_the_task_id = $this->db->get(db_prefix() . 'cases_checkboxes')->row();
        $send_report_toclient_item_id = $get_the_task_id->id;
        // upload doc line of code
        $this->db->select('email,assign_group');
        $this->db->where('id', $lead_id);
        $result = $this->db->get(db_prefix() . 'leads')->row();
        $getemail = $result->email;
        $check_assign_group = $result->assign_group;
        $data = $this->Token_model->getToken();
        $get_id = array_column($data, 'token');
        $access_token = implode(',', $get_id);
        $data = $this->Contacts_model->getEmail($getemail);
        $get_id = array_column($data, 'id');
        $get_userid = array_column($data, 'userid');
        $get_firstname = array_column($data, 'firstname');
        $get_lastname = array_column($data, 'lastname');
        $dropbox_firstname = implode(',', $get_firstname);
        $dropbox_lastname = implode(',', $get_lastname);
        $get_id = implode(',', $get_id);
        $userid = implode(',', $get_userid);
        $leadData = $this->leads_model->get_lead_id($get_id);
        $user_id = $leadData->id;
        $user_name = $leadData->name;
        foreach ($_FILES['hold_back_details_file']['name'] as $key => $name) {
            $tmp_file = $_FILES['hold_back_details_file']['tmp_name'][$key];
            if (is_uploaded_file($tmp_file)) {
                $file_name = $_FILES['hold_back_details_file']['name'][$key];
                $data = $this->leads_model->upload_to_dropbox($access_token, $tmp_file, $file_name, $user_id, $dropbox_firstname, $dropbox_lastname);
                if ($data['status'] != 200) {
                    $this->leads_model->add_errors_logs($lead_id, get_staff_user_id(), get_staff_full_name(), 'Upload doc for holdback details', $data, $data['status'], 'Staff');
                    echo json_encode(
                        array(
                            'success' => false,
                            'response' => $data
                        )
                    );
                    exit;
                }
                $holdback_file_data = array(
                    'rel_id' => $lead_id,
                    'rel_type' => 'holdback_doc',
                    'file_name' => $data['file_name'],
                    'filetype' => $data['file_type'],
                    'file_url' => $data['file_url'],
                    'download_file_url' => $data['download_file_url'],
                    'dateadded' => date('Y-m-d H:i:s')
                );
                $this->db->insert(db_prefix() . 'files', $holdback_file_data);
                $hold_back_last_inserted_id = $this->db->insert_id();
                $holdback_files_inserted_ids[] = $hold_back_last_inserted_id;
            }
        }
        $last_casescheckboxfile_inserted_ids_string = implode(',', $holdback_files_inserted_ids);
        $data = array(
            'lead_id' => $lead_id,
            'file_id' => $last_casescheckboxfile_inserted_ids_string,
            'name' => 'Send Report to Client/copy to broker/ holdback information',
            'comment' => $hold_back_details_comments,
            'type' => 'holdback',
            'additional_data' => '',
            'created_at' => date('Y-m-d H:i:s'),
        );
        $this->leads_model->add_holdback_info($data);
        if (!empty($check_inserted_details)) {
            $response = array(
                'success' => true
            );
        } else {
            $response = array(
                'success' => true
            );
        }
        $this->output
            ->set_content_type('application/json')
            ->set_output(json_encode($response));
    }
    // get the holds data deatils
    public function get_holdback_data($lead_id)
    {
        $this->db->select('id, lead_id, file_id, type, name, comment, additional_data, created_at');
        $this->db->where('lead_id', $lead_id);
        $this->db->where('type', 'holdback');
        $query = $this->db->get(db_prefix() . 'leads_holdback');
        $holdback_details = $query->result_array();
        if (!empty($holdback_details)) {
            foreach ($holdback_details as $key => $holdback) {
                if (!empty($holdback['file_id'])) {
                    $file_ids = explode(',', $holdback['file_id']);
                    $this->db->select('id, file_name, file_url, filetype');
                    $this->db->from('tblfiles');
                    $this->db->where_in('id', $file_ids);
                    $files_query = $this->db->get();
                    $files_details = $files_query->result_array();
                    $holdback_details[$key]['files'] = $files_details;
                } else {
                    $holdback_details[$key]['files'] = array();
                }
            }
        } else {
            $holdback_details = array();
        }
        $this->output
            ->set_content_type('application/json')
            ->set_output(json_encode($holdback_details));
    }
    // get the checlist details for broker
    public function checklist_details_broker($lead_id = '', $stage_id = '')
    {
        $this->db->where('rel_id', $lead_id);
        $this->db->where('rel_type', 'user-task');
        $this->db->where_in('type', array('broker'));
        $this->db->order_by('order_no', 'ASC');
        if (!empty($stage_id) && $stage_id == 1) {
            // $this->db->where('type', 'client');
        }
        if (!empty($stage_id)) {
            $this->db->where('leads_status', $stage_id);
        }
        $query_tasks = $this->db->get(db_prefix() . 'tasks');
        $task_data = $query_tasks->result();
        // echo $this->db->last_query();
        $save = [];
        $order_flag = 1;
        foreach ($task_data as $task_value) {

            $this->db->where('task_id', $task_value->id);
            $this->db->where('rel_id', $lead_id);
            $this->db->where('rel_type', 'client-doc');
            $query_files = $this->db->get(db_prefix() . 'files');
            $file_data = $query_files->result_array();
            // get task liet
            $this->db->select('doc_type, instruction');
            $this->db->where('task_id', $task_value->id);
            $file_instruction_data = $this->db->get(db_prefix() . 'file_instruction')->row();

            // Check if file_data is not empty
            if (!empty($file_data)) {
                for ($i = 0; $i < count($file_data); $i++) {
                    $file_type_string = $file_data[$i]['filetype'];
                    $first_part = explode('/', $file_type_string)[1];
                    $directLink = str_replace('raw=1', 'dl=1', $file_data[$i]['file_url']);
                    $file_data[$i]['dl_file_url'] = $directLink;
                    $file_data[$i]['check_filetype'] = $first_part;
                    if (!empty($file_data[$i]['item_type_id'])) {
                        $comma_separated_names = get_checklist_item_names($this, $file_data[$i]['item_type_id']);
                    } else {
                        $comma_separated_names = '';
                    }
                }
            }
            $new_task_date = time_ago($task_value->dateadded);
            $dt_new_task_date = _dt($task_value->dateadded);
            $rejected_reason = get_checklist_rejected_reason($this, $task_value->id);
            $save[] = [
                'id' => $task_value->id,
                'order_no' => ($task_value->order_no) ? $task_value->order_no : $order_flag++,
                'type' => $task_value->type,
                'checkbox_status' => $task_value->checkbox_status,
                'name' => $task_value->name,
                'ld_notes' => $task_value->ld_notes,
                'description' => $task_value->description,
                'doc_type' => $file_instruction_data->doc_type,
                'instruction' => $file_instruction_data->instruction,
                'dateadded' => (string) $task_value->dateadded,
                'new_dateadded' => $new_task_date,
                'dt_new_dateadded' => (string) $dt_new_task_date,
                'status' => $task_value->status,
                'file_data' => $file_data,
                'rejected_reason' => $rejected_reason ?: '-',
                'checklist_lead_status' => $task_value->leads_status,
                'show_item_names' => $comma_separated_names,
                'broker_fee_na' => $task_value->broker_fee_na,
            ];
        }

        $data = $this->output
            ->set_content_type('application/json')
            ->set_output(json_encode($save));

        return $data;
    }
    // get the borrower name
    public function get_borrower_name($lead_borrow_id)
    {
        $borrower_name = get_borrwer_name_by_id($this, $lead_borrow_id);
        echo json_encode($borrower_name);
    }
    // get the specific borrower details
    function get_specific_borrower_details()
    {
        $borrowerId = $this->input->post('borrowerId');
        $lead_id = $this->input->post('lead_id');
        $data = get_all_leads_borrow_data_by_id($this, $lead_id, $borrowerId);
        if (!empty($data)) {
            $response = array(
                'success' => true,
                'data' => $data
            );
        } else {
            $response = array(
                'success' => false,
                'data' => $data
            );
        }
        $this->output
            ->set_content_type('application/json')
            ->set_output(json_encode($response));
    }
    // update borrower details
    function update_borrower_details_by_id($lead_id)
    {
        $borrower_id = $this->input->post('client_contact_borrower_id');
        if ($lead_id == $borrower_id) {
            $data = [
                'name' => $this->input->post('borrow_firstname') . ' ' . $this->input->post('borrow_middlename') . ' ' . $this->input->post('borrow_lastname'),
                'email' => $this->input->post('borrow_email'),
                'phonenumber' => $this->input->post('borrow_phone'),
                // 'address'    => $this->input->post('borrow_address'),

            ];
            $this->db->where('id', $lead_id);
            $update = $this->db->update(db_prefix() . 'leads', $data);
        } else {
            $data = [
                'borrow_firstname' => $this->input->post('borrow_firstname'),
                'borrow_middlename' => $this->input->post('borrow_middlename'),
                'borrow_lastname' => $this->input->post('borrow_lastname'),
                'borrow_email' => $this->input->post('borrow_email'),
                'borrow_phone' => $this->input->post('borrow_phone'),
                // 'borrow_address'    => $this->input->post('borrow_address'),
            ];
            $this->db->where('id', $borrower_id);
            $update = $this->db->update(db_prefix() . 'leads_borrow', $data);
        }
        if ($update) {
            echo json_encode([
                'success' => true,
                'id' => $lead_id,
                'leadView' => $this->_get_lead_data($lead_id),
            ]);
        } else {
            echo json_encode(['success' => false]);
        }
    }
    // checklist deatils show for borrower
    public function checklist_details_for_borrower($lead_id = '', $stage_id = '')
    {
        $this->db->select('id');
        $this->db->where('lead_id', $lead_id);
        $get_all_borrower_id = $this->db->get(db_prefix() . 'leads_borrow')->result_array();
        $borrower_ids = array_column($get_all_borrower_id, 'id');

        $response_data = [];

        foreach ($borrower_ids as $borrower_id) {
            $this->db->where('rel_id', $lead_id);
            $this->db->where('rel_type', 'user-task');
            $this->db->where('type', 'client');
            $this->db->where('lead_borrow_id', $borrower_id);
            if (!empty($stage_id)) {
                $this->db->where('leads_status', $stage_id);
            }
            $tasks = $this->db->get(db_prefix() . 'tasks')->result();

            foreach ($tasks as $task) {
                $this->db->where('task_id', $task->id);
                $this->db->where('rel_id', $lead_id);
                $this->db->where('rel_type', 'client-doc');
                $file_data = $this->db->get(db_prefix() . 'files')->result_array();

                $this->db->select('doc_type, instruction');
                $this->db->where('task_id', $task->id);
                $file_instruction_data = $this->db->get(db_prefix() . 'file_instruction')->row();

                $comma_separated_names = null;
                foreach ($file_data as &$file) {
                    $first_part = explode('/', $file['filetype'])[1] ?? '';
                    $file['dl_file_url'] = str_replace('raw=1', 'dl=1', $file['file_url']);
                    $file['check_filetype'] = $first_part;
                    if (!empty($file['item_type_id'])) {
                        $comma_separated_names = get_checklist_item_names($this, $file['item_type_id']);
                    }
                }

                $response_data[] = [
                    'id' => $task->id,
                    'borrower_id' => $borrower_id,
                    'name' => $task->name,
                    'description' => $task->description,
                    'doc_type' => $file_instruction_data->doc_type ?? '',
                    'instruction' => $file_instruction_data->instruction ?? '',
                    'dateadded' => (string) $task->dateadded,
                    'new_dateadded' => time_ago($task->dateadded),
                    'dt_new_dateadded' => _dt($task->dateadded),
                    'status' => $task->status,
                    'file_data' => $file_data,
                    'rejected_reason' => get_checklist_rejected_reason($this, $task->id),
                    'checklist_lead_status' => $task->leads_status,
                    'show_item_names' => $comma_separated_names,
                ];
            }

            // Add empty borrower section if no tasks
            if (empty($tasks)) {
                $response_data[] = [
                    'id' => null,
                    'borrower_id' => $borrower_id,
                    'name' => '',
                    'description' => '',
                    'doc_type' => '',
                    'instruction' => '',
                    'dateadded' => '',
                    'new_dateadded' => '',
                    'dt_new_dateadded' => '',
                    'status' => '',
                    'file_data' => [],
                    'rejected_reason' => '',
                    'checklist_lead_status' => '',
                    'show_item_names' => '',
                ];
            }
        }

        return $this->output
            ->set_content_type('application/json')
            ->set_output(json_encode($response_data));
    }
    // get the all doc links and checklist for first borrower
    public function get_all_borrower_client_doc($lead_id, $lead_status, $type, $borrower_id = '')
    {
        $this->db->select('id');
        $this->db->where('rel_id', $lead_id);
        $this->db->where('rel_type', 'user-task');
        $this->db->where_in('status', [1, 2, 5]);
        if ($type == 'client') {
            $this->db->where('type', 'client');
        } else {
            $this->db->where('type', 'broker');
        }
        if ($borrower_id) {
            $this->db->where('lead_borrow_id', $borrower_id);
        } else {
            $this->db->where('lead_borrow_id', 0);
        }
        if (!empty($lead_status)) {
            $this->db->where('leads_status', $lead_status);
        }
        $query_tasks = $this->db->get(db_prefix() . 'tasks');
        $task_data = $query_tasks->result_array();
        $task_ids = array_column($task_data, 'id');

        if (empty($task_ids)) {
            echo json_encode([]);
            return;
        }

        $this->db->select('files.id, files.file_url, files.dateadded, files.filetype, files.file_name, tasks.name as task_name');
        $this->db->from(db_prefix() . 'files');
        $this->db->join(db_prefix() . 'tasks', 'tasks.id = files.task_id');
        $this->db->where_in('files.task_id', $task_ids);
        $this->db->where('files.rel_id', $lead_id);
        $this->db->where('files.rel_type', 'client-doc');
        $files_data = $this->db->get()->result_array();

        echo json_encode($files_data);
        return;
    }

    // checklist details for first borrower or user
    public function checklist_details($lead_id = '', $stage_id = '')
    {
        $this->db->select('id,name,ld_notes,description,dateadded,status,rejection_reason,rel_id,rel_type,type,checkbox_status,leads_status,order_no,lead_borrow_id');
        $this->db->where('rel_id', $lead_id);
        $this->db->where('rel_type', 'user-task');
        $this->db->where('type', 'client');
        $this->db->where('lead_borrow_id', 0);
        $this->db->order_by('order_no', 'ASC');
        if (!empty($stage_id)) {
            $this->db->where('leads_status', $stage_id);
        }
        $query_tasks = $this->db->get(db_prefix() . 'tasks');
        $task_data = $query_tasks->result();

        $save = [];
        $order_flag = 1; // Initialize order flag for ordering tasks
        foreach ($task_data as $task_value) {

            $this->db->where('task_id', $task_value->id);
            $this->db->where('rel_id', $lead_id);
            $this->db->where('rel_type', 'client-doc');
            $query_files = $this->db->get(db_prefix() . 'files');
            $file_data = $query_files->result_array();
            // get task liet
            $this->db->select('doc_type, instruction');
            $this->db->where('task_id', $task_value->id);
            $file_instruction_data = $this->db->get(db_prefix() . 'file_instruction')->row();

            // Check if file_data is not empty
            if (!empty($file_data)) {
                for ($i = 0; $i < count($file_data); $i++) {
                    $file_type_string = $file_data[$i]['filetype'];
                    $first_part = explode('/', $file_type_string)[1];
                    $directLink = str_replace('raw=1', 'dl=1', $file_data[$i]['file_url']);
                    $file_data[$i]['dl_file_url'] = $directLink;
                    $file_data[$i]['check_filetype'] = $first_part;
                    if (!empty($file_data[$i]['item_type_id']) && $task_value->id == $file_data[$i]['task_id']) {
                        $comma_separated_names = get_checklist_item_names($this, $file_data[$i]['item_type_id']);
                    } else {
                        $comma_separated_names = null;
                    }
                }
            } else {
                $comma_separated_names = null;
            }
            $new_task_date = time_ago($task_value->dateadded);
            $dt_new_task_date = _dt($task_value->dateadded);
            // get the rejection reason for the every checklsit
            $rejected_reason = get_checklist_rejected_reason($this, $task_value->id);
            $save[] = [
                'id' => $task_value->id,
                'order_no' => ($task_value->order_no) ? $task_value->order_no : $order_flag++,
                'checkbox_status' => $task_value->checkbox_status,
                'name' => $task_value->name,
                'type' => $task_value->type,
                'rel_type' => $task_value->rel_type,
                'rel_id' => $task_value->rel_id,
                'description' => $task_value->description,
                'ld_notes' => $task_value->ld_notes,
                'doc_type' => $file_instruction_data->doc_type,
                'instruction' => $file_instruction_data->instruction,
                'dateadded' => (string) $task_value->dateadded,
                'new_dateadded' => $new_task_date,
                'dt_new_dateadded' => (string) $dt_new_task_date,
                'status' => $task_value->status,
                'file_data' => $file_data,
                'rejected_reason' => $rejected_reason ?: '-',
                'checklist_lead_status' => $task_value->leads_status,
                'show_item_names' => $comma_separated_names,
            ];
        }

        $data = $this->output
            ->set_content_type('application/json')
            ->set_output(json_encode($save));

        return $data;
    }
    // DL check details get
    public function dl_check_other_item_checklist_details($lead_id = '', $stage_id = '')
    {
        $this->db->select('id,name,ld_notes,description,dateadded,status,rejection_reason,rel_id,rel_type,type,checkbox_status,leads_status');
        $this->db->where('rel_id', $lead_id);
        $this->db->where('rel_type', 'dl-check-user-task');
        $this->db->where('type', 'other');
        $this->db->where('lead_borrow_id', 0);
        if (!empty($stage_id)) {
            $this->db->where('leads_status', $stage_id);
        }
        $query_tasks = $this->db->get(db_prefix() . 'tasks');
        $task_data = $query_tasks->result();

        $save = [];

        foreach ($task_data as $task_value) {

            $this->db->where('task_id', $task_value->id);
            $this->db->where('rel_id', $lead_id);
            $this->db->where('rel_type', 'client-doc');
            $query_files = $this->db->get(db_prefix() . 'files');
            $file_data = $query_files->result_array();
            // get task liet
            $this->db->select('doc_type, instruction');
            $this->db->where('task_id', $task_value->id);
            $file_instruction_data = $this->db->get(db_prefix() . 'file_instruction')->row();

            // Check if file_data is not empty
            if (!empty($file_data)) {
                for ($i = 0; $i < count($file_data); $i++) {
                    $file_type_string = $file_data[$i]['filetype'];
                    $first_part = explode('/', $file_type_string)[1];
                    $directLink = str_replace('raw=1', 'dl=1', $file_data[$i]['file_url']);
                    $file_data[$i]['dl_file_url'] = $directLink;
                    $file_data[$i]['check_filetype'] = $first_part;
                    if (!empty($file_data[$i]['item_type_id']) && $task_value->id == $file_data[$i]['task_id']) {
                        $comma_separated_names = get_checklist_item_names($this, $file_data[$i]['item_type_id']);
                    } else {
                        $comma_separated_names = null;
                    }
                }
            } else {
                $comma_separated_names = null;
            }
            $new_task_date = time_ago($task_value->dateadded);
            $dt_new_task_date = _dt($task_value->dateadded);
            // get the rejection reason for the every checklsit
            $rejected_reason = get_checklist_rejected_reason($this, $task_value->id);
            $save[] = [
                'id' => $task_value->id,
                'checkbox_status' => $task_value->checkbox_status,
                'name' => $task_value->name,
                'type' => $task_value->type,
                'rel_type' => $task_value->rel_type,
                'rel_id' => $task_value->rel_id,
                'description' => $task_value->description,
                'ld_notes' => $task_value->ld_notes,
                'doc_type' => $file_instruction_data->doc_type,
                'instruction' => $file_instruction_data->instruction,
                'dateadded' => (string) $task_value->dateadded,
                'new_dateadded' => $new_task_date,
                'dt_new_dateadded' => (string) $dt_new_task_date,
                'status' => $task_value->status,
                'file_data' => $file_data,
                'rejected_reason' => $rejected_reason ?: '-',
                'checklist_lead_status' => $task_value->leads_status,
                'show_item_names' => $comma_separated_names,
            ];
        }

        $data = $this->output
            ->set_content_type('application/json')
            ->set_output(json_encode($save));

        return $data;
    }
    // get checklist details by id
    public function checklist_details_by_id($task_id = '')
    {
        $this->db->where('id', $task_id);
        $this->db->where('rel_type', 'user-task');
        $query_tasks = $this->db->get(db_prefix() . 'tasks');
        $task_data = $query_tasks->result();

        $save = [];

        foreach ($task_data as $task_value) {
            $this->db->where('task_id', $task_value->id);
            $this->db->where('rel_type', 'client-doc');
            $query_files = $this->db->get(db_prefix() . 'files');
            $file_data = $query_files->result_array();
            // get task liet
            $this->db->select('doc_type, instruction');
            $this->db->where('task_id', $task_value->id);
            $file_instruction_data = $this->db->get(db_prefix() . 'file_instruction')->row();

            // Check if file_data is not empty
            if (!empty($file_data)) {
                for ($i = 0; $i < count($file_data); $i++) {
                    $file_type_string = $file_data[$i]['filetype'];
                    $first_part = explode('/', $file_type_string)[1];
                    $directLink = str_replace('raw=1', 'dl=1', $file_data[$i]['file_url']);
                    $file_data[$i]['dl_file_url'] = $directLink;
                    $file_data[$i]['check_filetype'] = $first_part;
                }
            }
            // get the item type ids
            $get_item_name_id = $task_value->Item_name;
            $item_name_array = explode(',', $get_item_name_id);
            $item_name_array = array_map('intval', $item_name_array);
            // get the item type name
            $this->db->select('Item_name');
            $this->db->where_in('id', $item_name_array);
            $query = $this->db->get(db_prefix() . 'checklist_item_type');
            $results = $query->result_array();
            $comma_separated_names = implode(', ', array_column($results, 'Item_name'));

            $new_task_date = time_ago($task_value->dateadded);
            $dt_new_task_date = _dt($task_value->dateadded);
            $save[] = [
                'id' => $task_value->id,
                'name' => $task_value->name,
                'ld_notes' => $task_value->ld_notes,
                'task_leads_status' => $task_value->leads_status,
                'description' => $task_value->description,
                'doc_type' => $file_instruction_data->doc_type,
                'instruction' => $file_instruction_data->instruction,
                'dateadded' => (string) $task_value->dateadded,
                'new_dateadded' => $new_task_date,
                'dt_new_dateadded' => (string) $dt_new_task_date,
                'status' => $task_value->status,
                'file_data' => $file_data,
                'show_item_names' => $comma_separated_names
            ];
        }

        $data = $this->output
            ->set_content_type('application/json')
            ->set_output(json_encode($save));

        return $data;
    }
    // delete the chekclsit item image
    public function checklist_image_delete($lead_id)
    {
        $file_id = $this->input->post('id');
        $this->db->select('email');
        $this->db->where('id', $lead_id);
        $result = $this->db->get(db_prefix() . 'leads')->row();
        $getemail = $result->email;
        $data = $this->Token_model->getToken();
        $get_id = array_column($data, 'token');
        $access_token = implode(',', $get_id);
        $data = $this->Contacts_model->getEmail($getemail);
        $get_id = array_column($data, 'id');
        $get_userid = array_column($data, 'userid');
        $get_firstname = array_column($data, 'firstname');
        $get_lastname = array_column($data, 'lastname');
        $dropbox_firstname = implode(',', $get_firstname);
        $dropbox_lastname = implode(',', $get_lastname);
        $get_id = implode(',', $get_id);
        $userid = implode(',', $get_userid);
        $leadData = $this->leads_model->get_lead_id($get_id);
        $user_id = $leadData->id;
        $user_name = $leadData->name;
        // get the files name
        $this->db->select('file_name');
        $this->db->where('id', $file_id);
        $delete_file_data = $this->db->get(db_prefix() . 'files')->row();
        $cleanedString = '';
        if ($delete_file_data) {
            $cleanedString = $delete_file_data->file_name;
        }
        // delete record from dropbox
        $imagePath = '/uploads/' . $user_id . '_' . $dropbox_firstname . "_" . $dropbox_lastname . '/' . $cleanedString;

        $responsedelete = $this->leads_model->deleteFile($access_token, $imagePath);
        if ($responsedelete === false) {
            $this->leads_model->add_errors_logs($lead_id, get_staff_user_id(), get_staff_full_name(), 'Image Delete function checklist_image_delete($lead_id)', 'Image Delete function checklist_image_delete($lead_id)', 400, 'Staff');
        }
        // get the task id
        $this->db->select('task_id,file_name');
        $this->db->where('id', $file_id);
        $get_the_task_id = $this->db->get(db_prefix() . 'files')->row();
        // delete file
        $this->db->where('id', $file_id);
        $delete_check = $this->db->delete(db_prefix() . 'files');
        // update the task record
        $task_update_data = array(
            'checkbox_status' => 0
        );
        $this->db->where('id', $get_the_task_id->task_id);
        $this->db->update(db_prefix() . 'tasks', $task_update_data);
        // redirect the tab of case
        $this->db->select('leads_status,name ,rel_id');
        $this->db->where('id', $get_the_task_id->task_id);
        $this->db->where('rel_type', 'user-task');
        $checklist_stage_details = $this->db->get(db_prefix() . 'tasks')->row();
        $leads_status = $checklist_stage_details->leads_status;
        // refresh the activity log
        $add_activity_data = [
            'leadid' => $lead_id,
            'staffid' => get_staff_user_id(),
            'full_name' => get_staff_full_name(),
            'description' => 'Document of (' . $checklist_stage_details->name . ') deleted by ' . get_staff_full_name() . ' .',
            'date' => date('Y-m-d H:i:s'),
        ];
        $this->db->insert(db_prefix() . 'lead_activity_log', $add_activity_data);
        switch ($leads_status) {
            case 1:
                $leads_status_value = '#file_opened';
                $complete_stage_button = 1;
                break;
            case 2:
                $leads_status_value = '#instructions_received';
                $complete_stage_button = 2;
                break;
            case 3:
                $leads_status_value = '#outstanding_items';
                $complete_stage_button = 3;
                break;
            case 4:
                $leads_status_value = '#request_for_funds';
                $complete_stage_button = 4;
                break;
            default:
                $leads_status_value = '';
                break;
        }

        $response = array(
            'success' => true,
            'status' => 'success',
            'message' => 'Tasks deleted successfully',
            'leads_status' => $leads_status_value,
            'complete_stage_buttonid' => $complete_stage_button,
            'id' => $lead_id,
            'leadView' => $this->_get_lead_data($lead_id),
        );
        $this->output
            ->set_content_type('application/json')
            ->set_output(json_encode($response));
    }
    // delete the request for funds images delete
    public function delete_cases_checkbox_file($lead_id)
    {
        $file_id = $this->input->post('file_id');
        $leads_status = $this->input->post('leads_status');
        $this->db->select('email');
        $this->db->where('id', $lead_id);
        $result = $this->db->get(db_prefix() . 'leads')->row();
        $getemail = $result->email;
        $data = $this->Token_model->getToken();
        $get_id = array_column($data, 'token');
        $access_token = implode(',', $get_id);
        $data = $this->Contacts_model->getEmail($getemail);
        $get_id = array_column($data, 'id');
        $get_userid = array_column($data, 'userid');
        $get_firstname = array_column($data, 'firstname');
        $get_lastname = array_column($data, 'lastname');
        $dropbox_firstname = implode(',', $get_firstname);
        $dropbox_lastname = implode(',', $get_lastname);
        $get_id = implode(',', $get_id);
        $userid = implode(',', $get_userid);
        $leadData = $this->leads_model->get_lead_id($get_id);
        $user_id = $leadData->id;
        $user_name = $leadData->name;
        // get the files name
        $this->db->select('file_name,cases_checkbox_id');
        $this->db->where('id', $file_id);
        $delete_file_data = $this->db->get(db_prefix() . 'cases_checkbox_files')->row();
        $cleanedString = '';
        if ($delete_file_data) {
            $cleanedString = $delete_file_data->file_name;
        }
        // get the item leads status id 
        $this->db->select('leads_status');
        $this->db->where('id', $delete_file_data->cases_checkbox_id);
        $case_checkbox_leads_status = $this->db->get(db_prefix() . 'cases_checkboxes')->row();
        // delete record from dropbox
        $imagePath = '/uploads/' . $user_id . '_' . $dropbox_firstname . "_" . $dropbox_lastname . '/' . $cleanedString;

        $responsedelete = $this->leads_model->deleteFile($access_token, $imagePath);
        // get the task id
        $this->db->select('cases_checkbox_id');
        $this->db->where('id', $file_id);
        $get_the_task_id = $this->db->get(db_prefix() . 'cases_checkbox_files')->row();
        // delete file
        $this->db->where('id', $file_id);
        $delete_check = $this->db->delete(db_prefix() . 'cases_checkbox_files');
        // update the task record
        $task_update_data = array(
            'status' => 0
        );
        $this->db->where('id', $get_the_task_id->cases_checkbox_id);
        $this->db->update(db_prefix() . 'tasks', $task_update_data);
        // get the items name for activitly logs
        $this->db->select('title');
        $this->db->where('id', $get_the_task_id->cases_checkbox_id);
        $get_item_name = $this->db->get(db_prefix() . 'cases_checkboxes')->row();
        // refresh the activity log
        $add_activity_data = [
            'leadid' => $lead_id,
            'staffid' => get_staff_user_id(),
            'full_name' => get_staff_full_name(),
            'description' => 'Document of (' . $get_item_name->title . ') has been deleted by ' . get_staff_full_name() . ' .',
            'date' => date('Y-m-d H:i:s'),
        ];
        $this->db->insert(db_prefix() . 'lead_activity_log', $add_activity_data);
        switch ($case_checkbox_leads_status->leads_status) {
            case 1:
                $leads_status_value = '#file_opened';
                $complete_stage_button = 1;
                break;
            case 2:
                $leads_status_value = '#instructions_received';
                $complete_stage_button = 2;
                break;
            case 3:
                $leads_status_value = '#outstanding_items';
                $complete_stage_button = 3;
                break;
            // secure payout and other items for outstnaing created by appointment leads status
            case 7:
                $leads_status_value = '#outstanding_items';
                $complete_stage_button = 3;
                break;
            case 4:
                $leads_status_value = '#request_for_funds';
                $complete_stage_button = 4;
                break;
            default:
                $leads_status_value = '';
                break;
        }

        $response = array(
            'success' => true,
            'status' => 'success',
            'message' => 'Tasks deleted successfully',
            'leads_status' => $leads_status_value,
            'complete_stage_buttonid' => $complete_stage_button,
            'id' => $lead_id,
            'leadView' => $this->_get_lead_data($lead_id),
        );
        $this->output
            ->set_content_type('application/json')
            ->set_output(json_encode($response));
    }
    // Remove Checklist
    public function delete_checklist_details($id)
    {
        // get the lead_id
        $this->db->select('leads_status, rel_id,name');
        $this->db->where('id', $id);
        $this->db->where('rel_type', 'user-task');
        $checklist_stage_details = $this->db->get(db_prefix() . 'tasks')->row();
        $leads_status = $checklist_stage_details->leads_status;
        $lead_id = $checklist_stage_details->rel_id;
        $task_name = $checklist_stage_details->name;

        $this->db->where('id', $id);
        $this->db->where('rel_type', 'user-task');
        $this->db->delete(db_prefix() . 'tasks');

        // Check if the deletion was successful
        if ($this->db->affected_rows() > 0) {
            // Deleted Record from file instrction
            $this->db->where('task_id', $id);
            $this->db->delete(db_prefix() . 'file_instruction');
            // Delete record from tblfiles
            $this->db->where('task_id', $id);
            $this->db->where('rel_type', 'client-doc');
            $this->db->delete(db_prefix() . 'files');
            $data = array(
                'task_id' => NULL
            );
            $this->db->where('lead_id', $lead_id);
            $this->db->where('task_id', $id);
            $this->db->update(db_prefix() . 'alerts', $data);

            // Deletion was successful
            $insert_task_activity = array(
                'leadid' => $lead_id,
                'task_id' => $id,
                'staffid' => get_staff_user_id(),
                'full_name' => get_staff_full_name(),
                'activity_type' => 'task-activity',
                'description' => "Checklist (" . $task_name . ") has been deleted successfully.",
                'date' => date('Y-m-d H:i:s'),
            );
            leads_activity_log($this, $insert_task_activity);
            // refresh the activity log
            switch ($leads_status) {
                case 1:
                    $leads_status_value = '#file_opened';
                    $complete_stage_button = 1;
                    break;
                case 2:
                    $leads_status_value = '#instructions_received';
                    $complete_stage_button = 2;
                    break;
                case 3:
                    $leads_status_value = '#outstanding_items';
                    $complete_stage_button = 3;
                    break;
                case 4:
                    $leads_status_value = '#request_for_funds';
                    $complete_stage_button = 4;
                    break;
                default:
                    $leads_status_value = '';
                    break;
            }

            $response = array(
                'success' => true,
                'status' => 'success',
                'message' => 'Tasks deleted successfully',
                'leads_status' => $leads_status_value,
                'complete_stage_buttonid' => $complete_stage_button,
                'id' => $lead_id,
                'leadView' => $this->_get_lead_data($lead_id),
            );
            $this->output
                ->set_content_type('application/json')
                ->set_output(json_encode($response));
        } else {
            $response = array(
                'status' => 'error',
                'message' => 'No tasks found for deletion'
            );
            echo json_encode($response);
            exit();
        }
    }
    // Delete the bulk checklist items 
    public function delete_bulk_checklist($lead_id)
    {
        $items = $this->input->post('items');
        $item_title = '';

        if (!is_array($items) || empty($items)) {
            echo json_encode(['status' => false, 'message' => 'No items selected.']);
            return;
        }

        foreach ($items as $item) {
            if (!isset($item['id'])) {
                continue;
            }

            $id = (int) $item['id'];
            $type = strtolower(trim($item['type']));

            if ($type === 'client' || $type === 'broker') {
                $task_data = get_task_name_by_task_id($this, $id);
                $item_title = $task_data->name;

                $this->db->where('id', $id);
                $this->db->delete(db_prefix() . 'tasks');
            } else {
                $cases_checkboxes_data = get_cases_checkbox_by_id($this, $id);
                $item_title = $cases_checkboxes_data->title;

                $this->db->where('id', $id);
                $this->db->delete(db_prefix() . 'cases_checkboxes');
            }

            $insert_task_activity = array(
                'leadid' => $lead_id,
                'task_id' => '',
                'staffid' => get_staff_user_id(),
                'full_name' => get_staff_full_name(),
                'activity_type' => '',
                'description' => 'Items (' . $item_title . ') has been deleted by ' . get_staff_full_name() . '.',
                'additional_data' => '',
                'reason' => '',
                'date' => date('Y-m-d H:i:s'),
            );
            leads_activity_log($this, $insert_task_activity);
        }

        echo json_encode(['status' => true, 'message' => 'Selected items deleted successfully.']);
    }

    // get the checklist using id
    public function get_checklist_details_by_id($lead_id)
    {
        $checklist_id = $this->input->get('checklistId');
        $this->db->select('name,ld_notes,leads_status,type');
        $this->db->where('id', $checklist_id);
        $checklist_data = $this->db->get(db_prefix() . 'tasks')->row();
        if (!empty($checklist_data)) {
            $response = array(
                'success' => true,
                'name' => $checklist_data->name,
                'notes' => str_replace(["\n", '<br>', '<br/>', '<br />'], '<br>', $checklist_data->ld_notes),
                'leads_status' => $checklist_data->leads_status,
                'type' => $checklist_data->type,
                'id' => $checklist_id,
            );
        } else {
            $response = array(
                'success' => false,
            );
        }
        $this->output
            ->set_content_type('application/json')
            ->set_output(json_encode($response));
    }
    // get the ld checklist details using id
    public function get_ld_checklist_details_by_id($lead_id)
    {
        $checklist_id = $this->input->get('checklistId');
        $this->db->select('title,description,leads_status,req_comments');
        $this->db->where('id', $checklist_id);
        $checklist_data = $this->db->get(db_prefix() . 'cases_checkboxes')->row();
        // get the all files of ld checklist
        $this->db->select('id,filetype,file_url,lender_name,payout_expire_date');
        $this->db->where('cases_checkbox_id', $checklist_id);
        $get_all_file_data = $this->db->get(db_prefix() . 'cases_checkbox_files')->result_array();
        // get the all lenders name
        $this->db->select('id,bank_name');
        $lender_data = $this->db->get(db_prefix() . 'bank')->result_array();
        if (!empty($checklist_data)) {
            $response = array(
                'success' => true,
                'name' => $checklist_data->title,
                'req_comments' => $checklist_data->req_comments,
                'notes' => str_replace(["\n", '<br>', '<br/>', '<br />'], '<br>', $checklist_data->description),
                'leads_status' => $checklist_data->leads_status,
                'files_data' => $get_all_file_data,
                'lender_data' => $lender_data,
            );
        } else {
            $response = array(
                'success' => false,
            );
        }
        $this->output
            ->set_content_type('application/json')
            ->set_output(json_encode($response));
    }
    // update the record of checklsit by id
    public function update_checklist_item_by_id($lead_id)
    {
        $checklist_id = $this->input->post('client_checklist_id');
        $notes = $this->input->post('update_item_notes');
        $checklist_name = $this->input->post('update_item_name');
        // update record and checklist live
        $data = array(
            'name' => $checklist_name,
            'ld_notes' => str_replace(['<br />', '<br>', '<br/>'], "\n", nl2br($notes))
        );
        $this->db->where('id', $checklist_id);
        $this->db->update(db_prefix() . 'tasks', $data);
        if ($this->db->affected_rows() > 0) {
            $insert_task_activity = array(
                'leadid' => $lead_id,
                'staffid' => get_staff_user_id(),
                'full_name' => get_staff_full_name(),
                'description' => 'Item (' . $checklist_name . ') details updated by ' . get_staff_full_name(),
                'date' => date('Y-m-d H:i:s'),
            );
            leads_activity_log($this, $insert_task_activity);
            // pass the response
            // get the updated stage checklist 
            $this->db->select('leads_status');
            $this->db->where('id', $checklist_id);
            $get_task_status = $this->db->get(db_prefix() . 'tasks')->row();
            // update the last contact date 
            $this->leads_model->update_leads_last_contact_date($lead_id);
            switch ($get_task_status->leads_status) {
                case 1:
                    $leads_status_value = '#file_opened';
                    break;
                case 2:
                    $leads_status_value = '#instructions_received';
                    break;
                case 3:
                    $leads_status_value = '#outstanding_items';
                    break;
                case 4:
                    $leads_status_value = '#request_for_funds';
                    break;
                default:
                    $leads_status_value = '';
                    break;
            }

            $response = array(
                'success' => true,
                'leads_status' => $leads_status_value,
                'client_checklist_id' => $checklist_id,
                'client_checklist_name' => $checklist_name,
                'update_item_notes' => $data['ld_notes'],
                'id' => $lead_id,
                'leadView' => $this->_get_lead_data($lead_id),
            );
        } else {
            $response = array(
                'success' => false,
            );
        }
        $this->output
            ->set_content_type('application/json')
            ->set_output(json_encode($response));
    }
    // update the ld checklsit items using id
    public function update_ld_checklist_item_by_id($lead_id)
    {
        $checklist_id = $this->input->post('ld_checklist_id');
        $notes = $this->input->post('update_item_ld_notes');
        $checklist_name = $this->input->post('update_ld_item_name');
        $update_ld_req_comments = $this->input->post('update_ld_req_comments');
        $files_ids = $this->input->post('file_ids');
        // update record and checklist live
        $data = array(
            'title' => $checklist_name,
            'req_comments' => $update_ld_req_comments,
            'description' => str_replace(['<br />', '<br>', '<br/>'], "\n", nl2br($notes))
        );
        $this->db->where('id', $checklist_id);
        $this->db->update(db_prefix() . 'cases_checkboxes', $data);
        // update the record of all files 
        if ($files_ids && is_array($files_ids)) {
            foreach ($files_ids as $file_id) {
                // Prepare the data to be updated
                $cases_checkboxes_data = array(
                    'lender_name' => $this->input->post('lender_name_' . $file_id),
                    'payout_expire_date' => $this->input->post('payout_expire_time_' . $file_id)
                );
                // Update the record in the database
                $this->db->where('id', $file_id);
                $this->db->update(db_prefix() . 'cases_checkbox_files', $cases_checkboxes_data);
            }
        }
        if ($this->db->affected_rows() > 0) {
            $insert_task_activity = array(
                'leadid' => $lead_id,
                'staffid' => get_staff_user_id(),
                'full_name' => get_staff_full_name(),
                'description' => 'Item (' . $checklist_name . ') details updated by ' . get_staff_full_name(),
                'date' => date('Y-m-d H:i:s'),
            );
            leads_activity_log($this, $insert_task_activity);
            // pass the response
            // get the updated stage checklist 
            $this->db->select('leads_status');
            $this->db->where('id', $checklist_id);
            $get_task_status = $this->db->get(db_prefix() . 'cases_checkboxes')->row();
            // update the last contact date 
            $this->leads_model->update_leads_last_contact_date($lead_id);
            switch ($get_task_status->leads_status) {
                case 1:
                    $leads_status_value = '#file_opened';
                    break;
                case 2:
                    $leads_status_value = '#instructions_received';
                    break;
                case 3:
                    $leads_status_value = '#outstanding_items';
                    break;
                // secure payouts lead_status value is 7 and its show in the outstanding item stage
                case 7:
                    $leads_status_value = '#outstanding_items';
                    break;
                case 4:
                    $leads_status_value = '#request_for_funds';
                    break;
                default:
                    $leads_status_value = '';
                    break;
            }

            $response = array(
                'success' => true,
                'leads_status' => $leads_status_value,
                'id' => $lead_id,
                'ld_checklist_id' => $checklist_id,
                'update_item_ld_notes' => $notes,
                'update_ld_item_name' => $checklist_name,
                'update_ld_req_comments' => $update_ld_req_comments,
                'leadView' => $this->_get_lead_data($lead_id),
            );
        } else {
            $response = array(
                'success' => false,
            );
        }
        $this->output
            ->set_content_type('application/json')
            ->set_output(json_encode($response));
    }
    // update the item order details
    public function update_task_order($lead_id)
    {
        $task_order = $this->input->post('task_order');

        if (!empty($task_order)) {
            foreach ($task_order as $task) {
                if ($task['type'] == 'client' || $task['type'] == 'client-borrower' || $task['type'] == 'broker') {
                    $this->db->where('id', $task['id']);
                    $this->db->update(db_prefix() . 'tasks', [
                        // 'type' => $task['type'],      
                        'order_no' => $task['order']
                    ]);
                } else {
                    $this->db->where('id', $task['id']);
                    $this->db->update(db_prefix() . 'cases_checkboxes', [
                        // 'type' => $task['type'],      
                        'order_no' => $task['order']
                    ]);
                }
            }
            echo json_encode(['status' => 'success']);
        } else {
            echo json_encode(['status' => 'error', 'message' => 'Invalid input']);
        }
    }

    // get all the record of checklist
    public function checklistrecord($lead_id, $task_id)
    {
        $this->db->select('assign_group');
        $this->db->where('id', $lead_id);
        $lead_data = $this->db->get(db_prefix() . 'leads')->row();
        $staff_group_name = get_group_name_of_staff($this, get_staff_user_id());
        // get the checklsit/task data
        $this->db->select('name,description');
        $this->db->where('id', $task_id);
        $this->db->where('rel_type', 'user-task');
        $task_data = $this->db->get(db_prefix() . 'tasks')->row();
        // get the file instruction dat
        $this->db->select('instruction,doc_type');
        $this->db->where('task_id', $task_id);
        $this->db->where('lead_id', $lead_id);
        $file_instruction_data = $this->db->get(db_prefix() . 'file_instruction')->row();
        // get the id of doc_type
        $doc_array = ['Png' => 1, 'Pdf' => 2, 'Jpeg' => 3, 'Zip' => 4, 'HEIC' => 5];
        $file_instructions = explode(',', $file_instruction_data->doc_type);
        $matched_ids = [];

        foreach ($file_instructions as $instruction) {
            $file_type = ucfirst(trim($instruction));
            if (isset($doc_array[$file_type])) {
                $matched_ids[] = $doc_array[$file_type];
            }
        }
        // Convert the array to a comma-separated string
        $instructionLines = explode("\n", $file_instruction_data->instruction);
        $trimmedLines = [];

        foreach ($instructionLines as $line) {
            $trimmedLine = trim($line);

            if ($trimmedLine !== "") {
                $trimmedLines[] = $trimmedLine;
            }
        }
        $valueProcessed = str_replace("\n\n", "\n", $file_instruction_data->instruction);
        $cleanedText = str_replace(["\n", '<br>', '<br/>', '<br />'], '<br>', $file_instruction_data->instruction);

        // Combine the lines into a single string without line breaks
        $instructionHtml = implode('<br>', $trimmedLines);
        $matched_ids_string = implode(',', $matched_ids);
        // get the checklist item name
        // get the item type ids
        $get_item_name_id = $task_data->Item_name;
        $item_name_array = explode(',', $get_item_name_id);
        $item_name_array = array_map('intval', $item_name_array);

        $data['task_id'] = $task_id;
        $data['lead_id'] = $lead_id;
        $data['samegroup'] = case_crud_permissions_by_role($this, $lead_data->assign_group, $staff_group_name);
        $data['name'] = $task_data->name;
        $data['description'] = $task_data->description;
        $data['doc_type'] = $matched_ids;
        $data['get_item_name_id'] = $item_name_array;
        $data['instruction'] = $cleanedText;
        $this->load->view('admin/checklist/checklistshow', ['data' => $data]);
    }
    // complete stage button visibility
    public function stage_complete_button_visibility($leadId)
    {
        // get the all status of checklist is approved or not
        $this->db->select('status');
        $this->db->where('rel_id', $leadId);
        $this->db->where('rel_type', 'user-task');
        $this->db->where('type', 'client');
        $this->db->where('leads_status', 1);
        $complete_stage_query = $this->db->get(db_prefix() . 'tasks');
        //  all_statuses_equal_to_4 it means all stages is approved 
        $file_opened_complete_stage_button = true;

        foreach ($complete_stage_query->result() as $row) {
            if ($row->status != 4) {
                $file_opened_complete_stage_button = false;
                break;
            }
        }
        $response = array(
            'success' => true,
            'file_opened_complete_stage_button' => $file_opened_complete_stage_button,
        );
        $this->output
            ->set_content_type('application/json')
            ->set_output(json_encode($response));
    }
    // DL-Check status  change code 
    public function dl_checklist_updateStatus()
    {
        $task_id = $this->input->post('task_id');
        $newStatus = $this->input->post('newStatus');
        $lead_id = $this->input->post('lead_id');
        $leads_status_value = '#file_opened';
        if (!empty($task_id)) {
            $task_updated_data = array(
                'status' => $newStatus,
                'rejection_reason' => ''
            );
            $this->db->where('id', $task_id);
            $this->db->update(db_prefix() . 'tasks', $task_updated_data);
            // check status is update or not
            if ($this->db->affected_rows() > 0) {
                // generate response
                $response = array(
                    'success' => true,
                    'leads_status_value' => $leads_status_value,
                );
            } else {
                // generate response
                $response = array(
                    'success' => false,
                    'leads_status_value' => $leads_status_value,
                );
            }
        } else {
            $response = array(
                'success' => false,
                'message' => 'Task ID or new status is missing.',
                'leads_status_value' => $leads_status_value,
            );
        }
        // update the last contact date 
        $this->leads_model->update_leads_last_contact_date($lead_id);

        $this->output
            ->set_content_type('application/json')
            ->set_output(json_encode($response));
    }
    // broker fee agreement check
    private function broker_fee_na_check($lead_id, $task_id, $broker_fee_na)
    {
        // $task_id = $this->input->post('task_id');
        // $broker_fee_na = $this->input->post('broker_fee_na');

        if ($task_id !== null && $task_id !== '') {

            $record_updated = $this->leads_model->update_broker_fee_na($task_id, $broker_fee_na);

            if ($record_updated) {
                $insert_task_activity = array(
                    'leadid' => $lead_id,
                    'staffid' => get_staff_user_id(),
                    'full_name' => get_staff_full_name(),
                    'description' => "Broker Fee N/A has been updated by " . get_staff_full_name() . ".",
                    'date' => date('Y-m-d H:i:s'),
                );
                leads_activity_log($this, $insert_task_activity);

                // echo json_encode([
                //     'success' => true,
                //     'message' => 'Broker Fee N/A updated successfully.'
                // ]);
                // return;
            }
            // else{
            //     echo json_encode([
            //         'success' => false,
            //         'message' => 'Update failed or no changes were made.'
            //     ]);
            //     return;
            // }

        }
        // else{
        //     echo json_encode([
        //         'success' => false,
        //         'message' => 'Invalid task ID provided.'
        //     ]);
        //     return;
        // }
    }
    // bulk update the checklist items details
    public function update_bulk_checklist_status($leadId)
    {
        $items = $this->input->post('items');
        $status = $this->input->post('status');
        if (!is_array($items) || empty($items) || !$status) {
            echo json_encode(['status' => false, 'message' => 'Invalid input or no status provided.']);
            return;
        }

        foreach ($items as $item) {
            if (!isset($item['id']) || !isset($item['type'])) {
                continue; // Skip invalid
            }

            $task_id = (int) $item['id'];
            $type = strtolower(trim($item['type']));

            if ($type === 'client' || $type === 'broker') {
                $this->db->where('id', $task_id);
                $this->db->update(db_prefix() . 'tasks', ['status' => $status]);


                // // get the title of checklist/task 
                $this->db->select('name,type,leads_status,type,status');
                $this->db->where('id', $task_id);
                $task_query_file = $this->db->get(db_prefix() . 'tasks')->row();
                $get_task_name = $task_query_file->name;
                $get_task_type = $task_query_file->type;
                $get_task_leads_status = $task_query_file->leads_status;
                $newStatus = $task_query_file->status;

                // if broker fee N/A option select
                if ($newStatus == 6) {
                    $this->broker_fee_na_check($leadId, $task_id, 1);
                } else {
                    $this->broker_fee_na_check($leadId, $task_id, 0);
                }
                if ($status == 3 || $status == 'Rejected') {
                    // file intsturciotn 
                    if ($get_task_leads_status == 1) {
                        $file_instruction_data = array(
                            'instruction' =>
                            'Please ensure the IDs show ALL edges, are CLEAR, have no flash spots, and are valid (NOT expired).' . "\n\r" .
                                'Your item has been rejected for the reason mentioned below. Please use the edit button in the top right and then the submit button below, to resend your updated ID.' . "\n\r"
                        );
                    }
                    if ($get_task_leads_status == 3) {
                        $file_instruction_data = array(
                            'instruction' =>
                            'Please use the buttons below to upload your item ensuring there are no flash spots, the picture is clear and the item is valid.' . "\n\r" .
                                'Your item has been rejected for the reason mentioned below. Please use the edit button in the top right and then the submit button below, to resend your updated ID.' . "\n\r"
                        );
                    }
                    $this->db->where('task_id', $task_id);
                    $this->db->where('lead_id', $leadId);
                    $this->db->update(db_prefix() . 'file_instruction', $file_instruction_data);
                }
                // Fetch the updated row
                // get status value for use in add activity log 
                $item_status_name = return_item_status_for_app_side($newStatus);
                // add activity log
                $this->db->select('*');
                $this->db->from(db_prefix() . 'lead_activity_log');
                $this->db->where('task_id', $task_id);
                $this->db->where('activity_type', 'task-activity');
                $this->db->order_by('date', 'desc');
                $this->db->limit(1);
                $query = $this->db->get();
                $latest_record = $query->row();
                if ($latest_record->additional_data == $item_status_name) {
                    $update_task_activity = array(
                        'leadid' => $leadId,
                        'task_id' => $task_id,
                        'staffid' => get_staff_user_id(),
                        'full_name' => get_staff_full_name(),
                        'activity_type' => 'task-activity',
                        'description' => 'Document has been ' . $item_status_name . ' by ' . get_staff_full_name() . '.',
                        'additional_data' => $item_status_name,
                        'date' => date('Y-m-d H:i:s'),
                    );
                    $this->db->where('task_id', $task_id);
                    $this->db->where('id', $latest_record->id);
                    $this->db->update(db_prefix() . 'lead_activity_log', $update_task_activity);
                } else {
                    if ($newStatus == 3) {
                        $statusChangeReason = isset($statusChangeReason) ? $statusChangeReason : '';
                        $description = $statusChangeReason . ' by ' . get_staff_full_name() . '.';
                    } else {
                        $description = 'Document has been ' . $item_status_name . ' by ' . get_staff_full_name() . '.';
                    }
                    $insert_task_activity = array(
                        'leadid' => $leadId,
                        'task_id' => $task_id,
                        'staffid' => get_staff_user_id(),
                        'full_name' => get_staff_full_name(),
                        'activity_type' => 'task-activity',
                        'description' => $description,
                        'additional_data' => $item_status_name,
                        'reason' => $statusChangeReason,
                        'date' => date('Y-m-d H:i:s'),
                    );
                    leads_activity_log($this, $insert_task_activity);
                }
                if($type === 'client'){
                    // notification push code 
                    $this->db->select('multiple_cases,client_id,phonenumber,name,email');
                    $this->db->where('id', $leadId);
                    $lead_data_check = $this->db->get(db_prefix() . 'leads');
                    if ($lead_data_check->num_rows() > 0) {
                        $lead_data = $lead_data_check->row();
                        $client_id = get_client_id_using_contact_id($this, $lead_data->client_id, $lead_data->multiple_cases);
                        $contact_id = get_contact_id_using_client_id($this, $client_id);
                        $notification_type = get_notification_type(2);
                        $client_notify_type = $notification_type . '-updated';
                        $client_notify_title = 'Checklist updated';
                        $client_notify_message = 'Document of checklist Item (' . $get_task_name . ') has been ' . $item_status_name . ' by ' . get_staff_full_name() . '.';
                        send_notification_in_mobile('client', get_staff_user_id(), $contact_id, $client_id, $leadId, $client_notify_title, $client_notify_message, $client_notify_type, $task_id);
                    }
                }
            } else {
                $this->db->where('id', $task_id);
                $this->db->update(db_prefix() . 'cases_checkboxes', ['secure_received_option' => $status]);
            }
        }

        echo json_encode(['success' => true, 'message' => 'Statuses updated successfully.']);
    }


    // change status of checklist 
    public function checklist_updateStatus()
    {
        $leadId = $this->input->post('lead_id');
        $task_id = $this->input->post('task_id');
        $newStatus = $this->input->post('newStatus');
        $statusChangeReason = $this->input->post('rejectionReason');
        $get_mail_subject = get_mail_subject($this, $leadId);
        // get the title of checklist/task 
        $this->db->select('name,type,leads_status,type');
        $this->db->where('id', $task_id);
        $task_query_file = $this->db->get(db_prefix() . 'tasks')->row();
        $get_task_name = $task_query_file->name;
        $get_task_type = $task_query_file->type;
        $get_task_leads_status = $task_query_file->leads_status;
        // get the files data
        $this->db->where('task_id', $task_id);
        $this->db->where('rel_id', $leadId);
        $this->db->where('rel_type', 'client-doc');
        $query_files = $this->db->get(db_prefix() . 'files')->row();
        if ((!empty($query_files) && get_current_staff_role($this, get_staff_user_id()) != 2) || get_current_staff_role($this, get_staff_user_id()) != 6) {
            if ($newStatus == 4 || $newStatus == 'Approved') {
                $task_updated_data = array(
                    'status' => $newStatus,
                    'checkbox_status' => '1',
                    'rejection_reason' => ''
                );
            } elseif ($newStatus == 3 || $newStatus == 'Rejected') {
                $task_updated_data = array(
                    'status' => $newStatus,
                    'checkbox_status' => '0',
                    'rejection_reason' => $statusChangeReason
                );
            } else {
                $task_updated_data = array(
                    'status' => $newStatus,
                    'rejection_reason' => ''
                );
            }
            // update status

            // if ($newStatus != 2 || $get_task_type == 'broker') {
            // Update DL checklist status
            if ($newStatus || $get_task_type == 'broker') {
                // $statusChangeReason = $this->input->post('rejectionReason');
                // if ($newStatus == 3 || $newStatus == 'Rejected') {
                //     $task_updated_data['rejection_reason'] = $statusChangeReason;
                // }else{
                //     $task_updated_data['rejection_reason'] = '';
                // }
                // update the insturciton when item is rejected show in app side
                $this->db->where('id', $task_id);
                $this->db->where('rel_id', $leadId);
                $this->db->where('rel_type', 'user-task');
                $this->db->update(db_prefix() . 'tasks', $task_updated_data);
                // if broker fee N/A option select
                if ($newStatus == 6) {
                    $this->broker_fee_na_check($leadId, $task_id, 1);
                } else {
                    $this->broker_fee_na_check($leadId, $task_id, 0);
                }
                if ($newStatus == 3 || $newStatus == 'Rejected') {
                    // file intsturciotn 
                    if ($get_task_leads_status == 1) {
                        $file_instruction_data = array(
                            'instruction' =>
                            'Please ensure the IDs show ALL edges, are CLEAR, have no flash spots, and are valid (NOT expired).' . "\n\r" .
                                'Your item has been rejected for the reason mentioned below. Please use the edit button in the top right and then the submit button below, to resend your updated ID.' . "\n\r"
                        );
                    }
                    if ($get_task_leads_status == 3) {
                        $file_instruction_data = array(
                            'instruction' =>
                            'Please use the buttons below to upload your item ensuring there are no flash spots, the picture is clear and the item is valid.' . "\n\r" .
                                'Your item has been rejected for the reason mentioned below. Please use the edit button in the top right and then the submit button below, to resend your updated ID.' . "\n\r"
                        );
                    }
                    $this->db->where('task_id', $task_id);
                    $this->db->where('lead_id', $leadId);
                    $this->db->update(db_prefix() . 'file_instruction', $file_instruction_data);
                }
                // Fetch the updated row
                $this->db->where('id', $task_id);
                $this->db->where('rel_id', $leadId);
                $this->db->where('rel_type', 'user-task');
                $query = $this->db->get(db_prefix() . 'tasks');
                $task_updated_row = $query->row();
                $leads_status = $task_updated_row->leads_status;
                // get the all status of checklist is approved or not
                $this->db->select('status');
                $this->db->where('rel_id', $leadId);
                $this->db->where('rel_type', 'user-task');
                $this->db->where('type', 'client');
                $this->db->where('leads_status', 1);
                $complete_stage_query = $this->db->get(db_prefix() . 'tasks');
                //  all_statuses_equal_to_4 it means all stages is approved 
                $all_statuses_equal_to_4 = true;

                foreach ($complete_stage_query->result() as $row) {
                    if ($row->status != 4) {
                        $all_statuses_equal_to_4 = false;
                        break;
                    }
                }

                // get status value for use in add activity log 
                $status = '';
                switch ($newStatus) {
                    case 1:
                        $status = 'Pending Review';
                        break;
                    case 2:
                        $status = 'Outstanding';
                        break;
                    case 3:
                        $status = 'Rejected';
                        break;
                    case 4:
                        $status = 'Approved';
                        break;
                    case 5:
                        $status = 'Uploaded';
                        break;
                    case 6:
                        $status = 'N/A';
                        break;
                    default:
                        $status = '';
                        break;
                }
                // add activity log
                $this->db->select('*');
                $this->db->from(db_prefix() . 'lead_activity_log');
                $this->db->where('task_id', $task_id);
                $this->db->where('activity_type', 'task-activity');
                $this->db->order_by('date', 'desc');
                $this->db->limit(1);
                $query = $this->db->get();
                $latest_record = $query->row();
                if ($latest_record->additional_data == $status) {
                    $update_task_activity = array(
                        'leadid' => $leadId,
                        'task_id' => $task_id,
                        'staffid' => get_staff_user_id(),
                        'full_name' => get_staff_full_name(),
                        'activity_type' => 'task-activity',
                        'description' => 'Document has been ' . $status . ' by ' . get_staff_full_name() . '.',
                        'additional_data' => $status,
                        'date' => date('Y-m-d H:i:s'),
                    );
                    $this->db->where('task_id', $task_id);
                    $this->db->where('id', $latest_record->id);
                    $this->db->update(db_prefix() . 'lead_activity_log', $update_task_activity);
                } else {
                    if ($newStatus == 3) {
                        $statusChangeReason = isset($statusChangeReason) ? $statusChangeReason : '';
                        $description = $statusChangeReason . ' by ' . get_staff_full_name() . '.';
                    } else {
                        $description = 'Document has been ' . $status . ' by ' . get_staff_full_name() . '.';
                    }
                    $insert_task_activity = array(
                        'leadid' => $leadId,
                        'task_id' => $task_id,
                        'staffid' => get_staff_user_id(),
                        'full_name' => get_staff_full_name(),
                        'activity_type' => 'task-activity',
                        'description' => $description,
                        'additional_data' => $status,
                        'reason' => $statusChangeReason,
                        'date' => date('Y-m-d H:i:s'),
                    );
                    leads_activity_log($this, $insert_task_activity);
                }
                // notificaation line of code 
                $this->db->select('id,multiple_cases,client_id,addedfrom');
                $this->db->where('id', $leadId);
                $lead_data_check = $this->db->get(db_prefix() . 'leads');
                if ($lead_data_check->num_rows() > 0) {
                    $lead_data = $lead_data_check->row();
                    $client_id = get_client_id_using_contact_id($this, $lead_data->client_id, $lead_data->multiple_cases);
                    // get the title of checklist/task 
                    $contact_id = get_contact_id_using_client_id($this, $client_id);
                    $notification_type = get_notification_type(2);
                    // send notification for the client when checklist status update
                    $this->db->select('type');
                    $this->db->where('id', $task_id);
                    $get_task_type = $this->db->get(db_prefix() . 'tasks')->row();
                    if ($get_task_type->type != 'broker') {
                        $client_notify_type = $notification_type . '-' . strtolower($status);
                        $client_notify_title = 'Checklist item status updated';
                        $client_notify_message = 'Checklist item (' . $get_task_name . ') has been ' . strtolower($status) . '.';
                        send_notification_in_mobile('client', get_staff_user_id(), $contact_id, $client_id, $leadId, $client_notify_title, $client_notify_message, $client_notify_type, $task_id, '', 'client');

                        // send  notiication in crm to all the team group member and staff
                        $this->db->select('assign_group,assigned');
                        $this->db->where('id', $leadId);
                        $lead_data_for_get_assign_group = $this->db->get(db_prefix() . 'leads')->row();
                        $current_staff_data = get_staff_ids_by_group($this, $lead_data_for_get_assign_group->assign_group);
                        foreach ($current_staff_data as $staff_notifiy_data) {
                            if (get_staff_user_id() != $staff_notifiy_data['staffid']) {
                                $ldteam_notify_type = $notification_type . '-' . strtolower($status);
                                $ld_team_notify_title = 'Checklist item status updated';
                                $ld_team_notify_message = 'Checklist item (' . $get_task_name . ') has been ' . strtolower($status) . '.';
                                // send notification to the crm
                                $this->leads_model->custom_lead_assigned_member_notification('staff', $leadId, $staff_notifiy_data['staffid'], get_staff_user_id(), '', 'Checklist item (' . $get_task_name . ') has been ' . strtolower($status) . '.');
                            }
                        }
                        // get the all admin staff ids
                        $admin_ids = get_all_admin_role_staff_ids($this);
                        foreach ($admin_ids as $admin_email) {
                            if (get_staff_user_id() != $admin_email['staffid']) {
                                $admin_notify_type = $notification_type . '-' . strtolower($status);
                                $admin_notify_title = 'Checklist item status updated';
                                $admin_notify_message = 'Checklist item (' . $get_task_name . ') has been ' . strtolower($status) . '.';
                                // send notification in crm
                                $this->leads_model->custom_lead_assigned_member_notification('staff', $leadId, $admin_email['staffid'], get_staff_user_id(), '', 'Checklist item (' . $get_task_name . ') has been ' . strtolower($status) . '.');
                            }
                        }
                    }
                    // send mail to the broker for approved/rejected status
                    if ($newStatus == 2 || $newStatus == 3 || $newStatus == 4) {
                        $broker_data = get_multiple_broker_details_using_addedfrom($this, $lead_data->addedfrom);
                        $get_client_name = get_client_name_using_taskid($this, $task_id, $leadId);
                        if ($newStatus == 3) {
                            $statusChangeReason = isset($statusChangeReason) ? $statusChangeReason : '';
                            $_POST['email_details_texting'] = 'Document of Client (' . $get_client_name['name'] . ') item (' . $get_task_name . ') has been Rejected' . ':' . $statusChangeReason;
                            $_POST['checklist_item_status'] = $newStatus;
                        } else {
                            $_POST['email_details_texting'] = 'Document of Client (' . $get_client_name['name'] . ') item (' . $get_task_name . ').';
                            $_POST['checklist_item_status'] = $newStatus;
                        }
                        $_POST['case_url'] = admin_url('cases/index/') . $leadId;
                        $subject = $get_mail_subject;
                        $replay_to_mail = get_all_staff_to_replay_email($this, get_staff_user_id(), $lead_data_for_get_assign_group->assign_group);
                        $html_content_confirmation_email_to_broker = $this->load->view('admin/leads/Email_template/broker/checklist_status_update', $_POST, TRUE);
                        // Send email to each broker
                        if (!empty($broker_data)) {
                            foreach ($broker_data as $broker) {
                                $_POST['broker_name'] = $broker['firstname'] . ' ' . $broker['lastname'];
                                // send_mailchimp_email($broker['email'], $subject, $html_content_confirmation_email_to_broker, $replay_to_mail, '', '', $lead_id);
                                $this->leads_model->custom_lead_assigned_member_notification('staff', $leadId, $broker['staffid'], get_staff_user_id(), '', 'Checklist item (' . $get_task_name . ') has been ' . strtolower($status) . '.');
                            }
                            // send the all admin notification and email to the admin broker
                            $brokerage_id = get_brokerage_id_using_leadid($this, $leadId);
                            $admin_broker_ids = get_all_admin_broker_role_staff_ids($this, $brokerage_id);
                            foreach ($admin_broker_ids as $admin_broker_email) {
                                if (get_staff_user_id() != $admin_broker_email['staffid'] && !in_array($admin_broker_email['staffid'], explode(',', $lead_data->addedfrom))) {
                                    $_POST['broker_name'] = $admin_broker_email['firstname'] . ' ' . $admin_broker_email['lastname'];
                                    // send_mailchimp_email($admin_broker_email['email'], $subject, $html_content_confirmation_email_to_broker, $replay_to_mail, '', '', $lead_id);
                                    $this->leads_model->custom_lead_assigned_member_notification('staff', $leadId, $admin_broker_email['staffid'], get_staff_user_id(), '', 'Checklist item (' . $get_task_name . ') has been ' . strtolower($status) . '.');
                                }
                            }
                        }
                    }
                }

                // echo true;
                switch ($leads_status) {
                    case 1:
                        $leads_status_value = '#file_opened';
                        $complete_stage_button = 1;
                        break;
                    case 2:
                        $leads_status_value = '#instructions_received';
                        $complete_stage_button = 2;
                        break;
                    case 3:
                        $leads_status_value = '#outstanding_items';
                        $complete_stage_button = 3;
                        break;
                    case 4:
                        $leads_status_value = '#request_for_funds';
                        $complete_stage_button = 4;
                        break;
                    default:
                        $leads_status_value = '';
                        break;
                }

                $response = array(
                    'success' => true,
                    'leads_status' => $leads_status_value,
                    'complete_stage_buttonid' => $complete_stage_button,
                    'all_statuses_equal_to_4' => $all_statuses_equal_to_4,
                    'id' => $leadId,
                    'leadView' => $this->_get_lead_data($leadId),
                );
            } else {
                // Fetch the updated row
                $this->db->select('leads_status');
                $this->db->where('id', $task_id);
                $this->db->where('rel_id', $leadId);
                $this->db->where('rel_type', 'user-task');
                $query = $this->db->get(db_prefix() . 'tasks');
                $task_updated_row = $query->row();
                $leads_status = $task_updated_row->leads_status;
                // echo true;
                switch ($leads_status) {
                    case 1:
                        $leads_status_value = '#file_opened';
                        $complete_stage_button = 1;
                        break;
                    case 2:
                        $leads_status_value = '#instructions_received';
                        $complete_stage_button = 2;
                        break;
                    case 3:
                        $leads_status_value = '#outstanding_items';
                        $complete_stage_button = 3;
                        break;
                    case 4:
                        $leads_status_value = '#request_for_funds';
                        $complete_stage_button = 4;
                        break;
                    default:
                        $leads_status_value = '';
                        break;
                }

                $response = array(
                    'success' => false,
                    'leads_status' => $leads_status_value,
                    'complete_stage_buttonid' => $complete_stage_button,
                    'newstatus' => $newStatus,
                    'id' => $leadId,
                    'leadView' => $this->_get_lead_data($leadId),
                );
            }
        } else {
            // Fetch the updated row
            $this->db->select('leads_status');
            $this->db->where('id', $task_id);
            $this->db->where('rel_id', $leadId);
            $this->db->where('rel_type', 'user-task');
            $query = $this->db->get(db_prefix() . 'tasks');
            $task_updated_row = $query->row();
            $leads_status = $task_updated_row->leads_status;
            switch ($leads_status) {
                case 1:
                    $leads_status_value = '#file_opened';
                    $complete_stage_button = 1;
                    break;
                case 2:
                    $leads_status_value = '#instructions_received';
                    $complete_stage_button = 2;
                    break;
                case 3:
                    $leads_status_value = '#outstanding_items';
                    $complete_stage_button = 3;
                    break;
                case 4:
                    $leads_status_value = '#request_for_funds';
                    $complete_stage_button = 4;
                    break;
                default:
                    $leads_status_value = '';
                    break;
            }
            // 
            $response = array(
                'success' => false,
                'leads_status' => $leads_status_value,
                'complete_stage_buttonid' => $complete_stage_button,
                'id' => $leadId,
                'leadView' => $this->_get_lead_data($leadId),
            );
        }
        // update the last contact date 
        $this->leads_model->update_leads_last_contact_date($leadId);
        $this->output
            ->set_content_type('application/json')
            ->set_output(json_encode($response));
    }
    // move case in on hold
    public function move_to_on_hold()
    {
        $on_hold_reason = $this->input->post('holdReason');
        $lead_id = $this->input->post('lead_id');
        // get the status id using lead id
        $stages_before_on_hold = get_current_stage_of_lead_status($this, $lead_id);
        $update_data = array(
            'on_hold_reason' => $on_hold_reason,
            'status' => 6,
            'stages_before_on_hold' => $stages_before_on_hold,
            'active_case' => 'Closed'
        );
        $this->db->where('id', $lead_id);
        $this->db->update(db_prefix() . 'leads', $update_data);
        $insert_task_activity = array(
            'leadid' => $lead_id,
            'staffid' => get_staff_user_id(),
            'full_name' => get_staff_full_name(),
            'description' => $on_hold_reason . ' - Case moved to On Hold by ' . get_staff_full_name(),
            'date' => date('Y-m-d H:i:s'),
        );
        leads_activity_log($this, $insert_task_activity);
        $response = array(
            'success' => true,
            'leads_status' => '#on_hold',
            'id' => $lead_id,
            'leadView' => $this->_get_lead_data($lead_id),
        );
        $this->output
            ->set_content_type('application/json')
            ->set_output(json_encode($response));
    }
    // get the summery for file opened
    public function get_summery_task_for_file_opened($lead_id)
    {
        $this->db->select('id,checkbox_status, name, description, status');
        $this->db->where('rel_id', $lead_id);
        $this->db->where('rel_type', 'user-task');
        $this->db->where('type', 'client');
        $this->db->where('leads_status', 1);
        $summery_data = $this->db->get(db_prefix() . 'tasks')->result_array();
        if (!empty($summery_data)) {
            $this->output
                ->set_content_type('application/json')
                ->set_output(json_encode($summery_data));
        } else {
            $this->output
                ->set_content_type('application/json')
                ->set_output(json_encode($summery_data));
        }
    }
    public function get_summery_task_for_file_opened_for_broker($lead_id)
    {
        $this->db->select('id,checkbox_status, name, description, status');
        $this->db->where('rel_id', $lead_id);
        $this->db->where('rel_type', 'user-task');
        $this->db->where('type', 'broker');
        $this->db->where('leads_status', 1);
        $summery_data = $this->db->get(db_prefix() . 'tasks')->result_array();
        if (!empty($summery_data)) {
            $this->output
                ->set_content_type('application/json')
                ->set_output(json_encode($summery_data));
        } else {
            $this->output
                ->set_content_type('application/json')
                ->set_output(json_encode($summery_data));
        }
    }
    // get the status and completed time for file opened summery
    public function get_summery_task_for_file_opened_status($lead_id)
    {
        $this->db->select('status,file_opened_started_at,file_opened_completed_at,file_opened_completed');
        $this->db->where('id', $lead_id);
        $get_summery_status_data = $this->db->get(db_prefix() . 'leads')->row();
        $response = array(
            'status' => $get_summery_status_data->status,
            'file_opened_completed' => $get_summery_status_data->file_opened_completed,
            'file_opened_completed_at' => $get_summery_status_data->file_opened_completed_at,
            'file_opened_started_at' => $get_summery_status_data->file_opened_started_at,
            'file_opened_started_at_get_day' => get_day($get_summery_status_data->file_opened_started_at),
            'file_opened_time' => get_day($get_summery_status_data->file_opened_completed_at),
        );
        if (!empty($get_summery_status_data)) {
            $this->output
                ->set_content_type('application/json')
                ->set_output(json_encode($response));
        } else {
            $this->output
                ->set_content_type('application/json')
                ->set_output(json_encode($response));
        }
    }
    // get the task uploaded files for file opened summery for client
    public function get_summery_task_for_file_opened_doc($lead_id)
    {
        // get all id of task table against the lead id
        $this->db->select('id');
        $this->db->where('rel_id', $lead_id);
        $this->db->where('rel_type', 'user-task');
        $this->db->where('type', 'client');
        $this->db->where('leads_status', 1);
        $summery_data = $this->db->get(db_prefix() . 'tasks')->result_array();
        $ids = array_column($summery_data, 'id');
        $comma_separated_ids = implode(',', $ids);
        // get all file of file opened
        if (!empty($ids)) {
            $this->db->select('files.file_url, files.dateadded, files.filetype, files.file_name, tasks.name as task_name');
            $this->db->from(db_prefix() . 'files');
            $this->db->join(db_prefix() . 'tasks', 'tasks.id = files.task_id');
            $this->db->where_in('files.task_id', $ids);
            $this->db->where('files.rel_id', $lead_id);
            $this->db->where('files.rel_type', 'client-doc');
            $files_data = $this->db->get()->result_array();
        }
        if (!empty($files_data)) {
            $this->output
                ->set_content_type('application/json')
                ->set_output(json_encode($files_data));
        } else {
            $this->output
                ->set_content_type('application/json')
                ->set_output(json_encode($files_data));
        }
    }
    // get the task uploaded files for file opened summery for broker
    public function get_summery_task_for_file_opened_doc_for_broker($lead_id)
    {
        // get all id of task table against the lead id
        $this->db->select('id');
        $this->db->where('rel_id', $lead_id);
        $this->db->where('rel_type', 'user-task');
        $this->db->where('type', 'broker');
        $this->db->where('leads_status', 1);
        $summery_data = $this->db->get(db_prefix() . 'tasks')->result_array();
        $ids = array_column($summery_data, 'id');
        $comma_separated_ids = implode(',', $ids);
        if (!empty($ids)) {
            $this->db->select('files.file_url, files.dateadded, files.filetype, files.file_name, tasks.name as task_name');
            $this->db->from(db_prefix() . 'files');
            $this->db->join(db_prefix() . 'tasks', 'tasks.id = files.task_id');
            $this->db->where_in('files.task_id', $ids);
            $this->db->where('files.rel_id', $lead_id);
            $this->db->where('files.rel_type', 'client-doc');
            $files_data = $this->db->get()->result_array();
        }
        if (!empty($files_data)) {
            $this->output
                ->set_content_type('application/json')
                ->set_output(json_encode($files_data));
        } else {
            $files_data = array(
                'success' => false
            );
            $this->output
                ->set_content_type('application/json')
                ->set_output(json_encode($files_data));
        }
    }
    // get the status and completed time for ID verification summery
    public function get_summery_task_for_id_verification_status($lead_id)
    {
        $this->db->select('status,id_verification_started_at,id_verification_completed_at,id_verification_completed');
        $this->db->where('id', $lead_id);
        $get_summery_status_data = $this->db->get(db_prefix() . 'leads')->row();
        $response = array(
            'status' => $get_summery_status_data->status,
            'id_verification_completed' => $get_summery_status_data->id_verification_completed,
            'id_verification_completed_at' => $get_summery_status_data->id_verification_completed_at,
            'id_verification_started_at' => $get_summery_status_data->id_verification_started_at,
            'id_verification_started_at_get_day' => get_day($get_summery_status_data->id_verification_started_at),
            'id_verification_time' => get_day($get_summery_status_data->id_verification_completed_at),
        );
        if (!empty($get_summery_status_data)) {
            $this->output
                ->set_content_type('application/json')
                ->set_output(json_encode($response));
        } else {
            $this->output
                ->set_content_type('application/json')
                ->set_output(json_encode($response));
        }
    }
    // get the doc files for the id verification
    public function get_summery_task_for_id_verification_doclink($lead_id)
    {
        // get the instruciton file id 
        $this->db->select('id');
        $this->db->where('lead_id', $lead_id);
        $this->db->where('stage_id', 8);
        $get_instruction_ids = $this->db->get(db_prefix() . 'instruction')->result_array();
        if (!empty($get_instruction_ids)) {
            $instruction_ids = array_column($get_instruction_ids, 'id');
            $this->db->select('downnload_file_url,file_url,file_type,file_name,created_at');
            $this->db->where_in('instruction_id', $instruction_ids);
            $id_verification_file_data = $this->db->get(db_prefix() . 'instruction_file')->result_array();
        }
        if (!empty($id_verification_file_data)) {
            $this->output
                ->set_content_type('application/json')
                ->set_output(json_encode($id_verification_file_data));
        } else {
            $this->output
                ->set_content_type('application/json')
                ->set_output(json_encode($id_verification_file_data));
        }
    }
    // get the status and completed time for instruction received summery
    public function get_summery_task_for_instruction_received_status($lead_id)
    {
        $this->db->select('status,ins_received_started_at,ins_received_completed_at,ins_received_completed');
        $this->db->where('id', $lead_id);
        $get_summery_status_data = $this->db->get(db_prefix() . 'leads')->row();
        $response = array(
            'status' => $get_summery_status_data->status,
            'ins_received_completed' => $get_summery_status_data->ins_received_completed,
            'ins_received_completed_at' => $get_summery_status_data->ins_received_completed_at,
            'ins_received_started_at' => $get_summery_status_data->ins_received_started_at,
            'ins_received_started_at_get_day' => get_day($get_summery_status_data->ins_received_started_at),
            'ins_received_time' => get_day($get_summery_status_data->ins_received_completed_at),
        );
        if (!empty($get_summery_status_data)) {
            $this->output
                ->set_content_type('application/json')
                ->set_output(json_encode($response));
        } else {
            $this->output
                ->set_content_type('application/json')
                ->set_output(json_encode($response));
        }
    }
    // get the doc files for the id verification
    public function get_summery_task_for_ins_received_doclink($lead_id)
    {
        // get the instruciton file id 
        $this->db->select('id');
        $this->db->where('lead_id', $lead_id);
        $this->db->where('stage_id', 2);
        $get_instruction_ids = $this->db->get(db_prefix() . 'instruction')->result_array();
        if (!empty($get_instruction_ids)) {
            $instruction_ids = array_column($get_instruction_ids, 'id');
            $this->db->select('downnload_file_url,file_url,file_type,file_name,created_at');
            $this->db->where_in('instruction_id', $instruction_ids);
            $id_verification_file_data = $this->db->get(db_prefix() . 'instruction_file')->result_array();
        }
        if (!empty($id_verification_file_data)) {
            $this->output
                ->set_content_type('application/json')
                ->set_output(json_encode($id_verification_file_data));
        } else {
            $this->output
                ->set_content_type('application/json')
                ->set_output(json_encode($id_verification_file_data));
        }
    }
    // get the set appointment time for summary
    public function get_set_appointment_time_for_summary($lead_id)
    {
        $this->db->select('date, end_date');
        $this->db->where('rel_id', $lead_id);
        $this->db->where('rel_type', 'lead');
        $this->db->order_by('id', 'desc');
        $this->db->limit(1);
        $get_data = $this->db->get(db_prefix() . 'reminders')->row();
        $response = array(
            'date' => $get_data->date,
            'format_date' => get_day($get_data->date),
            'end_date' => $get_data->end_date,
            'format_end_date' => get_day($get_data->end_date),
        );
        if (!empty($get_data)) {
            $this->output
                ->set_content_type('application/json')
                ->set_output(json_encode($response));
        } else {
            $this->output
                ->set_content_type('application/json')
                ->set_output(json_encode($response));
        }
    }

    // get the checkboxes for the appiontment
    public function get_summery_task_for_appointment($lead_id)
    {
        $this->db->select('id,leads_status, title, description, status');
        $this->db->where('lead_id', $lead_id);
        $this->db->where('leads_status', 0);
        $summery_data = $this->db->get(db_prefix() . 'cases_checkboxes')->result_array();
        if (!empty($summery_data)) {
            $this->output
                ->set_content_type('application/json')
                ->set_output(json_encode($summery_data));
        } else {
            $this->output
                ->set_content_type('application/json')
                ->set_output(json_encode($summery_data));
        }
    }
    // get the appointment status time and description
    public function get_summery_task_for_appointment_status($lead_id)
    {
        $this->db->select('status,app_request_started_at,app_request_completed_at,app_request_completed');
        $this->db->where('id', $lead_id);
        $get_summery_status_data = $this->db->get(db_prefix() . 'leads')->row();
        $response = array(
            'status' => $get_summery_status_data->status,
            'app_request_completed' => $get_summery_status_data->app_request_completed,
            'app_request_completed_at' => $get_summery_status_data->app_request_completed_at,
            'app_request_started_at' => $get_summery_status_data->app_request_started_at,
            'app_request_started_at_get_day' => get_day($get_summery_status_data->app_request_started_at),
            'app_request_time' => get_day($get_summery_status_data->app_request_completed_at),
        );
        if (!empty($get_summery_status_data)) {
            $this->output
                ->set_content_type('application/json')
                ->set_output(json_encode($response));
        } else {
            $this->output
                ->set_content_type('application/json')
                ->set_output(json_encode($response));
        }
    }
    // get the outstanding item status time and description
    public function get_summery_task_for_outstanding_item_team_status($lead_id)
    {
        $this->db->select('status,outstanding_item_started_at,out_items_completed,outstanding_item_completed_at');
        $this->db->where('id', $lead_id);
        $get_summery_status_data = $this->db->get(db_prefix() . 'leads')->row();
        $response = array(
            'status' => $get_summery_status_data->status,
            'out_items_completed' => $get_summery_status_data->out_items_completed,
            'outstanding_item_completed_at' => $get_summery_status_data->outstanding_item_completed_at,
            'outstanding_item_started_at' => $get_summery_status_data->outstanding_item_started_at,
            'outstanding_item_started_at_get_day' => get_day($get_summery_status_data->outstanding_item_started_at),
            'outstanding_item_time' => get_day($get_summery_status_data->outstanding_item_completed_at),
        );
        if (!empty($get_summery_status_data)) {
            $this->output
                ->set_content_type('application/json')
                ->set_output(json_encode($response));
        } else {
            $this->output
                ->set_content_type('application/json')
                ->set_output(json_encode($response));
        }
    }
    // get the ledger status time and description
    public function get_summery_ledger_status($lead_id)
    {
        $this->db->select('status,ledger_completed,ledger_started_at,ledger_completed_at');
        $this->db->where('id', $lead_id);
        $get_summery_status_data = $this->db->get(db_prefix() . 'leads')->row();
        $response = array(
            'status' => $get_summery_status_data->status,
            'ledger_completed' => $get_summery_status_data->ledger_completed,
            'ledger_completed_at' => $get_summery_status_data->ledger_completed_at,
            'ledger_started_at' => $get_summery_status_data->ledger_started_at,
            'ledger_started_at_get_day' => get_day($get_summery_status_data->ledger_started_at),
            'ledger_item_time' => get_day($get_summery_status_data->ledger_completed_at),
        );
        if (!empty($get_summery_status_data)) {
            $this->output
                ->set_content_type('application/json')
                ->set_output(json_encode($response));
        } else {
            $this->output
                ->set_content_type('application/json')
                ->set_output(json_encode($response));
        }
    }
    // get the ledger doc link
    public function get_summery_task_for_ledger_doclink($lead_id)
    {
        $this->db->select('id,lead_id,ledger_number,type,file_name,filetype,file_url,created_at,broker_status,broker_comment,broker_change_status_time');
        $this->db->where('lead_id', $lead_id);
        $this->db->where('bb_status', 'Approved');
        $result = $this->db->get(db_prefix() . 'leads_ledger')->result_array();
        $response = !empty($result) ? $result : null;
        $this->output
            ->set_content_type('application/json')
            ->set_output(json_encode($response));
    }
    // get request for funds doc link
    public function get_summery_task_for_request_for_funds_doclink($lead_id)
    {
        $this->db->select('id, title');
        $this->db->where('lead_id', $lead_id);
        $this->db->where('leads_status', 4);
        $get_record = $this->db->get(db_prefix() . 'cases_checkboxes')->result_array();

        foreach ($get_record as &$item) {
            $this->db->select('cases_checkbox_id, file_name, filetype, file_url, dateadded');
            $this->db->where('cases_checkbox_id', $item['id']);
            $this->db->where('rel_id', $lead_id);
            $this->db->where('rel_type', 'client-doc-request-for-funds');
            $files_data = $this->db->get(db_prefix() . 'cases_checkbox_files')->result_array();
            $item['file_data'] = $files_data;
        }
        $this->output
            ->set_content_type('application/json')
            ->set_output(json_encode($get_record));
    }

    // get the checkboxes for the request for funds
    public function get_summery_task_for_req_for_funds($lead_id)
    {
        $this->db->select('id,leads_status, title, description, status');
        $this->db->where('lead_id', $lead_id);
        $this->db->where('leads_status', 4);
        $summery_data = $this->db->get(db_prefix() . 'cases_checkboxes')->result_array();
        if (!empty($summery_data)) {
            $this->output
                ->set_content_type('application/json')
                ->set_output(json_encode($summery_data));
        } else {
            $this->output
                ->set_content_type('application/json')
                ->set_output(json_encode($summery_data));
        }
    }
    // get the request for funds status time and description
    public function get_summery_task_for_req_for_funds_status($lead_id)
    {
        $this->db->select('status,req_for_funds_completed,req_for_funds_started_at,req_for_funds_completed_at');
        $this->db->where('id', $lead_id);
        $get_summery_status_data = $this->db->get(db_prefix() . 'leads')->row();
        $response = array(
            'status' => $get_summery_status_data->status,
            'req_for_funds_completed' => $get_summery_status_data->req_for_funds_completed,
            'req_for_funds_completed_at' => $get_summery_status_data->req_for_funds_completed_at,
            'req_for_funds_started_at' => $get_summery_status_data->req_for_funds_started_at,
            'req_for_funds_started_at_get_day' => get_day($get_summery_status_data->req_for_funds_started_at),
            'req_for_funds_time' => get_day($get_summery_status_data->req_for_funds_completed_at),
        );
        if (!empty($get_summery_status_data)) {
            $this->output
                ->set_content_type('application/json')
                ->set_output(json_encode($response));
        } else {
            $this->output
                ->set_content_type('application/json')
                ->set_output(json_encode($response));
        }
    }
    // get the ledgers started and completed time
    public function get_summery_task_for_ledger_status($lead_id)
    {
        $this->db->select('created_at');
        $this->db->where('lead_id', $lead_id);
        $this->db->limit(1);
        $get_summery_status_data = $this->db->get(db_prefix() . 'leads_ledger')->row();
        // get the latest approved change time
        $this->db->select('id,ledger_number');
        $this->db->where('lead_id', $lead_id);
        $this->db->where('bb_status', 'Approved');
        $this->db->order_by('id', 'desc');
        $this->db->limit(1);
        $get_last_approved_time = $this->db->get(db_prefix() . 'leads_ledger')->row();
        // get the last approved status from logs of ledgers
        $this->db->select('id,created_at');
        $this->db->where('lead_id', $lead_id);
        $this->db->where('lead_ledger_number', $get_last_approved_time->ledger_number);
        $this->db->order_by('id', 'desc');
        $get_approved_logs = $this->db->get(db_prefix() . 'leads_ledger_logs')->row();
        $response = array(
            'ledger_completed_at' => $get_approved_logs->created_at,
            'ledger_started_at' => $get_summery_status_data->created_at,
            'ledger_started_at_get_day' => get_day($get_summery_status_data->created_at),
            'ledger_time' => get_day($get_approved_logs->created_at),
        );
        if (!empty($get_summery_status_data)) {
            $this->output
                ->set_content_type('application/json')
                ->set_output(json_encode($response));
        } else {
            $this->output
                ->set_content_type('application/json')
                ->set_output(json_encode($response));
        }
    }
    // get the last activity logs time 
    public function get_last_activity_log_time($lead_id)
    {
        $this->db->select('date');
        $this->db->where('leadid', $lead_id);
        $this->db->order_by('id', 'desc');
        $this->db->limit(1);
        $get_summery_status_data = $this->db->get(db_prefix() . 'lead_activity_log')->row();
        $response = array(
            'last_activity_logs' => $get_summery_status_data->date,
            'last_activity_logs_date' => get_day($get_summery_status_data->date),
        );
        if (!empty($get_summery_status_data)) {
            $this->output
                ->set_content_type('application/json')
                ->set_output(json_encode($response));
        } else {
            $this->output
                ->set_content_type('application/json')
                ->set_output(json_encode($response));
        }
    }
    // get the offer in date
    public function get_offer_in_date($lead_id)
    {
        $this->db->select('created_at');
        $this->db->where('lead_id', $lead_id);
        $this->db->limit(1);
        $get_offer_in_data = $this->db->get(db_prefix() . 'instruction')->row();
        $response = array(
            'offer_in' => $get_offer_in_data->created_at ?? '',
            'offer_in_date' => get_day($get_offer_in_data->created_at) ?? '',
        );
        $this->output
            ->set_content_type('application/json')
            ->set_output(json_encode($response));
    }
    // get the closed time and status
    public function get_summery_task_closed_status($lead_id)
    {
        $this->db->select('status,closed_completed_at');
        $this->db->where('id', $lead_id);
        $get_summery_status_data = $this->db->get(db_prefix() . 'leads')->row();
        $response = array(
            'status' => $get_summery_status_data->status,
            'closed_completed_at' => $get_summery_status_data->closed_completed_at,
            'closed_time' => get_day($get_summery_status_data->closed_completed_at),
        );
        if (!empty($get_summery_status_data)) {
            $this->output
                ->set_content_type('application/json')
                ->set_output(json_encode($response));
        } else {
            $this->output
                ->set_content_type('application/json')
                ->set_output(json_encode($response));
        }
    }
    public function get_summery_task_on_hold_status($lead_id)
    {
        $this->db->select('status,hold_completed_at,on_hold_reason');
        $this->db->where('id', $lead_id);
        $get_summery_status_data = $this->db->get(db_prefix() . 'leads')->row();
        $response = array(
            'status' => $get_summery_status_data->status,
            'on_hold_completed_at' => $get_summery_status_data->hold_completed_at,
            'on_hold_time' => get_day($get_summery_status_data->hold_completed_at),
            'on_hold_reason' => $get_summery_status_data->on_hold_reason,
        );
        if (!empty($get_summery_status_data)) {
            $this->output
                ->set_content_type('application/json')
                ->set_output(json_encode($response));
        } else {
            $this->output
                ->set_content_type('application/json')
                ->set_output(json_encode($response));
        }
    }
    // checkbox add for post appointemnt/outstanding items/request for funds
    public function add_checkboxes_for_appointment()
    {
        if (empty($_POST['checkbox_title'])) {
            $response = array(
                'status' => 'error',
                'field' => 'checkbox_title',
                'message' => 'This field is requried.'
            );
        } else {
            // Validation succeeded
            $checkbox_title = $this->input->post('checkbox_title');
            $select_type_ld_outstanding_item = $this->input->post('select_type_ld_outstanding_item');
            $leads_status = $this->input->post('leads_status');
            $leads_status_current_id = $this->input->post('leads_status_current_id');
            $checkbox_description = $this->input->post('checkbox_description');
            $checkbox_id = $this->input->post('checkbox_id');
            $lead_id = $this->input->post('lead_id');
            $checkbox_description = str_replace(['<br />', '<br>', '<br/>'], "\n", nl2br($checkbox_description));
            // this condition work when select the secure payout optoin
            $item_type = '';
            if (in_array($select_type_ld_outstanding_item, ['secure_charge', 'secure_private_charge_1', 'postponements', 'app_general'])) {
                $leads_status = 7;
            } elseif ($select_type_ld_outstanding_item === 'other_items') {
                $leads_status = 3;
            }
            switch ($leads_status) {
                case 1:
                    $leads_status_value = '#file_opened';
                    $complete_stage_button = 1;
                    break;
                case 2:
                    $leads_status_value = '#instructions_received';
                    $complete_stage_button = 2;
                    break;
                case 3:
                    $leads_status_value = '#outstanding_items';
                    $case_stage_name = 'Outstanding Item';
                    $complete_stage_button = 3;
                    break;
                case 4:
                    $leads_status_value = '#request_for_funds';
                    $case_stage_name = 'Request For Funds';
                    $complete_stage_button = 4;
                    break;
                case 5:
                    $leads_status_value = '#Closed';
                    $case_stage_name = 'Request For Funds';
                    break;
                case 7:
                    $leads_status_value = '#outstanding_items';
                    $complete_stage_button = 3;
                    break;
                case 8:
                    $leads_status_value = '#id_verification';
                    break;
                default:
                    $leads_status_value = '';
                    break;
            }
            if (!empty($leads_status)) {
                if (!empty($checkbox_id)) {
                    $data = array(
                        'title' => $checkbox_title,
                        'description' => $checkbox_description,
                        'leads_status' => $leads_status,
                    );

                    $this->db->where('id', $checkbox_id);
                    $this->db->update(db_prefix() . 'cases_checkboxes', $data);
                    $response = array(
                        'status' => 'success',
                        'message' => 'Form updated successfully.',
                        'leads_status' => $leads_status_value,
                        'complete_stage_buttonid' => $complete_stage_button,
                        'id' => $lead_id,
                        'leadView' => $this->_get_lead_data($lead_id),
                    );
                } else {
                    $secure_private_charge_unique_num = '';
                    if ($select_type_ld_outstanding_item == 'secure_private_charge_1') {
                        $secure_private_charge_unique_num = get_secure_private_charge_unique_number($this, $lead_id);
                        $secure_private_charge_unique_num++;
                    }
                    $data = array(
                        'lead_id' => $lead_id,
                        'unique_number' => $secure_private_charge_unique_num,
                        'title' => $checkbox_title,
                        'description' => $checkbox_description,
                        'leads_status' => $leads_status,
                        'type' => $select_type_ld_outstanding_item,
                        'status' => 0,
                        'created_at' => date('Y-m-d H:i:s')
                    );
                    $this->db->insert(db_prefix() . 'cases_checkboxes', $data);
                    // create the custom secure private charges items
                    if ($select_type_ld_outstanding_item == 'secure_private_charge_1') {
                        add_secure_private_charge_type_record($this, $lead_id, 7, $secure_private_charge_unique_num);
                    }
                    // add the activity of comments
                    $lead_activity_data = array(
                        'leadid' => $lead_id,
                        'description' => get_staff_full_name() . ' is creating a new item ' . $checkbox_title,
                        'date' => date('Y-m-d H:i:s'),
                        'staffid' => get_staff_user_id(),
                        'full_name' => get_staff_full_name()
                    );
                    $this->db->insert(db_prefix() . 'lead_activity_log', $lead_activity_data);
                    $response = array(
                        'status' => 'success',
                        'message' => 'Form submitted successfully.',
                        'leads_status' => $leads_status_value,
                        'complete_stage_buttonid' => $complete_stage_button,
                        'id' => $lead_id,
                        'leadView' => $this->_get_lead_data($lead_id),
                    );
                }
            } else {
                // checkboxes add for appointment section
                if (!empty($checkbox_id)) {
                    $data = array(
                        'title' => $checkbox_title,
                        'description' => $checkbox_description,
                    );

                    $this->db->where('id', $checkbox_id);
                    $this->db->update(db_prefix() . 'cases_checkboxes', $data);
                    $response = array(
                        'status' => 'success',
                        'message' => 'Form updated successfully.',
                        'leads_status' => $leads_status_value,
                        'complete_stage_buttonid' => $complete_stage_button,
                        'id' => $lead_id,
                        'leadView' => $this->_get_lead_data($lead_id),
                    );
                } else {
                    $data = array(
                        'lead_id' => $lead_id,
                        'title' => $checkbox_title,
                        'description' => $checkbox_description,
                        'status' => 0,
                        'created_at' => date('Y-m-d H:i:s')
                    );
                    $this->db->insert(db_prefix() . 'cases_checkboxes', $data);
                    // add the activity of comments
                    $lead_activity_data = array(
                        'leadid' => $lead_id,
                        'description' => get_staff_full_name() . ' is creating a new item ' . $checkbox_title,
                        'date' => date('Y-m-d H:i:s'),
                        'staffid' => get_staff_user_id(),
                        'full_name' => get_staff_full_name()
                    );
                    $this->db->insert(db_prefix() . 'lead_activity_log', $lead_activity_data);
                    $response = array(
                        'status' => 'success',
                        'message' => 'Form submitted successfully.',
                        'leads_status' => $leads_status_value,
                        'complete_stage_buttonid' => $complete_stage_button,
                        'id' => $lead_id,
                        'leadView' => $this->_get_lead_data($lead_id),
                    );
                }
            }
        }
        // update the last contact date 
        $this->leads_model->update_leads_last_contact_date($lead_id);
        $this->output
            ->set_content_type('application/json')
            ->set_output(json_encode($response));
    }
    // store private secure payout charges
    // public function add_private_store_secure_items()
    // {
    //     $lead_id = $this->input->post('lead_id');
    //     $select_type_ld_outstanding_item = $this->input->post('select_type_ld_outstanding_item');
    //     $leads_status_current_id = $this->input->post('leads_status_current_id');
    //     if ($select_type_ld_outstanding_item == 7) {
    //         $leads_status = 7;
    //     }
    //     $checkbox_items = [
    //         'Private A&D',
    //         'Private DRA',
    //         'Private Direction',
    //         'LSUC Check',
    //         'Lawyer V/C check/Call lawyer',
    //     ];

    //     foreach ($checkbox_items as $checkbox_title) {
    //         $data = [
    //             'lead_id' => $lead_id,
    //             'title' => $checkbox_title,
    //             'type' => 'secure_private_charge_1',
    //             'description' => '',
    //             'leads_status' => $leads_status ?? '',
    //             'status' => 0,
    //             'created_at' => date('Y-m-d H:i:s')
    //         ];
    //         $this->db->insert(db_prefix() . 'cases_checkboxes', $data);
    //         $lead_activity_data = [
    //             'leadid' => $lead_id,
    //             'description' => get_staff_full_name() . ' is creating a new item: ' . $checkbox_title,
    //             'date' => date('Y-m-d H:i:s'),
    //             'staffid' => get_staff_user_id(),
    //             'full_name' => get_staff_full_name()
    //         ];
    //         $this->db->insert(db_prefix() . 'lead_activity_log', $lead_activity_data);
    //     }
    //     $response = array(
    //         'status' => 'success',
    //         'message' => 'Form submitted successfully.',
    //         'leads_status' => '#outstanding_items',
    //         'complete_stage_buttonid' => 7,
    //         'id' => $lead_id,
    //         'leadView' => $this->_get_lead_data($lead_id),
    //     );
    //     // update the last contact date 
    //     $this->leads_model->update_leads_last_contact_date($lead_id);
    //     $this->output
    //         ->set_content_type('application/json')
    //         ->set_output(json_encode($response));
    // }
    // ld and broker comments
    public function ld_commentsadd($lead_id)
    {
        $this->load->library('form_validation');
        // Check if the request is an AJAX request
        $this->form_validation->set_rules('ld_comments', 'Broker Comment', 'required');

        // Define input names for reference
        $input_names = [
            'ld_comments' => 'ld_comments',
        ];
        $response = array(); // Initialize the response array

        if ($this->form_validation->run() == false) {
            // Validation failed
            $errors = [];

            foreach ($input_names as $field => $label) {
                $error = form_error($field);

                if (!empty($error)) {
                    $errors[$field] = $error;
                }
            }

            $response = array(
                'success' => false,
                'errors' => $errors,
            );
            echo json_encode($response);
            exit;
        } else {
            $_POST['get_afternoon_and_morning'] = get_afternoon_and_morning();
            $comment_text = $this->input->post('ld_comments');
            $contact_id = '';
            $response = '';
            $profile_url = '';
            $username = '';
            // Prepare comment data
            $commentData = array(
                'user_id' => 'You',
                // 'lead_id' => $lead_id,
                'comment' => $comment_text,
                'created_at' => time_ago(date('Y-m-d H:i:s')),
                'full_time' => date('m/d/y H:i:s')
            );

            // Get the contact id using lead id with multiple cases handled
            $this->db->select('*');
            $this->db->where('id', $lead_id);
            $this->db->where('multiple_cases', '0');
            $lead_query_data = $this->db->get(db_prefix() . 'leads');

            if ($lead_query_data->num_rows() > 0) {
                // Get the contact primary id
                $lead_data = $lead_query_data->row();
                $client_id = $lead_data->client_id;
                $username = $lead_data->name;
                $this->db->select('id,firstname,middlename,lastname');
                $this->db->where('userid', $client_id);
                $contact_query_data = $this->db->get(db_prefix() . 'contacts');
                if ($contact_query_data->num_rows() > 0) {
                    $contact_data = $contact_query_data->row();
                    $contact_id = $contact_data->id;
                    $contact_user_name = $contact_data->firstname . ' ' . $contact_data->middlename . ' ' . $contact_data->lastname;
                }
            } else {
                $this->db->select('*');
                $this->db->where('id', $lead_id);
                $lead_query_data = $this->db->get(db_prefix() . 'leads');
                $lead_data = $lead_query_data->row();
                $multiple_case_lead_id = $lead_data->multiple_cases;
                $username = $lead_data->name;
                // get client id of the parnet lead case 
                $this->db->select('client_id');
                $this->db->where('id', $multiple_case_lead_id);
                $lead_query_data = $this->db->get(db_prefix() . 'leads');
                $lead_data_parent_case = $lead_query_data->row();
                $client_id = $lead_data_parent_case->client_id;
                // Get the contact primary id
                $this->db->select('*');
                $this->db->where('userid', $client_id);
                $contact_query_data = $this->db->get(db_prefix() . 'contacts');
                $contact_data = $contact_query_data->row();
                $contact_id = $contact_data->id;
                $contact_user_name = $contact_data->firstname . ' ' . $contact_data->middlename . ' ' . $contact_data->lastname;
            }
            // Insert record in comments table
            $comments_data = array(
                'to_user_id' => $contact_id,
                'from_user_id' => get_staff_user_id(),
                'lead_id' => $lead_id,
                'comment_text' => $comment_text,
                'role' => 'ld-broker-staff',
                'type' => 'broker-to-ld',
                'created_at' => date('Y-m-d H:i:s'),
            );
            $this->db->insert(db_prefix() . 'comments', $comments_data);
            // // Get the ID of the inserted comment
            $comment_id = $this->db->insert_id();
            // get staff profile url
            $this->db->select('*');
            $this->db->where('staffid', get_staff_user_id());
            $query = $this->db->get(db_prefix() . 'staff');
            $staff_data = $query->row();
            $profile_check = $staff_data->profile_image;
            $staff_name = $staff_data->firstname . ' ' . $staff_data->lastname;
            if (!empty($profile_check)) {
                $profile_url = base_url('uploads/staff_profile_images/' . $staff_data->staffid . '/thumb_' . $staff_data->profile_image);
            } else {
                $profile_url = base_url('assets/images/user-placeholder.webp');
            }
            // Insert record in read_comment table
            $read_comment_data = array(
                'comment_id' => $comment_id,
                'to_user_id' => $contact_id,
                'from_user_id' => get_staff_user_id(),
                'lead_id' => $lead_id,
                'is_read' => '0',
                'type' => 'broker-to-ld',
            );
            $insert_read_comments = $this->db->insert(db_prefix() . 'read_comments', $read_comment_data);
            // add the activity of comments
            $lead_activity_data = array(
                'leadid' => $lead_id,
                'description' => get_staff_full_name() . ' sent a message to case (#' . $lead_id . ' Name:' . $contact_user_name . ').',
                'date' => date('Y-m-d H:i:s'),
                'staffid' => get_staff_user_id(),
                'full_name' => get_staff_full_name()
            );
            $this->db->insert(db_prefix() . 'lead_activity_log', $lead_activity_data);
            if ($insert_read_comments) {
                $commentData['profile_url'] = $profile_url;
                $commentData['staff_name'] = $staff_name;
                $commentHtml = $this->saveCommentAndGetHtml($commentData);
                // notificaation line of code 
                $this->db->select('id,multiple_cases,client_id,name,assign_group,assigned');
                $this->db->where('id', $lead_id);
                $lead_data_check = $this->db->get(db_prefix() . 'leads');
                if ($lead_data_check->num_rows() > 0) {
                    $lead_data = $lead_data_check->row();
                    $client_id = get_client_id_using_contact_id($this, $lead_data->client_id, $lead_data->multiple_cases);
                    $contact_id = get_contact_id_using_client_id($this, $client_id);
                    $notification_type = get_notification_type(3);
                    $comment_title = 'New Message Notification';
                    $this->db->select('assign_group,assigned');
                    $this->db->where('id', $lead_id);
                    $lead_data_for_get_assign_group = $this->db->get(db_prefix() . 'leads')->row();
                    $current_staff_data = get_staff_ids_by_group($this, $lead_data_for_get_assign_group->assign_group);
                    $replay_to_mail = get_all_staff_to_replay_email($this, get_staff_user_id(), $lead_data_for_get_assign_group->assign_group);
                    $_POST['case_url'] = admin_url('cases/index/') . $lead_id;
                    $_POST['lead_id'] = $lead_id;
                    if (get_current_staff_role($this, get_staff_user_id()) == 2 || get_current_staff_role($this, get_staff_user_id()) == 6) {
                        $lead_split_name = leads_splitFullName($lead_data->name);
                        $_POST['lead_id'] = $lead_id;
                        $_POST['name'] = $staff_name;
                        $subject = 'Case #' . $lead_id . ', ' . $lead_split_name['lastname'] . ', ' . $lead_split_name['firstname'] . ' ' . $lead_split_name['middlename'] . ' Message From Broker.';
                        $_POST['case_url'] = admin_url('cases/index/') . $lead_id;
                        $_POST['generic_email_title'] = '';
                        $_POST['generic_email_content'] = 'Good ' . get_afternoon_and_morning() . '<br> Please note the broker has sent a message on this file #' . $lead_id;
                        $_POST['generic_email_back_to_case_url'] = 'Please <a href="' . htmlspecialchars($_POST['case_url'], ENT_QUOTES, 'UTF-8') . '">Click here</a> to access the file.';
                        $html_content_confirmation_email_to_broker = $this->load->view('admin/leads/Email_template/generic_email_template', $_POST, TRUE);
                        // if current user is broker then send notification to ld-team 
                        foreach ($current_staff_data as $staff_notifiy_data) {
                            if ($staff_notifiy_data['role'] == 1) {
                                $staff_name = $staff_notifiy_data['firstname'] . ' ' . $staff_notifiy_data['lastname'];
                                $comment_message = get_staff_full_name() . ' sent a message to ' . $staff_name;
                                if (get_staff_user_id() != $staff_notifiy_data['staffid']) {
                                    $read_comment_data = array(
                                        'comment_id' => $comment_id,
                                        'to_user_id' => $staff_notifiy_data['staffid'],
                                        'from_user_id' => get_staff_user_id(),
                                        'lead_id' => $lead_id,
                                        'is_read' => '0',
                                        'type' => 'broker-to-ld'
                                    );
                                    $insert_read_comments = $this->db->insert(db_prefix() . 'read_comments', $read_comment_data);
                                    $ldteam_notify_type = $notification_type;
                                    $ld_team_notify_title = $comment_title;
                                    $ld_team_notify_message = $comment_message;
                                    $comment_type = 'broker';
                                    send_notification_in_mobile('staff', $staff_notifiy_data['staffid'], $contact_id, $client_id, $lead_id, $ld_team_notify_title, $ld_team_notify_message, $ldteam_notify_type, '', $comment_type);
                                    // send notification to the crm
                                    $this->leads_model->custom_lead_assigned_member_notification('staff', $lead_id, $staff_notifiy_data['staffid'], get_staff_user_id(), '', $comment_message);
                                    // Send the comment mail to the ld team
                                    // $html_content_confirmation_email_to_broker = $this->load->view('admin/leads/Email_template/broker_to_ld_comment', $_POST, TRUE);
                                    // send_mailchimp_email($staff_notifiy_data['email'], $subject, $html_content_confirmation_email_to_broker, $replay_to_mail, '', '', $lead_id);
                                }
                            }
                        }
                        // send notification to admin
                        // get the all admin staff ids
                        $admin_ids = get_all_admin_role_staff_ids($this);
                        foreach ($admin_ids as $admin_email) {
                            $get_staff_record = get_staff_name_by_id($this, $admin_email['staffid']);
                            $comment_message = get_staff_full_name() . ' sent a message to ' . $get_staff_record;
                            $read_comment_data = array(
                                'comment_id' => $comment_id,
                                'to_user_id' => $admin_email['staffid'],
                                'from_user_id' => get_staff_user_id(),
                                'lead_id' => $lead_id,
                                'is_read' => '0',
                                'type' => 'broker-to-ld'
                            );
                            $insert_read_comments = $this->db->insert(db_prefix() . 'read_comments', $read_comment_data);
                            $admin_notify_type = $notification_type;
                            $admin_notify_title = $comment_title;
                            $admin_notify_message = $comment_message;
                            $comment_type = 'broker';
                            send_notification_in_mobile('staff', $admin_email['staffid'], $contact_id, $client_id, $lead_id, $admin_notify_title, $admin_notify_message, $admin_notify_type, '', $comment_type);
                            $this->leads_model->custom_lead_assigned_member_notification('staff', $lead_id, $admin_email['staffid'], get_staff_user_id(), '', $comment_message);
                            // Send the comment mail to the admin
                            // $_POST['lead_id'] = $lead_id;
                            // $_POST['lead_name'] = $username;
                            // $_POST['name'] = $get_staff_record;
                            // $subject = 'New Message from ' . get_staff_full_name();
                            // $html_content_confirmation_email_to_broker = $this->load->view('admin/leads/Email_template/broker_to_ld_comment', $_POST, TRUE);
                            // send_mailchimp_email($admin_email['email'], $subject, $html_content_confirmation_email_to_broker, $replay_to_mail, '', '', $lead_id);
                        }
                        // Send Slack notification
                        $slack_message = " \n - Message from Broker \n - Review the message";
                        $send_notification = $this->slack->sendnotification($slack_message, $lead_id, $lead_data->assign_group, $lead_split_name['lastname'] . ', ' . $lead_split_name['firstname']);
                    } else {
                        // send the notificaiton to borker 
                        $this->db->select('addedfrom');
                        $this->db->where('id', $lead_id);
                        $get_broker_data = $this->db->get(db_prefix() . 'leads')->row();
                        // Check if the addedfrom data exists
                        if ($get_broker_data && !empty($get_broker_data->addedfrom)) {
                            $outbox_content = "Good {$_POST['get_afternoon_and_morning']},\n\nYou have a new broker message waiting for you for the file of #{$_POST['lead_id']}, {$_POST['lead_name']}.";
                            $addedfrom_ids = explode(',', $get_broker_data->addedfrom);
                            // get the staff data
                            foreach ($addedfrom_ids as $addedfrom_id) {
                                $get_staff_name = get_staff_name_by_id($this, $addedfrom_id);
                                $get_broker_email = get_staff_email_by_id($this, $addedfrom_id);
                                $comment_message = get_staff_full_name() . ' sent a message to ' . $get_staff_name;
                                $this->leads_model->custom_lead_assigned_member_notification('staff', $lead_id, $addedfrom_id, get_staff_user_id(), '', $comment_message);
                                // Send the comment mail to the broker
                                $_POST['lead_id'] = $lead_id;
                                $_POST['lead_name'] = $username;
                                $_POST['name'] = $get_staff_name;
                                $subject = 'New Message from ' . get_staff_full_name();
                                $html_content_confirmation_email_to_broker = $this->load->view('admin/leads/Email_template/broker_to_ld_comment', $_POST, TRUE);
                                $send_email_result = send_mailchimp_email($get_broker_email, $subject, $html_content_confirmation_email_to_broker, $replay_to_mail, '', '', $lead_id);
                                // add the record for outbox emails

                                $this->Outbox_model->save_outbox_email(
                                    $get_broker_email,
                                    '',
                                    '',
                                    $subject,
                                    $outbox_content,
                                    '',
                                    $lead_id,
                                    '',
                                    $html_content_confirmation_email_to_broker,
                                    $replay_to_mail,
                                    $send_email_result['status'],
                                    $send_email_result['mandrill_id'],
                                    1
                                );
                            }
                            // send the all admin notification and email to the admin broker
                            $brokerage_id = get_brokerage_id_using_leadid($this, $lead_id);
                            $admin_broker_ids = get_all_admin_broker_role_staff_ids($this, $brokerage_id);
                            foreach ($admin_broker_ids as $admin_broker_email) {
                                if (get_staff_user_id() != $admin_broker_email['staffid'] && !in_array($admin_broker_email['staffid'], explode(',', $get_broker_data->addedfrom))) {
                                    $comment_message = get_staff_full_name() . ' sent a message to ' . $admin_broker_email['firstname'] . ' ' . $admin_broker_email['lastname'];
                                    $this->leads_model->custom_lead_assigned_member_notification('staff', $lead_id, $admin_broker_email['staffid'], get_staff_user_id(), '', $comment_message);
                                    // Send the comment mail to the broker
                                    $_POST['lead_id'] = $lead_id;
                                    $_POST['lead_name'] = $username;
                                    $_POST['name'] = $admin_broker_email['firstname'] . ' ' . $admin_broker_email['lastname'];
                                    $subject = 'New Message from ' . get_staff_full_name();
                                    $html_content_confirmation_email_to_broker = $this->load->view('admin/leads/Email_template/broker_to_ld_comment', $_POST, TRUE);
                                    $send_email_result = send_mailchimp_email($admin_broker_email['staffid'], $subject, $html_content_confirmation_email_to_broker, $replay_to_mail, '', '', $lead_id);
                                    // add the record for outbox emails
                                    $this->Outbox_model->save_outbox_email(
                                        $admin_broker_email['staffid'],
                                        '',
                                        '',
                                        $subject,
                                        $outbox_content,
                                        '',
                                        $lead_id,
                                        '',
                                        $html_content_confirmation_email_to_broker,
                                        $replay_to_mail,
                                        $send_email_result['status'],
                                        $send_email_result['mandrill_id'],
                                        1
                                    );
                                }
                            }
                        }
                    }
                }
                $response = array(
                    'success' => true,
                    'comment_html' => $commentHtml,
                    'id' => $lead_id,
                    'leadView' => $this->_get_lead_data($lead_id),
                );
            } else {
                $response = array(
                    'success' => false,
                );
            }
        }

        header('Content-Type: application/json');
        echo json_encode($response);
    }
    // LD Comments Show
    public function ld_comments_show($lead_id)
    {
        if ($this->input->is_ajax_request()) {
            $profil_url = '';
            $contacts_data = '';
            $this->db->select('*');
            $this->db->where('lead_id', $lead_id);
            $this->db->where('type', 'broker-to-ld');
            $query = $this->db->get(db_prefix() . 'comments');

            if ($query->num_rows() > 0) {
                $result = $query->result_array();
                $comment_array_data = array();
                foreach ($result as $comment_values) {
                    if ($comment_values['role'] == 'client') {
                        $this->db->select('*');
                        $this->db->where('id', $comment_values['from_user_id']);
                        $query_contacts = $this->db->get(db_prefix() . 'contacts');
                        $contacts_data = $query_contacts->row();
                    }
                    $user_name = ($comment_values['role'] == 'staff') ? '' : $contacts_data->firstname . ' ' . $contacts_data->lastname;
                    $parent_lead_id = get_lead_parent_id($this, $lead_id);
                    if ($comment_values['role'] == 'staff' || $comment_values['role'] == 'ld-broker-staff') {
                        $this->db->select('*');
                        $this->db->where('staffid', $comment_values['from_user_id']);
                        $query = $this->db->get(db_prefix() . 'staff');
                        $staff_data = $query->row();
                        $profile_check = $staff_data->profile_image;
                        $staff_name = $staff_data->firstname . ' ' . $staff_data->lastname;
                        if (!empty($profile_check)) {
                            $profil_url = base_url('uploads/staff_profile_images/' . $staff_data->staffid . '/thumb_' . $staff_data->profile_image);
                        } else {
                            $profil_url = null;
                        }
                    } else {
                        $this->db->select('file_url');
                        $this->db->where('rel_id', $parent_lead_id);
                        $this->db->where('rel_type', 'profile-doc');
                        $query = $this->db->get(db_prefix() . 'files');
                        $file_data = $query->row();
                        $profil_url = $file_data->file_url;
                    }
                    $comment_array_data[] = array(
                        'lead_id' => $lead_id,
                        'user_name' => $user_name,
                        'comment_text' => $comment_values['comment_text'],
                        'created_at' => time_ago($comment_values['created_at']),
                        'full_time' => _dt($comment_values['created_at']),
                        'role' => $comment_values['role'],
                        'profile_url' => $profil_url,
                        'staff_name' => $staff_name,
                        'current_user_login_id' => get_staff_user_id(),
                        'from_user_id' => $comment_values['from_user_id']
                    );
                }

                $response = array(
                    'success' => true,
                    'comment_data' => $comment_array_data,
                );
            } else {
                $response = array(
                    'success' => false,
                );
            }

            header('Content-Type: application/json');
            echo json_encode($response);
        }
    }
    public function admin_ld_comments_show($lead_id)
    {
        if ($this->input->is_ajax_request()) {
            $profil_url = '';
            $contacts_data = '';
            $this->db->select('*');
            $this->db->where('lead_id', $lead_id);
            $this->db->where('type', 'admin-to-ld');
            $query = $this->db->get(db_prefix() . 'comments');

            if ($query->num_rows() > 0) {
                $result = $query->result_array();
                $comment_array_data = array();
                foreach ($result as $comment_values) {
                    if ($comment_values['role'] == 'client') {
                        $this->db->select('*');
                        $this->db->where('id', $comment_values['from_user_id']);
                        $query_contacts = $this->db->get(db_prefix() . 'contacts');
                        $contacts_data = $query_contacts->row();
                    }
                    $staffname = get_staff_data_by_id($this, $comment_values['from_user_id']);
                    $user_name = ($comment_values['role'] == 'staff') ? $staffname->firstname . ' ' . $staffname->lastname : $contacts_data->firstname . ' ' . $contacts_data->lastname;
                    $parent_lead_id = get_lead_parent_id($this, $lead_id);
                    if ($comment_values['role'] == 'staff' || $comment_values['role'] == 'ld-broker-staff') {
                        $this->db->select('*');
                        $this->db->where('staffid', $comment_values['from_user_id']);
                        $query = $this->db->get(db_prefix() . 'staff');
                        $staff_data = $query->row();
                        $profile_check = $staff_data->profile_image;
                        $staff_name = $staff_data->firstname . ' ' . $staff_data->lastname;
                        if (!empty($profile_check)) {
                            $profil_url = base_url('uploads/staff_profile_images/' . $staff_data->staffid . '/thumb_' . $staff_data->profile_image);
                        } else {
                            $profil_url = null;
                        }
                    } else {
                        $this->db->select('file_url');
                        $this->db->where('rel_id', $parent_lead_id);
                        $this->db->where('rel_type', 'profile-doc');
                        $query = $this->db->get(db_prefix() . 'files');
                        $file_data = $query->row();
                        $profil_url = $file_data->file_url;
                    }
                    $comment_array_data[] = array(
                        'lead_id' => $lead_id,
                        'user_name' => $user_name,
                        'comment_text' => $comment_values['comment_text'],
                        'created_at' => time_ago($comment_values['created_at']),
                        'full_time' => _dt($comment_values['created_at']),
                        'role' => $comment_values['role'],
                        'profile_url' => $profil_url,
                        'staff_name' => $staff_name,
                        'current_user_login_id' => get_staff_user_id(),
                        'from_user_id' => $comment_values['from_user_id']
                    );
                }

                $response = array(
                    'success' => true,
                    'comment_data' => $comment_array_data,
                );
            } else {
                $response = array(
                    'success' => false,
                );
            }
            header('Content-Type: application/json');
            echo json_encode($response);
        }
    }
    // read the case count 
    public function case_count_read($lead_id)
    {
        $action = $this->input->post('action');
        $type = '';

        if ($action == 'client_comment_action') {
            $type = 'client-to-ld';
        } elseif ($action == 'broker_comment_action') {
            $type = 'broker-to-ld';
        }
        $update_count = array(
            'case_is_read' => 1
        );

        $this->db->where('lead_id', $lead_id);
        $this->db->where('case_is_read', '0');
        $this->db->where('to_user_id', get_staff_user_id());
        $this->db->where('type', $type);
        $this->db->update(db_prefix() . 'read_comments', $update_count);

        if ($this->db->affected_rows() > 0) {
            $response = [
                'success' => true,
                'message' => 'Record updated successfully.'
            ];
        } else {
            $response = [
                'success' => false,
                'message' => 'No record updated. It might already be marked as read.'
            ];
        }
        echo json_encode($response);
        exit;
    }
    // notification count show
    public function ld_notification_case_comments_count()
    {
        $lead_id = $this->input->post('lead_id');
        $count = get_case_read_comment_count_client($this, $lead_id);
        echo json_encode(['client_comments_count' => $count]);
    }
    public function broker_notification_case_comments_count()
    {
        $lead_id = $this->input->post('lead_id');
        $count = get_case_read_comment_count_broker($this, $lead_id);
        echo json_encode(['client_comments_count' => $count]);
    }

    // Store comments
    public function commentsadd($lead_id)
    {
        $this->load->library('form_validation');
        // Check if the request is an AJAX request
        $this->form_validation->set_rules('comments', 'comment', 'required');

        // Define input names for reference
        $input_names = [
            'comments' => 'comments',
        ];
        $response = array();

        if ($this->form_validation->run() == false) {
            // Validation failed
            $errors = [];

            foreach ($input_names as $field => $label) {
                $error = form_error($field);

                if (!empty($error)) {
                    $errors[$field] = $error;
                }
            }

            $response = array(
                'success' => false,
                'errors' => $errors,
            );
            echo json_encode($response);
            exit;
        } else {
            // $lead_id = $this->input->post('lead_id');
            $comment_text = $this->input->post('comments');
            $contact_id = '';
            $response = '';
            $profile_url = '';
            $username = '';
            // Prepare comment data
            $commentData = array(
                'user_id' => 'You',
                // 'lead_id' => $lead_id,
                'comment' => $comment_text,
                'created_at' => time_ago(date('Y-m-d H:i:s')),
                'full_time' => date('m/d/y H:i:s')
            );

            // Get the contact id using lead id with multiple cases handled
            $this->db->select('*');
            $this->db->where('id', $lead_id);
            $this->db->where('multiple_cases', '0');
            $lead_query_data = $this->db->get(db_prefix() . 'leads');

            if ($lead_query_data->num_rows() > 0) {
                // Get the contact primary id
                $lead_data = $lead_query_data->row();
                $client_id = $lead_data->client_id;
                $username = $lead_data->name;
                $this->db->select('id,firstname,middlename,lastname');
                $this->db->where('userid', $client_id);
                $contact_query_data = $this->db->get(db_prefix() . 'contacts');
                if ($contact_query_data->num_rows() > 0) {
                    $contact_data = $contact_query_data->row();
                    $contact_id = $contact_data->id;
                    $contact_user_name = $contact_data->firstname . ' ' . $contact_data->middlename . ' ' . $contact_data->lastname;
                }
            } else {
                $this->db->select('*');
                $this->db->where('id', $lead_id);
                $lead_query_data = $this->db->get(db_prefix() . 'leads');
                $lead_data = $lead_query_data->row();
                $multiple_case_lead_id = $lead_data->multiple_cases;
                $username = $lead_data->name;
                // get client id of the parnet lead case 
                $this->db->select('client_id');
                $this->db->where('id', $multiple_case_lead_id);
                $lead_query_data = $this->db->get(db_prefix() . 'leads');
                $lead_data_parent_case = $lead_query_data->row();
                $client_id = $lead_data_parent_case->client_id;
                // Get the contact primary id
                $this->db->select('*');
                $this->db->where('userid', $client_id);
                $contact_query_data = $this->db->get(db_prefix() . 'contacts');
                $contact_data = $contact_query_data->row();
                $contact_id = $contact_data->id;
                $contact_user_name = $contact_data->firstname . ' ' . $contact_data->middlename . ' ' . $contact_data->lastname;
            }
            // Insert record in comments table
            $comments_data = array(
                'to_user_id' => $contact_id,
                'from_user_id' => get_staff_user_id(),
                'lead_id' => $lead_id,
                'comment_text' => $comment_text,
                'role' => 'staff',
                'type' => 'client-to-ld',
                'created_at' => date('Y-m-d H:i:s'),
            );
            $this->db->insert(db_prefix() . 'comments', $comments_data);
            // // Get the ID of the inserted comment
            $comment_id = $this->db->insert_id();
            // get staff profile url
            $this->db->select('*');
            $this->db->where('staffid', get_staff_user_id());
            $query = $this->db->get(db_prefix() . 'staff');
            $staff_data = $query->row();
            $profile_check = $staff_data->profile_image;
            $staff_name = $staff_data->firstname . ' ' . $staff_data->lastname;
            if (!empty($profile_check)) {
                $profile_url = base_url('uploads/staff_profile_images/' . $staff_data->staffid . '/thumb_' . $staff_data->profile_image);
            } else {
                $profile_url = base_url('assets/images/user-placeholder.webp');
            }
            // Insert record in read_comment table
            $read_comment_data = array(
                'comment_id' => $comment_id,
                'to_user_id' => $contact_id,
                'from_user_id' => get_staff_user_id(),
                'lead_id' => $lead_id,
                'is_read' => '0',
                'type' => 'client-to-ld',
            );
            $insert_read_comments = $this->db->insert(db_prefix() . 'read_comments', $read_comment_data);
            // add the activity of comments
            $lead_activity_data = array(
                'leadid' => $lead_id,
                'description' => get_staff_full_name() . ' sent a message to ' . $contact_user_name,
                'date' => date('Y-m-d H:i:s'),
                'staffid' => get_staff_user_id(),
                'full_name' => get_staff_full_name()
            );
            $this->db->insert(db_prefix() . 'lead_activity_log', $lead_activity_data);
            if ($insert_read_comments) {
                $commentData['profile_url'] = $profile_url;
                $commentData['staff_name'] = $staff_name;
                $commentHtml = $this->saveCommentAndGetHtml($commentData);
                // notificaation line of code 
                $this->db->select('id,multiple_cases,client_id');
                $this->db->where('id', $lead_id);
                $lead_data_check = $this->db->get(db_prefix() . 'leads');
                if ($lead_data_check->num_rows() > 0) {
                    $lead_data = $lead_data_check->row();
                    $client_id = get_client_id_using_contact_id($this, $lead_data->client_id, $lead_data->multiple_cases);
                    $contact_id = get_contact_id_using_client_id($this, $client_id);
                    $notification_type = get_notification_type(3);
                    $client_notify_type = $notification_type;
                    $client_notify_title = 'New Message Notification';
                    $client_notify_message = get_staff_full_name() . ' sent a message to ' . $contact_user_name;
                    $comment_type = 'client';
                    send_notification_in_mobile('client', get_staff_user_id(), $contact_id, $client_id, $lead_id, $client_notify_title, $client_notify_message, $client_notify_type, '', $comment_type);
                    // send  notiication in crm to all the team group member and staff
                    $comment_message = get_staff_full_name() . ' sent a message to ' . $contact_user_name;
                    $comment_title = 'New Message Notification';
                    $this->db->select('assign_group,assigned');
                    $this->db->where('id', $lead_id);
                    $lead_data_for_get_assign_group = $this->db->get(db_prefix() . 'leads')->row();
                    $current_staff_data = get_staff_ids_by_group($this, $lead_data_for_get_assign_group->assign_group);
                    foreach ($current_staff_data as $staff_notifiy_data) {
                        if (get_staff_user_id() != $staff_notifiy_data['staffid']) {
                            $ldteam_notify_type = $notification_type;
                            $ld_team_notify_title = $comment_title;
                            $ld_team_notify_message = $comment_message;
                            $comment_type = 'client';
                            send_notification_in_mobile('staff', $staff_notifiy_data['staffid'], $contact_id, $client_id, $lead_id, $ld_team_notify_title, $ld_team_notify_message, $ldteam_notify_type, '', $comment_type);

                            // send notification to the crm
                            $this->leads_model->custom_lead_assigned_member_notification('staff', $lead_id, $staff_notifiy_data['staffid'], get_staff_user_id(), '', $comment_message);
                        }
                    }
                    // get the all admin staff ids
                    $admin_ids = get_all_admin_role_staff_ids($this);
                    foreach ($admin_ids as $admin_email) {
                        if (get_staff_user_id() != $admin_email['staffid']) {
                            $admin_notify_type = $notification_type;
                            $admin_notify_title = $comment_title;
                            $admin_notify_message = $comment_message;
                            $comment_type = 'client';
                            send_notification_in_mobile('staff', $admin_email['staffid'], $contact_id, $client_id, $lead_id, $admin_notify_title, $admin_notify_message, $admin_notify_type, '', $comment_type);
                            $this->leads_model->custom_lead_assigned_member_notification('staff', $lead_id, $admin_email['staffid'], get_staff_user_id(), '', $comment_message);
                        }
                    }
                }
                $response = array(
                    'success' => true,
                    'comment_html' => $commentHtml,
                    'id' => $lead_id,
                    'leadView' => $this->_get_lead_data($lead_id),
                );
            } else {
                $response = array(
                    'success' => false,
                );
            }
        }

        header('Content-Type: application/json');
        echo json_encode($response);
    }
    // admin ld comments function 
    public function admin_ld_comments_add($lead_id)
    {
        $this->load->library('form_validation');
        // Check if the request is an AJAX request
        $this->form_validation->set_rules('comments', 'comment', 'required');

        // Define input names for reference
        $input_names = [
            'comments' => 'comments',
        ];
        $response = array();

        if ($this->form_validation->run() == false) {
            // Validation failed
            $errors = [];

            foreach ($input_names as $field => $label) {
                $error = form_error($field);

                if (!empty($error)) {
                    $errors[$field] = $error;
                }
            }

            $response = array(
                'success' => false,
                'errors' => $errors,
            );
            echo json_encode($response);
            exit;
        } else {
            // $lead_id = $this->input->post('lead_id');
            $comment_text = $this->input->post('comments');
            $contact_id = '';
            $response = '';
            $profile_url = '';
            $username = '';
            // Prepare comment data
            $commentData = array(
                'user_id' => 'You',
                // 'lead_id' => $lead_id,
                'comment' => $comment_text,
                'created_at' => time_ago(date('Y-m-d H:i:s')),
                'full_time' => date('m/d/y H:i:s')
            );

            // Get the contact id using lead id with multiple cases handled
            $this->db->select('*');
            $this->db->where('id', $lead_id);
            $this->db->where('multiple_cases', '0');
            $lead_query_data = $this->db->get(db_prefix() . 'leads');

            if ($lead_query_data->num_rows() > 0) {
                // Get the contact primary id
                $lead_data = $lead_query_data->row();
                $client_id = $lead_data->client_id;
                $username = $lead_data->name;
                $this->db->select('id,firstname,middlename,lastname');
                $this->db->where('userid', $client_id);
                $contact_query_data = $this->db->get(db_prefix() . 'contacts');
                if ($contact_query_data->num_rows() > 0) {
                    $contact_data = $contact_query_data->row();
                    $contact_id = $contact_data->id;
                    $contact_user_name = $contact_data->firstname . ' ' . $contact_data->middlename . ' ' . $contact_data->lastname;
                }
            } else {
                $this->db->select('*');
                $this->db->where('id', $lead_id);
                $lead_query_data = $this->db->get(db_prefix() . 'leads');
                $lead_data = $lead_query_data->row();
                $multiple_case_lead_id = $lead_data->multiple_cases;
                $username = $lead_data->name;
                // get client id of the parnet lead case 
                $this->db->select('client_id');
                $this->db->where('id', $multiple_case_lead_id);
                $lead_query_data = $this->db->get(db_prefix() . 'leads');
                $lead_data_parent_case = $lead_query_data->row();
                $client_id = $lead_data_parent_case->client_id;
                // Get the contact primary id
                $this->db->select('*');
                $this->db->where('userid', $client_id);
                $contact_query_data = $this->db->get(db_prefix() . 'contacts');
                $contact_data = $contact_query_data->row();
                $contact_id = $contact_data->id;
                $contact_user_name = $contact_data->firstname . ' ' . $contact_data->middlename . ' ' . $contact_data->lastname;
            }
            // Insert record in comments table
            $comments_data = array(
                'to_user_id' => $contact_id,
                'from_user_id' => get_staff_user_id(),
                'lead_id' => $lead_id,
                'comment_text' => $comment_text,
                'role' => 'staff',
                'type' => 'admin-to-ld',
                'created_at' => date('Y-m-d H:i:s'),
            );
            $this->db->insert(db_prefix() . 'comments', $comments_data);
            // // Get the ID of the inserted comment
            $comment_id = $this->db->insert_id();
            // get staff profile url
            $this->db->select('*');
            $this->db->where('staffid', get_staff_user_id());
            $query = $this->db->get(db_prefix() . 'staff');
            $staff_data = $query->row();
            $profile_check = $staff_data->profile_image;
            $staff_name = $staff_data->firstname . ' ' . $staff_data->lastname;
            if (!empty($profile_check)) {
                $profile_url = base_url('uploads/staff_profile_images/' . $staff_data->staffid . '/thumb_' . $staff_data->profile_image);
            } else {
                $profile_url = base_url('assets/images/user-placeholder.webp');
            }
            // Insert record in read_comment table
            $read_comment_data = array(
                'comment_id' => $comment_id,
                'to_user_id' => $contact_id,
                'from_user_id' => get_staff_user_id(),
                'lead_id' => $lead_id,
                'is_read' => '0',
                'type' => 'admin-to-ld',
            );
            $insert_read_comments = $this->db->insert(db_prefix() . 'read_comments', $read_comment_data);
            // add the activity of comments
            $lead_activity_data = array(
                'leadid' => $lead_id,
                'description' => get_staff_full_name() . ' sent a message to ' . $contact_user_name,
                'date' => date('Y-m-d H:i:s'),
                'staffid' => get_staff_user_id(),
                'full_name' => get_staff_full_name()
            );
            $this->db->insert(db_prefix() . 'lead_activity_log', $lead_activity_data);
            if ($insert_read_comments) {
                $commentData['profile_url'] = $profile_url;
                $commentData['staff_name'] = $staff_name;
                $commentHtml = $this->saveCommentAndGetHtml($commentData);
                // notificaation line of code 
                $this->db->select('id,multiple_cases,client_id');
                $this->db->where('id', $lead_id);
                $lead_data_check = $this->db->get(db_prefix() . 'leads');
                if ($lead_data_check->num_rows() > 0) {
                    $lead_data = $lead_data_check->row();
                    $client_id = get_client_id_using_contact_id($this, $lead_data->client_id, $lead_data->multiple_cases);
                    $contact_id = get_contact_id_using_client_id($this, $client_id);
                    $notification_type = get_notification_type(3);
                    // $client_notify_type = $notification_type;
                    // $client_notify_title = 'New Message Notification';
                    // $client_notify_message = get_staff_full_name() . ' sent a message to ' . $contact_user_name;
                    // $comment_type = 'client';
                    // send_notification_in_mobile('client', get_staff_user_id(), $contact_id, $client_id, $lead_id, $client_notify_title, $client_notify_message, $client_notify_type, '', $comment_type);
                    // // send  notiication in crm to all the team group member and staff
                    $comment_message = get_staff_full_name() . ' sent a message You.';
                    $comment_title = 'New Message Notification';
                    $this->db->select('assign_group,assigned');
                    $this->db->where('id', $lead_id);
                    $lead_data_for_get_assign_group = $this->db->get(db_prefix() . 'leads')->row();
                    $current_staff_data = get_staff_ids_by_group($this, $lead_data_for_get_assign_group->assign_group);
                    foreach ($current_staff_data as $staff_notifiy_data) {
                        if (get_staff_user_id() != $staff_notifiy_data['staffid']) {
                            $ldteam_notify_type = $notification_type;
                            $ld_team_notify_title = $comment_title;
                            $ld_team_notify_message = $comment_message;
                            $comment_type = 'staff';
                            send_notification_in_mobile('staff', $staff_notifiy_data['staffid'], $contact_id, $client_id, $lead_id, $ld_team_notify_title, $ld_team_notify_message, $ldteam_notify_type, '', $comment_type);

                            // send notification to the crm
                            $this->leads_model->custom_lead_assigned_member_notification('staff', $lead_id, $staff_notifiy_data['staffid'], get_staff_user_id(), '', $comment_message);
                        }
                    }
                    // get the all admin staff ids
                    $admin_ids = get_all_admin_role_staff_ids($this);
                    foreach ($admin_ids as $admin_email) {
                        if (get_staff_user_id() != $admin_email['staffid']) {
                            $admin_notify_type = $notification_type;
                            $admin_notify_title = $comment_title;
                            $admin_notify_message = $comment_message;
                            $comment_type = 'staff';
                            send_notification_in_mobile('staff', $admin_email['staffid'], $contact_id, $client_id, $lead_id, $admin_notify_title, $admin_notify_message, $admin_notify_type, '', $comment_type);
                            $this->leads_model->custom_lead_assigned_member_notification('staff', $lead_id, $admin_email['staffid'], get_staff_user_id(), '', $comment_message);
                        }
                    }
                }
                $response = array(
                    'success' => true,
                    'comment_html' => $commentHtml,
                    'id' => $lead_id,
                    'leadView' => $this->_get_lead_data($lead_id),
                );
            } else {
                $response = array(
                    'success' => false,
                );
            }
        }

        header('Content-Type: application/json');
        echo json_encode($response);
    }
    // Function to save the comment to the database and get the HTML representation
    private function saveCommentAndGetHtml($commentData)
    {
        //   <p class="author" style="margin-top: 5px;margin-left: 7px;">' .$commentData['staff_name']. '</p>  yeh phely tha 
        $commentHtml = '<div class="comment">';
        $commentHtml .= '<div style="display:flex;justify-content: end;">
                        <img loading="lazy" src=' . $commentData['profile_url'] . ' style="width: 4%;height: 32px;border-radius: 90%; margin-left: 7px;">
                        <p class="author" style="margin-top: 5px;margin-left: 7px;">' . $commentData['staff_name'] . ' (You) </p>
                        </div>';
        $commentHtml .= '<p style="margin-top: 10px;display: flex;justify-content: end; direction: ltr;">' . $commentData['comment'] . '</p>';
        $commentHtml .= '<div style="display: flex;justify-content: end;"><span class="date text-has-action" data-toggle="tooltip" sytle="display: flex;justify-content: end;" text-has-action" data-title="' . $commentData['full_time'] . '" data-original-title title>' . $commentData['created_at'] . '</span></div>';
        $commentHtml .= '</div>';
        return $commentHtml;
    }
    //  Comments show
    public function comments_show($lead_id)
    {
        if ($this->input->is_ajax_request()) {
            $profil_url = '';
            $contacts_data = '';
            $this->db->select('*');
            $this->db->where('lead_id', $lead_id);
            $this->db->where('type', 'client-to-ld');
            $query = $this->db->get(db_prefix() . 'comments');

            if ($query->num_rows() > 0) {
                $result = $query->result_array();
                $comment_array_data = array();
                foreach ($result as $comment_values) {
                    if ($comment_values['role'] == 'client') {
                        $this->db->select('*');
                        $this->db->where('id', $comment_values['from_user_id']);
                        $query_contacts = $this->db->get(db_prefix() . 'contacts');
                        $contacts_data = $query_contacts->row();
                    }
                    $user_name = ($comment_values['role'] == 'staff') ? '' : $contacts_data->firstname . ' ' . $contacts_data->lastname;
                    $parent_lead_id = get_lead_parent_id($this, $lead_id);
                    if ($comment_values['role'] == 'staff') {
                        $this->db->select('*');
                        $this->db->where('staffid', $comment_values['from_user_id']);
                        $query = $this->db->get(db_prefix() . 'staff');
                        $staff_data = $query->row();
                        $profile_check = $staff_data->profile_image;
                        $staff_name = $staff_data->firstname . ' ' . $staff_data->lastname;
                        if (!empty($profile_check)) {
                            $profil_url = base_url('uploads/staff_profile_images/' . $staff_data->staffid . '/thumb_' . $staff_data->profile_image);
                        } else {
                            $profil_url = null;
                        }
                    } else {
                        $this->db->select('file_url');
                        $this->db->where('rel_id', $parent_lead_id);
                        $this->db->where('rel_type', 'profile-doc');
                        $query = $this->db->get(db_prefix() . 'files');
                        $file_data = $query->row();
                        $profil_url = $file_data->file_url;
                    }
                    $comment_array_data[] = array(
                        'lead_id' => $lead_id,
                        'user_name' => $user_name,
                        'comment_text' => $comment_values['comment_text'],
                        'created_at' => time_ago($comment_values['created_at']),
                        'full_time' => _dt($comment_values['created_at']),
                        'role' => $comment_values['role'],
                        'profile_url' => $profil_url,
                        'staff_name' => $staff_name,
                        'current_user_login_id' => get_staff_user_id(),
                        'from_user_id' => $comment_values['from_user_id']
                    );
                }

                $response = array(
                    'success' => true,
                    'comment_data' => $comment_array_data,
                );
            } else {
                $response = array(
                    'success' => false,
                );
            }

            header('Content-Type: application/json');
            echo json_encode($response);
        }
    }
    public function broker_mail_funds_requested($lead_id)
    {
        $get_mail_subject = get_mail_subject_for_case_stages($this, $lead_id, 4);
        $this->db->select('name,email,addedfrom,phonenumber,client_id,multiple_cases,assign_group');
        $this->db->where('id', $lead_id);
        $get_record = $this->db->get(db_prefix() . 'leads')->row();
        $_POST['broker_name'] = get_staff_name_by_id($this, $get_record->addedfrom);
        $broker_data = get_multiple_broker_details_using_addedfrom($this, $get_record->addedfrom);
        // $subject = 'Funds Requested';
        $subject = $get_mail_subject;
        $replay_to_mail = get_all_staff_to_replay_email($this, get_staff_user_id(), $get_record->assign_group);
        $_POST['case_url'] = get_the_redirect_email_case_url($lead_id, 'broker');
        $html_content_confirmation_email_to_broker = $this->load->view('admin/leads/Email_template/broker/funds_requested_mail_to_broker', $_POST, TRUE);
        // Send email to the client
        $_POST['generic_email_title'] = '';
        $_POST['generic_email_back_to_case_url'] = '';
        $_POST['generic_email_content'] = 'We have requested funds from your new lender and they will now complete their final due diligence. As soon as your file has closed, we will let you know.';
        $html_content_welcome_email_to_user = $this->load->view('admin/leads/Email_template/generic_email_template', $_POST, TRUE);
        $all_client_email = get_all_client_email_using_lead_id($this, $lead_id);
        $to_all_client_email = explode(',', $all_client_email);
        $send_email_result = send_mailchimp_email($to_all_client_email, $subject, $html_content_welcome_email_to_user, $replay_to_mail, '', '', $lead_id);
        // add the record for outbox emails
        $this->Outbox_model->save_outbox_email(
            $to_all_client_email,
            '',
            '',
            $subject,
            $_POST['generic_email_content'],
            '',
            $lead_id,
            4,
            $html_content_welcome_email_to_user,
            $replay_to_mail,
            $send_email_result['status'],
            $send_email_result['mandrill_id'],
            1
        );
        // send sms to the client
        // $sms_message = 'We have requested closing funds from your new lender on your transaction. We shall let you know when your file has completed.Please DO NOT REPLY TO THIS TEXT.';
        // $all_client_phone_list = get_all_client_phonenumber_using_lead_id($this, $lead_id);
        // $this->send_sms($all_client_phone_list, $sms_message, $sms_message, $lead_id, '', '');

        $client_id = get_client_id_using_contact_id($this, $get_record->client_id, $get_record->multiple_cases);
        $contact_id = get_contact_id_using_client_id($this, $client_id);
        // // send notification for case closed
        $notification_type = get_notification_type(2);
        // $client_notify_type = $notification_type . '-created';
        // $client_notify_title = 'Requested Closing from your new lender.';
        // $client_notify_message = '';
        // send_notification_in_mobile('client', get_staff_user_id(), $contact_id, $client_id, $lead_id, $client_notify_title, $client_notify_message, $client_notify_type, '');

        // send  notiication in crm to all the team group member and staff when case closed
        $closed_message = '';
        $slack_message = 'Requested Closing from your new lender by ' . get_staff_full_name() . '.';
        $this->db->select('assign_group,assigned');
        $this->db->where('id', $lead_id);
        $lead_data_for_get_assign_group = $this->db->get(db_prefix() . 'leads')->row();
        $current_staff_data = get_staff_ids_by_group($this, $lead_data_for_get_assign_group->assign_group);

        // // add the app message 
        // $app_message = 'We have requested closing funds from your new lender on your transaction. We shall let you know when your file has completed.';
        // store_app_message_for_client($this, $lead_id, $app_message, 4);
        // store_app_message_for_client($this, $lead_id, $app_message, 5);

        if (!empty($broker_data)) {
            $broker_message = 'Requested Closing from your new lender.';

            $brokerage_id = get_brokerage_id_using_leadid($this, $lead_id);
            $admin_broker_ids = get_all_admin_broker_role_staff_ids($this, $brokerage_id);

            $broker_emails = array_column($broker_data, 'email');

            // Collect admin broker emails (filtered)
            $admin_broker_emails = [];
            foreach ($admin_broker_ids as $admin_broker) {
                if (get_staff_user_id() != $admin_broker['staffid'] && !in_array($admin_broker['staffid'], explode(',', $get_record->addedfrom))) {
                    $admin_broker_emails[] = $admin_broker['email'];
                }
            }

            // Merge and unique emails
            $to_emails = array_unique(array_merge($broker_emails, $admin_broker_emails));

            // Prepare broker name if required (optional)
            $_POST['broker_name'] = 'Team';

            // Send the email once
            if (!empty($to_emails)) {
                $send_email_result = send_mailchimp_email($to_emails, $subject, $html_content_confirmation_email_to_broker, $replay_to_mail, '', '', $lead_id);
                // add the record for outbox emails
                $this->Outbox_model->save_outbox_email(
                    $to_emails,
                    '',
                    '',
                    $subject,
                    $_POST['generic_email_content'],
                    '',
                    $lead_id,
                    4,
                    $html_content_confirmation_email_to_broker,
                    $replay_to_mail,
                    $send_email_result['status'],
                    $send_email_result['mandrill_id'],
                    1
                );
            }

            // Send CRM notification separately
            foreach ($broker_data as $broker) {
                $this->leads_model->custom_lead_assigned_member_notification('staff', $lead_id, $broker['staffid'], get_staff_user_id(), '', $broker_message);
            }
            foreach ($admin_broker_ids as $admin_broker) {
                if (get_staff_user_id() != $admin_broker['staffid'] && !in_array($admin_broker['staffid'], explode(',', $get_record->addedfrom))) {
                    $this->leads_model->custom_lead_assigned_member_notification('staff', $lead_id, $admin_broker['staffid'], get_staff_user_id(), '', $broker_message);
                }
            }
            // update the last contact date 
            $this->leads_model->update_leads_last_contact_date($lead_id);
            $this->leads_model->update_funds_requested_mail($lead_id);
            // add activity logs
            $insert_task_activity = array(
                'leadid' => $lead_id,
                'lead_status' => 4,
                'activity_type' => 'broker-notification-funds-requested',
                'staffid' => get_staff_user_id(),
                'full_name' => get_staff_full_name(),
                'description' => get_staff_full_name() . " sent an email to brokers. Dear Colleague,<br> We are delighted to inform you that the file has successfully moved through another milestone. We have all items required by the lender instructions and we have requested funds.<br> We await a review of any mortgage conditions that remain outstanding and thereafter the confirmation of funding.",
                'date' => date('Y-m-d H:i:s'),
            );
            leads_activity_log($this, $insert_task_activity);
            $response = array(
                'success' => true,
            );
        } else {
            $response = array(
                'success' => false,
            );
        }
        $this->output
            ->set_content_type('application/json')
            ->set_output(json_encode($response));
    }
    // in request for funds stage mail send mail to the client
    public function request_for_funds_report_mail($lead_id)
    {
        $get_mail_subject = get_mail_subject($this, $lead_id);
        $this->db->select('name,email,assign_group');
        $this->db->where('id', $lead_id);
        $get_data = $this->db->get(db_prefix() . 'leads')->row();
        // $subject = 'Funds Requested';
        $subject = $get_mail_subject;
        $_POST['user_name'] = $get_data->name;
        // get the all request for funds docs link
        $this->db->select('file_url,filetype');
        $this->db->where('rel_id', $lead_id);
        $this->db->where('rel_type', 'client-doc-request-for-funds');
        $get_file_data = $this->db->get(db_prefix() . 'cases_checkbox_files')->result_array();
        $_POST['close_attachment'] = $get_file_data;
        $replay_to_mail = get_all_staff_to_replay_email($this, get_staff_user_id(), $get_data->assign_group);
        $html_content_confirmation_email_to_broker = $this->load->view('admin/leads/Email_template/client/req_funds_report_mail', $_POST, TRUE);
        $all_client_email = get_all_client_email_using_lead_id($this, $lead_id);
        $to_all_client_email = explode(',', $all_client_email);
        $send_email_result = send_mailchimp_email($to_all_client_email, $subject, $html_content_confirmation_email_to_broker, $replay_to_mail, '', '', $lead_id);
        // add the record for outbox emails
        $this->Outbox_model->save_outbox_email(
            $to_all_client_email,
            '',
            '',
            $subject,
            $_POST['generic_email_content'],
            '',
            $lead_id,
            4,
            $html_content_confirmation_email_to_broker,
            $replay_to_mail,
            $send_email_result['status'],
            $send_email_result['mandrill_id'],
            1
        );
        if (!empty($get_data->email)) {
            $response = array(
                'success' => true,
            );
        } else {
            $response = array(
                'success' => false,
            );
        }
        $this->output
            ->set_content_type('application/json')
            ->set_output(json_encode($response));
    }
    // acivity refresh
    public function activity_refresh_show($lead_id)
    {
        $response = array(
            'success' => true,
            'id' => $lead_id,
            'leadView' => $this->_get_lead_data($lead_id),
        );
        header('Content-Type: application/json');
        echo json_encode($response);
    }
    // Comments refresh
    public function comments_refresh_show($lead_id)
    {
        $response = array(
            'success' => true,
            'id' => $lead_id,
            'leadView' => $this->_get_lead_data($lead_id),
        );
        header('Content-Type: application/json');
        echo json_encode($response);
    }
    // get secondary email 
    public function get_secondary_email()
    {
        $email = $this->input->post('email');
        $this->db->select('additional_email');
        $this->db->where('email', $email);
        $this->db->order_by('id', 'asc');
        $this->db->limit(1);
        $getrow = $this->db->get(db_prefix() . 'leads')->row();

        if ($getrow) {
            $response = [
                'success' => true,
                'additional_email' => $getrow->additional_email
            ];
        } else {
            $response = [
                'success' => false,
                'message' => 'No additional email found for the provided email'
            ];
        }
        echo json_encode($response);
    }

    // show the case notification 
    public function case_notifications($lead_id)
    {
        $this->db->where('touserid', get_staff_user_id());
        $this->db->where('lead_id', $lead_id);
        $this->db->order_by('date', 'desc');
        $notifications = $this->db->get(db_prefix() . 'notifications')->result_array();
        $i = 0;
        foreach ($notifications as $notification) {
            if (($notification['fromcompany'] == null && $notification['fromuserid'] != 0) || ($notification['fromcompany'] == null && $notification['fromclientid'] != 0)) {
                if ($notification['fromuserid'] != 0) {
                    $notifications[$i]['profile_image'] = '<a href="' . admin_url('staff/profile/' . $notification['fromuserid']) . '">' . staff_profile_image($notification['fromuserid'], [
                        'staff-profile-image-small',
                        'img-circle',
                        'pull-left',
                    ]) . '</a>';
                } else {
                    $notifications[$i]['profile_image'] = '<a href="' . admin_url('clients/client/' . $notification['fromclientid']) . '">
                    <img loading="lazy" class="client-profile-image-small img-circle pull-left" src="' . contact_profile_image_url($notification['fromclientid']) . '"></a>';
                }
            } else {
                $notifications[$i]['profile_image'] = '';
                $notifications[$i]['full_name'] = '';
            }
            $additional_data = '';
            if (!empty($notification['additional_data'])) {
                $additional_data = unserialize($notification['additional_data']);
                $x = 0;
                foreach ($additional_data as $data) {
                    if (strpos($data, '<lang>') !== false) {
                        $lang = get_string_between($data, '<lang>', '</lang>');
                        $temp = _l($lang);
                        if (strpos($temp, 'project_status_') !== false) {
                            $status = get_project_status_by_id(strafter($temp, 'project_status_'));
                            $temp = $status['name'];
                        }
                        $additional_data[$x] = $temp;
                    }
                    $x++;
                }
            }
            $notifications[$i]['description'] = _l($notification['description'], $additional_data);
            $notifications[$i]['date'] = time_ago($notification['date']);
            $notifications[$i]['full_date'] = $notification['date'];
            $i++;
        }
        $this->output
            ->set_content_type('application/json')
            ->set_output(json_encode($notifications));
    }

    private function _get_lead_data($id = '')
    {
        $reminder_data = '';
        $file_query = null;
        $samegroup = '';
        $data['lead_locked'] = false;
        $data['openEdit'] = $this->input->get('edit') ? true : false;
        $data['members'] = $this->staff_model->get('', ['is_not_staff' => 0, 'active' => 1]);
        $data['status_id'] = $this->input->get('status_id') ? $this->input->get('status_id') : get_option('leads_default_status');
        $data['base_currency'] = get_base_currency();

        if (is_numeric($id)) {
            $leadWhere = (has_permission('leads', '', 'view') ? [] : '(assigned = ' . get_staff_user_id() . ' OR addedfrom=' . get_staff_user_id() . ' OR is_public=1)');

            $lead = $this->leads_model->get($id, $leadWhere);
            // get first/parent case lead id
            $this->db->select('*');
            $this->db->where('id', $id);
            $this->db->where('multiple_cases', '0');
            $query = $this->db->get(db_prefix() . 'leads');
            if ($query->num_rows() > 0) {
                $parent_case_record = $query->row();
                $parent_case_id = $parent_case_record->id;
                // get file url using lead id
                $this->db->select('*');
                $this->db->where('rel_id', $parent_case_id);
                $this->db->where('rel_type', 'profile-doc');
                $file_query = $this->db->get(db_prefix() . 'files');
            } else {
                $this->db->select('*');
                $this->db->where('id', $id);
                $lead_query = $this->db->get(db_prefix() . 'leads');
                if ($lead_query->num_rows() > 0) {
                    $parent_case_record = $lead_query->row();
                    $parent_case_id = $parent_case_record->multiple_cases;
                    // get file url using lead id
                    $this->db->select('*');
                    $this->db->where('rel_id', $parent_case_id);
                    $this->db->where('rel_type', 'profile-doc');
                    $file_query = $this->db->get(db_prefix() . 'files');
                }
            }
            if ($file_query !== null && $file_query->num_rows() > 0) {
                $file_data = $file_query->row();
                $file_url = $file_data->file_url;
            } else {
                $file_url = base_url('/assets/images/user-placeholder.webp');
            }
            // get additional email for contact model
            $addedfrom_select_check = '';
            $this->db->select('*');
            $this->db->where('id', $id);
            $Leads_query = $this->db->get(db_prefix() . 'leads');
            $get_leads_row = '';
            if ($Leads_query->num_rows() > 0) {
                $get_leads_row = $Leads_query->row();
                $get_client_id = $get_leads_row->client_id;
                $addedfrom_select_check = $get_leads_row->addedfrom;
                $lead_selected_brokerage_id = $get_leads_row->brokerage_id;
                // get contact table row
                $this->db->select('*');
                $this->db->where('userid', $get_client_id);
                $contact_query = $this->db->get(db_prefix() . 'contacts');
                if ($contact_query->num_rows() > 0) {
                    $get_contact_row = $contact_query->row();
                    $get_additional_email = $get_contact_row->additional_email;
                }
            }
            // get broker name 
            $broker_name_profile_show = get_staff_full_name_using_lead_addedfrom($this, $addedfrom_select_check);
            // get staff name by staff_group and leads_group 
            if (!empty($lead->assign_group)) {
                $get_staff_name_by_group = get_all_staff_name_email_by_group_for_porfile($this, $lead->assign_group);
                $data['get_staff_name_by_group'] = $get_staff_name_by_group;
            }
            if (!$lead) {
                header('HTTP/1.0 404 Not Found');
                echo _l('lead_not_found');
                die;
            }

            if (total_rows(db_prefix() . 'clients', ['leadid' => $id]) > 0) {
                $data['lead_locked'] = ((!is_admin() && get_option('lead_lock_after_convert_to_customer') == 1) ? true : false);
            }

            $state_data = $this->db->get(db_prefix() . 'states')->result_array();
            // Define the manual data to be added
            $manual_state = array(
                'id' => 1000,
                'state_name' => 'Other'
            );
            // Add the manual data to the beginning of the $state_data array
            array_push($state_data, $manual_state);
            $reminder_data = $this->load->view('admin/includes/modals/reminder', [
                'id' => $lead->id,
                'name' => 'lead',
                'members' => $data['members'],
                'state_data' => $state_data,
                'reminder_title' => _l('lead_set_reminder_title'),
            ], true);
            // Get the count of reminders for the given rel_id
            $this->db->where('rel_id', $id);
            $data['reminder_count_check'] = $this->db->count_all_results(db_prefix() . 'reminders');
            // get case related count
            $data['client_comments_count'] = get_case_read_comment_count_client($this, $id);
            $data['broker_comments_count'] = get_case_read_comment_count_broker($this, $id);
            // get the reminder data
            $this->db->select('date, staff, state_id');
            $this->db->where('rel_id', $id);
            $this->db->order_by('id', 'desc');
            $this->db->limit(1);
            $query = $this->db->get(db_prefix() . 'reminders');

            // Check if reminder data exists
            if ($query->num_rows() > 0) {
                $get_reminder_data = $query->row();
                $reminder_staff_name = get_staff_name_by_id($this, $get_reminder_data->staff);
                $data['reminder_staff_name'] = $reminder_staff_name;
                $data['reminder_latest_date'] = $get_reminder_data->date;
                $data['reminder_state_name'] = get_state_name($get_reminder_data->state_id);
                $data['reminder_state_address'] = get_state_address($get_reminder_data->state_id);
            } else {
                $data['reminder_staff_name'] = '';
                $data['reminder_latest_date'] = '';
                $data['reminder_state_name'] = '';
                $data['reminder_state_address'] = '';
            }

            // group match check 
            $staff_group_name = get_group_name_of_staff($this, get_staff_user_id());
            $samegroup = case_crud_permissions_by_role($this, $get_leads_row->assign_group, $staff_group_name);
            // get all stages of cases
            $leads_status_id_data = get_ids_leads_status($this);
            $leads_status_current_id = get_current_stage_of_lead_status($this, $id);
            $ledger_completed_stage = get_ledger_completed_value($this, $id);
            $current_status_order_id = get_current_stage_of_status_order($this, $leads_status_current_id);
            $leads_status_id = [];
            foreach ($leads_status_id_data as $key => $value) {
                $leads_status_id[$key] = $value;
            }
            // get the checklist item type
            $this->db->select('*');
            $checklist_item_type_data = $this->db->get(db_prefix() . 'checklist_item_type')->result_array();
            // get the broker data
            $get_broker_data = get_broker_data($this);
            // get checklist template file open ids
            $get_checklist_template_status_fileopen_id = get_checklist_template_status_fileopen($this);
            // get id of checklist template according to the Outstanding Item
            $get_checklist_template_status_outstanding_id = get_checklist_template_status_outstanding($this);
            $get_checklist_template_status_outstanding_for_ld_team = get_checklist_template_status_outstanding_for_ld_team($this);
            // get id of checklist template according to the Instruction receive 
            $get_checklist_template_status_instruction_receive_id = get_checklist_template_status_instruction_receive($this);
            // get id of checklist template according to the request for funds
            $get_checklist_template_status_request_for_fund_id = get_checklist_template_status_request_for_fund($this);
            // get id of checklist template according to the Close
            $get_checklist_template_status_close_id = get_checklist_template_status_close($this);
            // get id of checklist template according to the  On Hold
            $get_checklist_template_status_on_hold_id = get_checklist_template_status_on_hold($this);

            // get count of file opened checklist
            $count_of_file_open_checklist = count_of_file_open_checklist($this, $id);
            // get count of Instruction item checklist
            $count_of_instruction_receive_checklist = count_of_instruction_receive_checklist($this, $id);
            // get count of outstanding item checklist
            $count_of_outstanding_item_checklist = count_of_outstanding_item_checklist($this, $id);
            // get count of request for funds
            $count_of_request_for_funds_checklist = count_of_request_for_funds_checklist($this, $id);
            if (empty($get_additional_email)) {
                $get_additional_email = '';
            }

            // add the TO mail Client and Brokers
            $to_broker_emails = get_all_staff_name_email_by_addedfrom_for_to($this, $id, 1);
            $data['to_broker_emails'] = $to_broker_emails;
            $brokerage_id = get_brokerage_id_using_leadid($this, $id);
            $to_brokerage_emails = get_all_staff_against_brokerage_id_for_to_email($this, $brokerage_id);
            $data['to_brokerage_emails'] = $to_brokerage_emails;
            $client_email = get_client_email_using_lead_id($this, $id);
            $data['to_client_email'] = $client_email;
            $to_all_case_clients_email = get_all_client_email_using_lead_id($this, $id);
            $data['to_all_case_clients_email'] = $to_all_case_clients_email;
            $data['to_client_and_broker_email'] = $to_broker_emails . ',' . $client_email;
            $bcc_closing_emails = ($brokerage_id == 1 && base_url() != 'https://dev.platform.legaldirect.ca/') ? 'closings@nuborrow.com,accounting@nuborrow.com,nb@legaldirect.ca,bb@legaldirect.ca' : 'nb@legaldirect.ca,bb@legaldirect.ca';
            $data['bcc_closing_emails'] = $bcc_closing_emails . ',' . $to_broker_emails;
            // add the cc emails 
            $cc_group_memebers = get_all_staff_name_email_by_group_for_cc($this, $id, $get_leads_row->assign_group);
            $data['cc_group_memebers'] = $cc_group_memebers;
            $data['group_members_or_broker_emails'] = $cc_group_memebers . ',' . $to_broker_emails;
            // get all client emails count
            $data['all_clients_email_count'] = get_all_clients_email_counts_separately($this, $id);
            $change_password_flag = get_app_side_change_password_flag($this, $get_leads_row->email);
            $data['change_password_flag'] = $change_password_flag;
            // get the back data forinstruction received
            $get_lender_ids = getLenderDetailsByLeadId($this, $id);
            $this->db->select('*');
            if (!empty($get_lender_ids)) {
                $this->db->where_in('id', $get_lender_ids);
            }
            $back_data = $this->db->get(db_prefix() . 'bank')->result_array();
            $data['lead'] = $lead;
            $data['current_lead_status'] = get_current_stage_of_lead_status($this, $id);
            $data['back_data'] = $back_data;
            $data['hosper_lender_count'] = get_hosper_lender_details($this, $id);
            $data['instruction_count'] = get_instruction_count($this, $id);
            $data['get_broker_data'] = $get_broker_data;
            $data['profile_url'] = $file_url;
            $data['broker_name_profile_show'] = $broker_name_profile_show;
            $data['addition_email'] = $get_additional_email;
            $data['current_status_order_id'] = $current_status_order_id;
            // $data['get_staff_name_by_group'] = $get_staff_name_by_group;
            $data['samegroup'] = $samegroup;
            $data['addedfrom_select_check'] = $addedfrom_select_check;
            $data['lead_selected_brokerage_id'] = $lead_selected_brokerage_id;
            $data['selected_brokerage_name'] = get_brokerage_name_using_brokerage_id($this, $lead_selected_brokerage_id);
            $data['selected_brokerage_color'] = get_brokerage_color_using_brokerage_id($this, $lead_selected_brokerage_id);
            $data['mail_activity'] = $this->leads_model->get_mail_activity($id);
            $data['notes'] = $this->misc_model->get_notes($id, 'lead');
            $data['activity_log'] = $this->leads_model->get_lead_activity_log($id);

            $data['leads_status_id'] = $leads_status_id;
            $data['checklist_item_type_data'] = $checklist_item_type_data;
            $data['leads_status_current_id'] = $leads_status_current_id;
            $data['ledger_completed_stage'] = $ledger_completed_stage;
            $data['get_checklist_template_status_fileopen_id'] = $get_checklist_template_status_fileopen_id;
            $data['get_checklist_template_status_outstanding_id'] = $get_checklist_template_status_outstanding_id;
            $data['get_checklist_template_status_outstanding_for_ld_team'] = $get_checklist_template_status_outstanding_for_ld_team;
            $data['get_checklist_template_status_instruction_receive_id'] = $get_checklist_template_status_instruction_receive_id;
            $data['get_checklist_template_status_request_for_fund_id'] = $get_checklist_template_status_request_for_fund_id;
            $data['get_checklist_template_status_close_id'] = $get_checklist_template_status_close_id;
            $data['get_checklist_template_status_on_hold_id'] = $get_checklist_template_status_on_hold_id;
            $data['count_of_file_open_checklist'] = $count_of_file_open_checklist;
            $data['count_of_instruction_receive_checklist'] = $count_of_instruction_receive_checklist;
            $data['count_of_outstanding_item_checklist'] = $count_of_outstanding_item_checklist;
            $data['count_of_request_for_funds_checklist'] = $count_of_request_for_funds_checklist;
            $data['ledger_completed'] = $get_leads_row->ledger_completed;
            $data['closed_completed_at'] = $get_leads_row->closed_completed_at;
            $data['active_case'] = $get_leads_row->active_case;
            if (is_gdpr() && get_option('gdpr_enable_consent_for_leads') == '1') {
                $this->load->model('gdpr_model');
                $data['purposes'] = $this->gdpr_model->get_consent_purposes($lead->id, 'lead');
                $data['consents'] = $this->gdpr_model->get_consents(['lead_id' => $lead->id]);
            }
            // get the reminders count
            $leadProfileBadges = new LeadProfileBadges($id);
            // $data['total_reminders'] = $leadProfileBadges->getCount('reminders');
            $data['total_notes'] = $leadProfileBadges->getCount('notes');
            $data['latest_notes'] = get_latest_notes($this, $id);
            $data['total_attachments'] = $leadProfileBadges->getCount('attachments');
            $data['total_tasks'] = $leadProfileBadges->getCount('tasks');
            $data['total_proposals'] = $leadProfileBadges->getCount('proposals');
        }
        $this->db->select('id,name');
        $this->db->order_by('statusorder', 'asc');
        $leads_status = $this->db->get(db_prefix() . 'leads_status')->result_array();
        $add_ledger = array(
            'id' => 9,
            'name' => 'Send Ledger'
        );
        array_push($leads_status, $add_ledger);
        $data['leads_status'] = $leads_status;
        // get the brokerage data
        $brokerage_data = array();
        $brokerage_dropdown_data = get_brokerage_dropdown_data($this);
        if (!empty($brokerage_dropdown_data)) {
            foreach ($brokerage_dropdown_data as $row) {
                $fullName = $row['name'];
                $brokerage_data[$row['id']] = $fullName;
            }
        }
        $data['brokerage_data'] = $brokerage_data;
        $data['merital_s'] = array(
            'Common Law' => 'Common Law',
            'Divorced' => 'Divorced',
            'Married' => 'Married',
            'Single' => 'Single',
            'Separated' => 'Separated',
            'Consenting/spouse & guarantor' => 'Consenting/spouse & guarantor',
            'Consenting/spouse' => 'Consenting/spouse',
            'Widowed' => 'Widowed'
        );
        // get the leads transaction data
        $this->db->select('*');
        $transaction_data = $this->db->get(db_prefix() . 'leads_transaction_details')->result_array();
        $data['transaction'] = $transaction_data;

        $data['preferred_contact_method_array'] = array(
            '' => 'Nothing selected',
            'Phone' => 'Phone',
            'Email' => 'Email',
        );
        $data['borrow_position'] = array(
            'Borrower' => 'Borrower',
            'Consenting Spouse' => 'Consenting Spouse',
            'Guarantor' => 'Guarantor',
        );
        // get the all lenders details
        $this->db->select('*');
        $this->db->order_by('bank_name', 'ASC');
        $lender_data = $this->db->get(db_prefix() . 'bank')->result_array();
        $data['lender_data'] = $lender_data;
        // get the all borrower first name
        $data['get_all_lead_borrower_first_name'] = get_all_lead_borrower_first_name($this, $id);
        // get the task id using lead id for get a files_url
        $data['close_attachment'] = get_file_attachment($this, $id);
        $data['close_attachment_for_instruction_idverification'] = get_all_instruction_idverification_stage_file($this, $id);
        // get group names
        $this->db->select('group_name');
        $query = $this->db->get(db_prefix() . 'group');
        $staff_group = array();
        if ($query->num_rows() > 0) {
            $result = $query->result_array();
            foreach ($result as $row) {
                $group_name = $row['group_name'];
                $staff_group[$group_name] = $group_name;
            }
        }
        $data['staff_group'] = $staff_group;
        // get all id of task table against the lead id for broker check it is upload the doc or not if upload the doc
        //  the admin assign the case otherwise its is not possible
        $this->db->select('id');
        $this->db->where('rel_id', $id);
        $this->db->where('rel_type', 'user-task');
        $this->db->where('type', 'broker');
        $this->db->where('leads_status', 1);
        $summery_data = $this->db->get(db_prefix() . 'tasks')->result_array();

        // Extracting IDs from the result
        $ids = array_column($summery_data, 'id');

        // If there are no IDs, prevent further querying to avoid errors
        if (!empty($ids)) {
            // Creating a comma-separated list of IDs for the IN clause
            $comma_separated_ids = implode(',', $ids);

            // Fetch files based on the extracted IDs
            $this->db->select('file_url, dateadded, filetype, file_name');
            $this->db->where_in('task_id', $ids);
            $this->db->where('rel_id', $id);
            $this->db->where('rel_type', 'client-doc');
            $files_data = $this->db->get(db_prefix() . 'files')->result_array();
        }
        if (!empty($files_data)) {
            $broker_upload_file = true;
        } else {
            $broker_upload_file = false;
        }
        $data['broker_upload_file'] = $broker_upload_file;
        // get the leads Borrow data 
        $data['leads_borrow'] = get_all_leads_borrow_data($this, $id);
        $data['leads_borrow_count'] = get_leads_borrow_count($this, $id);
        $data['leads_bank_details'] = leads_bank_details($this, $id);
        $data['laywer_firm_data'] = get_laywer_firm_list($this);
        // get the state names for create a new case
        $this->db->select('id,state_name');
        $state_query_data = $this->db->get(db_prefix() . 'states')->result_array();
        $data['state_query_data'] = $state_query_data;

        $data['statuses'] = $this->leads_model->get_leads_status_wrapper();
        $data['timeline_status'] = get_timeline_status();
        $data['sources'] = $this->leads_model->get_source();
        $data['final_close_count'] = get_final_report_activity_count($this, $id, 5, 'closed-emails');
        $data['lender_appt_confirmation_email_status'] = $this->leads_model->check_lender_appt_confirmation_email($id);
        $data['appt_client_email_draft'] = get_email_draft_details($this, $id, 7, 'appointment_client_emailContent');
        // nuborrow files items records show
        $data['uncategorized_nuborrow_files'] = $this->leads_model->get_uncategorized_nuborrow_files($id);
        // outbox record show 
        $data['outbox_records'] = $this->Outbox_model->get_all_outbox($id, [], '', 10, 0, false);
        $data['outbox_count'] = $this->Outbox_model->get_all_outbox($id, '', '', '', '', true);
        // Merging Doc Data 
        $data['merging_doc_data'] = $this->MergingDoc_model->get_merging_doc_data($id);
        $data = hooks()->apply_filters('lead_view_data', $data);

        return [
            'data' => $this->load->view('admin/leads/lead', $data, true),
            'reminder_data' => $reminder_data,
        ];
    }
    // get the brokerage assign broker data
    public function get_brokerage_assign_broker()
    {
        $lead_id = $this->input->post('lead_id');
        $brokerage_id = $this->input->post('brokerage_id');
        // get the brokerage data 
        $broker_id = get_staff_role_id($this, 'Broker');
        $this->db->select('staffid, firstname,lastname');
        $this->db->where_in('role', ['2', '6']);
        $this->db->where('brokerage_ids', $brokerage_id);
        $this->db->order_by('firstname', 'ASC');
        $query = $this->db->get(db_prefix() . 'staff');
        if ($query && $query->num_rows() > 0) {
            $brokerage_data = $query->result_array();
        } else {
            $brokerage_data = array();
        }
        echo json_encode($brokerage_data);
        exit;
    }

    public function leads_kanban_load_more()
    {
        if (!is_staff_member()) {
            ajax_access_denied();
        }

        $status = $this->input->get('status');
        $page = $this->input->get('page');

        $this->db->where('id', $status);
        $status = $this->db->get(db_prefix() . 'leads_status')->row_array();

        $status_loop_ids = [];

        if ($status['id'] == 1 || $status['id'] == 8) {
            $status_loop_ids = [1];
        }

        if ($status['id'] == 2 || $status['id'] == 7) {
            $status_loop_ids = [2];
        }

        if (empty($status_loop_ids)) {
            $status_loop_ids = [$status['id']];
        }
        $filters = $this->session->userdata('kanban_filters');

        foreach ($status_loop_ids as $loop_status_id) {
            // $leads = (new LeadsKanban($loop_status_id))
            //     ->search($this->input->get('search'))
            //     ->sortBy(
            //         $this->input->get('sort_by'),
            //         $this->input->get('sort')
            //     )
            //     ->page($page)->get();
            $kanban = new LeadsKanban($loop_status_id);
            $kanban->setCustomFilters($filters);

            $leads = $kanban
                ->search($this->input->get('search'))
                ->sortBy(
                    $this->input->get('sort_by'),
                    $this->input->get('sort')
                )
                ->page($page)
                ->get();

            $lead_ids = array_column($leads, 'id');
            if (!empty($lead_ids)) {
                if (!empty($lead_ids)) {
                    $this->db->select('id, name, assign_group, multiple_cases, status, secondary_name, transaction, brokerage_id, lender_ids, app_email_requested, active_case, addedfrom, upload_doc');
                    $this->db->where_in('id', $lead_ids);
                    $leads_data = $this->db->get(db_prefix() . 'leads')->result_array();
                    $leads_map = array_column($leads_data, null, 'id');
                }


                $group_names = array_unique(array_column($leads_data, 'assign_group'));
                if (!empty($group_names)) {
                    $this->db->select('group_name, group_color');
                    $this->db->where_in('group_name', $group_names);
                    $groups_data = $this->db->get(db_prefix() . 'group')->result_array();
                    $groups_map = array_column($groups_data, 'group_color', 'group_name');
                }

                $brokerage_ids = array_unique(array_column($leads_data, 'brokerage_id'));

                $addedfrom_ids = array_unique(array_reduce($leads_data, function ($carry, $item) {
                    $ids = explode(',', $item['addedfrom']);
                    foreach ($ids as $id) {
                        $carry[] = (int) trim($id);
                    }
                    return $carry;
                }, []));
                if (!empty($brokerage_ids)) {
                    $this->db->select('id, name, color');
                    $this->db->where_in('id', $brokerage_ids);
                    $brokerage_data = $this->db->get(db_prefix() . 'brokerage')->result_array();
                    $brokerage_map = array_column($brokerage_data, null, 'id');
                }

                $this->db->select('lead_id, bank_id, transaction_id');
                $this->db->where_in('lead_id', $lead_ids);
                $bank_details = $this->db->get(db_prefix() . 'leads_bank_details')->result_array();
                $bank_map = [];
                foreach ($bank_details as $bank) {
                    $bank_map[$bank['lead_id']] = $bank;
                }

                $transaction_ids = [];
                foreach ($bank_details as $bank) {
                    if (!empty($bank['transaction_id'])) {
                        $transaction_ids = array_merge($transaction_ids, explode(',', $bank['transaction_id']));
                    }
                }
                $transaction_ids = array_unique($transaction_ids);


                if (!empty($transaction_ids)) {
                    $this->db->select('id, name');
                    $this->db->where_in('id', $transaction_ids);
                    $transactions = $this->db->get(db_prefix() . 'leads_transaction_details')->result_array();
                    $transaction_map = array_column($transactions, 'name', 'id');
                }
                $this->db->select('rel_id, COUNT(id) as reminder_count');
                $this->db->where_in('rel_id', $lead_ids);
                $this->db->group_by('rel_id');
                $reminders = $this->db->get(db_prefix() . 'reminders')->result_array();
                $reminder_map = array_column($reminders, 'reminder_count', 'rel_id');

                $this->db->select('rel_id, COUNT(id) as task_count');
                $this->db->where_in('rel_id', $lead_ids);
                $this->db->where('rel_type', 'user-task');
                $this->db->group_by('rel_id');
                $tasks = $this->db->get(db_prefix() . 'tasks')->result_array();
                $task_map = array_column($tasks, 'task_count', 'rel_id');

                $this->db->select('lead_id, COUNT(id) as notification_count');
                $this->db->from(db_prefix() . 'notifications');
                $this->db->where_in('lead_id', $lead_ids);
                $this->db->where('isread', '0');
                $this->db->where('touserid', get_staff_user_id());
                $this->db->where_in('additional_data', ['user', 'broker', 'client']);
                $this->db->group_by('lead_id');
                $notifications = $this->db->get()->result_array();

                $notification_map = array_column($notifications, 'notification_count', 'lead_id');

                // get count for send comment by broker
                // $this->db->select('lead_id, COUNT(id) as broker_counter');
                // $this->db->from(db_prefix() . 'read_comments');
                // $this->db->where_in('lead_id', $lead_ids);
                // $this->db->where('to_user_id', get_staff_user_id());
                // $this->db->where('case_is_read', 0);
                // $this->db->where('type', 'broker-to-ld');
                // $this->db->group_by('lead_id');
                // $broker_counter = $this->db->get()->result_array();

                // $broker_notification_map = array_column($broker_counter, 'broker_counter', 'lead_id');

                $this->db->select('lead_id, COUNT(id) as instructions_count');
                $this->db->where('stage_id', 2);
                $this->db->where_in('lead_id', $lead_ids);
                $this->db->group_by('lead_id');
                $instructions = $this->db->get(db_prefix() . 'instruction')->result_array();
                $instructions_map = array_column($instructions, 'instructions_count', 'lead_id');
            }

            foreach ($leads as $lead) {
                $lead_id = $lead['id'];
                $lead_data = $leads_map[$lead_id] ?? null;

                if (!$lead_data)
                    continue;

                $case_group_color = $groups_map[$lead_data['assign_group']] ?? '';

                $brokerage = $brokerage_map[$lead_data['brokerage_id']] ?? [];

                $first_transaction_id = explode(',', $bank_map[$lead_id]['transaction_id'] ?? '')[0] ?? null;
                $transaction_name = $first_transaction_id ? ($transaction_map[$first_transaction_id] ?? '') : '';

                $primary_name = explode(' ', $lead_data['name'], 3);
                $firstname = $primary_name[0] ?? '';
                $middlename = $primary_name[1] ?? '';
                $lastname = $primary_name[2] ?? '';

                $secondary_name = explode(' ', $lead_data['secondary_name'], 3);
                $secondary_firstname = $secondary_name[0] ?? '';
                $secondary_middlename = $secondary_name[1] ?? '';
                $secondary_lastname = $secondary_name[2] ?? '';

                $reminder_count = $reminder_map[$lead_id] ?? 0;
                $notification_count = $notification_map[$lead_id] ?? 0;
                $broker_notification_count = $broker_notification_map[$lead_id] ?? 0;
                // $notification_count = $notification_count + $broker_notification_count;
                $notification_count = $notification_count;

                $task_count = $task_map[$lead_id] ?? 0;
                $instructions_count = $instructions_map[$lead_id] ?? 0;

                $this->load->view('admin/leads/_kan_ban_card', [
                    'lead' => $lead,
                    'name' => $lead_data['name'],
                    'active_case' => $lead_data['active_case'],
                    'firstname' => $firstname,
                    'middlename' => $middlename,
                    'lastname' => $lastname,
                    'secondary_firstname' => $secondary_firstname,
                    'secondary_middlename' => $secondary_middlename,
                    'secondary_lastname' => $secondary_lastname,
                    'status' => $lead_data['status'],
                    // 'base_currency' => $base_currency,
                    'leads_data' => $lead_data,
                    'case_group_color' => $case_group_color,
                    'brokerage_data' => $brokerage,
                    'transaction' => $transaction_name,
                    'reminder_count_check' => $reminder_count,
                    'staff_notification_count_check' => $notification_count,
                    'task_count' => $task_count,
                    'instructions_count' => $instructions_count,
                    'upload_doc' => $lead_data['upload_doc'],
                ]);
            }
            // foreach ($leads as $lead) {
            //     $this->db->select('name,assign_group,multiple_cases,status,secondary_name,transaction,brokerage_id,lender_ids,app_email_requested');
            //     $this->db->where('id', $lead['id']);
            //     $leads_data = $this->db->get(db_prefix() . 'leads')->row();

            //     // Get the groups color
            //     $this->db->select('group_color');
            //     $this->db->where('group_name', $leads_data->assign_group);
            //     $case_group_data = $this->db->get(db_prefix() . 'group')->row();
            //     $case_group_color = $case_group_data->group_color;

            //     // Get the brokerage details
            //     $this->db->select('name,color,mandatory');
            //     $this->db->where('id', $leads_data->brokerage_id);
            //     $brokerage_data = $this->db->get(db_prefix() . 'brokerage')->row();

            //     // Get the first lender ids
            //     $this->db->select('transaction_id');
            //     $this->db->where('lead_id', $lead['id']);
            //     $this->db->where('bank_id', $leads_data->lender_ids);
            //     $leads_bank_details_data = $this->db->get(db_prefix() . 'leads_bank_details')->row();

            //     // Get the transaction details
            //     $transaction_ids = explode(',', $leads_bank_details_data->transaction_id);
            //     $first_transaction_id = $transaction_ids[0];
            //     $this->db->select('name');
            //     $this->db->where('id', $first_transaction_id);
            //     $get_lead_transaction_data = $this->db->get(db_prefix() . 'leads_transaction_details')->row();

            //     // Get the reminders details count
            //     $this->db->where('rel_id', $lead['id']);
            //     $reminder_count_check = $this->db->count_all_results(db_prefix() . 'reminders');

            //     // Get the uploaded items count
            //     $this->db->where('rel_id', $lead['id']);
            //     $this->db->where('rel_type', 'user-task');
            //     $task_count = $this->db->count_all_results(db_prefix() . 'tasks');

            //     // Get unread notifications specific to the staff from 'read_comments'
            //     $this->db->where('touserid', get_staff_user_id());
            //     $this->db->where('lead_id', $lead['id']);
            //     $this->db->where('isread', '0');
            //     $this->db->where('additional_data', 'user');
            //     $notification_count = $this->db->count_all_results(db_prefix() . 'notifications');

            //     // Get unread broker-to-ld notifications from 'notifications'
            //     $this->db->where('lead_id', $lead['id']);
            //     $this->db->where('to_user_id', get_staff_user_id());
            //     $this->db->where('case_is_read', '0');
            //     $this->db->where('type', 'broker-to-ld');
            //     $read_comments_count = $this->db->count_all_results(db_prefix() . 'read_comments');
            //     $staff_notification_count_check = $read_comments_count + $notification_count;

            //     // Break the string of primary name
            //     $primary_name = explode(' ', $leads_data->name, 3);
            //     $firstname = $primary_name[0] ?? '';
            //     $middlename = $primary_name[1] ?? '';
            //     $lastname = $primary_name[2] ?? '';

            //     // Break the string of secondary name
            //     $secondary_name = explode(' ', $leads_data->secondary_name, 3);
            //     $secondary_firstname = $secondary_name[0] ?? '';
            //     $secondary_middlename = $secondary_name[1] ?? '';
            //     $secondary_lastname = $secondary_name[2] ?? '';

            //     $this->load->view('admin/leads/_kan_ban_card', [
            //         'lead' => $lead,
            //         'status' => $status,
            //         'name' => $leads_data->name,
            //         'firstname' => $firstname,
            //         'lastname' => $lastname,
            //         'secondary_middlename' => $secondary_middlename,
            //         'status' => $status,
            //         'leads_data' => $leads_data,
            //         'case_group_color' => $case_group_color,
            //         'brokerage_data' => $brokerage_data,
            //         'transaction' => $get_lead_transaction_data->name,
            //         'reminder_count_check' => $reminder_count_check,
            //         'staff_notification_count_check' => $staff_notification_count_check,
            //         'task_count' => $task_count,
            //         'instructions_count' => $instructions_count,
            //         'upload_doc' => $lead_data['upload_doc'],
            //     ]);
            // }
        }
    }
    public function switch_kanban($set = 0)
    {
        if ($set == 1) {
            $set = 'true';
        } else {
            $set = 'false';
        }
        $this->session->set_userdata([
            'leads_kanban_view' => $set,
        ]);
        redirect($_SERVER['HTTP_REFERER']);
    }

    public function switch_kanban_for_dashboard($set = 0)
    {
        if ($set == 1) {
            $set = 'false';
        } else {
            $set = 'true';
        }
        $this->session->set_userdata([
            'leads_kanban_view' => $set,
        ]);
        redirect(admin_url('cases'));
    }

    public function export($id)
    {
        if (is_admin()) {
            $this->load->library('gdpr/gdpr_lead');
            $this->gdpr_lead->export($id);
        }
    }

    /* Delete lead from database */
    public function delete($id)
    {
        if (!$id) {
            redirect(admin_url('leads'));
        }

        if (!has_permission('leads', '', 'delete')) {
            access_denied('Delete Lead');
        }

        $response = $this->leads_model->delete($id);
        if (is_array($response) && isset($response['referenced'])) {
            set_alert('warning', _l('is_referenced', _l('lead_lowercase')));
        } elseif ($response === true) {
            set_alert('success', _l('deleted', 'Case'));
        } else {
            set_alert('warning', _l('problem_deleting', _l('lead_lowercase')));
        }

        $ref = $_SERVER['HTTP_REFERER'];

        // if user access leads/inded/ID to prevent redirecting on the same url because will throw 404
        if (!$ref || strpos($ref, 'index/' . $id) !== false) {
            redirect(admin_url('leads'));
        }

        redirect($ref);
    }

    public function mark_as_lost($id)
    {
        if (!is_staff_member() || !$this->leads_model->staff_can_access_lead($id)) {
            ajax_access_denied();
        }
        $message = '';
        $success = $this->leads_model->mark_as_lost($id);
        if ($success) {
            $message = _l('lead_marked_as_lost');
        }
        echo json_encode([
            'success' => $success,
            'message' => $message,
            'leadView' => $this->_get_lead_data($id),
            'id' => $id,
        ]);
    }

    public function unmark_as_lost($id)
    {
        if (!is_staff_member() || !$this->leads_model->staff_can_access_lead($id)) {
            ajax_access_denied();
        }
        $message = '';
        $success = $this->leads_model->unmark_as_lost($id);
        if ($success) {
            $message = _l('lead_unmarked_as_lost');
        }
        echo json_encode([
            'success' => $success,
            'message' => $message,
            'leadView' => $this->_get_lead_data($id),
            'id' => $id,
        ]);
    }

    public function mark_as_junk($id)
    {
        if (!is_staff_member() || !$this->leads_model->staff_can_access_lead($id)) {
            ajax_access_denied();
        }
        $message = '';
        $success = $this->leads_model->mark_as_junk($id);
        if ($success) {
            $message = _l('lead_marked_as_junk');
        }
        echo json_encode([
            'success' => $success,
            'message' => $message,
            'leadView' => $this->_get_lead_data($id),
            'id' => $id,
        ]);
    }

    public function unmark_as_junk($id)
    {
        if (!is_staff_member() || !$this->leads_model->staff_can_access_lead($id)) {
            ajax_access_denied();
        }
        $message = '';
        $success = $this->leads_model->unmark_as_junk($id);
        if ($success) {
            $message = _l('lead_unmarked_as_junk');
        }
        echo json_encode([
            'success' => $success,
            'message' => $message,
            'leadView' => $this->_get_lead_data($id),
            'id' => $id,
        ]);
    }

    public function add_activity()
    {
        $leadid = $this->input->post('leadid');
        if (!is_staff_member() || !$this->leads_model->staff_can_access_lead($leadid)) {
            ajax_access_denied();
        }
        if ($this->input->post()) {
            $message = $this->input->post('activity');
            $aId = $this->leads_model->log_lead_activity($leadid, $message);
            if ($aId) {
                $this->db->where('id', $aId);
                $this->db->update(db_prefix() . 'lead_activity_log', ['custom_activity' => 1]);
            }
            echo json_encode(['leadView' => $this->_get_lead_data($leadid), 'id' => $leadid]);
        }
    }
    // get the activity logs by id
    public function get_logs_by_id()
    {
        $log_id = $this->input->get('log_id');
        $lead_id = $this->input->get('lead_id');

        // get the activity log details
        $this->db->select('description');
        $this->db->where('id', $log_id);
        $this->db->where('leadid', $lead_id);
        $get_activity_data = $this->db->get(db_prefix() . 'lead_activity_log')->row();

        if (!empty($get_activity_data)) {
            $response = array(
                'success' => true,
                'log_description' => $get_activity_data->description
            );
        } else {
            $response = array(
                'success' => false,
                'log_description' => null
            );
        }

        $this->output
            ->set_content_type('application/json')
            ->set_output(json_encode($response));
    }

    public function get_convert_data($id)
    {
        if (!is_staff_member() || !$this->leads_model->staff_can_access_lead($id)) {
            ajax_access_denied();
        }
        if (is_gdpr() && get_option('gdpr_enable_consent_for_contacts') == '1') {
            $this->load->model('gdpr_model');
            $data['purposes'] = $this->gdpr_model->get_consent_purposes($id, 'lead');
        }
        $data['lead'] = $this->leads_model->get($id);
        $this->load->view('admin/leads/convert_to_customer', $data);
    }

    /**
     * Convert lead to client
     * @since  version 1.0.1
     * @return mixed
     */
    public function convert_to_customer()
    {
        if (!is_staff_member()) {
            access_denied('Lead Convert to Customer');
        }

        if ($this->input->post()) {
            $default_country = get_option('customer_default_country');
            $data = $this->input->post();
            $data['password'] = $this->input->post('password', false);

            $original_lead_email = $data['original_lead_email'];
            unset($data['original_lead_email']);

            if (isset($data['transfer_notes'])) {
                $notes = $this->misc_model->get_notes($data['leadid'], 'lead');
                unset($data['transfer_notes']);
            }

            if (isset($data['transfer_consent'])) {
                $this->load->model('gdpr_model');
                $consents = $this->gdpr_model->get_consents(['lead_id' => $data['leadid']]);
                unset($data['transfer_consent']);
            }

            if (isset($data['merge_db_fields'])) {
                $merge_db_fields = $data['merge_db_fields'];
                unset($data['merge_db_fields']);
            }

            if (isset($data['merge_db_contact_fields'])) {
                $merge_db_contact_fields = $data['merge_db_contact_fields'];
                unset($data['merge_db_contact_fields']);
            }

            if (isset($data['include_leads_custom_fields'])) {
                $include_leads_custom_fields = $data['include_leads_custom_fields'];
                unset($data['include_leads_custom_fields']);
            }

            if ($data['country'] == '' && $default_country != '') {
                $data['country'] = $default_country;
            }

            $data['billing_street'] = $data['address'];
            $data['billing_city'] = $data['city'];
            $data['billing_state'] = $data['state'];
            $data['billing_zip'] = $data['zip'];
            $data['billing_country'] = $data['country'];

            $data['is_primary'] = 1;
            $id = $this->clients_model->add($data, true);
            if ($id) {
                $primary_contact_id = get_primary_contact_user_id($id);

                if (isset($notes)) {
                    foreach ($notes as $note) {
                        $this->db->insert(db_prefix() . 'notes', [
                            'rel_id' => $id,
                            'rel_type' => 'customer',
                            'dateadded' => $note['dateadded'],
                            'addedfrom' => $note['addedfrom'],
                            'description' => $note['description'],
                            'date_contacted' => $note['date_contacted'],
                        ]);
                    }
                }
                if (isset($consents)) {
                    foreach ($consents as $consent) {
                        unset($consent['id']);
                        unset($consent['purpose_name']);
                        $consent['lead_id'] = 0;
                        $consent['contact_id'] = $primary_contact_id;
                        $this->gdpr_model->add_consent($consent);
                    }
                }
                if (!has_permission('customers', '', 'view') && get_option('auto_assign_customer_admin_after_lead_convert') == 1) {
                    $this->db->insert(db_prefix() . 'customer_admins', [
                        'date_assigned' => date('Y-m-d H:i:s'),
                        'customer_id' => $id,
                        'staff_id' => get_staff_user_id(),
                    ]);
                }
                $this->leads_model->log_lead_activity($data['leadid'], 'not_lead_activity_converted', false, serialize([
                    get_staff_full_name(),
                ]));
                $default_status = $this->leads_model->get_status('', [
                    'isdefault' => 1,
                ]);
                $this->db->where('id', $data['leadid']);
                $this->db->update(db_prefix() . 'leads', [
                    'date_converted' => date('Y-m-d H:i:s'),
                    'status' => $default_status[0]['id'],
                    'junk' => 0,
                    'lost' => 0,
                ]);
                // Check if lead email is different then client email
                $contact = $this->clients_model->get_contact(get_primary_contact_user_id($id));
                if ($contact->email != $original_lead_email) {
                    if ($original_lead_email != '') {
                        $this->leads_model->log_lead_activity($data['leadid'], 'not_lead_activity_converted_email', false, serialize([
                            $original_lead_email,
                            $contact->email,
                        ]));
                    }
                }
                if (isset($include_leads_custom_fields)) {
                    foreach ($include_leads_custom_fields as $fieldid => $value) {
                        // checked don't merge
                        if ($value == 5) {
                            continue;
                        }
                        // get the value of this leads custom fiel
                        $this->db->where('relid', $data['leadid']);
                        $this->db->where('fieldto', 'leads');
                        $this->db->where('fieldid', $fieldid);
                        $lead_custom_field_value = $this->db->get(db_prefix() . 'customfieldsvalues')->row()->value;
                        // Is custom field for contact ot customer
                        if ($value == 1 || $value == 4) {
                            if ($value == 4) {
                                $field_to = 'contacts';
                            } else {
                                $field_to = 'customers';
                            }
                            $this->db->where('id', $fieldid);
                            $field = $this->db->get(db_prefix() . 'customfields')->row();
                            // check if this field exists for custom fields
                            $this->db->where('fieldto', $field_to);
                            $this->db->where('name', $field->name);
                            $exists = $this->db->get(db_prefix() . 'customfields')->row();
                            $copy_custom_field_id = null;
                            if ($exists) {
                                $copy_custom_field_id = $exists->id;
                            } else {
                                // there is no name with the same custom field for leads at the custom side create the custom field now
                                $this->db->insert(db_prefix() . 'customfields', [
                                    'fieldto' => $field_to,
                                    'name' => $field->name,
                                    'required' => $field->required,
                                    'type' => $field->type,
                                    'options' => $field->options,
                                    'display_inline' => $field->display_inline,
                                    'field_order' => $field->field_order,
                                    'slug' => slug_it($field_to . '_' . $field->name, [
                                        'separator' => '_',
                                    ]),
                                    'active' => $field->active,
                                    'only_admin' => $field->only_admin,
                                    'show_on_table' => $field->show_on_table,
                                    'bs_column' => $field->bs_column,
                                ]);
                                $new_customer_field_id = $this->db->insert_id();
                                if ($new_customer_field_id) {
                                    $copy_custom_field_id = $new_customer_field_id;
                                }
                            }
                            if ($copy_custom_field_id != null) {
                                $insert_to_custom_field_id = $id;
                                if ($value == 4) {
                                    $insert_to_custom_field_id = get_primary_contact_user_id($id);
                                }
                                $this->db->insert(db_prefix() . 'customfieldsvalues', [
                                    'relid' => $insert_to_custom_field_id,
                                    'fieldid' => $copy_custom_field_id,
                                    'fieldto' => $field_to,
                                    'value' => $lead_custom_field_value,
                                ]);
                            }
                        } elseif ($value == 2) {
                            if (isset($merge_db_fields)) {
                                $db_field = $merge_db_fields[$fieldid];
                                // in case user don't select anything from the db fields
                                if ($db_field == '') {
                                    continue;
                                }
                                if ($db_field == 'country' || $db_field == 'shipping_country' || $db_field == 'billing_country') {
                                    $this->db->where('iso2', $lead_custom_field_value);
                                    $this->db->or_where('short_name', $lead_custom_field_value);
                                    $this->db->or_like('long_name', $lead_custom_field_value);
                                    $country = $this->db->get(db_prefix() . 'countries')->row();
                                    if ($country) {
                                        $lead_custom_field_value = $country->country_id;
                                    } else {
                                        $lead_custom_field_value = 0;
                                    }
                                }
                                $this->db->where('userid', $id);
                                $this->db->update(db_prefix() . 'clients', [
                                    $db_field => $lead_custom_field_value,
                                ]);
                            }
                        } elseif ($value == 3) {
                            if (isset($merge_db_contact_fields)) {
                                $db_field = $merge_db_contact_fields[$fieldid];
                                if ($db_field == '') {
                                    continue;
                                }
                                $this->db->where('id', $primary_contact_id);
                                $this->db->update(db_prefix() . 'contacts', [
                                    $db_field => $lead_custom_field_value,
                                ]);
                            }
                        }
                    }
                }
                // set the lead to status client in case is not status client
                $this->db->where('isdefault', 1);
                $status_client_id = $this->db->get(db_prefix() . 'leads_status')->row()->id;
                $this->db->where('id', $data['leadid']);
                $this->db->update(db_prefix() . 'leads', [
                    'status' => $status_client_id,
                ]);

                set_alert('success', _l('lead_to_client_base_converted_success'));

                if (is_gdpr() && get_option('gdpr_after_lead_converted_delete') == '1') {
                    // When lead is deleted
                    // move all proposals to the actual customer record
                    $this->db->where('rel_id', $data['leadid']);
                    $this->db->where('rel_type', 'lead');
                    $this->db->update('proposals', [
                        'rel_id' => $id,
                        'rel_type' => 'customer',
                    ]);

                    $this->leads_model->delete($data['leadid']);

                    $this->db->where('userid', $id);
                    $this->db->update(db_prefix() . 'clients', ['leadid' => null]);
                }

                log_activity('Created Lead Client Profile [LeadID: ' . $data['leadid'] . ', ClientID: ' . $id . ']');
                hooks()->do_action('lead_converted_to_customer', ['lead_id' => $data['leadid'], 'customer_id' => $id]);
                redirect(admin_url('clients/client/' . $id));
            }
        }
    }

    /* Used in kanban when dragging and mark as */
    public function update_lead_status()
    {
        if ($this->input->post() && $this->input->is_ajax_request()) {
            $this->leads_model->update_lead_status($this->input->post());
        }
    }

    public function update_status_order()
    {
        if ($post_data = $this->input->post()) {
            $this->leads_model->update_status_order($post_data);
        }
    }

    public function add_lead_attachment()
    {
        $id = $this->input->post('id');
        $lastFile = $this->input->post('last_file');

        if (!is_staff_member() || !$this->leads_model->staff_can_access_lead($id)) {
            ajax_access_denied();
        }

        handle_lead_attachments($id);
        echo json_encode(['leadView' => $lastFile ? $this->_get_lead_data($id) : [], 'id' => $id]);
    }

    public function add_external_attachment()
    {
        if ($this->input->post()) {
            $this->leads_model->add_attachment_to_database(
                $this->input->post('lead_id'),
                $this->input->post('files'),
                $this->input->post('external')
            );
        }
    }

    public function delete_attachment($id, $lead_id)
    {
        if (!is_staff_member() || !$this->leads_model->staff_can_access_lead($lead_id)) {
            ajax_access_denied();
        }
        echo json_encode([
            'success' => $this->leads_model->delete_lead_attachment($id),
            'leadView' => $this->_get_lead_data($lead_id),
            'id' => $lead_id,
        ]);
    }

    public function delete_note($id, $lead_id)
    {
        if (!is_staff_member() || !$this->leads_model->staff_can_access_lead($lead_id)) {
            ajax_access_denied();
        }
        echo json_encode([
            'success' => $this->misc_model->delete_note($id),
            'leadView' => $this->_get_lead_data($lead_id),
            'id' => $lead_id,
        ]);
    }

    public function update_all_proposal_emails_linked_to_lead($id)
    {
        $success = false;
        $email = '';
        if ($this->input->post('update')) {
            $this->load->model('proposals_model');

            $this->db->select('email');
            $this->db->where('id', $id);
            $email = $this->db->get(db_prefix() . 'leads')->row()->email;

            $proposals = $this->proposals_model->get('', [
                'rel_type' => 'lead',
                'rel_id' => $id,
            ]);
            $affected_rows = 0;

            foreach ($proposals as $proposal) {
                $this->db->where('id', $proposal['id']);
                $this->db->update(db_prefix() . 'proposals', [
                    'email' => $email,
                ]);
                if ($this->db->affected_rows() > 0) {
                    $affected_rows++;
                }
            }

            if ($affected_rows > 0) {
                $success = true;
            }
        }

        echo json_encode([
            'success' => $success,
            'message' => _l('proposals_emails_updated', [
                _l('lead_lowercase'),
                $email,
            ]),
        ]);
    }

    public function save_form_data()
    {
        $data = $this->input->post();

        // form data should be always sent to the request and never should be empty
        // this code is added to prevent losing the old form in case any errors
        if (!isset($data['formData']) || isset($data['formData']) && !$data['formData']) {
            echo json_encode([
                'success' => false,
            ]);
            die;
        }

        // If user paste with styling eq from some editor word and the Codeigniter XSS feature remove and apply xss=remove, may break the json.
        $data['formData'] = preg_replace('/=\\\\/m', "=''", $data['formData']);

        $this->db->where('id', $data['id']);
        $this->db->update(db_prefix() . 'web_to_lead', [
            'form_data' => $data['formData'],
        ]);
        if ($this->db->affected_rows() > 0) {
            echo json_encode([
                'success' => true,
                'message' => _l('updated_successfully', _l('web_to_lead_form')),
            ]);
        } else {
            echo json_encode([
                'success' => false,
            ]);
        }
    }

    public function form($id = '')
    {
        if (!is_admin()) {
            access_denied('Web To Lead Access');
        }
        if ($this->input->post()) {
            if ($id == '') {
                $data = $this->input->post();
                $id = $this->leads_model->add_form($data);
                if ($id) {
                    set_alert('success', _l('added_successfully', _l('web_to_lead_form')));
                    redirect(admin_url('leads/form/' . $id));
                }
            } else {
                $success = $this->leads_model->update_form($id, $this->input->post());
                if ($success) {
                    set_alert('success', _l('updated_successfully', _l('web_to_lead_form')));
                }
                redirect(admin_url('leads/form/' . $id));
            }
        }

        $data['formData'] = [];
        $custom_fields = get_custom_fields('leads', 'type != "link"');

        $cfields = format_external_form_custom_fields($custom_fields);
        $data['title'] = _l('web_to_lead');

        if ($id != '') {
            $data['form'] = $this->leads_model->get_form([
                'id' => $id,
            ]);
            $data['title'] = $data['form']->name . ' - ' . _l('web_to_lead_form');
            $data['formData'] = $data['form']->form_data;
        }

        $this->load->model('roles_model');
        $data['roles'] = $this->roles_model->get();
        $data['sources'] = $this->leads_model->get_source();
        $data['statuses'] = $this->leads_model->get_status();

        $data['members'] = $this->staff_model->get('', [
            'active' => 1,
            'is_not_staff' => 0,
        ]);

        $data['languages'] = $this->app->get_available_languages();
        $data['cfields'] = $cfields;

        $db_fields = [];
        $fields = [
            'name',
            'title',
            'email',
            'phonenumber',
            'lead_value',
            'company',
            'address',
            'city',
            'state',
            'country',
            'zip',
            'description',
            'website',
        ];

        $fields = hooks()->apply_filters('lead_form_available_database_fields', $fields);

        $className = 'form-control';

        foreach ($fields as $f) {
            $_field_object = new stdClass();
            $type = 'text';
            $subtype = '';
            if ($f == 'email') {
                $subtype = 'email';
            } elseif ($f == 'description' || $f == 'address') {
                $type = 'textarea';
            } elseif ($f == 'country') {
                $type = 'select';
            }

            if ($f == 'name') {
                $label = _l('lead_add_edit_name');
            } elseif ($f == 'email') {
                $label = _l('lead_add_edit_email');
            } elseif ($f == 'phonenumber') {
                $label = _l('lead_add_edit_phonenumber');
            } elseif ($f == 'lead_value') {
                $label = _l('lead_add_edit_lead_value');
                $type = 'number';
            } else {
                $label = _l('lead_' . $f);
            }

            $field_array = [
                'subtype' => $subtype,
                'type' => $type,
                'label' => $label,
                'className' => $className,
                'name' => $f,
            ];

            if ($f == 'country') {
                $field_array['values'] = [];

                $field_array['values'][] = [
                    'label' => '',
                    'value' => '',
                    'selected' => false,
                ];

                $countries = get_all_countries();
                foreach ($countries as $country) {
                    $selected = false;
                    if (get_option('customer_default_country') == $country['country_id']) {
                        $selected = true;
                    }
                    array_push($field_array['values'], [
                        'label' => $country['short_name'],
                        'value' => (int) $country['country_id'],
                        'selected' => $selected,
                    ]);
                }
            }

            if ($f == 'name') {
                $field_array['required'] = true;
            }

            $_field_object->label = $label;
            $_field_object->name = $f;
            $_field_object->fields = [];
            $_field_object->fields[] = $field_array;
            $db_fields[] = $_field_object;
        }
        $data['bodyclass'] = 'web-to-lead-form';
        $data['db_fields'] = $db_fields;
        $this->load->view('admin/leads/formbuilder', $data);
    }

    public function forms($id = '')
    {
        if (!is_admin()) {
            access_denied('Web To Lead Access');
        }

        if ($this->input->is_ajax_request()) {
            $this->app->get_table_data('web_to_lead');
        }

        $data['title'] = _l('web_to_lead');
        $this->load->view('admin/leads/forms', $data);
    }

    public function delete_form($id)
    {
        if (!is_admin()) {
            access_denied('Web To Lead Access');
        }

        $success = $this->leads_model->delete_form($id);
        if ($success) {
            set_alert('success', _l('deleted', _l('web_to_lead_form')));
        }

        redirect(admin_url('leads/forms'));
    }

    // Sources
    /* Manage leads sources */
    public function sources()
    {
        if (!is_admin()) {
            access_denied('Leads Sources');
        }
        $data['sources'] = $this->leads_model->get_source();
        $data['title'] = 'Leads sources';
        $this->load->view('admin/leads/manage_sources', $data);
    }

    /* Add or update leads sources */
    public function source()
    {
        if (!is_admin() && get_option('staff_members_create_inline_lead_source') == '0') {
            access_denied('Leads Sources');
        }
        if ($this->input->post()) {
            $data = $this->input->post();
            if (!$this->input->post('id')) {
                $inline = isset($data['inline']);
                if (isset($data['inline'])) {
                    unset($data['inline']);
                }

                $id = $this->leads_model->add_source($data);

                if (!$inline) {
                    if ($id) {
                        set_alert('success', _l('added_successfully', _l('lead_source')));
                    }
                } else {
                    echo json_encode(['success' => $id ? true : false, 'id' => $id]);
                }
            } else {
                $id = $data['id'];
                unset($data['id']);
                $success = $this->leads_model->update_source($data, $id);
                if ($success) {
                    set_alert('success', _l('updated_successfully', _l('lead_source')));
                }
            }
        }
    }

    /* Delete leads source */
    public function delete_source($id)
    {
        if (!is_admin()) {
            access_denied('Delete Lead Source');
        }
        if (!$id) {
            redirect(admin_url('leads/sources'));
        }
        $response = $this->leads_model->delete_source($id);
        if (is_array($response) && isset($response['referenced'])) {
            set_alert('warning', _l('is_referenced', _l('lead_source_lowercase')));
        } elseif ($response == true) {
            set_alert('success', _l('deleted', _l('lead_source')));
        } else {
            set_alert('warning', _l('problem_deleting', _l('lead_source_lowercase')));
        }
        redirect(admin_url('leads/sources'));
    }

    // Statuses
    /* View leads statuses */
    public function statuses()
    {
        if (!is_admin()) {
            access_denied('Leads Statuses');
        }
        $data['statuses'] = $this->leads_model->get_status();
        $data['title'] = 'Leads statuses';
        $this->load->view('admin/leads/manage_statuses', $data);
    }

    /* Add or update leads status */
    public function status()
    {
        if (!is_admin() && get_option('staff_members_create_inline_lead_status') == '0') {
            access_denied('Leads Statuses');
        }
        if ($this->input->post()) {
            $data = $this->input->post();
            if (!$this->input->post('id')) {
                $inline = isset($data['inline']);
                if (isset($data['inline'])) {
                    unset($data['inline']);
                }
                $id = $this->leads_model->add_status($data);
                if (!$inline) {
                    if ($id) {
                        set_alert('success', _l('added_successfully', _l('lead_status')));
                    }
                } else {
                    echo json_encode(['success' => $id ? true : false, 'id' => $id]);
                }
            } else {
                $id = $data['id'];
                unset($data['id']);
                $success = $this->leads_model->update_status($data, $id);
                if ($success) {
                    set_alert('success', _l('updated_successfully', _l('lead_status')));
                }
            }
        }
    }

    /* Delete leads status from databae */
    public function delete_status($id)
    {
        if (!is_admin()) {
            access_denied('Leads Statuses');
        }
        if (!$id) {
            redirect(admin_url('leads/statuses'));
        }
        $response = $this->leads_model->delete_status($id);
        if (is_array($response) && isset($response['referenced'])) {
            set_alert('warning', _l('is_referenced', _l('lead_status_lowercase')));
        } elseif ($response == true) {
            set_alert('success', _l('deleted', _l('lead_status')));
        } else {
            set_alert('warning', _l('problem_deleting', _l('lead_status_lowercase')));
        }
        redirect(admin_url('leads/statuses'));
    }
    // closed stage complete
    public function closed_stage_complete()
    {
        $lead_id = $this->input->post('lead_id');

        $success = $this->leads_model->update_closed_status($lead_id);

        // get the details of final report sent or not
        $data = get_final_report_activity_count($this, $lead_id, 5, 'closed-emails');
        if ($success) {
            // update the closed keys
            update_case_closed_keys($this, $lead_id);

            $resposne = array(
                'success' => true,
                'message' => 'Closed stage completed successfully',
                'data' => $data,
                'id' => $lead_id,
                'leadView' => $this->_get_lead_data($lead_id),
            );
        } else {
            $resposne = array(
                'success' => false,
                'message' => 'Closed stage not completed!',
                'data' => $data,
            );
        }
        $this->output
            ->set_content_type('application/json')
            ->set_output(json_encode($resposne));
    }
    /* Add new lead note */
    public function add_note($rel_id)
    {
        if (!is_staff_member() || !$this->leads_model->staff_can_access_lead($rel_id)) {
            ajax_access_denied();
        }

        if ($this->input->post()) {
            $data = $this->input->post();

            if ($data['contacted_indicator'] == 'yes') {
                $contacted_date = to_sql_date($data['custom_contact_date'], true);
                $data['date_contacted'] = $contacted_date;
            }

            unset($data['contacted_indicator']);
            unset($data['custom_contact_date']);

            $data['description'] = isset($data['lead_note_description']) ? $data['lead_note_description'] : $data['description'];
            $get_bob_data = get_bb_data($this);
            if ($get_bob_data->staffid == get_staff_user_id()) {
                // Causing issues with duplicate ID or if my prefixed file for lead.php is used
                $group_name = get_the_group_name_using_leadid($this, $rel_id);
                $lead_name = get_lead_name_using_lead_id($this, $rel_id);
                $lead_name = leads_splitFullName($lead_name);
                $slack_message = "\n- A message has been sent to you  from " . get_staff_full_name() . ".\n- " . $data['lead_note_description'];
                $send_notification = $this->slack->sendnotification($slack_message, $rel_id, $group_name, $lead_name['lastname'] . ', ' . $lead_name['firstname'] . ' ' . $lead_name['middlename']);
                // send email to the team
                // $this->db->select('assign_group,assigned,name');
                // $this->db->where('id', $rel_id);
                // $lead_data = $this->db->get(db_prefix() . 'leads')->row();
                // $current_staff_data = get_staff_ids_by_group($this, $lead_data->assign_group);
                // $_POST['case_url'] = admin_url('cases/index/') . $rel_id;
                // $_POST['user_name'] = '';
                // $_POST['generic_email_content_title'] = 'Good ' . get_afternoon_and_morning();
                // $_POST['generic_email_content'] = 'On the file of ' . $rel_id . ', ' . $lead_name['lastname'] . ', ' . $lead_name['firstname'] . ', a message has been to you from Bob: <br>' . $data['lead_note_description'] . '.<br>';
                // $_POST['generic_email_back_to_case_url'] = 'Please <a href="' . htmlspecialchars($_POST['case_url'], ENT_QUOTES, 'UTF-8') . '">Click here</a> to access the file.';
                // $html_content_welcome_email_to_user = $this->load->view('admin/leads/Email_template/generic_email_template', $_POST, TRUE);
                // $subject = get_mail_subject($this, $rel_id);
                // $replay_to_mail = get_all_staff_to_replay_email($this, get_staff_user_id(), $lead_data->assign_group, '');
                // foreach ($current_staff_data as $staff_notifiy_data) {
                //     send_mailchimp_email($staff_notifiy_data['email'], $subject, $html_content_welcome_email_to_user, $replay_to_mail, '', '', $rel_id);
                // }
            }
            if (isset($data['lead_note_description'])) {
                unset($data['lead_note_description']);
            }
            $note_id = $this->misc_model->add_note($data, 'lead', $rel_id);

            if ($note_id) {
                if (isset($contacted_date)) {
                    $this->db->where('id', $rel_id);
                    $this->db->update(db_prefix() . 'leads', [
                        'lastcontact' => $contacted_date,
                    ]);
                    if ($this->db->affected_rows() > 0) {
                        $this->leads_model->log_lead_activity($rel_id, 'not_lead_activity_contacted', false, serialize([
                            get_staff_full_name(get_staff_user_id()),
                            _dt($contacted_date),
                        ]));
                    }
                }
            }
        }
        echo json_encode(['leadView' => $this->_get_lead_data($rel_id), 'id' => $rel_id]);
    }

    public function email_integration_folders()
    {
        if (!is_admin()) {
            ajax_access_denied('Leads Test Email Integration');
        }

        app_check_imap_open_function();

        $imap = new Imap(
            $this->input->post('email'),
            $this->input->post('password', false),
            $this->input->post('imap_server'),
            $this->input->post('encryption')
        );

        try {
            echo json_encode($imap->getSelectableFolders());
        } catch (ConnectionErrorException $e) {
            echo json_encode([
                'alert_type' => 'warning',
                'message' => $e->getMessage(),
            ]);
        }
    }

    public function test_email_integration()
    {
        if (!is_admin()) {
            access_denied('Leads Test Email Integration');
        }

        app_check_imap_open_function(admin_url('leads/email_integration'));

        $mail = $this->leads_model->get_email_integration();
        $password = $mail->password;

        if (false == $this->encryption->decrypt($password)) {
            set_alert('danger', _l('failed_to_decrypt_password'));
            redirect(admin_url('leads/email_integration'));
        }

        $imap = new Imap(
            $mail->email,
            $this->encryption->decrypt($password),
            $mail->imap_server,
            $mail->encryption
        );

        try {
            $connection = $imap->testConnection();

            try {
                $connection->getMailbox($mail->folder);
                set_alert('success', _l('lead_email_connection_ok'));
            } catch (MailboxDoesNotExistException $e) {
                set_alert('danger', str_replace(["\n", 'Mailbox'], ['<br />', 'Folder'], addslashes($e->getMessage())));
            }
        } catch (ConnectionErrorException $e) {
            $error = str_replace("\n", '<br />', addslashes($e->getMessage()));
            set_alert('danger', _l('lead_email_connection_not_ok') . '<br /><br /><b>' . $error . '</b>');
        }

        redirect(admin_url('leads/email_integration'));
    }

    public function email_integration()
    {
        if (!is_admin()) {
            access_denied('Leads Email Intregration');
        }
        if ($this->input->post()) {
            $data = $this->input->post();
            $data['password'] = $this->input->post('password', false);

            if (isset($data['fakeusernameremembered'])) {
                unset($data['fakeusernameremembered']);
            }
            if (isset($data['fakepasswordremembered'])) {
                unset($data['fakepasswordremembered']);
            }

            $success = $this->leads_model->update_email_integration($data);
            if ($success) {
                set_alert('success', _l('leads_email_integration_updated'));
            }
            redirect(admin_url('leads/email_integration'));
        }
        $data['roles'] = $this->roles_model->get();
        $data['sources'] = $this->leads_model->get_source();
        $data['statuses'] = $this->leads_model->get_status();

        $data['members'] = $this->staff_model->get('', [
            'active' => 1,
            'is_not_staff' => 0,
        ]);

        $data['title'] = _l('leads_email_integration');
        $data['mail'] = $this->leads_model->get_email_integration();

        $data['bodyclass'] = 'leads-email-integration';
        $this->load->view('admin/leads/email_integration', $data);
    }

    public function change_status_color()
    {
        if ($this->input->post() && is_admin()) {
            $this->leads_model->change_status_color($this->input->post());
        }
    }

    public function import()
    {
        if (!is_admin() && get_option('allow_non_admin_members_to_import_leads') != '1') {
            access_denied('Leads Import');
        }

        $dbFields = $this->db->list_fields(db_prefix() . 'leads');
        array_push($dbFields, 'tags');

        $this->load->library('import/import_leads', [], 'import');
        $this->import->setDatabaseFields($dbFields)
            ->setCustomFields(get_custom_fields('leads'));

        if ($this->input->post('download_sample') === 'true') {
            $this->import->downloadSample();
        }

        if (
            $this->input->post()
            && isset($_FILES['file_csv']['name']) && $_FILES['file_csv']['name'] != ''
        ) {
            $this->import->setSimulation($this->input->post('simulate'))
                ->setTemporaryFileLocation($_FILES['file_csv']['tmp_name'])
                ->setFilename($_FILES['file_csv']['name'])
                ->perform();

            $data['total_rows_post'] = $this->import->totalRows();

            if (!$this->import->isSimulation()) {
                set_alert('success', _l('import_total_imported', $this->import->totalImported()));
            }
        }

        $data['statuses'] = $this->leads_model->get_status();
        $data['sources'] = $this->leads_model->get_source();
        $data['members'] = $this->staff_model->get('', ['is_not_staff' => 0, 'active' => 1]);

        $data['title'] = _l('import');
        $this->load->view('admin/leads/import', $data);
    }

    public function validate_unique_field()
    {
        if ($this->input->post()) {

            // First we need to check if the field is the same
            $lead_id = $this->input->post('lead_id');
            $field = $this->input->post('field');
            $value = $this->input->post($field);

            if ($lead_id != '') {
                $this->db->select($field);
                $this->db->where('id', $lead_id);
                $row = $this->db->get(db_prefix() . 'leads')->row();
                if ($row->{$field} == $value) {
                    echo json_encode(true);
                    die();
                }
            }
            // Add phone number validation
            echo total_rows(db_prefix() . 'leads', [$field => $value]) > 0 ? 'true' : 'true';
        }
    }


    public function bulk_action()
    {
        if (!is_staff_member()) {
            ajax_access_denied();
        }

        hooks()->do_action('before_do_bulk_action_for_leads');
        $total_deleted = 0;
        if ($this->input->post()) {
            $ids = $this->input->post('ids');
            $status = $this->input->post('status');
            $source = $this->input->post('source');
            $assigned = $this->input->post('assigned');
            $visibility = $this->input->post('visibility');
            $tags = $this->input->post('tags');
            $last_contact = $this->input->post('last_contact');
            $lost = $this->input->post('lost');
            $has_permission_delete = has_permission('leads', '', 'delete');
            if (is_array($ids)) {
                foreach ($ids as $id) {
                    if ($this->input->post('mass_delete')) {
                        if ($has_permission_delete) {
                            if ($this->leads_model->delete($id)) {
                                $total_deleted++;
                            }
                        }
                    } else {
                        if ($status || $source || $assigned || $last_contact || $visibility) {
                            $update = [];
                            if ($status) {
                                // We will use the same function to update the status
                                $this->leads_model->update_lead_status([
                                    'status' => $status,
                                    'leadid' => $id,
                                ]);
                            }
                            if ($source) {
                                $update['source'] = $source;
                            }
                            if ($assigned) {
                                $update['assign_group'] = $assigned;
                            }
                            if ($last_contact) {
                                $last_contact = to_sql_date($last_contact, true);
                                $update['lastcontact'] = $last_contact;
                            }

                            if ($visibility) {
                                if ($visibility == 'public') {
                                    $update['is_public'] = 1;
                                } else {
                                    $update['is_public'] = 0;
                                }
                            }

                            if (count($update) > 0) {
                                $this->db->where('id', $id);
                                $this->db->update(db_prefix() . 'leads', $update);
                            }
                        }
                        if ($tags) {
                            handle_tags_save($tags, $id, 'lead');
                        }
                        if ($lost == 'true') {
                            $this->leads_model->mark_as_lost($id);
                        }
                    }
                }
            }
        }

        if ($this->input->post('mass_delete')) {
            set_alert('success', 'Total cases deleted ' . $total_deleted);
        }
    }

    public function download_files($lead_id)
    {
        if (!is_staff_member() || !$this->leads_model->staff_can_access_lead($lead_id)) {
            ajax_access_denied();
        }

        $files = $this->leads_model->get_lead_attachments($lead_id);

        if (count($files) == 0) {
            redirect($_SERVER['HTTP_REFERER']);
        }

        $path = get_upload_path_by_type('lead') . $lead_id;

        $this->load->library('zip');

        foreach ($files as $file) {
            $this->zip->read_file($path . '/' . $file['file_name']);
        }

        $this->zip->download('files.zip');
        $this->zip->clear_data();
    }
}
