<?php

use chriskacerguis\RestServer\RestController;

class V1 extends RestController
{
    public function __construct()
    {

        parent::__construct();
        //error_reporting(E_ALL);
        $this->load->library('form_validation');
        $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->model('Token_model');
        header('Access-Control-Allow-Origin: *');
        header("Access-Control-Allow-Methods: PUT, GET, POST, DELETE, OPTIONS");
    }
    private function extractToken($authorizationHeader)
    {
        // Extract the token from the header (you need to implement this)
        // Example: "Bearer YOUR_API_TOKEN" -> "YOUR_API_TOKEN"
        return str_replace('Bearer ', '', $authorizationHeader);
    }

    private function isValidToken_lead($token)
    {

        return $token === get_option('broker_case_api_token');
    }
    public function token_post()
    {
        $input = json_decode(file_get_contents("php://input"), true);

        $client_id = trim($this->input->post('client_id'));
        $client_secret = trim($this->input->post('client_secret'));

        // Basic authentication check
     
        if (
            $client_id === unlayer_extract(getenv('NUBORROW_CLIENT_ID'), $_ENV['Nuborrow_Lock_signature']) && 
            $client_secret ===  unlayer_extract(getenv('NUBORROW_CLIENT_SECRET'), $_ENV['Nuborrow_Lock_signature'])
            ) {
            $access_token = bin2hex(string: random_bytes(32));
            $refresh_token = bin2hex(random_bytes(32));
            $expires_at = date("Y-m-d H:i:s", strtotime("+1 hour"));

            $this->db->insert(db_prefix() . 'nuborrow_api_tokens', [
                'client_id' => $client_id,
                'access_token' => $access_token,
                'refresh_token' => $refresh_token,
                'expires_at' => $expires_at,
            ]);

            echo json_encode([
                'status' => 200,
                'message' => 'Token generated successfully',
                'access_token' => $access_token,
                'refresh_token' => $refresh_token,
                'expires_in' => 3600
            ]);
        } else {
            echo json_encode([
                'status' => 400,
                'message' => 'Unauthorized Person! please provide the valid client_id and client_secret!',
            ]);
        }
    }
    public function refresh_token_post()
    {
        $input = json_decode(file_get_contents("php://input"), true);
        $refresh_token = trim($this->input->post('refresh_token')) ?? '';

        $this->db->where('refresh_token', $refresh_token);
        $query = $this->db->get(db_prefix() . 'nuborrow_api_tokens');

        if ($query->num_rows() > 0) {
            $access_token = bin2hex(random_bytes(32));
            $expires_at = date("Y-m-d H:i:s", strtotime("+1 hour"));

            $this->db->where('refresh_token', $refresh_token);
            $this->db->update(db_prefix() . 'nuborrow_api_tokens', [
                'access_token' => $access_token,
                'expires_at' => $expires_at
            ]);

            echo json_encode([
                'status' => 200,
                'message' => 'Token refreshed successfully',
                'access_token' => $access_token,
                'expires_in' => 3600
            ]);
        } else {
            echo json_encode([
                'status' => 400,
                'message' => 'Refresh token is invalid!',
            ]);
        }
    }
    private function validate_token()
    {
        $headers = $this->input->request_headers();
        $token = $headers['Authorization'] ?? '';

        if (!$token) {
            return false;
        }
        // Remove Bearer prefix if present
        if (stripos($token, 'Bearer ') === 0) {
            $token = trim(str_ireplace('Bearer', '', $token));
        }

        $this->db->where('access_token', $token);
        $this->db->where('expires_at >=', date('Y-m-d H:i:s'));
        $this->db->order_by('id', 'DESC');
        $this->db->limit(1);
        $query = $this->db->get(db_prefix() . 'nuborrow_api_tokens');

        return $query->num_rows() > 0;
    }

    public function cases_post()
    {
        /*
            {
            "name": "John Doe",
            "email": "john.doe@example.com",
            "phonenumber": "123-456-7890",
            "address": "123 Main St, City, Country",
            "addedfrom": 4
            }
        */
        // if(base_url() == 'https://platform.legaldirect.ca/'){
        //     return $this->response([
        //         'success' => 400,
        //         'message' => 'you have not access to this API for Live push cases.',
        //     ], 400);
        // }

        $input = file_get_contents("php://input");

        $_POST = json_decode($input, true);
        //$this->form_validation->set_rules('place', 'City', 'trim|required');
        $authorizationHeader = $this->input->get_request_header('Authorization');
        $token = $this->extractToken($authorizationHeader);
        // if ($this->isValidToken_lead($token)) {
        if ($this->validate_token()) {
            if (!empty($_POST)) {
                $data = $_POST;
                $nuborrow_lead_id = $data['id'];
                $lender_name = $data['lender_name'] ?? '';
                $money_need = $data['money_need'] ?? '';
                $lender_id = '';
                if(!empty($lender_name)){
                    $check_lender_name = search_lender_name($this, $lender_name);
                    if(empty($check_lender_name)){
                        $this->db->insert(db_prefix() . 'bank', [
                            'bank_name' => $lender_name,
                            'created_at' => date('Y-m-d H:i:s'),
                            'updated_at' => date('Y-m-d H:i:s'),
                        ]);
                        if ($this->db->affected_rows() > 0) {
                            $lender_id = $this->db->insert_id();
                        } else {
                            echo json_encode([
                                'success' => 400,
                                'message' => "Lender details could not be inserted. Please try again.",
                            ]);
                            die;
                        }
                    }else{
                        $lender_id = $check_lender_name->id;
                    }
                }
                if(!empty(check_nuborrow_leadid_inserted($this, $nuborrow_lead_id))){
                    return $this->response([
                        'success' => 400,
                        'message' => 'Nuborrow lead ID already exists.'
                    ], 400);
                }
                $allowed_titles = [
                    'ID\'s',
                    'LD consent form',
                    'Commitment',
                    'Broker fee agreement',
                    'Draft figures',
                    'Marriage disclosure/marital status',
                    'Void cheque(s)',
                    'Property tax statement',
                    'Appraisal',
                    'Other',
                    'Mortgage Statement'
                ];

                // lead/case name split and store in the database
                $split_names = leads_splitFullName($data['name']);

                $allowedKeys = ['name', 'zip', 'city', 'state', 'address', 'email', 'phonenumber', 'status', 'sp_notes', 'country', 'marital_status', 'co_borrower', 'uploaded_files', 'mortgage_type', 'prepaid_rate'];

                // Filter the $data array to keep only allowed keys
                $data = array_filter(
                    $data,
                    fn($key) => in_array($key, $allowedKeys),
                    ARRAY_FILTER_USE_KEY
                );
                if (empty($split_names['lastname']) && !empty($split_names['middlename'])) {
                    $split_names['lastname'] = $split_names['middlename'];
                    $split_names['middlename'] = '';
                }
                $data['firstname'] = $split_names['firstname'];
                $data['middlename'] = $split_names['middlename'];
                $data['lastname'] = $split_names['lastname'];
                $data['status'] = 1;
                $data['active_case'] = 'Active';
                $data['description'] = $data['sp_notes'] ?? '';
                $data['lastcontact'] = date('Y-m-d H:i:s');
                $data['last_status_change'] = date('Y-m-d H:i:s');
                $data['country'] = (!empty($data['country'])) ? $data['country'] : '40';
                $data['lender_ids'] = $lender_id;
                $brokerage_data = get_brokerage_data($this);
                foreach ($brokerage_data as $data_brokerage) {
                    if ($data_brokerage['name'] == 'Nuborrow' || $data_brokerage['name'] == 'nuborrow') {
                        $data['brokerage_id'] = $data_brokerage['id'];
                    }
                }
                // $this->db->select('id, client_id, email, active_case');
                // $this->db->from(db_prefix() . 'leads');
                // $this->db->where('email', $data['email']);
                // // $this->db->where('active_case', 'Active');
                // $query = $this->db->get();
                // if ($query->num_rows() > 0) {
                // 	// Fetch all rows and get last result 
                // 	$results = $query->row();
                // 	// $lastRow = end($results);
                // 	$lastColumn_id = $results->id;
                // 	// $lastColumn_client_id = $results->client_id;
                // 	// insert/add leads data
                // 	$data = add_leads($data);
                // 	$data['multiple_cases'] = $lastColumn_id;
                // 	// $data['client_id'] = $lastColumn_client_id;
                // 	if (empty($data['addedfrom'])) {
                // 		$data['addedfrom'] = get_staff_user_id();
                // 	}
                // 	$this->db->insert(db_prefix() . 'leads', $data);
                // 	$insert_id = $this->db->insert_id();
                // } else {
                // 	// insert/add clients
                // 	$data = add_leads($data);
                // 	$clients = add_clients($data);
                // 	$this->db->insert(db_prefix() . 'clients', $clients);
                // 	$client_id = $this->db->insert_id();
                // 	// insert/add leads
                // 	$data['client_id'] = $client_id;
                // 	if (empty($data['addedfrom'])) {
                // 		$data['addedfrom'] = get_staff_user_id();
                // 	}
                // 	// //tbl leads insert 
                // 	$this->db->insert(db_prefix() . 'leads', $data);
                // 	$insert_id = $this->db->insert_id();
                // 	//  insert/add contact
                // 	$contact = add_contacts($data);
                // 	$contact['userid'] = $client_id;
                // 	$rand_password = generateRandomPassword($insert_id, $data['name']);
                // 	$hashed_password = password_hash($rand_password, PASSWORD_BCRYPT);
                // 	$contact['password'] = $hashed_password;
                // 	$this->db->insert(db_prefix() . 'contacts', $contact);

                // }
                $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' => 400,
                        'alert_type' => "warning",
                        'message' => "Staff Email Already in Use. Please choose a different email address for the case.",
                    ]);
                    die;
                }
                $data_add = $this->add($data);
                $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}");
                if(!empty($lender_id) && !empty($id)){
                    $data = [
                        'lead_id' => $id,
                        'bank_id' => $lender_id,
                        'index' => 0,
                        'transaction_id' => 0,
                        'loan_amount' => $money_need,
                        '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);
                //     }
                // }
                $co_borrowers = $this->input->post('co_borrower');
                if (!empty($co_borrowers) && is_array($co_borrowers)) {
                    foreach ($co_borrowers as $co_borrower) {
                        // Map directly without changing keys
                        $leads_borrow_data = [
                            'lead_id' => $id,
                            'borrow_firstname' => isset($co_borrower['firstname']) ? $co_borrower['firstname'] : '',
                            'borrow_middlename' => '',
                            'borrow_lastname' => isset($co_borrower['lastname']) ? $co_borrower['lastname'] : '',
                            'borrow_address' => isset($co_borrower['borrow_address']) ? $co_borrower['borrow_address'] : $data['address'],
                            'borrow_position' => isset($co_borrower['borrow_position']) ? $co_borrower['borrow_position'] : $data['position'],
                            'borrow_city' => isset($co_borrower['borrow_city']) ? $co_borrower['borrow_city'] : $data['city'],
                            'borrow_province' => isset($co_borrower['borrow_province']) ? $co_borrower['borrow_province'] : $data['state'],
                            'borrow_zipcode' => isset($co_borrower['borrow_zipcode']) ? $co_borrower['borrow_zipcode'] : $data['zip'],
                            'borrow_email' => isset($co_borrower['email']) ? $co_borrower['email'] : '',
                            'borrow_phone' => isset($co_borrower['phonenumber']) ? $co_borrower['phonenumber'] : '',
                            'borrow_martial_status' => isset($co_borrower['borrow_martial_status']) ? $co_borrower['borrow_martial_status'] : $data['marital_status'],
                            'borrow_preferred_method' => '',
                            'created_at' => date('Y-m-d H:i:s'),
                        ];
                        // Insert if name exists
                        if ($leads_borrow_data['borrow_firstname'] != '' || $leads_borrow_data['borrow_lastname'] != '') {
                            $lead_borrower_id = $this->leads_model->add_leads_borrow_records($leads_borrow_data);
                            // Load checklist templates
                            $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);
                        }
                    }
                }
                $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;
                    // 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);
                    $this->db->order_by('order_no', 'asc');
                    $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']);
                    // }
                    // 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 Nuborrow.';
                        $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 Nuborrow. \n - Please review and assign.";
                    $this->slack->sendnotification($slack_message, $id, $check_assign_group, $lead_name['lastname'] . ', ' . $lead_name['firstname']);

                    $_POST['generic_email_title'] = 'Case Created';
                    $_POST['generic_email_back_to_case_url'] = 'Please <a href="' . htmlspecialchars($_POST['case_url'], ENT_QUOTES, 'UTF-8') . '">Clicking here</a> to access the file and allocate it to the relevant team.';
                    $_POST['generic_email_content'] = 'Congratulations. Nuborrow has sent a new instruction, Case ' . $id . ', ' . $split_names['lastname'] . ', ' . $split_names['firstname'] . '.';
                    $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_mailchimp_email('hassannasir6321@gmail.com', $subject, $html_content_welcome_email_to_user, $replay_to_mail, '', '', $id);
                    } else {
                        send_mailchimp_email('newcases@legaldirect.ca', $subject, $html_content_welcome_email_to_user, $replay_to_mail, '', '', $id);
                    }
                    // 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') . '">Clicking 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_mailchimp_email('hassannasir6321@gmail.com', $subject, $html_content_welcome_email_to_user, $replay_to_mail, '', '', $id);
                    //     } else {
                    //         send_mailchimp_email('newcases@legaldirect.ca', $subject, $html_content_welcome_email_to_user, $replay_to_mail, '', '', $id);
                    //     }
                    //     // send notification in crm to all admins
                    //     $case_created_message = 'New case (ID: #' . $id . ' & Name:' . $case_name . ') created by Nuborrow.';
                    //     $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 Nuborrow.';
                    //             // 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);
                    //         }
                    //     }
                    // }
                }
                // 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') : '';

                // upload doc againts the case and different ids
                $data = $this->Contacts_model->getEmail($data['email']);
                $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);
                $OtherItemCounter = 0;
                $NuborrowBrokerLastOrderno = get_tasks_last_order_no_using_lead_id_type($this, $id, 'broker');
                foreach ($_POST['uploaded_files'] as $file) {
                    $doc_title = $file['title'];
                    $file_url = $file['file_url'];

                    $upload_response = $this->leads_model->upload_remote_file_to_dropbox(
                        $file_url,
                        $doc_title,
                        $id,
                        $dropbox_firstname,
                        $dropbox_lastname
                    );

                    // get the item id details
                    if (!empty($doc_title) && in_array($doc_title, $allowed_titles)){
                        /*
                            If Nuborrow selects multiple "Other" items:
                            - The first selected item will be saved with its actual name.
                            - Any additional selected "Other" items will be saved as: Other1, Other2, Other3, and so on.
                            - This ensures unique naming for each "Other" item in case of multiple selections.
                        */
                        $OtherItemCounter = nuborrow_add_multiple_other_items_counter($OtherItemCounter, $doc_title);
                        if (strtolower($doc_title) == 'other') {
                            $doc_title = 'Other' . $OtherItemCounter;
                            $otherTaskData = [
                                'name' => $doc_title,
                                'description' => 'Please enter the details of ' . $doc_title . ' according to the instruction',
                                'status' => '2',
                                'dateadded' => date('Y-m-d H:i:s'),
                                'rel_id' => $id,
                                'rel_type' => 'user-task',
                                'leads_status' => '1',
                                'type' => 'broker',
                                'order_no' => ($NuborrowBrokerLastOrderno++) + 1, // Remove '1' to revert back to previous state.
                            ];
                            $this->leads_model->insert_nuborrow_task_for_multiple_other_items($id, $otherTaskData, $OtherItemCounter);

                        }
                        
                        $task_id = get_task_id_by_task_name($this, $doc_title, $id);
                        $cases_checkbox_id = empty($task_id) ? get_cases_checkbox_id_by_title($this, $id, $doc_title) : '';
                        if(!empty($task_id)) {
                            $this->leads_model->client_related_doc_add_in_db($task_id, $id, 'client-doc', $upload_response);
                            // update status againts cases
                            $get_task_record = get_task_name_by_task_id($this, $task_id);
                            if ($get_task_record->type == 'broker') {
                                if (preg_match('/\b(photo id\s*\d*|paper id\s*\d*)\b/i', $get_task_record->name)) {
                                    $task_data = array(
                                        'status' => 1,
                                        'checkbox_status' => 1,
                                        'ld_notes' => $file['other_description'] ?? '',
                                    );
                                } else {
                                    $task_data = array(
                                        'status' => 5,
                                        'checkbox_status' => 1,
                                        'ld_notes' => $file['other_description'] ?? '',
                                    );
                                }
                            } else {
                                $task_data = array(
                                    'status' => 1,
                                    'checkbox_status' => 1,
                                    'ld_notes' => $file['other_description'] ?? '',
                                );
                            }
                            $this->db->where('id', $task_id);
                            $this->db->update(db_prefix() . 'tasks', $task_data);
                        }
                        if(!empty($cases_checkbox_id)) {
                            $checkbox_type = get_cases_checkbox_type_by_id($this, $id, $cases_checkbox_id);
                            $this->leads_model->ldteam_related_doc_add_in_db($cases_checkbox_id, $id, $checkbox_type, $upload_response);
                        }
                    }
                    // if no item title give to the file then add in nuborrow-files type
                    if (empty($doc_title) && !in_array($doc_title, $allowed_titles)) {
                        $this->leads_model->client_related_doc_add_in_db($task_id, $id, 'nuborrow-files', $upload_response);
                    }
                    // nuborrow leadid add in db
                    $this->leads_model->add_nuborrow_lead_id($id, $nuborrow_lead_id);
                }

                $this->response(array('status' => 200, 'message' => "Successfully case added!"), 200);
            } else {
                $this->response(array('status' => 400, 'message' => "Please check POST DATA"), 400);
            }
        } else {
            $this->response(array('status' => 400, 'message' => "Unauthorized"), 400);
        }
    }
    // 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'] = admin_url('cases/index/') . $lead_id;
    //                 $_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_mailchimp_email($broker_email, $subject, $html_content_confirmation_email_to_broker, $replay_to_mail, '', '', $lead_id);

    //                 $new_case_message = 'Please check your email. The case group has been updated by Nuborrow 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' => 'Nuborrow',
    //                     'description' => '<p>Dear Colleague</p>
    //                                                 <p>Thank you for your kind instruction. We look forward to working with you on this transaction period.</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'] = admin_url('cases/index/') . $lead_id;
    //                     $_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_mailchimp_email($broker_email, $subject, $html_content_confirmation_email_to_broker, $replay_to_mail, '', '', $lead_id);

    //                     $new_case_message = 'Please check your email. The case group has been updated by Nuborrow 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 period.</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);
    //                 }
    //             }
    //         }
    //     }
    // }
    private function add($data)
    {
        $tags = '';
        if (isset($data['tags'])) {
            $tags = $data['tags'];
            unset($data['tags']);
        }
        if (isset($data['uploaded_files'])) {
            unset($data['uploaded_files']);
        }
        if (isset($data['sp_notes'])) {
            unset($data['sp_notes']);
        }
        // check new lender column exit or not
        if (!empty($data['new_transaction_name'])) {
            $data['transaction'] = $data['new_transaction_name'];
        }
        unset($data['new_transaction_name']);
        if (isset($data['co_borrower'])) {
            unset($data['co_borrower']);
        }
        if(isset($data['lender_name'])) {
            unset($data['lender_name']);
        }
        if(isset($data['mortgage_type'])) {
            unset($data['mortgage_type']);
        }
        if(isset($data['money_need'])) {
            unset($data['money_need']);
        }
        for ($i = 2; $i <= $data['total_fields']; $i++) {
            if (isset($data['borrow_firstname' . $i]) || isset($data['borrow_lastname' . $i]) || isset($data['borrow_address' . $i]) || isset($data['borrow_position' . $i])) {
                unset($data['borrow_firstname' . $i]);
                unset($data['borrow_lastname' . $i]);
                unset($data['borrow_address' . $i]);
                unset($data['borrow_position' . $i]);
                unset($data['borrow_middlename' . $i]);
                unset($data['borrow_city' . $i]);
                unset($data['borrow_province' . $i]);
                unset($data['borrow_zipcode' . $i]);
                unset($data['borrow_email' . $i]);
                unset($data['borrow_phone' . $i]);
                unset($data['borrow_preferred_method' . $i]);
                unset($data['borrow_martial_status' . $i]);
            }
        }

        if (isset($data['total_fields'])) {
            $total_fields = $data['total_fields'];
            unset($data['total_fields']);
        }
        // unset the lender details fields
        if (is_array($data['loan_total_post_req']) && isset($data['loan_total_post_req'][0])) {
            $data['loan_total_post_req'] = $data['loan_total_post_req'][0];
        }
        $lenderDetailsArray = json_decode($data['loan_total_post_req'], true);
        if (is_array($lenderDetailsArray)) {
            foreach ($lenderDetailsArray as $lender) {
                if (!isset($lender['lenderId'], $lender['index'])) {
                    continue;
                }
                $lenderId = (string) $lender['lenderId'];
                $index = (int) $lender['index'];
                $loanKey = "loan_amount_{$lenderId}_{$index}";
                $transactionKey = "transaction_{$lenderId}_{$index}";
                $newTransactionKey = "new_transaction_name_{$lenderId}_{$index}";
                if (isset($data[$loanKey])) {
                    unset($data[$loanKey]);
                }
                if (isset($data[$transactionKey])) {
                    unset($data[$transactionKey]);
                }
                if (isset($data[$newTransactionKey])) {
                    unset($data[$newTransactionKey]);
                }
            }
        }
        if (isset($data['loan_total_post_req'])) {
            unset($data['loan_total_post_req']);
        }
        // $this->load->helper('leads_helper');
        // $this->load->library('sms/Sms_twilio');
        // Check record exist in leads table then only insert in multiple record in leads table
        $this->db->select('*');
        $this->db->from(db_prefix() . 'leads');
        $this->db->where('email', $data['email']);
        // $this->db->where('active_case', 'Active');
        $query = $this->db->get();
        if ($query->num_rows() > 0) {
            // Fetch all rows and get last result 
            $results = $query->row();
            // $lastRow = end($results);
            $lastColumn_id = $results->id;
            $additional_email = $results->additional_email;
            $secondary_email_check = $results->secondary_email_check;
            // $lastColumn_client_id = $results->client_id;
            // insert/add leads data
            $data = add_leads($data);
            $data['multiple_cases'] = $lastColumn_id;
            $data['additional_email'] = $additional_email;
            $data['secondary_email_check'] = $secondary_email_check;
            $data['excepting_closing_date'] = to_sql_date($data['excepting_closing_date'], true);
            $data['file_opened_started_at'] = date('Y-m-d H:i:s');
            $data['case_creator_id'] = (!empty(get_staff_user_id())) ? get_staff_user_id() : 0;
            $data['active_case'] = 'Active';
            // $data['client_id'] = $lastColumn_client_id;
            if (empty($data['addedfrom'])) {
                $data['addedfrom'] = (!empty(get_staff_user_id())) ? get_staff_user_id() : 0;
            } else {
                $data['addedfrom'] = implode(',', $data['addedfrom']);
            }
            // set the lender ids
            // if (!empty($data['lender_ids'])) {
            //     $data['lender_ids'] = implode(',', $data['lender_ids']);
            // }
            $keysToRemove = array('firstname', 'middlename', 'lastname');
            // Remove the keys from the array
            foreach ($keysToRemove as $key) {
                unset($data[$key]);
            }
            $this->db->insert(db_prefix() . 'leads', $data);
            $insert_id = $this->db->insert_id();

        } else {
            // insert/add clients
            $data = add_leads($data);
            $clients = add_clients($data);
            $this->db->insert(db_prefix() . 'clients', $clients);
            $client_id = $this->db->insert_id();
            // insert/add leads
            $data['client_id'] = $client_id;
            if (empty($data['addedfrom'])) {
                $data['addedfrom'] = (!empty(get_staff_user_id())) ? get_staff_user_id() : 0;
            }
            $additional_email = $data['additional_email'];
            // //tbl leads insert 
            $data['excepting_closing_date'] = to_sql_date($data['excepting_closing_date'], true);
            $lead_data_array = array(
                'is_public' => $data['is_public'],
                'secondary_email_check' => $data['secondary_email_check'],
                'description' => $data['description'],
                'lastcontact' => $data['lastcontact'],
                'address' => $data['address'],
                // 'addedfrom' => get_broker_agent_staffid($this, $data['addedfrom']),
                'case_creator_id' => (!empty(get_staff_user_id())) ? get_staff_user_id() : 0,
                'addedfrom' => (!empty($data['addedfrom']) && is_array($data['addedfrom'])) ? implode(',', $data['addedfrom']) : $data['addedfrom'],
                'brokerage_id' => $data['brokerage_id'],
                'assign_group' => $data['assign_group'],
                'status' => $data['status'],
                'email' => $data['email'],
                'additional_email' => $additional_email,
                'name' => $data['name'],
                'phonenumber' => $data['phonenumber'],
                'country' => $data['country'],
                'state' => $data['state'],
                'city' => $data['city'],
                'zip' => $data['zip'],
                'active_case' => 'Active',
                'martial_status' => $data['marital_status'],
                'transaction' => $data['transaction'],
                'secondary_name' => $data['secondary_name'],
                'client_id' => $data['client_id'],
                'multiple_cases' => $data['multiple_cases'],
                'dateadded' => $data['dateadded'],
                'dateassigned' => $data['dateassigned'],
                'last_status_change' => $data['last_status_change'],
                'excepting_closing_date' => $data['excepting_closing_date'],
                'preferred_contact_method' => $data['preferred_contact_method'],
                'loan_amount' => $data['loan_amount'],
                'lender_ids' => !empty($data['lender_ids']) ? $data['lender_ids'] : null,
                'lead_borrow_position' => $data['lead_borrow_position'],
                'second_broker_firstname' => $data['second_broker_firstname'],
                'second_broker_lastname' => $data['second_broker_lastname'],
                'second_broker_email' => $data['second_broker_email'],
                'contacted_notes' => $data['contacted_notes'],
                'file_opened_started_at' => date('Y-m-d H:i:s'),
                'pin_check' => $data['pin_check'],
                'mortgage_type' => $data['mortgage_type'],
                'prepaid_rate' => $data['prepaid_rate']
            );
            $this->db->insert(db_prefix() . 'leads', $lead_data_array);
            $insert_id = $this->db->insert_id();
            //  insert/add contact
            $contact = add_contacts($data);
            $contact['userid'] = $client_id;
            $contact['additional_email'] = $additional_email;
            $rand_password = generateRandomPassword($insert_id, $data['name']);
            $hashed_password = password_hash($rand_password, PASSWORD_BCRYPT);
            $contact['password'] = $hashed_password;
            $this->db->insert(db_prefix() . 'contacts', $contact);
        }

        if ($insert_id) {
            log_activity('New Case Added [ID: ' . $insert_id . '] by Nuborrow.');
            handle_tags_save($tags, $insert_id, 'lead');

            if (isset($custom_fields)) {
                handle_custom_fields_post($insert_id, $custom_fields);
            }
            hooks()->do_action('lead_created', $insert_id);

            return array(
                'id' => $insert_id,
                'password' => $rand_password,
            );
        }

        return false;

    }
}
