<?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 Cases 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->model('Outbox_model');
    }

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

        if (!is_staff_member()) {
            access_denied('Cases');
        }
        if (get_current_staff_role($this, get_staff_user_id()) == 2 || get_current_staff_role($this, get_staff_user_id()) == 6) {
            $this->session->set_userdata([
                'leads_kanban_view' => 'true',
            ]);
        }
        $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('*');
        $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);
        // Kanban filter reset when new page load
        $this->session->unset_userdata('kanban_filters');

        $this->load->view('admin/leads/manage_leads', $data);
    }
    // reports function

    public function reports($type, $reports_filter_data, $id = '')
    {
        close_setup_menu();

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

        $data['switch_kanban'] = false;
        $this->session->set_userdata('leads_kanban_view', 'true');
        if ($this->session->userdata('leads_kanban_view') == 'false') {
            $data['switch_kanban'] = true;
            $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('*');
        $lender_data = $this->db->get(db_prefix() . 'bank')->result_array();
        $data['lender_data'] = $lender_data;
        $data['staff_record'] = get_all_staff($this);
        // reports data 
        $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;
        // reports stage selected  id 
        if ($type == 'status') {
            $data['reports_stage'] = $reports_filter_data;
        }
        if ($type == 'broker') {
            $data['reports_broker'] = $reports_filter_data;
        }
        // reports group selected 
        if ($type == 'groups') {
            $data['stage_group'] = $reports_filter_data;
        }
        // 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);
        $this->load->view('admin/leads/manage_leads', $data);
    }
    // custom checklist record
    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());
        // case crud permission
        $samegroup = case_crud_permissions_by_role($this, $lead_data->assign_group, $staff_group_name);
        // get the checklsit/task data
        $this->db->select('name,description,Item_name,ld_notes');
        $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 checklist item type
        $this->db->select('*');
        $checklist_item_type_data = $this->db->get(db_prefix() . 'checklist_item_type')->result_array();
        // 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);
        // show the ld notes
        $ld_notes_Lines = explode("\n", $task_data->ld_notes);
        $trimmedLines_ld_notes = [];

        foreach ($ld_notes_Lines as $line) {
            $trimmedLine_ld_notes = trim($line);

            if ($trimmedLine_ld_notes !== "") {
                $trimmedLines_ld_notes[] = $trimmedLine_ld_notes;
            }
        }
        str_replace("\n\n", "\n", $task_data->ld_notes);
        $cleanedText_ld_notes = str_replace(["\n", '<br>', '<br/>', '<br />'], '<br>', $task_data->ld_notes);
        // get the item type ids
        $get_item_name_id = $task_data->Item_name;
        $item_name_array = explode(',', $get_item_name_id); // Split the string into an array using comma as delimiter
        $item_name_array = array_map('intval', $item_name_array);
        // Combine the lines into a single string without line breaks
        $instructionHtml = implode('<br>', $trimmedLines);
        $ld_notes_Html = implode('<br>', $trimmedLines_ld_notes);
        $matched_ids_string = implode(',', $matched_ids);
        // 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'));
        // $comma_separated_names now contains the item names as a comma-separated string


        $data['task_id'] = $task_id;
        $data['lead_id'] = $lead_id;
        $data['samegroup'] = $samegroup;
        $data['name'] = $task_data->name;
        $data['description'] = $task_data->description;
        $data['doc_type'] = $matched_ids;
        $data['instruction'] = $cleanedText;
        $data['ld_notes'] = $cleanedText_ld_notes;
        $data['show_item_names'] = $comma_separated_names;
        $this->load->view('admin/checklist/checklistshow', ['data' => $data, 'checklist_item_type_data' => $checklist_item_type_data, 'get_item_name_id' => $item_name_array]);
    }
    // Checklist template function
    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();
        // get the broker name
        $this->db->select('staffid,firstname,lastname');
        $this->db->where('role', '2');
        $broker_data = $this->db->get(db_prefix() . 'staff')->result_array();
        // get the checklist item type
        $this->db->select('*');
        $checklist_item_type_data = $this->db->get(db_prefix() . 'checklist_item_type')->result_array();
        if ($id) {
            // get the checklist template data
            $this->db->select('id,order_no,case_status,title,doc_type,description,instruction,addedfrom,Item_name,type');
            $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];
                    }
                }
            }
            // get the item type ids
            $get_item_name_id = $checklist_templates_formdata->Item_name;
            $checklist_type = $checklist_templates_formdata->type;
            $item_name_array = explode(',', $get_item_name_id); // Split the string into an array using comma as delimiter
            $item_name_array = array_map('intval', $item_name_array); // Convert each element to integer


            // 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);
            //  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, 'broker_data' => $broker_data, 'checklist_item_type_data' => $checklist_item_type_data, 'get_item_name_id' => $item_name_array, 'checklist_type' => $checklist_type]);
        } else {
            $this->load->view('admin/checklist/checklist_template', ['lead_status_data' => $lead_status_data, 'checklist_templates' => $checklist_templates, 'broker_data' => $broker_data, 'checklist_item_type_data' => $checklist_item_type_data]);
        }
    }
    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');
        $addedfrom = $this->input->post('addedfrom');
        $Item_name = $this->input->post('Item_name');
        $outstanding_type = $this->input->post('outstanding_type');
        if (is_array($doc_type) && !empty($doc_type)) {
            $doc_type_string = implode(',', $doc_type);
        }
        if (is_array($Item_name) && !empty($Item_name)) {
            $Item_name_string = implode(',', $Item_name);
        }
        $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[500]');
        // $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');
        // $this->form_validation->set_rules('Item_name[]', 'Item Type', 'required');
        $this->form_validation->set_rules('addedfrom', 'Broker', '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,
                    'Item_name' => $Item_name_string,
                    'description' => $checklist_description,
                    'instruction' => $checklist_instruction_new,
                    'addedfrom' => $addedfrom,
                    'type' => $outstanding_type
                ];
                if (!empty($id)) {
                    // Before Update the existing checklist template
                    $checklist_title = get_checklist_template_title_using_id($this, $id);
                    $checklist_type = get_checklist_template_type_using_id($this, $id);
                    $file_status = get_checklist_template_leads_status_using_id($this, $id);
                    if ($checklist_title != $name || $checklist_type != $outstanding_type || $file_status != $lead_status) {
                        if ($outstanding_type == 'broker' || $outstanding_type == 'client') {
                            $task_update_data = array(
                                'name' => $name,
                                'type' => $outstanding_type,
                                'leads_status' => $lead_status,
                            );
                            $this->leads_model->update_task_details_using_checklist_temp_id($id, $outstanding_type, $task_update_data);
                        } else {
                            $checkbox_update_data = array(
                                'title' => $name,
                                'type' => $outstanding_type,
                                'leads_status' => $lead_status,
                            );
                            $this->leads_model->update_checkboxes_details($id, $outstanding_type, $checkbox_update_data);
                        }
                    }

                    $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 the ledger/bank details
    public function lender($id = '')
    {
        if (!empty($id)) {
            $this->db->select('*');
            $this->db->where('id', $id);
            $this->db->order_by('bank_name', 'asc');
            $query_data = $this->db->get(db_prefix() . 'bank')->row();
            if (!empty($query_data)) {
                $this->load->view('admin/leads/add_bank_lender', ['lender_data' => $query_data]);
            } else {
                redirect(admin_url('cases/lender'));
            }
        } else {
            $this->load->view('admin/leads/add_bank_lender');
        }
    }
    public function add_lender()
    {
        if (empty($_POST['lender'])) {
            $response = array(
                'status' => 'error',
                'message' => 'Lender name field is required.'
            );
        } else {
            // Validation succeeded
            $lender = $this->input->post('lender');
            $lender_address = $this->input->post('lender_address');
            $lender_phoneno = $this->input->post('lender_phoneno');
            $lender_id = $this->input->post('lender_id');
            if (!empty($lender_id)) {
                $data = array(
                    'bank_name' => $lender,
                    'lender_address' => $lender_address,
                    'lender_phoneno' => $lender_phoneno,
                    'updated_at' => date('Y-m-d H:i:s')
                );
                $this->db->where('id', $lender_id);
                $this->db->update(db_prefix() . 'bank', $data);
                $response = array(
                    'status' => 'success',
                    'message' => 'Form submitted successfully.'
                );
            } else {
                $data = array(
                    'bank_name' => $lender,
                    'lender_address' => $lender_address,
                    'lender_phoneno' => $lender_phoneno,
                    'created_at' => date('Y-m-d H:i:s')
                );
                $this->db->where('bank_name', $lender);
                $query = $this->db->get(db_prefix() . 'bank');

                if ($query->num_rows() > 0) {
                    // State already exists
                    $response = array(
                        'status' => 'error',
                        'message' => 'Ledger already exists.'
                    );
                } else {
                    $this->db->insert(db_prefix() . 'bank', $data);
                    $response = array(
                        'status' => 'success',
                        'message' => 'Form submitted successfully.'
                    );
                }
            }

        }

        // Send JSON response
        header('Content-Type: application/json');
        echo json_encode($response);
    }
    public function show_all_lender()
    {
        $this->db->select('*');
        $this->db->order_by('bank_name', 'asc');
        $query = $this->db->get(db_prefix() . 'bank')->result_array();
        echo json_encode($query);
    }
    public function delete_lender()
    {
        $lender_id = $this->input->post('id');
        $this->db->where('id', $lender_id);
        $this->db->delete(db_prefix() . 'bank');
        $response = array(
            'status' => 'success'
        );
        header('Content-Type: application/json');
        echo json_encode($response);
    }
    // add and load the brokagesr 
    public function brokerage($id = '')
    {
        $roles = $this->roles_model->get_by_id(2);
        $brokerage_data = get_brokerage_data($this);
        // get staff details 
        $this->db->select(
            'tblstaff.staffid AS staff_id, ' .
            'tblbrokerage.id AS brokerage_id, ' .
            'tblstaff.firstname, tblstaff.lastname, tblstaff.email, ' .
            'tblbrokerage.name AS brokerage_name, tblbrokerage.address'
        );
        $this->db->from('tblstaff');
        $this->db->join('tblbrokerage', 'tblbrokerage.id = tblstaff.brokerage_ids', 'LEFT');
        $this->db->where('tblstaff.role', 2);
        $staff_data = $this->db->get()->result();

        if (!empty($id)) {
            $this->db->select('*');
            $this->db->where('id', $id);
            $query_data = $this->db->get(db_prefix() . 'brokerage')->row();
            $query_data->roles = $roles;
            $query_data->all_brokerage_data = $brokerage_data;
            $query_data->staff_data = $staff_data;
            if (!empty($query_data)) {
                $this->load->view('admin/leads/brokerage', ['brokerage_data' => $query_data]);
            } else {
                redirect(admin_url('cases/brokerage'));
            }
        } else {
            $data['roles'] = $roles;
            $data['all_brokerage_data'] = $brokerage_data;
            $data['staff_data'] = $staff_data;
            $this->load->view('admin/leads/brokerage', $data);
        }
    }
    public function add_brokerage()
    {
        if (empty($_POST['name'])) {
            $response = array(
                'status' => 'error',
                'message' => 'Brokerage name field is required.'
            );
        } else {
            // Validation succeeded
            $name = $this->input->post('name');
            $email = $this->input->post('email');
            $address = $this->input->post('address');
            $phoneno = $this->input->post('phone');
            $color = $this->input->post('color');
            $mandatory = $this->input->post('mandatory');
            $brokerage_id = $this->input->post('brokerage_id');
            if (!empty($brokerage_id)) {
                $data = array(
                    'name' => $name,
                    'email' => $email,
                    'address' => $address,
                    'phone' => $phoneno,
                    'color' => $color,
                    'mandatory' => ($mandatory == 'on') ? 1 : 0,
                    'updated_at' => date('Y-m-d H:i:s')
                );
                $this->db->where('id', $brokerage_id);
                $this->db->update(db_prefix() . 'brokerage', $data);
                $response = array(
                    'status' => 'success',
                    'message' => 'Form submitted successfully.'
                );
            } else {
                $data = array(
                    'name' => $name,
                    'email' => $email,
                    'address' => $address,
                    'phone' => $phoneno,
                    'color' => $color,
                    'mandatory' => ($mandatory == 'on') ? 1 : 0,
                    'created_at' => date('Y-m-d H:i:s')
                );
                $this->db->where('name', $name);
                $query = $this->db->get(db_prefix() . 'brokerage');

                if ($query->num_rows() > 0) {
                    // State already exists
                    $response = array(
                        'status' => 'error',
                        'message' => 'name already exists.'
                    );
                } else {
                    $this->db->insert(db_prefix() . 'brokerage', $data);
                    $response = array(
                        'status' => 'success',
                        'message' => 'Form submitted successfully.'
                    );
                }
            }

        }

        // Send JSON response
        header('Content-Type: application/json');
        echo json_encode($response);
    }
    public function show_all_brokerage()
    {
        $this->db->select('*');
        $query = $this->db->get(db_prefix() . 'brokerage')->result_array();
        echo json_encode($query);
    }
    public function delete_brokerage()
    {
        $brokerage_id = $this->input->post('id');
        // check brokerage id is exit in staff or not
        $brokerage_count = $this->db->where('brokerage_ids', $brokerage_id)
            ->count_all_results(db_prefix() . 'staff');
        if ($brokerage_count > 0) {
            $response = array(
                'status' => 'fail'
            );
        } else {
            $this->db->where('id', $brokerage_id);
            $this->db->delete(db_prefix() . 'brokerage');
            $response = array(
                'status' => 'success'
            );
        }
        header('Content-Type: application/json');
        echo json_encode($response);
    }
    // show the laywer
    public function laywer($type = '', $id = '')
    {
        $roles = $this->roles_model->get_by_id(5);
        $laywer_data = get_laywer_firm_data($this);
        // get staff details 
        $this->db->select(
            'tbllaywer.id AS laywer_id, ' .
            'tbllaywer_firm.id AS laywer_firm_id, ' .
            'tbllaywer.firstname, tbllaywer.lastname, tbllaywer.email, tbllaywer.phone, tbllaywer.address as laywer_address, ' .
            'tbllaywer_firm.name AS laywer_firm_name, tbllaywer_firm.address as laywer_firm_address'
        );
        $this->db->from('tbllaywer');
        $this->db->join('tbllaywer_firm', 'tbllaywer_firm.id = tbllaywer.laywer_firm_id', 'LEFT');
        $staff_data = $this->db->get()->result();

        if ($type == 'laywer-firm' && !empty($id)) {
            $this->db->select('*');
            $this->db->where('id', $id);
            $query_data = $this->db->get(db_prefix() . 'laywer_firm')->row();
            $query_data->roles = $roles;
            $query_data->all_laywer_data = $laywer_data;
            $query_data->staff_data = $staff_data;
            $query_data->type = $type;
            if (!empty($query_data)) {
                $this->load->view('admin/leads/laywer', ['laywer_firm_data' => $query_data]);
            } else {
                redirect(admin_url('cases/laywer'));
            }
        } else if ($type == 'update-laywer' && !empty($id)) {
            $this->db->select('*');
            $this->db->where('id', $id);
            $laywer_data = $this->db->get(db_prefix() . 'laywer')->row();

            // Fetch all lawyer firm details
            $this->db->select('*');
            $laywer_firm_data = $this->db->get(db_prefix() . 'laywer_firm')->result_array();

            if (!empty($laywer_data)) {
                $laywer_data->roles = isset($roles) ? $roles : [];
                $laywer_data->staff_data = isset($staff_data) ? $staff_data : [];
                $laywer_data->type = isset($type) ? $type : '';
                $laywer_data->laywer_firm_data = $laywer_firm_data;
                $this->load->view('admin/leads/laywer', ['laywer_firm_data' => $laywer_data]);
            } else {
                redirect(admin_url('cases/laywer'));
            }
        } else {
            $data['roles'] = $roles;
            $data['all_laywer_data'] = $laywer_data;
            $data['staff_data'] = $staff_data;
            $this->load->view('admin/leads/laywer', $data);
        }
    }
    public function add_laywer_firm()
    {
        if (empty($_POST['name'])) {
            $response = array(
                'status' => 'error',
                'message' => 'Law Firm name field is required.'
            );
        } else {
            // Validation succeeded
            $name = $this->input->post('name');
            $email = $this->input->post('email');
            $address = $this->input->post('address');
            $phoneno = $this->input->post('phone');
            $color = $this->input->post('color');
            $laywer_firm_id = $this->input->post('laywer_firm_id');
            if (!empty($laywer_firm_id)) {
                $data = array(
                    'name' => $name,
                    'email' => $email,
                    'address' => $address,
                    'phone' => $phoneno,
                    'color' => $color,
                    'updated_at' => date('Y-m-d H:i:s')
                );
                $this->db->where('id', $laywer_firm_id);
                $this->db->update(db_prefix() . 'laywer_firm', $data);
                $response = array(
                    'status' => 'success',
                    'message' => 'Form submitted successfully.'
                );
            } else {
                $data = array(
                    'name' => $name,
                    'email' => $email,
                    'address' => $address,
                    'phone' => $phoneno,
                    'color' => $color,
                    'created_at' => date('Y-m-d H:i:s')
                );
                $this->db->where('name', $name);
                $query = $this->db->get(db_prefix() . 'laywer_firm');

                if ($query->num_rows() > 0) {
                    // State already exists
                    $response = array(
                        'status' => 'error',
                        'message' => 'name already exists.'
                    );
                } else {
                    $this->db->insert(db_prefix() . 'laywer_firm', $data);
                    $response = array(
                        'status' => 'success',
                        'message' => 'Form submitted successfully.'
                    );
                }
            }

        }

        // Send JSON response
        header('Content-Type: application/json');
        echo json_encode($response);
    }
    public function add_laywer()
    {
        // Validation succeeded
        $firstname = $this->input->post('firstname');
        $lastname = $this->input->post('lastname');
        $email = $this->input->post('email');
        $address = $this->input->post('address');
        $phoneno = $this->input->post('phone');
        $laywer_firm_id = $this->input->post('laywer_firm_id');
        $laywer_id = $this->input->post('laywer_id');
        if (!empty($laywer_firm_id)) {
            if (!empty($laywer_id)) {
                $data = array(
                    'firstname' => $firstname,
                    'lastname' => $lastname,
                    'email' => $email,
                    'address' => $address,
                    'phone' => $phoneno,
                    'laywer_firm_id' => $laywer_firm_id,
                    'updated_at' => date('Y-m-d H:i:s')
                );
                $this->db->where('id', $laywer_id);
                $this->db->update(db_prefix() . 'laywer', $data);
                $response = array(
                    'success' => 'true',
                    'message' => 'Form submitted successfully.'
                );
            } else {
                $data = array(
                    'firstname' => $firstname,
                    'lastname' => $lastname,
                    'email' => $email,
                    'address' => $address,
                    'phone' => $phoneno,
                    'laywer_firm_id' => $laywer_firm_id,
                    'created_at' => date('Y-m-d H:i:s')
                );
                $this->db->insert(db_prefix() . 'laywer', $data);
                $response = array(
                    'success' => 'true',
                    'message' => 'Form submitted successfully.'
                );
            }
        } else {
            $response = array(
                'success' => 'fail',
                'message' => 'Form not submit!.'
            );
        }

        // Send JSON response
        header('Content-Type: application/json');
        echo json_encode($response);
    }
    public function update_lawyer()
    {
        $this->load->library('form_validation');

        // Set validation rules
        $this->form_validation->set_rules('firstname', 'First Name', 'required');
        $this->form_validation->set_rules('email', 'Email', 'required');
        $this->form_validation->set_rules('lawyer_firm_ids', 'Lawyer Firm', 'required', [
            'required' => 'Please select a lawyer firm.',
        ]);

        if ($this->form_validation->run() === false) {
            // Validation failed, return errors
            echo json_encode([
                'success' => false,
                'errors' => [
                    'firstname' => form_error('firstname'),
                    'email' => form_error('email'),
                    'lawyer_firm_ids' => form_error('lawyer_firm_ids'),
                ],
            ]);
            return;
        }

        $id = $this->input->post('laywer_id');
        $data = [
            'firstname' => $this->input->post('firstname'),
            'lastname' => $this->input->post('lastname'),
            'phone' => $this->input->post('phonenumber'),
            'email' => $this->input->post('email'),
            'address' => $this->input->post('address'),
            'laywer_firm_id' => $this->input->post('lawyer_firm_ids'),
        ];
        $this->db->where('id', $id);
        $update = $this->db->update(db_prefix() . 'laywer', $data);

        if ($update) {
            echo json_encode(['success' => true]);
        } else {
            echo json_encode(['success' => false, 'message' => 'Failed to update the record.']);
        }
    }
    // delete laywer 
    public function delete_laywer()
    {
        $laywer_id = $this->input->post('laywer_id');

        if (!$laywer_id) {
            echo json_encode([
                'success' => false,
                'message' => 'Invalid request. Lawyer ID is required.',
            ]);
            return;
        }

        $this->db->where('id', $laywer_id);
        $deleted = $this->db->delete(db_prefix() . 'laywer');

        if ($deleted) {
            echo json_encode([
                'success' => true,
                'message' => 'Lawyer record deleted successfully.',
            ]);
        } else {
            echo json_encode([
                'success' => false,
                'message' => 'Failed to delete lawyer record. Please try again.',
            ]);
        }
    }
    public function laywer_email_exists()
    {
        $email = $this->input->post('email');

        $this->db->where('email', $email);
        $exists = $this->db->get(db_prefix() . 'laywer')->row();
        if ($exists) {
            echo json_encode(['success' => false, 'message' => 'Email already exists.']);
        } else {
            echo json_encode(['success' => true, 'message' => 'Email is available.']);
        }
    }

    public function show_all_laywer_firm()
    {
        $this->db->select('*');
        $this->db->order_by('name', 'ASC');
        $query = $this->db->get(db_prefix() . 'laywer_firm')->result_array();
        echo json_encode($query);
    }
    public function delete_laywer_firm()
    {
        $laywer_firm_ids = $this->input->post('id');
        // check brokerage id is exit in staff or not
        $brokerage_count = $this->db->where('laywer_firm_ids', $laywer_firm_ids)
            ->count_all_results(db_prefix() . 'staff');
        if ($brokerage_count > 0) {
            $response = array(
                'status' => 'fail'
            );
        } else {
            $this->db->where('id', $laywer_firm_ids);
            $this->db->delete(db_prefix() . 'laywer_firm');
            $response = array(
                'status' => 'success'
            );
        }
        header('Content-Type: application/json');
        echo json_encode($response);
    }
    // add appointment states 
    public function states($id = '')
    {
        if (!empty($id)) {
            $this->db->select('*');
            $this->db->where('id', $id);
            $query_data = $this->db->get(db_prefix() . 'states')->row();
            if (!empty($query_data)) {
                $this->load->view('admin/leads/appointment_states', ['state_data' => $query_data]);
            } else {
                redirect(admin_url('cases/states'));
            }
        } else {
            $this->load->view('admin/leads/appointment_states');
        }
    }
    public function add_states()
    {
        if (empty($_POST['state'])) {
            $response = array(
                'status' => 'error',
                'message' => 'State field is required.'
            );
        } else {
            // Validation succeeded
            $state = $this->input->post('state');
            $state_address = $this->input->post('address');
            $state_id = $this->input->post('state_id');
            if (!empty($state_id)) {
                $data = array(
                    'state_name' => $state,
                    'state_address' => $state_address,
                );
                $this->db->where('id', $state_id);
                $this->db->update(db_prefix() . 'states', $data);
                $response = array(
                    'status' => 'success',
                    'message' => 'Form submitted successfully.'
                );
            } else {
                $data = array(
                    'state_name' => $state,
                    'state_address' => $state_address,
                );
                $this->db->where('state_name', $state);
                $query = $this->db->get(db_prefix() . 'states');

                if ($query->num_rows() > 0) {
                    // State already exists
                    $response = array(
                        'status' => 'error',
                        'message' => 'State already exists.'
                    );
                } else {
                    $this->db->insert(db_prefix() . 'states', $data);
                    $response = array(
                        'status' => 'success',
                        'message' => 'Form submitted successfully.'
                    );
                }
            }

        }

        // Send JSON response
        header('Content-Type: application/json');
        echo json_encode($response);
    }
    public function show_all_states()
    {
        $this->db->select('id,state_name,state_address');
        $query = $this->db->get(db_prefix() . 'states')->result_array();
        echo json_encode($query);
    }
    public function delete_state()
    {
        $state_id = $this->input->post('id');
        $this->db->where('id', $state_id);
        $this->db->delete(db_prefix() . 'states');
        $response = array(
            'status' => 'success'
        );
        header('Content-Type: application/json');
        echo json_encode($response);
    }
    public function checkboxes($id = '')
    {
        $this->db->select('id,name');
        $this->db->order_by('statusorder', 'asc');
        $leads_status = $this->db->get(db_prefix() . 'leads_status')->result_array();
        if (!empty($id)) {
            $this->db->select('*');
            $this->db->where('id', $id);
            $query_data = $this->db->get(db_prefix() . 'checkboxes')->row();
            if (!empty($query_data)) {
                $this->load->view('admin/leads/checkboxes', ['checkbox_data' => $query_data, 'leads_status' => $leads_status]);
            } else {
                redirect(admin_url('cases/checkboxes'));
            }
        } else {
            $this->load->view('admin/leads/checkboxes', ['leads_status' => $leads_status]);
        }
    }
    public function add_checkboxes()
    {
        if (empty($_POST['checkbox_title'])) {
            $response = array(
                'status' => 'error',
                'field' => 'checkbox_title',
                'message' => 'post-appointment title field is required.'
            );
        } elseif (empty($_POST['checkbox_description'])) {
            $response = array(
                'status' => 'error',
                'field' => 'checkbox_description',
                'message' => 'post-appointment description field is required.'
            );
        } else {
            // Validation succeeded
            $checkbox_title = $this->input->post('checkbox_title');
            $leads_status = $this->input->post('leads_status');
            $checkbox_description = $this->input->post('checkbox_description');
            $checkbox_id = $this->input->post('checkbox_id');
            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() . 'checkboxes', $data);
                $response = array(
                    'status' => 'success',
                    'message' => 'Form updated successfully.'
                );
            } else {
                $data = array(
                    'title' => $checkbox_title,
                    'description' => $checkbox_description,
                    'leads_status' => $leads_status,
                    'status' => 0,
                    'created_at' => date('Y-m-d H:i:s')
                );
                $this->db->insert(db_prefix() . 'checkboxes', $data);
                $response = array(
                    'status' => 'success',
                    'message' => 'Form submitted successfully.'
                );
            }

        }
        header('Content-Type: application/json');
        echo json_encode($response);
    }

    public function show_all_checkboxes()
    {
        $this->db->select('*');
        $query = $this->db->get(db_prefix() . 'checkboxes')->result_array();
        foreach ($query as &$data) {
            $this->db->select('name');
            $this->db->where('id', $data['leads_status']);
            $status_name = $this->db->get(db_prefix() . 'leads_status')->row();
            $data['status_name'] = $status_name->name;
        }
        echo json_encode($query);
    }
    public function show_all_checkboxes_for_appointment($lead_id)
    {
        $this->db->select('*');
        $this->db->where('leads_status', '0');
        $this->db->where('lead_id', $lead_id);
        $this->db->order_by('order_no', 'asc');
        $query = $this->db->get(db_prefix() . 'cases_checkboxes')->result_array();
        $order_flag = 1;
        foreach ($query as &$data) {
            $data['order_no'] = (!empty($data['order_no'])) ? $data['order_no'] : $order_flag++;

            $this->db->select('name');
            $this->db->where('id', $data['leads_status']);
            $status_name = $this->db->get(db_prefix() . 'leads_status')->row();
            $data['status_name'] = $status_name->name;
        }
        echo json_encode($query);
    }
    public function show_all_checkboxes_for_requrest_funds($lead_id)
    {
        $this->db->select('*');
        $this->db->where('leads_status', '4');
        $this->db->where('lead_id', $lead_id);
        $this->db->order_by('order_no', 'asc');
        $query = $this->db->get(db_prefix() . 'cases_checkboxes')->result_array();
        $order_flag = 1;
        foreach ($query as &$data) {
            // Add order_no logic
            $data['order_no'] = (!empty($data['order_no'])) ? $data['order_no'] : $order_flag++;

            $this->db->select('name');
            $this->db->where('id', $data['leads_status']);
            $status_name = $this->db->get(db_prefix() . 'leads_status')->row();
            $data['status_name'] = $status_name->name;
            // get the case_checkboxes file
            $this->db->select('id,cases_checkbox_id,file_name,filetype,file_url,dateadded');
            $this->db->where('cases_checkbox_id', $data['id']);
            $get_cases_checkboxes_data = $this->db->get(db_prefix() . 'cases_checkbox_files')->result();
            $data['get_cases_checkboxes_data'] = $get_cases_checkboxes_data;
        }
        echo json_encode($query);
    }
    public function show_all_checkboxes_for_outstanding_ld_team($lead_id)
    {
        $this->db->select('*');
        $this->db->where('leads_status', '3');
        $this->db->where('lead_id', $lead_id);
        $this->db->order_by('order_no', 'asc');
        $query = $this->db->get(db_prefix() . 'cases_checkboxes')->result_array();
        $order_flag = 1;

        foreach ($query as &$data) {
            // Add order_no logic
            $data['order_no'] = (!empty($data['order_no'])) ? $data['order_no'] : $order_flag++;

            $this->db->select('name');
            $this->db->where('id', $data['leads_status']);
            $status_name = $this->db->get(db_prefix() . 'leads_status')->row();
            $data['status_name'] = $status_name->name;
            // get the case_checkboxes file
            $this->db->select('id,cases_checkbox_id,file_name,filetype,file_url,dateadded,lender_name,payout_expire_date');
            $this->db->where('cases_checkbox_id', $data['id']);
            $get_cases_checkboxes_data = $this->db->get(db_prefix() . 'cases_checkbox_files')->result();
            $data['get_cases_checkboxes_data'] = $get_cases_checkboxes_data;
        }
        echo json_encode($query);
    }
    public function show_all_checkboxes_for_outstanding_ld_team_payouts($lead_id)
    {
        $this->db->select('*');
        $this->db->where('leads_status', '7');
        $this->db->where('lead_id', $lead_id);
        $this->db->order_by('order_no', 'asc');
        $query = $this->db->get(db_prefix() . 'cases_checkboxes')->result_array();
        $order_flag = 1;
        foreach ($query as &$data) {
            $data['description'] = str_replace(["\n", '<br>', '<br/>', '<br />'], '<br>', $data['description']);
            // Add order_no logic
            $data['order_no'] = (!empty($data['order_no'])) ? $data['order_no'] : $order_flag++;

            $this->db->select('name');
            $this->db->where('id', $data['leads_status']);
            $status_name = $this->db->get(db_prefix() . 'leads_status')->row();
            $data['status_name'] = $status_name->name;
            // get the case_checkboxes file
            $this->db->select('id,cases_checkbox_id,file_name,filetype,file_url,dateadded,lender_name,payout_expire_date');
            $this->db->where('cases_checkbox_id', $data['id']);
            $get_cases_checkboxes_data = $this->db->get(db_prefix() . 'cases_checkbox_files')->result();
            $data['get_cases_checkboxes_data'] = $get_cases_checkboxes_data;
        }
        echo json_encode($query);
    }
    public function delete_checkbox()
    {
        $state_id = $this->input->post('id');
        $this->db->where('id', $state_id);
        $this->db->delete(db_prefix() . 'checkboxes');
        $response = array(
            'status' => 'success'
        );
        header('Content-Type: application/json');
        echo json_encode($response);
    }
    public function delete_checkbox_for_appointment($lead_id)
    {
        $state_id = $this->input->post('id');
        // get checklist details
        $this->db->select('title');
        $this->db->where('id', $state_id);
        $get_record = $this->db->get(db_prefix() . 'cases_checkboxes')->row();
        // delete checklist 
        $this->db->where('id', $state_id);
        $this->db->delete(db_prefix() . 'cases_checkboxes');
        $response = array(
            'status' => 'success'
        );
        $insert_task_activity = array(
            'leadid' => $lead_id,
            'staffid' => get_staff_user_id(),
            'full_name' => get_staff_full_name(),
            'activity_type' => 'task-activity',
            'description' => "Checklist item (" . $get_record->title . ") has been deleted  by " . get_staff_full_name(),
            'date' => date('Y-m-d H:i:s'),
        );
        leads_activity_log($this, $insert_task_activity);
        header('Content-Type: application/json');
        echo json_encode($response);
    }
    public function update_checkbox_status()
    {
        $checkboxId = $this->input->post('id');
        $response = array();

        if (!empty($checkboxId)) {
            // Get current checkbox status
            $this->db->select('status');
            $this->db->where('id', $checkboxId);
            $checkboxStatus = $this->db->get(db_prefix() . 'cases_checkboxes')->row();

            if (!empty($checkboxStatus)) {
                $status = $checkboxStatus->status;
                $newStatus = ($status == 1) ? 0 : 1;
                $checked = ($status == 1) ? '' : 'checked';
                $data = array('status' => $newStatus);
                $this->db->where('id', $checkboxId);
                $this->db->update(db_prefix() . 'cases_checkboxes', $data);

                if ($this->db->affected_rows() > 0) {
                    $response['status'] = 'success';
                    $response['checked'] = $checked;
                } else {
                    $response['status'] = 'error';
                    $response['message'] = 'Failed to update checkbox status';
                }
            } else {
                $response['status'] = 'error';
                $response['message'] = 'Checkbox not found';
            }
        } else {
            $response['status'] = 'error';
            $response['message'] = 'Checkbox ID is missing';
        }

        header('Content-Type: application/json');
        echo json_encode($response);
    }
    // update the secure payout expire dates
    public function update_secure_payout_expire_date($lead_id)
    {
        $expire_date = $this->input->post('expire_date');
        $checkbox_id = $this->input->post('id');
        // update the expire date in cases_checkboxes table
        $affected = $this->leads_model->update_checkbox_expire_date($lead_id, $checkbox_id, $expire_date);

        if ($affected > 0) {
            // 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' => 'Secure payout expire date updated to ' . $expire_date . ' by ' . get_staff_full_name(),
                'date' => date('Y-m-d H:i:s'),
            );
            leads_activity_log($this, $insert_task_activity);
            // pass success response
            $response = array(
                'success' => true,
                'id' => $checkbox_id,
                'expire_date' => $expire_date,
                'status' => 'success',
                'message' => 'expire Date updated successfully.'
            );
        } else {
            $response = array(
                'success' => false,
                'status' => 'error',
                'message' => 'expire Date not updated.'
            );
        }
        $this->output
            ->set_content_type('application/json')
            ->set_output(json_encode($response));
    }
    // update secure Received yes/no
    public function update_secure_received($lead_id)
    {
        $checkbox_id = $this->input->post('id');
        $secure_received_option_value = $this->input->post('secure_received_option');

        if ($checkbox_id && $secure_received_option_value !== null) {
            // Update the secure received status in cases_checkboxes table
            $affected = $this->leads_model->update_secure_received_status($checkbox_id, $secure_received_option_value);

            if ($affected > 0) {
                // Add activity log
                $insert_task_activity = array(
                    'leadid' => $lead_id,
                    'staffid' => get_staff_user_id(),
                    'full_name' => get_staff_full_name(),
                    'activity_type' => '',
                    'description' => 'Secure item received status updated to ' . $secure_received_option_value . ' by ' . get_staff_full_name(),
                    'date' => date('Y-m-d H:i:s'),
                );
                leads_activity_log($this, $insert_task_activity);

                $response = array(
                    'success' => true,
                    'checkbox_id' => $checkbox_id,
                    'secure_item_received' => $secure_received_option_value,
                    'message' => 'Secure payout Received updated successfully.'
                );
            } else {
                $response = array(
                    'success' => false,
                    'message' => 'Secure payout Received not updated.'
                );
            }
        } else {
            $response = array(
                'success' => false,
                'message' => 'Secure payout Received not updated.'
            );
        }

        $this->output
            ->set_content_type('application/json')
            ->set_output(json_encode($response));
    }
    
    //uncategorized documents get form the nuborrow
    public function get_uncategorized_documents($lead_id)
    {
        // Get Uncategorized Nuborrow Files
        $this->db->where('rel_id', $lead_id);
        $this->db->where('rel_type', 'nuborrow-files');
        $files = $this->db->get(db_prefix() . 'files')->result_array();

        // Get Task Items with Lead/Borrower Name
        $this->db->select('id, name, lead_borrow_id, type');
        $this->db->where('rel_id', $lead_id);
        $tasks = $this->db->get(db_prefix() . 'tasks')->result_array();

        foreach ($tasks as &$task) {
            $task['display_name'] = $task['name'];

            if ($task['lead_borrow_id'] == 0) {
                $lead = $this->db->get_where(db_prefix() . 'leads', ['id' => $lead_id])->row();
                if ($lead && $task['type'] == 'client') {
                    $n = leads_splitFullName($lead->name);
                    $task['display_name'] .= ' (' . trim($n['lastname'] . ', ' . $n['firstname'] . ' ' . $n['middlename']) . ')';
                }
            } else {
                $borrow = $this->db->get_where(db_prefix() . 'leads_borrow', ['id' => $task['lead_borrow_id']])->row();
                if ($borrow && $task['type'] == 'client') {
                    $task['display_name'] .= ' (' . trim($borrow->borrow_firstname . ' ' . $borrow->borrow_lastname . ' ' . $borrow->borrow_middlename) . ')';
                }
            }
        }

        // Get Cases Checkboxes with Title
        $this->db->select('id, title');
        $this->db->where('lead_id', $lead_id);
        $cases = $this->db->get(db_prefix() . 'cases_checkboxes')->result_array();

        echo json_encode([
            'files' => $files,
            'tasks' => $tasks,
            'cases' => $cases,
        ]);
    }

    public function nuborrow_bulk_assign_document_type($lead_id)
    {
        $assignments = $this->input->post('assignments');
        $success = 0;
        $failed = 0;
        
        foreach ($assignments as $assignment) {
            $file_id = $assignment['file_id'];
            $rel_type = $assignment['rel_type'];
            $itemid = $assignment['itemid'];

            // Set Client And Broker Status. 
            if (!empty($itemid)) {
                $this->db->where('id', $itemid);
                $task = $this->db->get(db_prefix() . 'tasks')->row();
    
                if ($task) {
                    $status = ($task->type == 'client') ? 1 : 5; // 1(Pending Review) for client, 5(Uploaded) for broker
                    $this->leads_model->update_status_by_task_id($itemid, $status);
                }
                if($task->type == 'client' && $status == 1){
                    $description = 'Document has been Pending Review by ' . get_staff_full_name() . '.';
                    $insert_task_activity = array(
                        'leadid' => $lead_id,
                        'task_id' => $itemid,
                        'staffid' => get_staff_user_id(),
                        'full_name' => get_staff_full_name(),
                        'activity_type' => 'task-activity',
                        'description' => $description,
                        'additional_data' => 'Pending Review',
                        'reason' => '',
                        'date' => date('Y-m-d H:i:s'),
                    );
                    leads_activity_log($this, $insert_task_activity);
                }
            }

            if ($rel_type == 'task') {
                $this->db->where('id', $file_id);
                $this->db->update(db_prefix() . 'files', [
                    'rel_type' => 'client-doc',
                    'task_id' => $itemid,
                ]);
                $this->db->affected_rows() > 0 ? $success++ : $failed++;
            } elseif ($rel_type == 'case') {
                $get_ld_item_details = get_cases_checkbox_by_id($this, $itemid);
                $item_type = 'client-doc-outstanding-item';
                if ($get_ld_item_details && $get_ld_item_details->leads_status == 4) {
                    $item_type = 'client-doc-request-for-funds';
                }

                $tblfile_attachments = $this->leads_model->get_file_attachment_by_id($file_id);
                if ($tblfile_attachments) {
                    $insert_data = [
                        'cases_checkbox_id' => $itemid,
                        'rel_id' => $lead_id,
                        'rel_type' => $item_type,
                        'file_name' => $tblfile_attachments->file_name,
                        'filetype' => $tblfile_attachments->filetype,
                        'file_url' => $tblfile_attachments->file_url,
                        'download_file_url' => $tblfile_attachments->download_file_url,
                        'dateadded' => $tblfile_attachments->dateadded
                    ];
                    $this->leads_model->insert_cases_checkboxes_files($insert_data);

                    $this->db->where('id', $file_id);
                    $this->db->delete(db_prefix() . 'files');

                    $this->db->affected_rows() > 0 ? $success++ : $failed++;
                } else {
                    $failed++;
                }
            } else {
                $failed++;
            }
        }

        echo json_encode(['status' => true, 'message' => "Bulk assign done. Success: $success, Failed: $failed"]);
    }



    public function delete_document()
    {
        $file_id = $this->input->post('file_id');

        $this->db->where('id', $file_id);
        $this->db->delete(db_prefix() . 'files');

        echo json_encode(['status' => true]);
    }


}
