<?php

defined('BASEPATH') or exit('No direct script access allowed');

use chriskacerguis\RestServer\RestController;
use Firebase\JWT\JWT; // Import JWT library

class User extends RestController
{
    private $appKey = 'deh0r98qh2zi04k';
    private $appSecret = 'ai3t7vc77cvt4vd';
    private $redirectUri = 'https://platform.legaldirect.ca/api/User/tokenget';
    public $access_token;
    public function __construct()
    {
        parent::__construct();
        if (base_url() == 'https://dev.platform.legaldirect.ca/') {
            $this->appKey = 'atcksepiq6w9wzo';
            $this->appSecret = 'tye7w7g8khh68ri';
            $this->redirectUri = 'https://dev.platform.legaldirect.ca/api/User/tokenget';
        } else {
            $this->appKey = 'deh0r98qh2zi04k';
            $this->appSecret = 'ai3t7vc77cvt4vd';
            $this->redirectUri = 'https://platform.legaldirect.ca/api/User/tokenget';
        }
        $this->load->helper('date');
        $this->load->library('form_validation');
        $this->load->database();
        $this->load->model('Contacts_model');
        $this->load->model('Leads_model');
        $this->load->model('Token_model');
        $this->load->library('email');
        $this->load->library('AuthMiddleware');
        $this->load->helper('response_helper');
        $this->load->helper('notification_helper');
        $this->load->helper('userimage_url_helper');
        $this->load->helper('leads_helper');
        $this->load->helper('staff_helper');
        $this->load->helper('userid_get_helper');
        $this->load->library('session');
        $this->load->helper(array('form', 'url'));
        $this->load->database();
        $this->load->model('Notification_model');
        $this->load->model('Comment_model');
        $this->load->model('file_instruction_model');
        $this->load->library('pagination');
        $this->load->library('Slack');
    }
    private function send_post_request($url, $data)
    {
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);

        $response = curl_exec($ch);

        // Check for cURL errors
        if (curl_errno($ch)) {
            echo 'cURL error: ' . curl_error($ch);
        }

        curl_close($ch);

        return json_decode($response, true);
    }

    public function refresh_dropbox_token_get()
    {
        // Obtain app-specific credentials from the Dropbox App Console
        if (base_url() == 'https://dev.platform.legaldirect.ca/') {
            $Dropbox_CLIENT_ID = unlayer_extract(getenv('DROPBOX_CLIENT_ID_DEV'), $_ENV['Dropbox_Lock_signature']);
            $Dropbox_CLIENT_SECRET = unlayer_extract(getenv('DROPBOX_CLIENT_SECRET_DEV'), $_ENV['Dropbox_Lock_signature']);
        } else {
            $Dropbox_CLIENT_ID = unlayer_extract(getenv('DROPBOX_CLIENT_ID_PROD'), $_ENV['Dropbox_Lock_signature']);
            $Dropbox_CLIENT_SECRET = unlayer_extract(getenv('DROPBOX_CLIENT_SECRET_PROD'), $_ENV['Dropbox_Lock_signature']);
        }

        // Get the refresh token from the database
        $data = $this->Token_model->getToken();
        $refreshToken = array_column($data, 'refresh_token');
        $refreshToken = implode(',', $refreshToken);

        // Check if a refresh token is available
        if (!empty($refreshToken)) {
            // Construct the URL for the token refresh
            $tokenRefreshURL = 'https://api.dropbox.com/oauth2/token';

            // Prepare the parameters for the refresh token request
            $params = array(
                'grant_type' => 'refresh_token',
                'refresh_token' => $refreshToken,
                'client_id' => $Dropbox_CLIENT_ID,
                'client_secret' => $Dropbox_CLIENT_SECRET,
            );

            // Send a POST request to refresh the token
            $response = $this->send_post_request($tokenRefreshURL, $params);
            // Handle the response
            if ($response['access_token']) {
                $newAccessToken = $response['access_token'];
                $expires_in = $response['expires_in'];
                // Update the database with the new access token
                $data = array(
                    'token' => $newAccessToken,
                    'expire_time' => $expires_in,
                    'created_at' => date('Y-m-d H:i:s'),
                );

                $this->db->where('id', '1');
                $this->db->update(db_prefix() . 'token', $data);
                return true;
            } else {
                // Check if the error is due to a malformed refresh token
                if (isset($response['error']) && $response['error'] === 'invalid_grant') {
                    echo 'Refresh token is invalid or malformed. You may need to reauthorize the user.';
                } else {
                    echo 'Failed to refresh the token. ' . json_encode($response);
                }
            }
        } else {
            echo 'No refresh token available.';
        }
    }
    public function userdata_post()
    {
        $getemail = $this->authmiddleware->verifyToken();
        if (!empty($getemail)) {
            if ($this->input->server('REQUEST_METHOD') === 'POST') {
                $data = $this->Contacts_model->getEmail($getemail);
                if (!empty($data)) {
                    $get_role = array_column($data, 'role');
                    $role_string = implode(',', $get_role);
                    if ($role_string == 'client') {
                        $Response_Data = responseData($data);
                        $get_is_password_changed = array_column($data, 'is_password_changed');
                        $is_password_changed_string = implode(',', $get_is_password_changed);
                        if ($is_password_changed_string == 'false') {
                            $Response_Data['is_password_changed'] = false;
                        } else {
                            $Response_Data['is_password_changed'] = true;
                        }
                        $user_details_data = getid_contact_by_user($this, $getemail);
                        $leadData = $this->Leads_model->get_lead_id($user_details_data->id);
                        $user_id = $leadData->id;
                        $image_url = get_images_by_user($this, $user_id);
                        if (!empty($image_url)) {
                            $Response_Data['profile_url'] = $image_url->file_url;
                        } else {
                            $Response_Data['profile_url'] = '';
                        }
                    } else {
                        // array to string convert the profile image
                        $get_profile_image = array_column($data, 'profile_image');
                        $profile_image_string = implode(',', $get_profile_image);
                        // array to string convert the staffid
                        $get_staffid = array_column($data, 'staffid');
                        $string_staffid = implode(',', $get_staffid);
                        // get the respose from helper
                        $Response_Data = responseData_staff($data);
                        // check roles 
                        if (is_numeric($Response_Data['role']) && $Response_Data['role'] > 0) {
                            $role = $Response_Data['role'];
                            $Response_Data['role'] = if_role_is_id_then_get_staff_role_name($this, $role);
                            $Response_Data['profile_url'] = get_staff_profile_url($string_staffid, $profile_image_string);
                        }
                    }
                    $response = array(
                        'status' => 200,
                        'message' => 'User Details.',
                        'data' => $Response_Data
                    );
                    getresponse($this, $response);
                } else {
                    $response = array(
                        'status' => 400,
                        'message' => 'User Details is not exist in our record.',
                        'data' => null,
                    );
                    getresponse($this, $response);
                }
            } else {
                $response = array(
                    'status' => 400,
                    'message' => 'The requested method is not supported.',
                    'data' => null,
                );
                getresponse($this, $response);
            }
        }
    }
    // connect to the dropbox 
    public function dropbox_connect_post()
    {
        // Obtain app-specific credentials from the Dropbox App Console
        if (base_url() == 'https://dev.platform.legaldirect.ca/') {
            $clientID = 'atcksepiq6w9wzo';
            $clientSecret = 'tye7w7g8khh68ri';
        } else {
            $clientID = 'deh0r98qh2zi04k';
            $clientSecret = 'ai3t7vc77cvt4vd';
        }
        $redirectURI = base_url() . 'api/User/tokenget'; // Replace with your callback URL
        // Construct the Dropbox authorization URL
        $authURL = 'https://www.dropbox.com/oauth2/authorize' .
            '?response_type=code' .
            '&client_id=' . $clientID .
            '&redirect_uri=' . urlencode($redirectURI);
        header('Location: ' . $authURL);
    }

    public function tokenget_get()
    {
        $code = $this->input->get('code');
        if (!empty($code)) {
            // Exchange the authorization code for an access token
            $response = $this->exchangeAuthorizationCodeForAccessToken($code);
            $access_token = $response['access_token'];
            $refresh_token = $response['refresh_token'];
            $expires_in = $response['expires_in'];
            $data = $this->Token_model->getToken();
            $get_id = array_column($data, 'token');
            $user_token = implode(',', $get_id);
            if (!empty($user_token)) {
                if (!empty($access_token)) {
                    $data = array(
                        'token' => $access_token,
                        'refresh_token' => $refresh_token,
                        'expire_time' => $expires_in,
                        'created_at' => date('Y-m-d H:i:s'),
                    );
                    $this->db->where('token', $user_token);
                    $this->db->update(db_prefix() . 'token', $data);
                } else {
                    echo 'Access token is not get.';
                }
            } else {
                if (!empty($access_token)) {
                    // print_r($access_token);
                    $data = array(
                        'token' => $access_token,
                        'refresh_token' => $refresh_token,
                        'created_at' => date('Y-m-d H:i:s'),
                        // Use `time()` instead of `Time()` for the current timestamp
                    );

                    $this->db->insert(db_prefix() . 'token', $data);

                    // $inserted_id = $this->Token_model->insertToken($data);
                } else {
                    // echo 'Access token is not get.';
                    $response = array(
                        'status' => 400,
                        'message' => 'Access token is not get.',
                        'data' => null,
                    );
                    getresponse($this, $response);
                }
            }
        } else {
            $response = array(
                'status' => 400,
                'message' => 'dropbox token is expired.',
                'data' => null,
            );
            getresponse($this, $response);
        }
    }
    public function edituploadfile_post()
    {
        $data = $this->Token_model->getToken();
        $get_id = array_column($data, 'token');
        $access_token = implode(',', $get_id);
        $task_id = $this->post('task_id');
        $delete_file_id = $this->post('file_id');
        $item_type_id = $this->post('item_type_id');
        // Validate and authenticate the user (you may implement your own authentication logic)
        $getemail = $this->authmiddleware->verifyToken();
        if (!empty($task_id) && !empty($_FILES['userfile']['name'][0])) {
            if (empty($getemail)) {
                $response = array(
                    'status' => 400,
                    'message' => 'Authentication failed.',
                    'data' => null,
                );
                getresponse($this, $response);
            } else {
                $data = $this->Contacts_model->getEmail($getemail);
                $get_id = array_column($data, 'id');
                $get_userid = array_column($data, 'userid');
                $get_firstname = array_column($data, 'firstname');
                $get_lastname = array_column($data, 'lastname');
                $get_id = implode(',', $get_id);
                $userid = implode(',', $get_userid);
                $dropbox_firstname = implode(',', $get_firstname);
                $dropbox_lastname = implode(',', $get_lastname);
                $leadData = $this->Leads_model->get_lead_id($get_id);
                $user_id = $leadData->id;
                $user_name = $leadData->name;
                // Check if it's a POST request
                if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
                    $response = array(
                        'status' => 400,
                        'message' => 'Invalid request method.',
                        'data' => null,
                    );
                    getresponse($this, $response);
                } else {
                    $refresh_token_change = $this->Leads_model->refresh_dropbox_token_get();
                    if ($refresh_token_change) {
                        if (!empty($delete_file_id)) {
                            $file_ids = explode(',', $delete_file_id);
                            foreach ($file_ids as $file_id) {
                                $file_id = trim($file_id);
                                $this->db->select('id,task_id,rel_id,rel_type,file_name,filetype,file_url,doc_status,staffid,contact_id,task_comment_id,dateadded');
                                $this->db->from(db_prefix() . 'files');
                                $this->db->where('id', $file_id);
                                $query = $this->db->get();
                                // Check if the query was successful
                                if ($query) {
                                    // Get the result as an object
                                    $result = $query->row();

                                    // Check if there is a result
                                    if ($result) {
                                        // Access the columns using object properties
                                        $fileId = $result->id;
                                        $cleanedString = $result->file_name;
                                        // Access other columns as needed
                                        $data = $this->Contacts_model->getEmail($getemail);
                                        // $get_id = array_column($data, 'id');
                                        // $user_id = implode(',', $get_id);
                                        $access_token_data = $this->Token_model->getToken();
                                        $get_id = array_column($access_token_data, 'token');
                                        $access_token = implode(',', $get_id);

                                        //$imagePath = '/uploads/' . $user_id . '_' . $dropbox_firstname . "_" . $dropbox_lastname . '/' . $cleanedString;
                                        $sanitized_firstname = str_replace(' ', '_', $dropbox_firstname);
                                        $sanitized_lastname = str_replace(' ', '_', $dropbox_lastname);

                                        $remote_path = '/uploads/' . $user_id . '_' . $sanitized_firstname . "_" . $sanitized_lastname . '/' . $cleanedString;

                                        $remote_path = str_replace(' ', '-', $remote_path);

                                        $remote_path = preg_replace('/\/+/', '/', $remote_path);
                                        // $responsedelete = $this->deleteFile($access_token, $imagePath);
                                        $responsedelete = $this->Leads_model->deleteFile($access_token, $remote_path);
                                        if ($responsedelete) {
                                            $this->db->select('*');
                                            $this->db->from(db_prefix() . 'files');
                                            $this->db->where('file_name', $cleanedString);
                                            // Perform the delete operation
                                            $DeleteResponse = $this->db->delete();
                                            $data = responseData($data);
                                            // The file was successfully deleted then send all code of getchecklist api
                                            $this->db->select('id, name, description, dateadded, status, rel_id, lead_borrow_id');
                                            $this->db->from(db_prefix() . 'tasks');
                                            $this->db->where('id', $task_id);
                                            $this->db->where('rel_type', 'user-task');
                                            $this->db->where('type', 'client');
                                            $query = $this->db->get();

                                            if ($query->num_rows() > 0) {
                                                $user_task_records = $query->result();
                                                foreach ($user_task_records as $record_task) {
                                                    $status = return_item_status_for_app_side($record_task->status);

                                                    $checklist_instruction = $this->file_instruction_model->get_instruction_by_taskid($record_task->id);
                                                    $instructions = is_array($checklist_instruction) && array_key_exists('instruction', $checklist_instruction)
                                                        ? explode("\n\r", $checklist_instruction['instruction'])
                                                        : [];

                                                    $resultArray = [];

                                                    foreach ($instructions as $instruction) {
                                                        $items = array_map('trim', explode(',', $instruction));
                                                        if (!empty(implode(',', $items))) {
                                                            $resultArray[] = implode(',', $items);
                                                        }
                                                    }
                                                    $file_type_check = is_array($checklist_instruction) && array_key_exists('doc_type', $checklist_instruction)
                                                        ? explode(',', $checklist_instruction['doc_type'])
                                                        : [];
                                                    if ($file_type_check === 'jpeg' || $file_type_check === 'jpg' || $file_type_check === 'png' || $file_type_check === 'avif') {
                                                        $file_type = 'image';
                                                    } else if ($file_type_check == 'pdf') {
                                                        $file_type = 'pdf';
                                                    } else {
                                                        $file_type = 'other';
                                                    }
                                                    $checklist = [
                                                        'id' => $record_task->id,
                                                        'title' => $record_task->name,
                                                        'client_checklist_name' => get_checklist_client_name($this, $record_task->rel_id, $record_task->lead_borrow_id),
                                                        'description' => $record_task->description,
                                                        'status' => $status,
                                                        'instructions' => $resultArray,
                                                        'doc_types' => $file_type
                                                    ];

                                                }

                                                // get files of checklist by tesk_id
                                                $this->db->select('id,filetype,file_url');
                                                $this->db->from(db_prefix() . 'files');
                                                $this->db->where('task_id', $task_id);
                                                $this->db->where('rel_type', 'client-doc');
                                                $query = $this->db->get();

                                                if ($query->num_rows() > 0) {
                                                    $all_checklist_files = $query->result();
                                                    foreach ($all_checklist_files as $files_data) {
                                                        $filetype_check = explode('/', $files_data->filetype)[1];
                                                        if ($filetype_check == 'jpeg' || $filetype_check == 'jpg' || $filetype_check == 'png' || $filetype_check == 'avif') {
                                                            $filetype = 'image';
                                                        } else if ($filetype_check == 'pdf') {
                                                            $filetype = 'pdf';
                                                        } else {
                                                            $filetype = 'other';
                                                        }
                                                        $files_details[] = [
                                                            'id' => (int) $files_data->id,
                                                            'file_type' => $filetype,
                                                            'file_url' => $files_data->file_url,
                                                        ];
                                                    }
                                                }
                                                // get activity log by task_id
                                                $this->db->select('additional_data,description,date,full_name,reason');
                                                $this->db->from(db_prefix() . 'lead_activity_log');
                                                $this->db->where('task_id', $task_id);
                                                $this->db->where('activity_type', 'task-activity');
                                                $this->db->order_by('date', 'DESC');
                                                $query = $this->db->get();
                                                if ($query->num_rows() > 0) {
                                                    $activity_list = $query->result();
                                                    foreach ($activity_list as $activity_data) {
                                                        $message = $activity_data->additional_data == 'Rejected'
                                                            ? $activity_data->reason . " - Rejected by " . $activity_data->full_name . "."
                                                            : $activity_data->description;

                                                        $activity_details[] = [
                                                            'name' => $activity_data->full_name,
                                                            'status' => $activity_data->additional_data,
                                                            'description' => $message,
                                                            'created_at' => strtotime($activity_data->date),
                                                        ];
                                                    }
                                                }
                                                $data = $checklist;
                                                $data['files_list'] = $files_details;
                                                $data['activities'] = $activity_details;
                                                $response = [
                                                    'status' => 200,
                                                    'message' => 'Document are updated successfully.',
                                                    'data' => $data,
                                                ];
                                                getresponse($this, $response);
                                            }
                                        } else {
                                            // Error handling: Display an error message
                                            $this->Leads_model->add_errors_logs($user_id, $userid, $user_name, 'Image is not Deleted', 'Image is not Deleted properly for using this fucntion edituploadfile_post() in app.', 400, 'client');
                                            $response = array(
                                                'status' => 400,
                                                'message' => 'Files is not exist in our record.',
                                                'data' => null,
                                            );
                                        }
                                    } else {
                                        // No matching record found
                                        $response = array(
                                            'status' => 400,
                                            'message' => 'No record found.',
                                            'data' => null,
                                        );
                                    }
                                } else {
                                    $response = array(
                                        'status' => 400,
                                        'message' => 'No record found',
                                        'data' => null,
                                    );
                                }
                            }
                            getresponse($this, $response);
                        }
                        if (empty($_FILES['userfile']['name'][0])) {
                            $response = array(
                                'status' => 400,
                                'message' => 'File Field is empty.',
                                'data' => null,
                            );
                        } else {
                            $upload_data = array();
                            // Process uploaded files
                            foreach ($_FILES['userfile']['name'] as $key => $name) {
                                $tmp_file = $_FILES['userfile']['tmp_name'][$key];
                                if (is_uploaded_file($tmp_file)) {
                                    // This file was uploaded via HTTP POST
                                    $file_name = $_FILES['userfile']['name'][$key];
                                    $upload_result = $this->Leads_model->upload_to_dropbox($access_token, $tmp_file, $file_name, $user_id, $dropbox_firstname, $dropbox_lastname);
                                    if ($upload_result['status'] == 200) {
                                        $save[] = $this->addFileUrlToDatabase($user_id, $user_name, $task_id, $item_type_id, $upload_result['file_type'], $upload_result['file_name'], $upload_result['flie_url'], $upload_result['download_file_url']);
                                    } else {
                                        $this->Leads_model->add_errors_logs($user_id, $userid, $user_name, 'Upload doc from app side', $upload_result, $upload_result['status'], 'client');
                                        $response = array(
                                            'status' => 400,
                                            'message' => 'Failed to upload file, please try again.',
                                            'data' => array(),
                                        );
                                        getresponse($this, $response);
                                    }
                                } else {
                                    $this->Leads_model->add_errors_logs($user_id, $userid, $user_name, 'Upload doc from app side', 'file is not properly get form the app.', 400, 'client');
                                    $response = array(
                                        'status' => 400,
                                        'message' => 'Failed to upload file,because of malicious file.',
                                        'data' => array(),
                                    );
                                    getresponse($this, $response);
                                }
                            }
                            if (!empty($save)) {
                                // get the task name
                                $get_task_data = get_task_name_by_task_id($this, $task_id);
                                // get the current lead id using tbltask
                                $this->db->select('rel_id');
                                $this->db->where('id', $task_id);
                                $get_query_task_for_leadid = $this->db->get(db_prefix() . 'tasks');
                                if ($get_query_task_for_leadid->num_rows() > 0) {
                                    $task_info = $get_query_task_for_leadid->row();
                                    $current_lead_id_get_by_task = $task_info->rel_id;
                                }
                                // send notification in crm to the LD-team and admin
                                $this->db->select('assign_group,assigned,name');
                                $this->db->where('id', $current_lead_id_get_by_task);
                                $lead_data_for_get_assign_group = $this->db->get(db_prefix() . 'leads')->row();
                                $message_submitted = 'Document of checklist Item (' . $get_task_data->name . ') has been submitted by ' . $user_name . '  for the case (ID: #' . $current_lead_id_get_by_task . ', Name: ' . $lead_data_for_get_assign_group->name . ').';
                                // notification push code 
                                $this->db->select('multiple_cases,client_id,assign_group');
                                $this->db->where('id', $user_id);
                                $lead_data_check = $this->db->get(db_prefix() . 'leads');
                                if ($lead_data_check->num_rows() > 0) {
                                    $lead_data = $lead_data_check->row();
                                    if ($lead_data->client_id == 0) {
                                        // get the parnet id of lead
                                        $partent_lead_id = $lead_data->multiple_cases;
                                        $this->db->select('id,multiple_cases,client_id');
                                        $this->db->where('id', $partent_lead_id);
                                        $lead_parent_data_check = $this->db->get(db_prefix() . 'leads')->row();
                                        $client_id = $lead_parent_data_check->client_id;
                                    } else {
                                        $client_id = $lead_data->client_id;
                                    }
                                    $contact_id = get_contact_id_using_client_id($this, $client_id);
                                    $current_staff_data = get_staff_ids_by_group($this, $lead_data_for_get_assign_group->assign_group);
                                    foreach ($current_staff_data as $staff_notifiy_data) {
                                        // Get notification type
                                        $notification_type = get_notification_type(2);
                                        $values = array(
                                            'staff_id' => $staff_notifiy_data['staffid'],
                                            'contact_id' => $contact_id,
                                            'client_id' => $client_id,
                                            'lead_id' => $current_lead_id_get_by_task,
                                            // 'task_id' => $record_task->id,
                                            'task_id' => $task_id,
                                            'send_to' => 'staff',
                                            'title' => 'Submitted Document',
                                            'message' => $message_submitted,
                                            'type' => $notification_type . '-submitted',
                                        );
                                        add_alerts_user($values);
                                        $this->Leads_model->custom_lead_assigned_member_notification('client', $current_lead_id_get_by_task, $staff_notifiy_data['staffid'], $user_id, '', $message_submitted);
                                    }
                                    // 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']) {
                                            // Get notification type
                                            $notification_type = get_notification_type(2);
                                            $values = array(
                                                'staff_id' => $admin_email['staffid'],
                                                'contact_id' => $contact_id,
                                                'client_id' => $client_id,
                                                'lead_id' => $user_id,
                                                'task_id' => $task_id,
                                                'send_to' => 'staff',
                                                'title' => 'Submitted Document',
                                                'message' => $message_submitted,
                                                'type' => $notification_type . '-submitted',
                                            );
                                            add_alerts_user($values);
                                            $this->Leads_model->custom_lead_assigned_member_notification('client', $current_lead_id_get_by_task, $admin_email['staffid'], $user_id, '', $message_submitted);
                                        }
                                    }
                                    $slack_message = $message_submitted;
                                    // $this->slack->sendnotification($slack_message, $current_lead_id_get_by_task);
                                }
                                $this->db->where('id', $task_id);
                                $Data = array(
                                    'status' => '1',
                                );
                                $check = $this->db->update(db_prefix() . 'tasks', $Data);
                                $this->db->select('id, name, description, dateadded, status, rel_id,rel_type,addedfrom,lead_borrow_id');
                                $this->db->from(db_prefix() . 'tasks');
                                $this->db->where('id', $task_id);
                                $this->db->where('rel_type', 'user-task');
                                $this->db->where('type', 'client');
                                $query = $this->db->get();
                                if ($query->num_rows() > 0) {
                                    $user_task_records = $query->result();
                                    foreach ($user_task_records as $record_task) {
                                        if ($record_task->status == '1' && $record_task->id == $task_id) {
                                            $this->db->select('*');
                                            $this->db->from(db_prefix() . 'lead_activity_log');
                                            $this->db->where('task_id', $task_id);
                                            $this->db->where('activity_type', 'task-activity');
                                            $this->db->order_by('date', 'desc');
                                            $this->db->limit(1);
                                            $query = $this->db->get();
                                            $latest_record = $query->row();
                                            if ($latest_record->additional_data == 'Pending Review') {
                                                $update_task_activity = array(
                                                    'leadid' => $current_lead_id_get_by_task,
                                                    'task_id' => $task_id,
                                                    'full_name' => $user_name,
                                                    'activity_type' => 'task-activity',
                                                    'description' => $message_submitted,
                                                    'additional_data' => 'Pending Review',
                                                    'date' => date('Y-m-d H:i:s'),
                                                );
                                                $this->db->where('task_id', $task_id);
                                                $this->db->where('id', $latest_record->id);
                                                $this->db->update(db_prefix() . 'lead_activity_log', $update_task_activity);
                                            } else {
                                                $insert_task_activity = array(
                                                    'leadid' => $current_lead_id_get_by_task,
                                                    'task_id' => $task_id,
                                                    'full_name' => $user_name,
                                                    'activity_type' => 'task-activity',
                                                    'description' => $message_submitted,
                                                    'additional_data' => 'Pending Review',
                                                    'date' => date('Y-m-d H:i:s'),
                                                );
                                                leads_activity_log($this, $insert_task_activity);
                                            }
                                        }
                                        $status = return_item_status_for_app_side($record_task->status);
                                        $checklist_instruction = $this->file_instruction_model->get_instruction_by_taskid($record_task->id);
                                        $instructions = is_array($checklist_instruction) && array_key_exists('instruction', $checklist_instruction)
                                            ? explode("\n\r", $checklist_instruction['instruction'])
                                            : [];

                                        $resultArray = [];

                                        foreach ($instructions as $instruction) {
                                            $items = array_map('trim', explode(',', $instruction));
                                            if (!empty(implode(',', $items))) {
                                                $resultArray[] = implode(',', $items);
                                            }
                                        }
                                        $checklist = [
                                            'id' => $record_task->id,
                                            'title' => $record_task->name,
                                            'client_checklist_name' => get_checklist_client_name($this, $record_task->rel_id, $record_task->lead_borrow_id),
                                            'description' => $record_task->description,
                                            'status' => $status,
                                            'instructions' => $resultArray,
                                            'doc_types' => is_array($checklist_instruction) && array_key_exists('doc_type', $checklist_instruction) ? explode(',', $checklist_instruction['doc_type']) : [],
                                            'files_list' => $save,
                                        ];
                                        if (!empty($check)) {
                                            $response = array(
                                                'status' => 200,
                                                'message' => 'File uploaded to Dropbox successfully.',
                                                'data' => $checklist,
                                            );
                                            getresponse($this, $response);
                                        } else {
                                            $response = array(
                                                'status' => 200,
                                                'message' => 'File uploaded to Dropbox successfully but you checklist status is not update,Please Contact with admin.',
                                                'data' => $save
                                            );
                                            getresponse($this, $response);
                                        }
                                    }

                                } else {
                                    $response = array(
                                        'status' => 400,
                                        'message' => 'Checklist record not found.',
                                        'data' => null,
                                    );
                                    getresponse($this, $response);
                                }
                            }
                        }
                    }
                }
            }
        } else {
            $message = 'Please provide the required field.';
            $response = array(
                'status' => 400,
                'message' => $message,
                'data' => null,
            );
            getresponse($this, $response);
        }
    }
    public function upload_post()
    {
        $data = $this->Token_model->getToken();
        $get_id = array_column($data, 'token');
        $access_token = implode(',', $get_id);
        // Validate and authenticate the user (you may implement your own authentication logic)   
        $getemail = $this->authmiddleware->verifyToken();

        if (empty($getemail)) {
            $response = array(
                'status' => 400,
                'message' => 'Authentication failed.',
                'data' => null,
            );
            getresponse($this, $response);
        } else {
            $data = $this->Contacts_model->getEmail($getemail);
            $get_id = array_column($data, 'id');
            $get_userid = array_column($data, 'userid');
            $get_firstname = array_column($data, 'firstname');
            $get_lastname = array_column($data, 'lastname');
            $dropbox_firstname = implode(',', $get_firstname);
            $dropbox_lastname = implode(',', $get_lastname);
            $get_id = implode(',', $get_id);
            $userid = implode(',', $get_userid);
            $leadData = $this->Leads_model->get_lead_id($get_id);
            $user_id = $leadData->id;
            $user_name = $leadData->name;
            // Check if it's a POST request
            if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
                $response = array(
                    'status' => 400,
                    'message' => 'Invalid request method.',
                    'data' => null,
                );
                getresponse($this, $response);
            } else {
                // $refresh_token_change = $this->refresh_dropbox_token_get();
                // if ($refresh_token_change) {
                if (empty($_FILES['userfile']['name'][0])) {
                    $response = array(
                        'status' => 400,
                        'message' => 'Userfile Field is required.',
                        'data' => null,
                    );
                    getresponse($this, $response);
                } else {
                    $upload_data = array();
                    // Process uploaded files
                    // foreach ($_FILES['userfile']['name'] as $key => $name) {
                    //     $tmp_file = $_FILES['userfile']['tmp_name'][$key];
                    //     $task_id = $this->post('task_id');
                    //     $item_type_id = $this->post('item_type_id');
                    //     if (is_uploaded_file($tmp_file)) {
                    //         // This file was uploaded via HTTP POST
                    //         $file_name = $_FILES['userfile']['name'][$key];
                    //         $upload_result = $this->Leads_model->upload_to_dropbox($access_token, $tmp_file, $file_name, $user_id, $dropbox_firstname, $dropbox_lastname);
                    //         if ($upload_result['status'] == 200) {
                    //             $save[] = $this->addFileUrlToDatabase($user_id, $user_name, $task_id, $item_type_id, $upload_result['file_type'], $upload_result['file_name'], $upload_result['file_url'], $upload_result['download_file_url']);
                    //         } else {
                    //             // $this->upload_post();
                    //             $this->Leads_model->add_errors_logs($user_id, $userid, $user_name, 'Upload doc from app side', $upload_result, $upload_result['status'], 'client');
                    //             $response = array(
                    //                 'status' => 400,
                    //                 'message' => 'Failed to upload files please try again.',
                    //                 'data' => array(),
                    //             );
                    //             getresponse($this, $response);
                    //         }
                    //     } else {
                    //         $this->Leads_model->add_errors_logs($user_id, $userid, $user_name, 'Upload doc from app side', 'file is not properly get form the app.', 400, 'client');
                    //         $response = array(
                    //             'status' => 400,
                    //             'message' => 'Your internet connection appears to be unstable. Please ensure you have a stable connection and try again.',
                    //             'data' => array(),
                    //         );
                    //         getresponse($this, $response);
                    //     }
                    // }
                    $task_id = $this->post('task_id');
                    $item_type_id = $this->post('item_type_id');

                    foreach ($_FILES['userfile']['name'] as $key => $name) {
                        $tmp_file = $_FILES['userfile']['tmp_name'][$key];
                        if (is_uploaded_file($tmp_file)) {
                            $file_name = $_FILES['userfile']['name'][$key];

                            // Upload to Dropbox
                            $upload_result = $this->Leads_model->upload_to_dropbox(
                                $access_token, $tmp_file, $file_name, $user_id, $dropbox_firstname, $dropbox_lastname
                            );

                            if ($upload_result['status'] == 200) {
                                $save[] = $this->addFileUrlToDatabase(
                                    $user_id, $user_name, $task_id, $item_type_id,
                                    $upload_result['file_type'], $upload_result['file_name'],
                                    $upload_result['file_url'], $upload_result['download_file_url']
                                );
                            } else {
                                // Defer error logging (optional)
                                $this->Leads_model->add_errors_logs(
                                    $user_id, $userid, $user_name, 'Upload doc from app side',
                                    $upload_result, $upload_result['status'], 'client'
                                );

                                getresponse($this, [
                                    'status' => 400,
                                    'message' => 'Failed to upload files. Please try again.',
                                    'data' => []
                                ]);
                            }
                        } else {
                            $this->Leads_model->add_errors_logs(
                                $user_id, $userid, $user_name, 'Upload doc from app side',
                                'File is not properly received from the app.', 400, 'client'
                            );

                            getresponse($this, [
                                'status' => 400,
                                'message' => 'Unstable internet. Please try again.',
                                'data' => []
                            ]);
                        }
                    }
                    if (!empty($save)) {
                        $this->db->where('id', $task_id);
                        $Data = array(
                            'status' => '1',
                            'checkbox_status' => '1',
                        );
                        $check = $this->db->update(db_prefix() . 'tasks', $Data);
                        // update key to show the Review ledgers in kanban card
                        $brokerActionTimePassed = after_one_day_of_case_broker_client_items_trigger($this, $user_id);
                        if ($brokerActionTimePassed == false) {
                            update_key_of_upload_docs($this, $userid, 1);
                        }

                        $this->db->select('id, name, description, dateadded, status, rel_id,rel_type,addedfrom,lead_borrow_id');
                        $this->db->from(db_prefix() . 'tasks');
                        $this->db->where('id', $task_id);
                        $this->db->where('rel_type', 'user-task');
                        $this->db->where('type', 'client');
                        $query = $this->db->get();
                        if ($query->num_rows() > 0) {
                            // get the current lead id using tbltask
                            $this->db->select('rel_id');
                            $this->db->where('id', $task_id);
                            $get_query_task_for_leadid = $this->db->get(db_prefix() . 'tasks');
                            if ($get_query_task_for_leadid->num_rows() > 0) {
                                $task_info = $get_query_task_for_leadid->row();
                                $current_lead_id_get_by_task = $task_info->rel_id;
                            }
                            $user_task_records = $query->result();
                            // get the task name
                            $get_task_data = get_task_name_by_task_id($this, $task_id);
                            $message_submitted = 'Document of checklist Item (' . $get_task_data->name . ') has been submitted by ' . $user_name . '.';
                            foreach ($user_task_records as $record_task) {
                                if ($record_task->status == '1' && $record_task->id == $task_id) {
                                    // get the lead activity log data 
                                    $this->db->select('id,additional_data');
                                    $this->db->from(db_prefix() . 'lead_activity_log');
                                    $this->db->where('task_id', $task_id);
                                    $this->db->where('activity_type', 'task-activity');
                                    $this->db->order_by('date', 'desc');
                                    $this->db->limit(1);
                                    $query = $this->db->get();
                                    $latest_record = $query->row();
                                    if ($latest_record->additional_data == 'Pending Review') {
                                        $update_task_activity = array(
                                            'leadid' => $current_lead_id_get_by_task,
                                            'task_id' => $task_id,
                                            'full_name' => $user_name,
                                            'activity_type' => 'task-activity',
                                            'description' => $message_submitted,
                                            'additional_data' => 'Pending Review',
                                            'date' => date('Y-m-d H:i:s'),
                                        );
                                        $this->db->where('task_id', $task_id);
                                        $this->db->where('id', $latest_record->id);
                                        $this->db->update(db_prefix() . 'lead_activity_log', $update_task_activity);
                                    } else {
                                        $insert_task_activity = array(
                                            'leadid' => $current_lead_id_get_by_task,
                                            'task_id' => $task_id,
                                            'full_name' => $user_name,
                                            'activity_type' => 'task-activity',
                                            'description' => $message_submitted,
                                            'additional_data' => 'Pending Review',
                                            'date' => date('Y-m-d H:i:s'),
                                        );
                                        leads_activity_log($this, $insert_task_activity);
                                    }
                                }
                                $status = return_item_status_for_app_side($record_task->status);
                                $checklist_instruction = $this->file_instruction_model->get_instruction_by_taskid($record_task->id);
                                $instructions = is_array($checklist_instruction) && array_key_exists('instruction', $checklist_instruction)
                                    ? explode("\n\r", $checklist_instruction['instruction'])
                                    : [];

                                $resultArray = [];

                                foreach ($instructions as $instruction) {
                                    $items = array_map('trim', explode(',', $instruction));
                                    if (!empty(implode(',', $items))) {
                                        $resultArray[] = implode(',', $items);
                                    }
                                }
                                $checklist = [
                                    'id' => $record_task->id,
                                    'title' => $record_task->name,
                                    'client_checklist_name' => get_checklist_client_name($this, $record_task->rel_id, $record_task->lead_borrow_id),
                                    'description' => $record_task->description,
                                    'status' => $status,
                                    'instructions' => $resultArray,
                                    'doc_types' => is_array($checklist_instruction) && array_key_exists('doc_type', $checklist_instruction) ? explode(',', $checklist_instruction['doc_type']) : [],
                                    'files_list' => $save,
                                ];
                                if (!empty($check)) {
                                    // notification push code 
                                    $this->db->select('multiple_cases,client_id,assign_group');
                                    $this->db->where('id', $user_id);
                                    $lead_data_check = $this->db->get(db_prefix() . 'leads');
                                    if ($lead_data_check->num_rows() > 0) {
                                        $lead_data = $lead_data_check->row();
                                        if ($lead_data->client_id == 0) {
                                            // get the parnet id of lead
                                            $partent_lead_id = $lead_data->multiple_cases;
                                            $this->db->select('id,multiple_cases,client_id');
                                            $this->db->where('id', $partent_lead_id);
                                            $lead_parent_data_check = $this->db->get(db_prefix() . 'leads')->row();
                                            $client_id = $lead_parent_data_check->client_id;
                                        } else {
                                            $client_id = $lead_data->client_id;
                                        }
                                        $contact_id = get_contact_id_using_client_id($this, $client_id);
                                        // send notification in crm to the LD-team and admin
                                        $this->db->select('assign_group,assigned,name,email');
                                        $this->db->where('id', $current_lead_id_get_by_task);
                                        $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);
                                        // send email to the ld and admins
                                        $get_mail_subject = get_mail_subject($this, $current_lead_id_get_by_task);
                                        // send email code 
                                        $replay_to_mail = $lead_data_for_get_assign_group->email;
                                        $_POST['case_url'] = admin_url('cases/index/') . $user_id;
                                        $_POST['generic_email_title'] = '';
                                        $_POST['generic_email_content'] = 'Good ' . get_afternoon_and_morning() . '<br> Please note the client has uploaded ' . $user_id;
                                        $_POST['generic_email_back_to_case_url'] = 'Please <a href="' . htmlspecialchars($_POST['case_url'], ENT_QUOTES, 'UTF-8') . '">Click here</a> to access the file.';
                                        $html_content_confirmation_email_to_broker = $this->load->view('admin/leads/Email_template/generic_email_template', $_POST, TRUE);
                                        $subject = get_mail_subject_for_case_stages($this, $current_lead_id_get_by_task, 1);
                                        foreach ($current_staff_data as $staff_notifiy_data) {
                                            $notification_type = get_notification_type(2);
                                            $values = array(
                                                'staff_id' => $staff_notifiy_data['staffid'],
                                                'contact_id' => $contact_id,
                                                'client_id' => $client_id,
                                                'lead_id' => $user_id,
                                                'task_id' => $record_task->id,
                                                'send_to' => 'staff',
                                                'title' => 'Submitted Document',
                                                'message' => $message_submitted,
                                                'type' => $notification_type . '-submitted',
                                            );
                                            add_alerts_user($values);
                                            // send email to the ld tam 
                                            if ($staff_notifiy_data['role'] != 4) {
                                                send_mailchimp_email($staff_notifiy_data['email'], $subject, $html_content_confirmation_email_to_broker, $replay_to_mail, '', '');
                                                $this->Leads_model->custom_lead_assigned_member_notification('client', $current_lead_id_get_by_task, $staff_notifiy_data['staffid'], $user_id, '', $message_submitted);
                                            }
                                        }
                                        // get the all admin staff ids
                                        $admin_ids = get_all_admin_role_staff_ids($this);
                                        foreach ($admin_ids as $admin_email) {
                                            $notification_type = get_notification_type(2);
                                            $values = array(
                                                'staff_id' => $admin_email['staffid'],
                                                'contact_id' => $contact_id,
                                                'client_id' => $client_id,
                                                'lead_id' => $user_id,
                                                'task_id' => $record_task->id,
                                                'send_to' => 'staff',
                                                'title' => 'Submitted Document',
                                                'message' => $message_submitted,
                                                'type' => $notification_type . '-submitted',
                                            );
                                            add_alerts_user($values);
                                            // send slack notification in ld-channel
                                            // $this->slack->sendnotification($slack_message);
                                            // send notificataion in crm
                                            // send email to the admins
                                            // send_mailchimp_email($admin_email['email'], $subject, $html_content_confirmation_email_to_broker, $replay_to_mail, '', '');
                                            $this->Leads_model->custom_lead_assigned_member_notification('client', $current_lead_id_get_by_task, $admin_email['staffid'], $user_id, '', $message_submitted);
                                        }
                                        // Send Slack notification
                                        $group_name = get_the_group_name_using_leadid($this, $user_id);
                                        $lead_name = get_lead_name_using_lead_id($this, $user_id);
                                        $lead_split_name = leads_splitFullName($lead_name);
                                        $case_split_name = $lead_split_name['lastname'] . ', ' . $lead_split_name['firstname'];
                                        $slack_message = "\n - Document Uploaded by client \n - (" . $get_task_data->name . ') has been uploaded.';
                                        $send_notification = $this->slack->sendnotification($slack_message, $user_id, $group_name, $case_split_name, true);
                                    }
                                    $response = array(
                                        'status' => 200,
                                        'message' => 'File uploaded to Dropbox successfully.',
                                        'data' => $checklist,
                                    );
                                    getresponse($this, $response);
                                } else {
                                    $response = array(
                                        'status' => 200,
                                        'message' => 'File uploaded to Dropbox successfully but you checklist status is not update,Please Contact with admin.',
                                        'data' => $save
                                    );
                                    getresponse($this, $response);
                                }
                            }

                        } else {
                            $response = array(
                                'status' => 400,
                                'message' => 'No record found.',
                                'data' => null,
                            );
                            getresponse($this, $response);
                        }
                    }
                }
                // } else {
                //     echo "refresh token is not change";
                // }
            }
        }

    }
    // Function to add the latest file URL to the database
    private function addFileUrlToDatabase($user_id, $user_name, $task_id, $item_type_id, $file_type, $unique_filename, $file_url, $download_file_url)
    {
        // Check if the file already exists in the database
        $existingFile = $this->db->get_where(db_prefix() . 'files', array('rel_id' => $user_id, 'file_name' => $unique_filename))->row();
        // convert file_url to direct url
        // $direct_url = str_replace('www.dropbox.com', 'dl.dropboxusercontent.com', $file_url);
        if ($existingFile) {
            // Update the existing record with the latest file URL
            $this->db->where('id', $existingFile->id);
            $this->db->update(db_prefix() . 'files', array('file_url' => $file_url, 'download_file_url' => $download_file_url));
            return array(
                'status' => 'updated',
                'message' => 'File URL updated successfully',
                'data' => array(
                    'file_url' => $file_url,
                ),
            );
        } else {
            $this->db->select('rel_id');
            $this->db->where('id', $task_id);
            $this->db->where('rel_type', 'user-task');
            $task_data = $this->db->get(db_prefix() . 'tasks')->row();
            $file_data = array(
                'rel_id' => $task_data->rel_id,
                'task_id' => $task_id,
                'item_type_id' => $item_type_id,
                'filetype' => $file_type,
                'file_name' => $unique_filename,
                'rel_type' => 'client-doc',
                'file_url' => $file_url,
                'download_file_url' => $download_file_url,
                'dateadded' => date('Y-m-d H:i:s'),
            );
            $this->db->insert(db_prefix() . 'files', $file_data);
            if ($this->db->affected_rows() > 0) {
                $inserted_id = $this->db->insert_id();
                $lead_activity_log_data = array(
                    'leadid' => $user_id,
                    'file_id' => $inserted_id,
                    'task_id' => $task_id,
                    'full_name' => $user_name,
                    'activity_type' => 'user-doc',
                    'description' => 'Document has been Pending Review by ' . $user_name . '.',
                    'additional_data' => 'Pending Review',
                    'date' => date('Y-m-d H:i:s'),
                );
                leads_activity_log($this, $lead_activity_log_data);
                return array(
                    'id' => $inserted_id,
                    'file_type' => explode('/', $file_type)[1],
                    'file_url' => $file_url,
                    // 'file_status' => 'Submitted',
                );
            }
        }
    }

    private function exchangeAuthorizationCodeForAccessToken($authorizationCode)
    {
        // Ensure $code is correctly populated
        $ch = curl_init('https://api.dropbox.com/oauth2/token');
        $data = [
            'code' => $authorizationCode,
            'grant_type' => 'authorization_code',
            'client_id' => $this->appKey,
            'client_secret' => $this->appSecret,
            'redirect_uri' => $this->redirectUri,
        ];

        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);

        $response = json_decode(curl_exec($ch), true);
        curl_close($ch);
        $access_token = $response['access_token'];
        return $response;
    }
    private function uploadToDropbox($access_token, $local_path, $remote_path)
    {
        $url = 'https://content.dropboxapi.com/2/files/upload';

        $headers = array(
            'Authorization: Bearer ' . $access_token,
            'Content-Type: application/octet-stream',
            'Dropbox-API-Arg: {"path":"' . $remote_path . '"}',
        );

        $ch = curl_init($url);

        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, file_get_contents($local_path));
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

        $response = curl_exec($ch);
        $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);

        curl_close($ch);

        return $http_code == 200;
    }
    // Fetch images from dropbox extra work
    public function getfiles_post()
    {
        $getemail = $this->authmiddleware->verifyToken();

        if (empty($getemail)) {

        } else {
            $data = $this->Contacts_model->getEmail($getemail);
            $get_id = array_column($data, 'id');
            $user_id = implode(',', $get_id);
            $get_firstname = array_column($data, 'firstname');
            $get_lastname = array_column($data, 'lastname');
            $dropbox_firstname = implode(',', $get_firstname);
            $dropbox_lastname = implode(',', $get_lastname);
            // Check if it's a POST request
            if ($_SERVER['REQUEST_METHOD'] !== 'POST') {

                $response = array(
                    'status' => 400,
                    'message' => 'Invalid request method.',
                    'data' => array()
                );
                getresponse($this, $response);
            } else {
                $dataToken = $this->Token_model->getToken();
                $get_token = array_column($dataToken, 'token');
                $access_token = implode(',', $get_token);

                $dropboxFolderPath = '/uploads/' . $user_id . '_' . $dropbox_firstname . "_" . $dropbox_lastname; // Update the folder path as needed

                $ch = curl_init("https://api.dropboxapi.com/2/files/list_folder");

                $requestData = json_encode([
                    'path' => $dropboxFolderPath,
                ]);

                curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
                curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
                curl_setopt($ch, CURLOPT_POSTFIELDS, $requestData);
                curl_setopt($ch, CURLOPT_HTTPHEADER, [
                    'Authorization: Bearer ' . $access_token,
                    'Content-Type: application/json',
                ]);

                $response = json_decode(curl_exec($ch), true);
                curl_close($ch);

                $files = [];

                if (!empty($response)) {
                    foreach ($response['entries'] as $entry) {
                        if (isset($entry['name']) && is_string($entry['name'])) {
                            if ($entry['.tag'] === 'file') {
                                $path = $entry['path_display'];
                                $filepath[] = $entry['path_display'];
                                $fileType = $this->getFileContentType($entry['name']);

                                $fileContent = $this->fetchFileContent($access_token, $path);
                                $this->db->select('id,task_id,rel_id,rel_type,file_name,filetype,file_url,doc_status,staffid,contact_id,task_comment_id,dateadded'); // Select all columns
                                $this->db->from(db_prefix() . 'files'); // Specify the table name
                                // Define your WHERE conditions
                                $this->db->where('file_name', $entry['name']);
                                $query = $this->db->get();
                                $Result = $query->result();
                                $get_doc_status = array_column($Result, 'doc_status');
                                $doc_status_string = implode(',', $get_doc_status);
                                $files[] = [
                                    'name' => $entry['name'],
                                    'type' => $fileType,
                                    'doc_status' => $doc_status_string,
                                    'file' => base64_encode($fileContent),
                                    // Encode as base64
                                ];
                            }
                        }
                    }
                }
                $data = responseData($data);
                $response = array(
                    'status' => 200,
                    'message' => 'Fetch Documents and User Details.',
                    'data' => array_merge($data, array('File_name' => $files))
                );
                getresponse($this, $response);
            }
        }

    }
    public function fetchFileContent($accessToken, $path)
    {
        $ch = curl_init("https://content.dropboxapi.com/2/files/download");

        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
        curl_setopt($ch, CURLOPT_HTTPHEADER, [
            'Authorization: Bearer ' . $accessToken,
            'Dropbox-API-Arg: ' . json_encode(['path' => $path]),
        ]);

        $fileContent = curl_exec($ch);
        curl_close($ch);

        return $fileContent;
    }
    public function getFileContentType($fileName)
    {
        $extension = pathinfo($fileName, PATHINFO_EXTENSION);
        switch (strtolower($extension)) {
            case 'jpg':
            case 'jpeg':
            case 'png':
                return 'image';
            case 'pdf':
                return 'pdf';
            case 'zip':
                return 'zip';
            default:
                return 'unknown';
        }
    }

    //Delete images from dropbox
    private function deleteFile($accessToken, $path)
    {
        $ch = curl_init("https://api.dropboxapi.com/2/files/delete_v2");

        $requestData = json_encode([
            'path' => $path,
        ]);

        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
        curl_setopt($ch, CURLOPT_POSTFIELDS, $requestData);
        curl_setopt($ch, CURLOPT_HTTPHEADER, [
            'Authorization: Bearer ' . $accessToken,
            'Content-Type: application/json',
        ]);

        // Set CURLOPT_RETURNTRANSFER to true to suppress output and retrieve the response data
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

        // Execute cURL and get the response data
        $response = curl_exec($ch);

        // Get the HTTP response code
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);

        curl_close($ch);

        // Check if the HTTP response code indicates success
        if ($httpCode === 200) {
            return true; // Success
        } else {
            return false; // Failure
        }
    }
    // Example usage:
    public function deleteImage_post()
    {
        $getemail = $this->authmiddleware->verifyToken();
        // Remove quotes and "String(25)" from the string
        // $cleanedString = str_replace('String(25) "', '', $path);
        if (empty($getemail)) {
        } else {
            if ($this->input->server('REQUEST_METHOD') === 'POST') {
                $id = $this->input->post('file_id');
                $this->db->select('id,task_id,rel_id,rel_type,file_name,filetype,file_url,doc_status,staffid,contact_id,task_comment_id,dateadded');
                $this->db->from(db_prefix() . 'files');
                $this->db->where('id', $id);
                $query = $this->db->get();
                // Check if the query was successful
                if ($query) {
                    // Get the result as an object
                    $result = $query->row();

                    // Check if there is a result
                    if ($result) {
                        // Access the columns using object properties
                        $fileId = $result->id;
                        $cleanedString = $result->file_name;
                        // Access other columns as needed
                        $data = $this->Contacts_model->getEmail($getemail);
                        $get_id = array_column($data, 'id');
                        $get_firstname = array_column($data, 'firstname');
                        $get_lastname = array_column($data, 'lastname');
                        $dropbox_firstname = implode(',', $get_firstname);
                        $dropbox_lastname = implode(',', $get_lastname);
                        $get_userid = array_column($data, 'userid');
                        $userid = implode(',', $get_userid);
                        $user_id = implode(',', $get_id);
                        $access_token_data = $this->Token_model->getToken();
                        $get_id = array_column($access_token_data, 'token');
                        $access_token = implode(',', $get_id);

                        $imagePath = '/uploads/' . $user_id . '_' . $dropbox_firstname . "_" . $dropbox_lastname . '/' . $cleanedString; // Update the path to the image you want to delete

                        $responsedelete = $this->deleteFile($access_token, $imagePath);

                        if ($responsedelete) {
                            // The file was successfully deleted
                            $this->db->select('*');
                            $this->db->from(db_prefix() . 'files');
                            $this->db->where('file_name', $cleanedString);
                            // Perform the delete operation
                            $DeleteResponse = $this->db->delete();
                            $data = responseData($data);
                            $response = array(
                                'status' => 200,
                                'message' => 'File are Delete Successfully.',
                                'data' => null,
                            );
                            getresponse($this, $response);
                        } else {
                            // Error handling: Display an error message
                            $this->Leads_model->add_errors_logs($user_id, $userid, $dropbox_firstname . " " . $dropbox_lastname, 'Image is not Deleted', 'Image is not Deleted properly for using this fucntion deleteImage_post() in app.', 400, 'client');
                            $response = array(
                                'status' => 400,
                                'message' => 'Files is not exist in our record.',
                                'data' => null,
                            );
                            getresponse($this, $response);
                        }
                    } else {
                        // No matching record found
                        $response = array(
                            'status' => 400,
                            'message' => '"No record found for ID' . $id,
                            'data' => null,
                        );
                        getresponse($this, $response);
                    }
                } else {
                    $response = array(
                        'status' => 400,
                        'message' => '"No record found',
                        'data' => null,
                    );
                    getresponse($this, $response);
                }
            } else {
                $response = array(
                    'status' => 400,
                    'message' => 'The requested method is not supported.',
                    'data' => null,
                );
                getresponse($this, $response);
            }
        }
    }
    // Get All FIles link
    public function getAllFileLinks_post()
    {
        $getemail = $this->authmiddleware->verifyToken();

        if (empty($getemail)) {

        } else {
            $data = $this->Contacts_model->getEmail($getemail);
            $get_id = array_column($data, 'id');
            $user_id = implode(',', $get_id);

            // Check if it's a POST request
            if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
                $response = array(
                    'status' => 400,
                    'message' => 'Invalid request method.',
                    'data' => null,
                );
                getresponse($this, $response);
            } else {
                // Get Dropbox access token from your database or configuration
                $accessTokenData = $this->Token_model->getToken();
                $accessToken = implode(',', array_column($accessTokenData, 'token'));
                $leadData = $this->Leads_model->get_lead_id($user_id);
                $this->db->select('id,task_id,rel_id,rel_type,file_name,filetype,file_url,doc_status,staffid,contact_id,task_comment_id,dateadded');
                $this->db->from(db_prefix() . 'files');
                $this->db->where('rel_id', $leadData->id);
                $this->db->where('rel_type', 'client-doc');
                $query = $this->db->get();

                $fileLinks = [];

                if ($query->num_rows() > 0) {
                    $records = $query->result();

                    foreach ($records as $record) {
                        $fileLink = [
                            'file_id' => $record->id,
                            'file_name' => $record->file_name,
                            'file_type' => explode('/', $record->filetype)[1],
                            'file_url' => $record->file_url,
                            'file_status' => $record->doc_status,
                            'file_created_at' => strtotime($record->dateadded),
                        ];

                        $fileLinks[] = $fileLink;
                    }
                }

                $response = [
                    'status' => 200,
                    'message' => 'File links retrieved successfully.',
                    'data' => $fileLinks,
                ];

                getresponse($this, $response);
            }
        }
    }
    private function listFiles($accessToken, $folderPath)
    {
        $ch = curl_init("https://api.dropboxapi.com/2/files/list_folder");

        $requestData = json_encode([
            'path' => $folderPath,
        ]);

        curl_setopt_array($ch, [
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_CUSTOMREQUEST => 'POST',
            CURLOPT_POSTFIELDS => $requestData,
            CURLOPT_HTTPHEADER => [
                'Authorization: Bearer ' . $accessToken,
                'Content-Type: application/json',
            ],
        ]);
        $response = json_decode(curl_exec($ch), true);
        curl_close($ch);
        $files = [];
        if (!empty($response['entries'])) {
            foreach ($response['entries'] as $entry) {
                if (isset($entry['name']) && is_string($entry['name']) && $entry['.tag'] === 'file') {
                    $files[] = $entry['path_display'];
                }
            }
        }
        return $files;
    }
    private function getTemporaryLinks($accessToken, $files)
    {
        $fileLinks = [];
        foreach ($files as $filePath) {
            $ch = curl_init("https://api.dropboxapi.com/2/files/get_temporary_link");

            $requestData = json_encode([
                'path' => $filePath,
            ]);
            curl_setopt_array($ch, [
                CURLOPT_RETURNTRANSFER => true,
                CURLOPT_CUSTOMREQUEST => 'POST',
                CURLOPT_POSTFIELDS => $requestData,
                CURLOPT_HTTPHEADER => [
                    'Authorization: Bearer ' . $accessToken,
                    'Content-Type: application/json',
                ],
            ]);
            $response = json_decode(curl_exec($ch), true);
            curl_close($ch);
            if (isset($response['link'])) {
                $fileInfo = [
                    'file_name' => $response['metadata']['name'],
                    'file_size' => $response['metadata']['size'],
                    'flie_url' => $response['link'],
                ];
                $fileLinks[] = $fileInfo;
            }
        }
        return $fileLinks;
    }

    // for permenatn link of files
    private function getPermanentLink($accessToken, $filePath)
    {
        $ch = curl_init("https://api.dropboxapi.com/2/files/get_temporary_link");

        $requestData = json_encode([
            'path' => $filePath,
        ]);

        curl_setopt_array($ch, [
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_CUSTOMREQUEST => 'POST',
            CURLOPT_POSTFIELDS => $requestData,
            CURLOPT_HTTPHEADER => [
                'Authorization: Bearer ' . $accessToken,
                'Content-Type: application/json',
            ],
        ]);

        $response = json_decode(curl_exec($ch), true);
        curl_close($ch);

        return $response;
    }

    private function createSharedLink($accessToken, $filePath)
    {
        $ch = curl_init("https://api.dropboxapi.com/2/sharing/create_shared_link");

        $requestData = json_encode([
            'path' => $filePath,
        ]);

        curl_setopt_array($ch, [
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_CUSTOMREQUEST => 'POST',
            CURLOPT_POSTFIELDS => $requestData,
            CURLOPT_HTTPHEADER => [
                'Authorization: Bearer ' . $accessToken,
                'Content-Type: application/json',
            ],
        ]);

        $response = json_decode(curl_exec($ch), true);
        curl_close($ch);

        return $response;
    }
    public function editprofile_post()
    {
        $getemail = $this->authmiddleware->verifyToken();
        if (empty($getemail)) {

        } else {
            $query_token = $this->Contacts_model->getEmail($getemail);
            if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
                $response = array(
                    'status' => 400,
                    'message' => 'Invalid request method.',
                    'data' => null,
                );
                getresponse($this, $response);
            } else {
                // get dropbox access token
                $first_name = $this->input->post('first_name');
                $last_name = $this->input->post('last_name');
                $phone_number = formatted_number($this->input->post('phone_number'));
                $additional_email = $this->input->post('additional_email');
                $accessTokenData = $this->Token_model->getToken();
                $accessToken = implode(',', array_column($accessTokenData, 'token'));
                $this->form_validation->set_rules('first_name', 'first name', 'required');
                $this->form_validation->set_rules('last_name', 'last name', 'required');
                // Set custom error messages
                $this->form_validation->set_message('required', 'The {field} field is required.');
                // Define $response before the if statement
                $response = array();

                if ($this->form_validation->run() == true) {
                    // get role and set condition
                    $get_role = array_column($query_token, 'role');
                    $role_string = implode(',', $get_role);
                    if ($role_string == 'client') {
                        $refresh_token_change = $this->Leads_model->refresh_dropbox_token_get();
                        if ($refresh_token_change) {
                            // Check record from contact
                            $this->db->select('id,userid,is_primary,firstname,lastname,email,additional_email,phonenumber,datecreated,password,active,role,is_password_changed');
                            $this->db->from(db_prefix() . 'contacts');
                            $this->db->where('email', $getemail);
                            $this->db->where('is_primary', '1');
                            $query = $this->db->get();
                            if (!empty($query)) {
                                $record = $query->result();
                                $get_id = array_column($record, 'id');
                                $user_id = array_column($record, 'userid');
                                $get_firstname = array_column($record, 'firstname');
                                $get_lastname = array_column($record, 'lastname');
                                $dropbox_firstname = implode(',', $get_firstname);
                                $dropbox_lastname = implode(',', $get_lastname);
                                $get_id = implode(',', $get_id);
                                $user_id = implode(',', $user_id);
                                // Update record for different tables
                                $contact_data = array(
                                    'firstname' => $first_name,
                                    'lastname' => $last_name,
                                    'phonenumber' => $phone_number,
                                    'additional_email' => $additional_email,
                                );
                                $contact_check = $this->updateTable_forcontact('contacts', $get_id, $contact_data);
                                // echo $this->db->last_query();exit;
                                // Update 'leads' table
                                $username = $first_name . ' ' . $last_name;
                                $lead_data = array(
                                    'name' => $username,
                                    'phonenumber' => $phone_number,
                                    'additional_email' => $additional_email,
                                );

                                // update all record in leads 
                                $this->db->where('email', $getemail);
                                $rows = $this->db->get(db_prefix() . 'leads')->result_array();
                                foreach ($rows as $row) {
                                    $this->db->where('id', $row['id']);
                                    $this->db->update(db_prefix() . 'leads', $lead_data);
                                    $leads_check = $this->updateTable_forleads('leads', $get_id, $lead_data);
                                }
                                // client data update
                                $client_data = array(
                                    'phonenumber' => $phone_number,
                                );
                                $leads_check = $this->updateTable_forclient('clients', $get_id, $client_data);
                                // Check if the update was successful
                                // Get the uploaded file
                                // get query for name get 
                                $this->db->select('id,userid,is_primary,firstname,lastname,email,additional_email,phonenumber,datecreated,password,active,role,is_password_changed');
                                $this->db->from(db_prefix() . 'contacts');
                                $this->db->where('id', $get_id);
                                $this->db->where('is_primary', '1');
                                $query_data = $this->db->get();
                                if (!empty($query_data)) {
                                    $record = $query_data->row();
                                    $first_name = $record->firstname;
                                    $last_name = $record->lastname;
                                }
                                $file = $_FILES['profile_image'];
                                if (!empty($file)) {
                                    // Check if the file is uploaded successfully
                                    if ($file['error'] !== UPLOAD_ERR_OK) {
                                        $data_user = responseData($query_token);
                                        $this->db->select('id,task_id,rel_id,rel_type,file_name,filetype,file_url,doc_status,staffid,contact_id,task_comment_id,dateadded');
                                        $this->db->from(db_prefix() . 'files');
                                        $this->db->where('contact_id', $get_id);
                                        $this->db->where('rel_type', 'profile-doc');
                                        $this->db->where('dateadded', 'DESC');
                                        $query = $this->db->get();
                                        $result = $query->row();
                                        if (!empty($result->file_url)) {
                                            $data_user['profile_url'] = $result->file_url;
                                        } else {
                                            $data_user['profile_url'] = '';
                                        }
                                        $data_user['first_name'] = $first_name;
                                        $data_user['last_name'] = $last_name;
                                        $get_is_password_changed = array_column($query_token, 'is_password_changed');
                                        $is_password_changed_string = implode(',', $get_is_password_changed);
                                        if ($is_password_changed_string == 'false') {
                                            $data_user['is_password_changed'] = false;
                                        } else {
                                            $data_user['is_password_changed'] = true;
                                        }
                                        $data_user['phone_number'] = $phone_number;
                                        $data_user['additional_email'] = $additional_email;
                                        $response = array(
                                            'status' => 200,
                                            'message' => 'Your Profile is updated successfully.',
                                            'data' => $data_user,
                                        );
                                        getresponse($this, $response);
                                    } else {
                                        // Generate a unique filename
                                        $uniqueFilename = time() . '_' . $file['name'];

                                        // Specify the Dropbox folder path
                                        $dropboxFolderPath = '/uploads/profile/' . $get_id . '_' . $dropbox_firstname . "_" . $dropbox_lastname;

                                        // Full path to the file on the server
                                        $filePath = $file['tmp_name'];

                                        // Full path to the file on Dropbox (including the unique filename)
                                        $dropboxFilePath = $dropboxFolderPath . '/' . $uniqueFilename;
                                        $this->db->select('id,task_id,rel_id,rel_type,file_name,filetype,file_url,doc_status,staffid,contact_id,task_comment_id,dateadded');
                                        $this->db->from(db_prefix() . 'files');
                                        $this->db->where('contact_id', $get_id);
                                        $this->db->order_by('dateadded', 'desc');
                                        $this->db->where('rel_type', 'profile-doc');
                                        $query = $this->db->get();
                                        $result = $query->row();
                                        // Check if there are any results
                                        if ($query->num_rows() > 0) {
                                            // Access the 'file detils' column
                                            $file_name = $result->file_name;
                                            $file_docstatus = $result->doc_status;
                                            $fileType = $result->filetype;
                                            // Fetch the result as an arrayy
                                            // Upload the file to Dropbox
                                            $Delete_imagePath = '/uploads/profile/' . $get_id . '_' . $dropbox_firstname . "_" . $dropbox_lastname . '/' . $file_name;
                                            if ($Delete_imagePath) {
                                                $delete_image_url = $this->deleteFile($accessToken, $Delete_imagePath);
                                                $uploadResult = $this->uploadToDropboxApi($accessToken, $filePath, $dropboxFilePath);
                                                // print_r($dropboxFilePath);exit;
                                                // Check if the file is successfully uploaded to Dropbox
                                                // Get file list
                                                $url_imagePath = '/uploads/profile/' . $get_id . '_' . $dropbox_firstname . "_" . $dropbox_lastname;
                                                $files = $this->listFiles($accessToken, $url_imagePath);

                                                // Fetch temporary links for each file
                                                $fileLinks = $this->getTemporaryLinks($accessToken, $files);
                                                // get permanent link of files
                                                $temporaryLink = $this->getPermanentLink($accessToken, $dropboxFilePath);

                                                if (isset($temporaryLink['link'])) {
                                                    // Temporary link received, now create a shared link
                                                    $sharedLink = $this->createSharedLink($accessToken, $dropboxFilePath);

                                                    if (isset($sharedLink['url'])) {
                                                        // Shared link obtained
                                                        $directLink = str_replace('dl=0', 'raw=1', $sharedLink['url']);
                                                        $fileLinks[0]['flie_url'] = $directLink;
                                                    } else {
                                                        // Handle the error when creating a shared link
                                                        echo "Error creating shared link";
                                                    }
                                                }

                                                $direct_url = str_replace('www.dropbox.com', 'dl.dropboxusercontent.com', $fileLinks[0]['flie_url']);
                                                $leadData = $this->Leads_model->get_lead_id($get_id);
                                                $file_data = array(
                                                    'rel_id' => $leadData->id,
                                                    'contact_id' => $get_id,
                                                    'filetype' => $file['type'],
                                                    'file_name' => $uniqueFilename,
                                                    'rel_type' => 'profile-doc',
                                                    'file_url' => $direct_url,
                                                    'dateadded' => date('Y-m-d H:i:s'),
                                                    // Add more fields if needed
                                                );
                                                if ($uploadResult) {
                                                    $this->db->where('contact_id', $get_id);
                                                    $this->db->where('rel_type', 'profile-doc');
                                                    // Perform the update
                                                    $this->db->update(db_prefix() . 'files', $file_data);
                                                    // update the profile image in profile_image
                                                    $data_profile_image = array(
                                                        'profile_image' => $direct_url
                                                    );
                                                    $this->db->where('id', $get_id);
                                                    $this->db->update(db_prefix() . 'contacts', $data_profile_image);

                                                    $data_user = responseData($query_token);
                                                    $data_user['profile_url'] = $direct_url;
                                                    $data_user['first_name'] = $first_name;
                                                    $data_user['last_name'] = $last_name;
                                                    $data_user['phone_number'] = $phone_number;
                                                    $data_user['additional_email'] = $additional_email;
                                                    $get_is_password_changed = array_column($query_token, 'is_password_changed');
                                                    $is_password_changed_string = implode(',', $get_is_password_changed);
                                                    if ($is_password_changed_string == 'false') {
                                                        $data_user['is_password_changed'] = false;
                                                    } else {
                                                        $data_user['is_password_changed'] = true;
                                                    }
                                                    $response = array(
                                                        'status' => 200,
                                                        'message' => 'Your Profile is updated successfully.',
                                                        'data' => $data_user,
                                                    );
                                                    getresponse($this, $response);
                                                } else {
                                                    $response = array(
                                                        'status' => 400,
                                                        'message' => 'Failed to upload file ,please try again.',
                                                        'data' => null,
                                                    );
                                                    getresponse($this, $response);
                                                }
                                            } else {
                                                $response = array(
                                                    'status' => 400,
                                                    'message' => 'Profile is not update, please try again.',
                                                    'data' => null,
                                                );
                                                getresponse($this, $response);
                                            }
                                        } else {
                                            // Upload the file to Dropbox
                                            $uploadResult = $this->uploadToDropboxApi($accessToken, $filePath, $dropboxFilePath);
                                            // print_r($dropboxFilePath);exit;
                                            // Check if the file is successfully uploaded to Dropbox
                                            if ($uploadResult) {
                                                $url_imagePath = '/uploads/profile/' . $get_id . '_' . $dropbox_firstname . "_" . $dropbox_lastname;
                                                $files = $this->listFiles($accessToken, $url_imagePath);
                                                // Fetch temporary links for each file
                                                $fileLinks = $this->getTemporaryLinks($accessToken, $files);
                                                // $fileLinks[0]['file_type'] = $fileType;
                                                // $fileLinks[0]['doc_status'] = $file_docstatus;
                                                // get permanent link of files
                                                $temporaryLink = $this->getPermanentLink($accessToken, $dropboxFilePath);

                                                if (isset($temporaryLink['link'])) {
                                                    // Temporary link received, now create a shared link
                                                    $sharedLink = $this->createSharedLink($accessToken, $dropboxFilePath);

                                                    if (isset($sharedLink['url'])) {
                                                        // Shared link obtained
                                                        $directLink = str_replace('dl=0', 'raw=1', $sharedLink['url']);
                                                        $fileLinks[0]['flie_url'] = $directLink;
                                                    } else {
                                                        // Handle the error when creating a shared link
                                                        $response = array(
                                                            'status' => 400,
                                                            'message' => 'Profile is not created because of url issue.',
                                                            'data' => null,
                                                        );
                                                        getresponse($this, $response);
                                                    }
                                                }
                                                $direct_url = str_replace('www.dropbox.com', 'dl.dropboxusercontent.com', $fileLinks[0]['flie_url']);
                                                $data_user = responseData($query_token);
                                                $data_user['first_name'] = $first_name;
                                                $data_user['last_name'] = $last_name;
                                                $data_user['phone_number'] = $phone_number;
                                                $data_user['additional_email'] = $additional_email;
                                                $leadData = $this->Leads_model->get_lead_id($get_id);
                                                $file_data = array(
                                                    'rel_id' => $leadData->id,
                                                    'contact_id' => $get_id,
                                                    'filetype' => $file['type'],
                                                    'file_name' => $uniqueFilename,
                                                    'rel_type' => 'profile-doc',
                                                    'file_url' => $direct_url,
                                                    'dateadded' => date('Y-m-d H:i:s'),
                                                    // Add more fields if needed
                                                );
                                                if ($uploadResult) {
                                                    $this->db->insert(db_prefix() . 'files', $file_data);
                                                    $data_profile_image = array(
                                                        'profile_image' => $direct_url
                                                    );
                                                    $this->db->where('id', $get_id);
                                                    $this->db->update(db_prefix() . 'contacts', $data_profile_image);
                                                    // $fileLinks[0]['first_name'] = $first_name;
                                                    // $fileLinks[0]['last_name'] = $last_name;
                                                    $data_user['profile_url'] = $direct_url;
                                                    $get_is_password_changed = array_column($query_token, 'is_password_changed');
                                                    $is_password_changed_string = implode(',', $get_is_password_changed);
                                                    if ($is_password_changed_string == 'false') {
                                                        $data_user['is_password_changed'] = false;
                                                    } else {
                                                        $data_user['is_password_changed'] = true;
                                                    }
                                                    $response = array(
                                                        'status' => 200,
                                                        'message' => 'Your Profile is updated successfully.',
                                                        'data' => $data_user,
                                                    );
                                                    getresponse($this, $response);
                                                } else {
                                                    $response = array(
                                                        'status' => 400,
                                                        'message' => 'Failed to upload file, please try again.',
                                                        'data' => null,
                                                    );
                                                    getresponse($this, $response);
                                                }
                                            }
                                        }
                                    }
                                } else {
                                    $data_user = responseData($query_token);
                                    $this->db->select('id,task_id,rel_id,rel_type,file_name,filetype,file_url,doc_status,staffid,contact_id,task_comment_id,dateadded');
                                    $this->db->from(db_prefix() . 'files');
                                    $this->db->where('contact_id', $get_id);
                                    $this->db->where('rel_type', 'profile-doc');
                                    $this->db->order_by('dateadded', 'desc');
                                    $query = $this->db->get();
                                    $result = $query->row();
                                    $data_user['profile_url'] = $result->file_url;
                                    $data_user['first_name'] = $first_name;
                                    $data_user['last_name'] = $last_name;
                                    $get_is_password_changed = array_column($query_token, 'is_password_changed');
                                    $is_password_changed_string = implode(',', $get_is_password_changed);
                                    if ($is_password_changed_string == 'false') {
                                        $data_user['is_password_changed'] = false;
                                    } else {
                                        $data_user['is_password_changed'] = true;
                                    }
                                    $data_user['phone_number'] = $phone_number;
                                    $data_user['additional_email'] = $additional_email;
                                    $response = array(
                                        'status' => 200,
                                        'message' => 'Your Profile is updated successfully.',
                                        'data' => $data_user,
                                    );
                                    getresponse($this, $response);
                                }
                            }
                        }
                    } else {
                        $get_staffid = array_column($query_token, 'staffid');
                        $staffid_string = implode(',', $get_staffid);
                        // staff data update
                        $staff_data = array(
                            'firstname' => $first_name,
                            'lastname' => $last_name,
                            'phonenumber' => $phone_number,
                        );
                        $file = $_FILES['profile_image'];
                        if (!empty($file)) {
                            $this->db->where('staffid', $staffid_string);
                            $update_record = $this->db->update(db_prefix() . 'staff', $staff_data);
                            if ($update_record) {
                                handle_staff_profile_image_upload($staffid_string);
                                $this->db->select('staffid,email,firstname,lastname,staff_group,phonenumber,password,datecreated,profile_image,admin,role,active,is_password_changed');
                                $this->db->from(db_prefix() . 'staff');
                                $this->db->where('staffid', $staffid_string);
                                // Get the results
                                $query = $this->db->get();
                                $data = $query->result();
                                // array to string convert the profile image
                                $get_profile_image = array_column($data, 'profile_image');
                                $profile_image_string = implode(',', $get_profile_image);
                                $staff_response = responseData_staff($data);
                                if (is_numeric($role_string) && $role_string > 0) {
                                    $role = $role_string;
                                    $staff_response['role'] = if_role_is_id_then_get_staff_role_name($this, $role);
                                    $staff_response['profile_url'] = get_staff_profile_url($staffid_string, $profile_image_string);
                                    $Response_Data = $staff_response;
                                }
                                $response = array(
                                    'status' => 200,
                                    'message' => 'Your Profile image and information is updated successfully.',
                                    'data' => $Response_Data,
                                );
                                getresponse($this, $response);
                            } else {
                                $response = array(
                                    'status' => 400,
                                    'message' => 'Sorry your profile is not update, please try again.',
                                    'data' => null,
                                );
                                getresponse($this, $response);
                            }
                        } else {
                            $this->db->where('staffid', $staffid_string);
                            $update_record = $this->db->update(db_prefix() . 'staff', $staff_data);
                            if ($update_record) {
                                $this->db->select('staffid,email,firstname,lastname,staff_group,phonenumber,password,datecreated,profile_image,admin,role,active,is_password_changed');
                                $this->db->from(db_prefix() . 'staff');
                                $this->db->where('staffid', $staffid_string);
                                // Get the results
                                $query = $this->db->get();
                                $data = $query->result();
                                // array to string convert the profile image
                                $get_profile_image = array_column($data, 'profile_image');
                                $profile_image_string = implode(',', $get_profile_image);
                                $staff_response = responseData_staff($data);
                                if (is_numeric($role_string) && $role_string > 0) {
                                    $role = $role_string;
                                    $staff_response['role'] = if_role_is_id_then_get_staff_role_name($this, $role);
                                    $staff_response['profile_url'] = get_staff_profile_url($staffid_string, $profile_image_string);
                                    $Response_Data = $staff_response;
                                }
                                $response = array(
                                    'status' => 200,
                                    'message' => 'Your Profile image and information is updated successfully.',
                                    'data' => $Response_Data,
                                );
                                getresponse($this, $response);
                            } else {
                                $response = array(
                                    'status' => 400,
                                    'message' => 'Sorry your profile is not update, please try again.',
                                    'data' => null,
                                );
                                getresponse($this, $response);
                            }
                        }
                    }
                } else {
                    // show the validation error when if condition false
                    $errors = array(
                        'first_name' => form_error('first_name'),
                        'last_name' => form_error('last_name'),
                    );
                    // Check if there are any validation errors
                    if (!empty($errors['first_name']) || !empty($errors['last_name'])) {
                        $response = array(
                            'status' => 400,
                            'message' => 'Please correct the errors below!',
                            'data' => null,
                        );
                        // Append error details to the message
                        if (!empty($errors['first_name'])) {
                            $response['message'] .= ' ' . $errors['first_name'];
                        }
                        if (!empty($errors['last_name'])) {
                            $response['message'] .= ' ' . $errors['last_name'];
                        }
                    }
                    // Return the JSON response
                    // Load the custom helper in your controller
                    getresponse($this, $response);
                }
            }
        }
    }
    private function updateTable_forcontact($table, $user_id, $data)
    {
        // Define your WHERE conditions for the update
        $this->db->where('id', $user_id);

        // Perform the update
        $this->db->update(db_prefix() . $table, $data);
        if ($this->db->affected_rows() > 0) {
            return true;
        } else {
            return false;
        }
    }
    private function updateTable_forclient($table, $user_id, $data)
    {
        // Define your WHERE conditions for the update
        $this->db->where('userid', $user_id);

        // Perform the update
        $this->db->update(db_prefix() . $table, $data);
        if ($this->db->affected_rows() > 0) {
            return true;
        } else {
            return false;
        }
    }
    private function updateTable_forleads($table, $user_id, $data)
    {
        // Define your WHERE conditions for the update
        $this->db->where('client_id', $user_id);

        // Perform the update
        $this->db->update(db_prefix() . $table, $data);
        if ($this->db->affected_rows() > 0) {
            return true;
        } else {
            return false;
        }
    }
    // Function to upload file to Dropbox using cURL
    private function uploadToDropboxApi($accessToken, $filePath, $dropboxFilePath)
    {
        $ch = curl_init('https://content.dropboxapi.com/2/files/upload');

        $headers = array(
            'Authorization: Bearer ' . $accessToken,
            'Content-Type: application/octet-stream',
            'Dropbox-API-Arg: {"path":"' . $dropboxFilePath . '","mode":"add"}',
        );

        $fileContent = file_get_contents($filePath);

        curl_setopt_array(
            $ch,
            array(
                CURLOPT_POST => true,
                CURLOPT_POSTFIELDS => $fileContent,
                CURLOPT_HTTPHEADER => $headers,
                CURLOPT_RETURNTRANSFER => true,
            )
        );

        $response = curl_exec($ch);
        $error = curl_error($ch);

        curl_close($ch);

        if ($error) {
            return false;
        }

        return $response;
    }

    // Get user Cases 
    public function getusercases_post()
    {
        $getemail = $this->authmiddleware->verifyToken();
        if (empty($getemail)) {
        } else {
            if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
                $response = array(
                    'status' => 400,
                    'message' => 'Invalid request method.',
                    'data' => null,
                );
                getresponse($this, $response);
            } else {
                $this->db->select('id,userid,is_primary,firstname,lastname,email,additional_email,phonenumber,datecreated,password,active,role,is_password_changed');
                $this->db->from(db_prefix() . 'contacts');
                $this->db->where('email', $getemail);
                $this->db->where('is_primary', '1');
                $query = $this->db->get();
                if (!empty($query)) {
                    $record = $query->result();
                    $get_id = array_column($record, 'id');
                    $userid = array_column($record, 'userid');
                    $get_id = implode(',', $get_id);
                    $user_id = implode(',', $userid);
                    $leadData = $this->Leads_model->get_lead_id($user_id);

                    // get lead status data
                    $this->db->select('name');
                    $this->db->from(db_prefix() . 'leads_status');
                    $this->db->where('id', $leadData->id);
                    $query = $this->db->get();
                    $leads_status_record = $query->result();
                    $get_leads_status_name = array_column($leads_status_record, 'name');
                    $stats_name = implode(',', $get_leads_status_name);
                    // get all files record about user
                    $this->db->select('id,task_id,rel_id,rel_type,file_name,filetype,file_url,doc_status,staffid,contact_id,task_comment_id,dateadded');
                    $this->db->from(db_prefix() . 'files');
                    $this->db->where('rel_id', $leadData->id);
                    $this->db->where('rel_type', 'client-doc');
                    $query = $this->db->get();
                    $leads_status_record = $query->result();
                    // Initialize arrays to store data
                    $file_names = [];
                    $file_types = [];
                    $file_urls = [];
                    $doc_statuses = [];

                    // Initialize arrays to store data
                    $files_data = [];

                    // Loop through each record

                    foreach ($leads_status_record as $record) {
                        // Create an array for each file
                        $file_data = [
                            'file_id' => $record->id,
                            'file_name' => $record->file_name,
                            'file_type' => explode('/', $record->filetype)[1],
                            'file_url' => $record->file_url,
                            'status' => $record->doc_status,
                            'created_at' => strtotime($record->dateadded),
                            'checklist_activity' => [],
                        ];

                        // Check record from contact
                        $this->db->select('*');
                        $this->db->from(db_prefix() . 'lead_activity_log');
                        $this->db->where('file_id', $record->id);
                        $this->db->where('activity_type', 'user-doc');
                        $query = $this->db->get();

                        if ($query->num_rows() > 0) {
                            // If there are records in the result set
                            $record_activity = $query->result();

                            // Extract data from the result set and add to checklist_activity
                            foreach ($record_activity as $details_activity) {
                                $message = $details_activity->additional_data == 'Rejected'
                                    ? $details_activity->reason . " - Rejected by " . $details_activity->full_name . "."
                                    : $details_activity->description;
                                $file_data['checklist_activity'][] = [
                                    'status' => $details_activity->additional_data,
                                    'date' => strtotime($details_activity->date),
                                    'description' => $message,
                                ];
                            }
                        }
                        // Add the file data to the main array
                        $files_data[] = $file_data;
                    }


                    // Leads/case file instruction
                    $this->db->select('*');
                    $this->db->from(db_prefix() . 'file_instruction');
                    $this->db->where('lead_id', $leadData->id);
                    $query = $this->db->get();
                    $file_instruction_data = $query->row();

                    // Check if file_instruction_data is not null before using its properties
                    if ($file_instruction_data) {
                        // Use the null coalescing operator to set 'updated_at'
                        if (!empty($file_instruction_data->updated_at)) {
                            $updated_at_timestamp = strtotime($file_instruction_data->updated_at);
                        } else {
                            $updated_at_timestamp = "";
                        }

                        $instruction_list_data = [
                            'instruction' => $file_instruction_data->instruction,
                            'created_at' => strtotime($file_instruction_data->created_at),
                            'updated_by' => $file_instruction_data->updated_by,
                            'updated_at' => $updated_at_timestamp,
                        ];
                    }
                    $data = array(
                        'id' => $leadData->id,
                        'name' => $leadData->name,
                        'started_date' => strtotime($leadData->dateadded),
                        'status' => $stats_name,
                    );

                    $response = array(
                        'status' => 200,
                        'message' => 'User Details.',
                        'data' => array_merge($data, ['instruction' => $instruction_list_data, 'check_list' => $files_data]),
                    );
                    getresponse($this, $response);
                } else {
                    $response = array(
                        'status' => 200,
                        'message' => 'user is not exist in our record.',
                        'data' => null,
                    );
                    getresponse($this, $response);
                }
            }
        }
    }
    // get user active cases
    public function getactivecase_post()
    {
        $getemail = $this->authmiddleware->verifyToken();
        if (empty($getemail)) {
        } else {
            if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
                $response = array(
                    'status' => 400,
                    'message' => 'Invalid request method.',
                    'data' => null,
                );
                getresponse($this, $response);
            } else {
                $this->db->select('id,name,secondary_name,title,company,description,country,zip,city,state,address,assigned,assign_group,dateadded,status,multiple_cases,active_case,addedfrom,email,phonenumber,client_id,martial_status,transaction,app_email_requested,funds_requested_mail');
                $this->db->from(db_prefix() . 'leads');
                $this->db->where('email', $getemail);
                $this->db->where('active_case', 'Active');
                $query = $this->db->get();

                // Check if there is at least one row
                if ($query->num_rows() > 0) {
                    $active_case_record = $query->row();
                    $this->db->select('id, name, description, dateadded, status, rel_id, lead_borrow_id, type, leads_status');
                    $this->db->from(db_prefix() . 'tasks');
                    $this->db->where('rel_id', $active_case_record->id);
                    $this->db->where('rel_type', 'user-task');
                    $this->db->where('type', 'client');
                    if (in_array($active_case_record->status, [1, 8, 2, 7]) && empty($active_case_record->app_email_requested)) {
                        $this->db->where('leads_status', 1);
                    } else {
                        $this->db->where_in('leads_status', [1, 3]);
                    }
                    $query = $this->db->get();

                    $user_task_records = $query->result();
                    $get_staff_group = $active_case_record->assign_group;
                    // get staff id
                    $this->db->select('*');
                    $this->db->where('group_name', $get_staff_group);
                    $query = $this->db->get(db_prefix() . 'group');
                    if ($query->num_rows() > 0) {
                        $result = $query->row();
                        $group_id = $result->id;
                        $group_name = $result->group_name;
                        $group_details = array(
                            'id' => $group_id,
                            'name' => $group_name,
                            'members' => array()
                        );

                        // get all staff details
                        $this->db->select('staffid,email,firstname,lastname,staff_group,phonenumber,password,datecreated,profile_image,admin,role,active,is_password_changed');
                        $this->db->where('staff_group', $group_name);
                        $staff_query = $this->db->get(db_prefix() . 'staff');

                        if ($staff_query->num_rows() > 0) {
                            $staff_data_Array = array();
                            foreach ($staff_query->result() as $staff_data_fetch) {
                                $staff_data_Array[] = array(
                                    'id' => $staff_data_fetch->staffid,
                                    'name' => $staff_data_fetch->firstname . ' ' . $staff_data_fetch->lastname,
                                    'profile_url' => isset($staff_data_fetch->profile_image) ? base_url('uploads/staff_profile_images/' . $staff_data_fetch->staffid . '/thumb_' . $staff_data_fetch->profile_image) : null,
                                );
                            }
                            $group_details['members'] = $staff_data_Array;
                        } else {
                            $group_details = null;
                        }
                    } else {
                        $group_id = null;
                        $group_name = null;
                    }
                    // Get total tasks count
                    $this->db->select('COUNT(id) as total_tasks');
                    $this->db->where('rel_id', $active_case_record->id);
                    $this->db->where('rel_type', 'user-task');
                    $this->db->where('type', 'client');
                    $total_tasks_query = $this->db->get(db_prefix() . 'tasks');
                    $total_tasks_result = $total_tasks_query->row();
                    $total_tasks_count = $total_tasks_result->total_tasks;

                    // Get completed tasks count
                    $this->db->select('COUNT(id) as completed_tasks');
                    $this->db->where('rel_id', $active_case_record->id);
                    $this->db->where('rel_type', 'user-task');
                    $this->db->where('status', '4');
                    $this->db->where('type', 'client');
                    $completed_tasks_query = $this->db->get(db_prefix() . 'tasks');
                    $completed_tasks_result = $completed_tasks_query->row();
                    $completed_tasks_count = $completed_tasks_result->completed_tasks;
                    // pass the curent stage status
                    $case_stage_message = show_current_stage_text_in_mobile_side($this, $active_case_record->id, $active_case_record->status);
                    if (empty($active_case_record->app_email_requested) && $active_case_record->status == 7) {
                        $case_stage_status = 'Appointment Pending';
                    } else {
                        $case_stage_status = get_status_name_by_using_status_id($this, $active_case_record->status);
                    }
                    // pass the latest status
                    $this->db->select('additional_data');
                    $this->db->where('leadid', $active_case_record->id);
                    $this->db->where('activity_type', 'task-activity');
                    $this->db->order_by('id', 'desc');
                    $this->db->limit(1);
                    $get_current_lead_query = $this->db->get(db_prefix() . 'lead_activity_log');
                    if ($get_current_lead_query->num_rows() > 0) {
                        $latest_activity = $get_current_lead_query->row();
                        if (!empty($latest_activity->additional_data)) {
                            $get_current_lead_active_status = $latest_activity->additional_data;
                        } else {
                            $get_current_lead_active_status = 'Active';
                        }
                    }
                    // break the string of primary name
                    $primary_name = explode(' ', $active_case_record->name, 3);
                    $firstname = '';
                    $middlename = '';
                    $lastname = '';

                    if (isset($primary_name[0])) {
                        $firstname = $primary_name[0];
                    }
                    if (isset($primary_name[1])) {
                        $middlename = $primary_name[1];
                    }
                    if (isset($primary_name[2])) {
                        $lastname = $primary_name[2];
                    }

                    // break the string of secondary name
                    $secondary_name = explode(' ', $active_case_record->secondary_name, 3);
                    $secondary_firstname = '';
                    $secondary_middlename = '';
                    $secondary_lastname = '';

                    if (isset($secondary_name[0])) {
                        $secondary_firstname = $secondary_name[0];
                    }
                    if (isset($secondary_name[1])) {
                        $secondary_middlename = $secondary_name[1];
                    }
                    if (isset($secondary_name[2])) {
                        $secondary_lastname = $secondary_name[2];
                    }
                    // get the transaction details
                    $leads_transacation_data = leads_bank_details($this, $active_case_record->id);
                    $transaction_name = '';
                    if (!empty($leads_transacation_data)) {
                        $transaction_name = get_transaction_name_by_id($this, $leads_transacation_data[0]['transaction_id']);
                    }
                    $funds_requested_mail = false;
                    if (!empty($active_case_record->funds_requested_mail) && $active_case_record->funds_requested_mail == 1) {
                        $funds_requested_mail = true;
                    }
                    $data = [
                        'case_id' => $active_case_record->id,
                        'name' => $active_case_record->name,
                        'address' => $active_case_record->address,
                        'started_at' => strtotime($active_case_record->dateadded),
                        'status' => $case_stage_status,
                        'case_active' => $active_case_record->active_case,
                        'case_stage_message' => $case_stage_message,
                        'item_status' => $get_current_lead_active_status,
                        'martial_status' => $active_case_record->martial_status,
                        // 'transaction' => $active_case_record->transaction,
                        'transaction' => $transaction_name,
                        'total_task' => $total_tasks_count,
                        'completed_task' => $completed_tasks_count,
                        'outstanding_stage_message' => 'Lender/Lawyer conditions being fulfilled by Legal Direct.',
                        'funds_requested_mail' => $funds_requested_mail,
                        'group' => $group_details,
                        'check_list' => [],
                    ];

                    foreach ($user_task_records as $record_task) {
                        $status = return_item_status_for_app_side($record_task->status);
                        $checklist_instruction = $this->file_instruction_model->get_instruction_by_taskid($record_task->id);
                        $instructions = is_array($checklist_instruction) && array_key_exists('instruction', $checklist_instruction)
                            ? explode("\n\r", $checklist_instruction['instruction'])
                            : [];

                        $resultArray = [];

                        foreach ($instructions as $instruction) {
                            $items = array_map('trim', explode(',', $instruction));
                            if (!empty(implode(',', $items))) {
                                $resultArray[] = implode(',', $items);
                            }
                        }
                        $checklist[] = [
                            'id' => $record_task->id,
                            'title' => $record_task->name,
                            'client_checklist_name' => get_checklist_client_name($this, $record_task->rel_id, $record_task->lead_borrow_id),
                            'checklist_stage_name' => get_status_name_by_using_status_id($this, $record_task->leads_status),
                            'description' => $record_task->description,
                            'status' => $status,
                            'instructions' => $resultArray,
                            'doc_types' => is_array($checklist_instruction) && array_key_exists('doc_type', $checklist_instruction) ? explode(',', $checklist_instruction['doc_type']) : [],
                            'type' => $record_task->type,
                            'checklist_user_id' => $record_task->lead_borrow_id
                        ];
                    }

                    $data['check_list'] = $checklist;
                    $response = [
                        'status' => 200,
                        'message' => 'Success',
                        'data' => $data,
                    ];
                    getresponse($this, $response);

                } else {
                    // if case closed then show the closed case details
                    $this->db->select('id,name,title,company,description,country,zip,city,state,address,assigned,assign_group,dateadded,status,multiple_cases,active_case,addedfrom,email,phonenumber,client_id,martial_status,transaction,app_email_requested,funds_requested_mail');
                    $this->db->from(db_prefix() . 'leads');
                    $this->db->where('email', $getemail);
                    $this->db->where('active_case', 'Closed');
                    $this->db->order_by('id', 'desc');
                    $query = $this->db->get();

                    // Check if there is at least one row
                    if ($query->num_rows() > 0) {
                        $active_case_record = $query->row();
                        $this->db->select('id, name, description, dateadded, status, rel_id, lead_borrow_id, type, leads_status');
                        $this->db->from(db_prefix() . 'tasks');
                        $this->db->where('rel_id', $active_case_record->id);
                        $this->db->where('rel_type', 'user-task');
                        $this->db->where('type', 'client');

                        if (in_array($active_case_record->status, [1, 8, 2, 7])) {
                            $this->db->where('leads_status', 1);
                        } else {
                            $this->db->where_in('leads_status', [1, 3]);
                        }

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

                        $user_task_records = $query->result();
                        $get_staff_group = $active_case_record->assign_group;
                        // get staff id
                        $this->db->select('*');
                        $this->db->where('group_name', $get_staff_group);
                        $query = $this->db->get(db_prefix() . 'group');
                        if ($query->num_rows() > 0) {
                            $result = $query->row();
                            $group_id = $result->id;
                            $group_name = $result->group_name;
                            $group_details = array(
                                'id' => $group_id,
                                'name' => $group_name,
                                'members' => array()
                            );

                            // get all staff details
                            $this->db->select('staffid,email,firstname,lastname,staff_group,phonenumber,password,datecreated,profile_image,admin,role,active,is_password_changed');
                            $this->db->where('staff_group', $group_name);
                            $staff_query = $this->db->get(db_prefix() . 'staff');

                            if ($staff_query->num_rows() > 0) {
                                $staff_data_Array = array();
                                foreach ($staff_query->result() as $staff_data_fetch) {
                                    $staff_data_Array[] = array(
                                        'id' => $staff_data_fetch->staffid,
                                        'name' => $staff_data_fetch->firstname . ' ' . $staff_data_fetch->lastname,
                                        'profile_url' => isset($staff_data_fetch->profile_image) ? base_url('uploads/staff_profile_images/' . $staff_data_fetch->staffid . '/thumb_' . $staff_data_fetch->profile_image) : null,
                                    );
                                }
                                $group_details['members'] = $staff_data_Array;
                            } else {
                                $group_details = null;
                            }
                        } else {
                            $group_id = null;
                            $group_name = null;
                        }
                        // Get total tasks count
                        $this->db->select('COUNT(id) as total_tasks');
                        $this->db->where('rel_id', $active_case_record->id);
                        $this->db->where('rel_type', 'user-task');
                        $this->db->where('type', 'client');
                        $total_tasks_query = $this->db->get(db_prefix() . 'tasks');
                        $total_tasks_result = $total_tasks_query->row();
                        $total_tasks_count = $total_tasks_result->total_tasks;

                        // Get completed tasks count
                        $this->db->select('COUNT(id) as completed_tasks');
                        $this->db->where('rel_id', $active_case_record->id);
                        $this->db->where('rel_type', 'user-task');
                        $this->db->where('status', '4');
                        $this->db->where('type', 'client');
                        $completed_tasks_query = $this->db->get(db_prefix() . 'tasks');
                        $completed_tasks_result = $completed_tasks_query->row();
                        $completed_tasks_count = $completed_tasks_result->completed_tasks;
                        // pass the curent stage status
                        $case_stage_message = show_current_stage_text_in_mobile_side($this, $active_case_record->id, $active_case_record->status);
                        if (empty($active_case_record->app_email_requested) && $active_case_record->status == 7) {
                            $case_stage_status = 'Appointment Pending';
                        } else {
                            $case_stage_status = get_status_name_by_using_status_id($this, $active_case_record->status);
                        }
                        // pass the latest status
                        $this->db->select('additional_data');
                        $this->db->where('leadid', $active_case_record->id);
                        $this->db->where('activity_type', 'task-activity');
                        $this->db->order_by('id', 'desc');
                        $this->db->limit(1);
                        $get_current_lead_query = $this->db->get(db_prefix() . 'lead_activity_log');
                        if ($get_current_lead_query->num_rows() > 0) {
                            $latest_activity = $get_current_lead_query->row();
                            if (!empty($latest_activity->additional_data)) {
                                $get_current_lead_active_status = $latest_activity->additional_data;
                            } else {
                                $get_current_lead_active_status = 'Active';
                            }
                        }
                        // break the string of primary name
                        $primary_name = explode(' ', $active_case_record->name, 3);
                        $firstname = '';
                        $middlename = '';
                        $lastname = '';

                        if (isset($primary_name[0])) {
                            $firstname = $primary_name[0];
                        }
                        if (isset($primary_name[1])) {
                            $middlename = $primary_name[1];
                        }
                        if (isset($primary_name[2])) {
                            $lastname = $primary_name[2];
                        }

                        // break the string of secondary name
                        $secondary_name = explode(' ', $active_case_record->secondary_name, 3);
                        $secondary_firstname = '';
                        $secondary_middlename = '';
                        $secondary_lastname = '';

                        if (isset($secondary_name[0])) {
                            $secondary_firstname = $secondary_name[0];
                        }
                        if (isset($secondary_name[1])) {
                            $secondary_middlename = $secondary_name[1];
                        }
                        if (isset($secondary_name[2])) {
                            $secondary_lastname = $secondary_name[2];
                        }
                        // get the transaction details
                        $leads_transacation_data = leads_bank_details($this, $active_case_record->id);
                        $transaction_name = '';
                        if (!empty($leads_transacation_data)) {
                            $transaction_name = get_transaction_name_by_id($this, $leads_transacation_data[0]['transaction_id']);
                        }
                        $funds_requested_mail = false;
                        if (!empty($active_case_record->funds_requested_mail) && $active_case_record->funds_requested_mail == 1) {
                            $funds_requested_mail = true;
                        }
                        $data = [
                            'case_id' => $active_case_record->id,
                            'name' => $active_case_record->name,
                            'address' => $active_case_record->address,
                            'started_at' => strtotime($active_case_record->dateadded),
                            'status' => $case_stage_status,
                            'case_active' => $active_case_record->active_case,
                            'case_stage_message' => $case_stage_message,
                            'item_status' => $get_current_lead_active_status,
                            'martial_status' => $active_case_record->martial_status,
                            // 'transaction' => $active_case_record->transaction,
                            'transaction' => $transaction_name,
                            'total_task' => $total_tasks_count,
                            'completed_task' => $completed_tasks_count,
                            'outstanding_stage_message' => 'Lender/Lawyer conditions being fulfilled by Legal Direct.',
                            'funds_requested_mail' => $funds_requested_mail,
                            'group' => $group_details,
                            'check_list' => [],
                        ];

                        foreach ($user_task_records as $record_task) {
                            $status = return_item_status_for_app_side($record_task->status);
                            $checklist_instruction = $this->file_instruction_model->get_instruction_by_taskid($record_task->id);
                            $instructions = is_array($checklist_instruction) && array_key_exists('instruction', $checklist_instruction)
                                ? explode("\n\r", $checklist_instruction['instruction'])
                                : [];

                            $resultArray = [];

                            foreach ($instructions as $instruction) {
                                $items = array_map('trim', explode(',', $instruction));
                                if (!empty(implode(',', $items))) {
                                    $resultArray[] = implode(',', $items);
                                }
                            }
                            $checklist[] = [
                                'id' => $record_task->id,
                                'title' => $record_task->name,
                                'client_checklist_name' => get_checklist_client_name($this, $record_task->rel_id, $record_task->lead_borrow_id),
                                'checklist_stage_name' => get_status_name_by_using_status_id($this, $record_task->leads_status),
                                'description' => $record_task->description,
                                'status' => $status,
                                'instructions' => $resultArray,
                                'doc_types' => is_array($checklist_instruction) && array_key_exists('doc_type', $checklist_instruction) ? explode(',', $checklist_instruction['doc_type']) : [],
                                'type' => $record_task->type,
                                'checklist_user_id' => $record_task->lead_borrow_id
                            ];
                        }

                        $data['check_list'] = $checklist;
                        $response = [
                            'status' => 200,
                            'message' => 'Success',
                            'data' => $data,
                        ];
                        getresponse($this, $response);

                    }
                }
            }
        }
    }

    // Get cases history
    public function getcasehistory_post()
    {
        $getemail = $this->authmiddleware->verifyToken();

        if (empty($getemail)) {
        } else {
            if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
                $response = [
                    'status' => 400,
                    'message' => 'Invalid request method.',
                    'data' => null,
                ];
                getresponse($this, $response);
            } else {
                $query_data = $this->Contacts_model->getEmail($getemail);

                if (empty($query_data)) {
                    $response = [
                        'status' => 400,
                        'message' => 'Invalid request method.',
                        'data' => null,
                    ];
                    getresponse($this, $response);
                }

                $get_role = array_column($query_data, 'role');
                $role_string = implode(',', $get_role);

                $this->db->select('id,name,title,company,description,country,zip,city,state,address,assigned,assign_group,dateadded,status,multiple_cases,active_case,source,lastcontact,addedfrom,email,leadorder,phonenumber,client_id,martial_status,transaction,app_email_requested');
                $this->db->from(db_prefix() . 'leads');

                if ($role_string == 'client') {
                    $this->db->where('email', $getemail);
                } else if ($role_string == '1' || $role_string == 1) {
                    $get_staff_group = array_column($query_data, 'staff_group');
                    $staff_group_string = implode(',', $get_staff_group);
                    $this->db->where('assign_group', $staff_group_string);
                }

                $this->db->group_start();
                $this->db->or_where('status', '5');
                $this->db->or_where('status', '6');
                $this->db->or_where('status', '9');
                $this->db->group_end();
                $this->db->order_by('dateadded', 'desc');
                $query = $this->db->get();
                if ($query->num_rows() > 0) {
                    $get_cases_record = $query->result();
                    $data = [];

                    foreach ($get_cases_record as $active_case_record) {
                        if (empty($active_case_record->app_email_requested) && $active_case_record->status == 7) {
                            $case_stage_status = 'Appointment Pending';
                        } else {
                            $case_stage_status = get_status_name_by_using_status_id($this, $active_case_record->status);
                        }
                        // Get total tasks count
                        $this->db->select('COUNT(id) as total_tasks');
                        $this->db->where('rel_id', $active_case_record->id);
                        $this->db->where('rel_type', 'user-task');
                        $this->db->where('type', 'client');
                        $total_tasks_query = $this->db->get(db_prefix() . 'tasks');
                        $total_tasks_result = $total_tasks_query->row();
                        $total_tasks_count = $total_tasks_result->total_tasks;

                        // Get completed tasks count
                        $this->db->select('COUNT(id) as completed_tasks');
                        $this->db->where('rel_id', $active_case_record->id);
                        $this->db->where('rel_type', 'user-task');
                        $this->db->where('status', '4');
                        $this->db->where('type', 'client');
                        $completed_tasks_query = $this->db->get(db_prefix() . 'tasks');
                        $completed_tasks_result = $completed_tasks_query->row();
                        $completed_tasks_count = $completed_tasks_result->completed_tasks;
                        // get the transaction details
                        $leads_transacation_data = leads_bank_details($this, $active_case_record->id);
                        $transaction_name = '';
                        if (!empty($leads_transacation_data)) {
                            $transaction_name = get_transaction_name_by_id($this, $leads_transacation_data[0]['transaction_id']);
                        }
                        $data[] = [
                            'case_id' => $active_case_record->id,
                            'name' => $active_case_record->name,
                            'address' => $active_case_record->address,
                            'started_at' => strtotime($active_case_record->dateadded),
                            'status' => $case_stage_status,
                            'case_active' => $active_case_record->active_case,
                            'martial_status' => $active_case_record->martial_status,
                            // 'transaction' => $active_case_record->transaction,
                            'transaction' => $transaction_name,
                            'total_task' => $total_tasks_count,
                            'completed_task' => $completed_tasks_count,
                        ];
                    }

                    $response = [
                        'status' => 200,
                        'message' => 'Success',
                        'data' => $data,
                    ];
                    getresponse($this, $response);
                } else {
                    $response = [
                        'status' => 200,
                        'message' => 'No History Found.',
                        'data' => null,
                    ];
                    getresponse($this, $response);
                }
            }
        }
    }

    // get case details by id
    public function getcasehistory_by_id_post()
    {
        $getemail = $this->authmiddleware->verifyToken();
        if (empty($getemail)) {
        } else {
            if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
                $response = array(
                    'status' => 400,
                    'message' => 'Invalid request method.',
                    'data' => null,
                );
                getresponse($this, $response);
            } else {
                $data = '';
                $query_data = $this->Contacts_model->getEmail($getemail);
                $get_role = array_column($query_data, 'role');
                $role_string = implode(',', $get_role);
                $brokername = '';
                $case_id = $this->post('case_id');
                $this->db->select('id,name,title,company,description,country,zip,city,state,address,assigned,assign_group,dateadded,status,multiple_cases,active_case,source,lastcontact,addedfrom,email,leadorder,phonenumber,client_id,martial_status,transaction,app_email_requested,funds_requested_mail');
                $this->db->where('id', $case_id);
                $query = $this->db->get(db_prefix() . 'leads');

                if ($query->num_rows() > 0) {
                    $case_result = $query->row();
                    // get the leads/case status
                    if (empty($active_case_record->app_email_requested) && $case_result->status == 7) {
                        $case_stage_status = 'Appointment Pending';
                    } else {
                        $case_stage_status = get_status_name_by_using_status_id($this, $case_result->status);
                    }
                    // get task details data 
                    $this->db->select('id, name, description, dateadded, status, rel_id,lead_borrow_id, type');
                    $this->db->from(db_prefix() . 'tasks');
                    $this->db->where('rel_id', $case_result->id);
                    $this->db->where('rel_type', 'user-task');
                    if ($role_string == 'client') {
                        $this->db->where('type', 'client');
                    }
                    // else{
                    //     $this->db->where('type', 'client');
                    // }
                    $query = $this->db->get();

                    $user_task_records = $query->result();
                    $get_staff_group = $case_result->assign_group;
                    // get broker name
                    $this->db->select('staffid,email,firstname,lastname,staff_group,phonenumber,password,datecreated,profile_image,admin,role,active,is_password_changed');
                    $this->db->where('staffid', $case_result->addedfrom);
                    $staff_record = $this->db->get(db_prefix() . 'staff');

                    if ($staff_record->num_rows() > 0) {
                        $staff_data = $staff_record->row();
                        $staff_name = $staff_data->firstname . ' ' . $staff_data->lastname;
                    }
                    // get staff id
                    $this->db->select('*');
                    $this->db->where('group_name', $get_staff_group);
                    $query = $this->db->get(db_prefix() . 'group');
                    if ($query->num_rows() > 0) {
                        $result = $query->row();
                        $group_id = $result->id;
                        $group_name = $result->group_name;
                        $group_details = array(
                            'id' => $group_id,
                            'name' => $group_name,
                            'members' => array()
                        );

                        // get all staff details
                        $this->db->select('staffid,email,firstname,lastname,staff_group,phonenumber,password,datecreated,profile_image,admin,role,active,is_password_changed');
                        $this->db->where('staff_group', $group_name);
                        $staff_query = $this->db->get(db_prefix() . 'staff');
                        if ($staff_query->num_rows() > 0) {
                            $staff_data_Array = array();
                            foreach ($staff_query->result() as $staff_data_fetch) {
                                $staff_data_Array[] = array(
                                    'id' => $staff_data_fetch->staffid,
                                    'name' => $staff_data_fetch->firstname . ' ' . $staff_data_fetch->lastname,
                                    'profile_url' => isset($staff_data_fetch->profile_image) ? base_url('uploads/staff_profile_images/' . $staff_data_fetch->staffid . '/thumb_' . $staff_data_fetch->profile_image) : null,
                                );
                            }
                            $group_details['members'] = $staff_data_Array;
                        }
                    }
                    // Get total tasks count
                    $this->db->select('COUNT(id) as total_tasks');
                    $this->db->where('rel_id', $case_result->id);
                    $this->db->where('rel_type', 'user-task');
                    $this->db->where('type', 'client');
                    $total_tasks_query = $this->db->get(db_prefix() . 'tasks');
                    $total_tasks_result = $total_tasks_query->row();
                    $total_tasks_count = $total_tasks_result->total_tasks;

                    // Get completed tasks count
                    $this->db->select('COUNT(id) as completed_tasks');
                    $this->db->where('rel_id', $case_result->id);
                    $this->db->where('rel_type', 'user-task');
                    $this->db->where('status', '4');
                    $this->db->where('type', 'client');
                    $completed_tasks_query = $this->db->get(db_prefix() . 'tasks');
                    $completed_tasks_result = $completed_tasks_query->row();
                    $completed_tasks_count = $completed_tasks_result->completed_tasks;
                    // get the transaction details
                    $leads_transacation_data = leads_bank_details($this, $case_result->id);
                    $transaction_name = '';
                    if (!empty($leads_transacation_data)) {
                        $transaction_name = get_transaction_name_by_id($this, $leads_transacation_data[0]['transaction_id']);
                    }
                    $funds_requested_mail = false;
                    if (!empty($case_result->funds_requested_mail) && $case_result->funds_requested_mail == 1) {
                        $funds_requested_mail = true;
                    }
                    $data = [
                        'case_id' => $case_result->id,
                        'name' => $case_result->name,
                        'address' => $case_result->address,
                        'started_at' => strtotime($case_result->dateadded),
                        'status' => $case_stage_status,
                        'case_active' => $case_result->active_case,
                        'martial_status' => $case_result->martial_status,
                        // 'transaction' => $case_result->transaction,
                        'transaction' => $transaction_name,
                        'broker_name' => $staff_name,
                        'total_task' => $total_tasks_count,
                        'completed_task' => $completed_tasks_count,
                        'outstanding_stage_message' => 'Lender/Lawyer conditions being fulfilled by Legal Direct.',
                        'funds_requested_mail' => $funds_requested_mail,
                        'group' => $group_details,
                        'check_list' => [],
                    ];
                    foreach ($user_task_records as $record_task) {
                        $status = return_item_status_for_app_side($record_task->status);
                        $checklist_instruction = $this->file_instruction_model->get_instruction_by_taskid($record_task->id);

                        if ($record_task->type == 'client' || $record_task->type == 'Client') {
                            $client_checklist_name = get_checklist_client_name($this, $record_task->rel_id, $record_task->lead_borrow_id);
                        } else {
                            $client_checklist_name = 'Broker';
                        }
                        $checklist[] = [
                            'id' => $record_task->id,
                            'title' => $record_task->name,
                            'client_checklist_name' => $client_checklist_name,
                            'description' => $record_task->description,
                            'status' => $status,
                            'instructions' => is_array($checklist_instruction) && array_key_exists('instruction', $checklist_instruction) ? explode(',', $checklist_instruction['instruction']) : [],
                            'doc_types' => is_array($checklist_instruction) && array_key_exists('doc_type', $checklist_instruction) ? explode(',', $checklist_instruction['doc_type']) : [],
                            'type' => $record_task->type
                        ];
                    }
                    if ($case_result->status == 1) {
                        $data['check_list'] = $checklist;
                    } elseif ($case_result->status == 3) {
                        $additional_checklist = get_ld_checklist_by_lead_id($this, $case_result->id, $case_result->status);
                        $data['check_list'] = array_merge($checklist, $additional_checklist);
                    }

                    $response = [
                        'status' => 200,
                        'message' => 'Success',
                        'data' => $data,
                    ];
                    getresponse($this, $response);
                } else {
                    $response = array(
                        'status' => 200,
                        'message' => 'Record not found.',
                        'data' => null,
                    );
                    getresponse($this, $response);
                }

            }
        }
    }
    // get cases by id user cases
    public function getchecklist_post()
    {
        $getemail = $this->authmiddleware->verifyToken();
        if (empty($getemail)) {
        } else {
            $task_id = $this->input->post('task_id');
            $type = $this->input->post('type');
            if (empty($type)) {
                $response = array(
                    'status' => 400,
                    'message' => 'Credentails type missing.',
                    'data' => null,
                );
                getresponse($this, $response);
                exit;
            }
            if (!$task_id) {
                $response = array(
                    'status' => 400,
                    'message' => 'Checklist is not exist in out record.',
                    'data' => null,
                );
                getresponse($this, $response);
            } else {
                // Check if it's a POST request
                if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
                    $response = array(
                        'status' => 400,
                        'message' => 'Invalid request method.',
                        'data' => null,
                    );
                    getresponse($this, $response);
                } else {
                    if ($type == 'ld_team') {
                        $this->db->select('id, title, description, leads_status, payout_expire_date, created_at');
                        $this->db->from(db_prefix() . 'cases_checkboxes');
                        $this->db->where('id', $task_id);
                        $query = $this->db->get();
                    } else {
                        $this->db->select('id, name, description,Item_name, dateadded, status, rel_id, lead_borrow_id');
                        $this->db->from(db_prefix() . 'tasks');
                        $this->db->where('id', $task_id);
                        $this->db->where('rel_type', 'user-task');
                        $query = $this->db->get();
                    }

                    if ($query->num_rows() > 0) {
                        $user_task_records = $query->result();
                        if ($type == 'ld_team') {
                            foreach ($user_task_records as $record_task) {
                                if (!empty($record_task->title)) {
                                    $status = '';
                                    // Retrieve checklist instruction (uncomment if function is defined)
                                    // $checklist_instruction = $ci->file_instruction_model->get_instruction_by_taskid($record_task->id);
                                    $checklist_instruction = []; // Placeholder for checklist instruction
                                    if ($record_task->lead_status == 3) {
                                        $client_checklist_name = ($record_task->leads_status == 7) ? 'secure_payout' : 'other';
                                    } else {
                                        $client_checklist_name = 'LD-Team';
                                    }
                                    $checklist = [
                                        'id' => $record_task->id,
                                        'title' => $record_task->title,
                                        'client_checklist_name' => $client_checklist_name,
                                        'description' => $record_task->description,
                                        'payout_expire_date' => $record_task->payout_expire_date,
                                        'status' => $status,
                                        'instructions' => null,
                                        'doc_types' => null,
                                        'type' => 'ld_team'
                                    ];
                                }
                            }
                            // get files of checklist by tesk_id
                            $this->db->select('id,filetype,file_url');
                            $this->db->from(db_prefix() . 'cases_checkbox_files');
                            $this->db->where('cases_checkbox_id', $task_id);
                            $query = $this->db->get();
                            $get_item_type_id = '';
                            if ($query->num_rows() > 0) {
                                $all_checklist_files = $query->result();
                                foreach ($all_checklist_files as $files_data) {
                                    $filetype_check = explode('/', $files_data->filetype)[1];
                                    if ($filetype_check == 'jpeg' || $filetype_check == 'jpg' || $filetype_check == 'png' || $filetype_check == 'avif') {
                                        $filetype = 'image';
                                    } else if ($filetype_check == 'pdf') {
                                        $filetype = 'pdf';
                                    } else {
                                        $filetype = 'other';
                                    }
                                    $files_details[] = [
                                        'id' => (int) $files_data->id,
                                        'file_type' => $filetype,
                                        'file_url' => $files_data->file_url,
                                    ];
                                }
                            }
                            $data = $checklist;
                            $data['files_list'] = $files_details;
                            $data['activities'] = null;
                        } else {
                            foreach ($user_task_records as $record_task) {
                                $get_item_name_id = $record_task->Item_name;
                                $item_name_array = explode(',', $get_item_name_id);
                                $item_name_array = array_map('intval', $item_name_array);
                                // get the item type name
                                $this->db->select('id,Item_name AS item_name');
                                $this->db->where_in('id', $item_name_array);
                                $query = $this->db->get(db_prefix() . 'checklist_item_type');
                                $results = $query->result_array();
                                $status = return_item_status_for_app_side($record_task->status);
                                $checklist_instruction = $this->file_instruction_model->get_instruction_by_taskid($record_task->id);
                                $instructions = is_array($checklist_instruction) && array_key_exists('instruction', $checklist_instruction)
                                    ? explode("\n\r", $checklist_instruction['instruction'])
                                    : [];

                                $resultArray = [];

                                foreach ($instructions as $instruction) {
                                    // $items = array_map('trim', explode(',', $instruction));
                                    $instruction = str_replace("\n", '', $instruction);
                                    $items = explode(',', $instruction);
                                    if (!empty(implode(',', $items))) {
                                        $resultArray[] = implode(',', $items);
                                    }
                                }
                                if ($record_task->type == 'client' || $record_task->type == 'Client') {
                                    $client_checklist_name = get_checklist_client_name($this, $record_task->rel_id, $record_task->lead_borrow_id);
                                } else {
                                    $client_checklist_name = 'Broker';
                                }
                                $checklist = [
                                    'id' => $record_task->id,
                                    'title' => $record_task->name,
                                    'client_checklist_name' => $client_checklist_name,
                                    'description' => $record_task->description,
                                    'payout_expire_date' => null,
                                    'status' => $status,
                                    'instructions' => $resultArray,
                                    'item_type' => $results,
                                    'type' => 'client',
                                    'doc_types' => is_array($checklist_instruction) && array_key_exists('doc_type', $checklist_instruction)
                                        ? explode(',', $checklist_instruction['doc_type'])
                                        : [],
                                ];

                            }

                            // get files of checklist by tesk_id
                            $this->db->select('id,filetype,file_url,item_type_id');
                            $this->db->from(db_prefix() . 'files');
                            $this->db->where('task_id', $task_id);
                            $this->db->where('rel_type', 'client-doc');
                            $query = $this->db->get();
                            $get_item_type_id = '';
                            if ($query->num_rows() > 0) {
                                $all_checklist_files = $query->result();
                                foreach ($all_checklist_files as $files_data) {
                                    $filetype_check = explode('/', $files_data->filetype)[1];
                                    if ($filetype_check == 'jpeg' || $filetype_check == 'jpg' || $filetype_check == 'png' || $filetype_check == 'avif') {
                                        $filetype = 'image';
                                    } else if ($filetype_check == 'pdf') {
                                        $filetype = 'pdf';
                                    } else {
                                        $filetype = 'other';
                                    }
                                    $files_details[] = [
                                        'id' => (int) $files_data->id,
                                        'file_type' => $filetype,
                                        'file_url' => $files_data->file_url,
                                    ];
                                }
                            }
                            // get the checklist item_type name
                            $this->db->select('item_type_id');
                            $this->db->from(db_prefix() . 'files');
                            $this->db->where('task_id', $task_id);
                            $this->db->where('rel_type', 'client-doc');
                            $this->db->order_by('id', 'desc');
                            $this->db->limit(1);
                            $query = $this->db->get();

                            if ($query->num_rows() > 0) {
                                $first_file_data = $query->row();
                                $get_item_type_id = $first_file_data->item_type_id;
                            }
                            if (!empty($get_item_type_id)) {
                                $this->db->select('Item_name');
                                $this->db->where_in('id', $get_item_type_id);
                                $query = $this->db->get(db_prefix() . 'checklist_item_type');
                                $results = $query->result_array();
                                $comma_separated_names = implode(', ', array_column($results, 'Item_name'));
                            } else {
                                $comma_separated_names = null;
                            }
                            // get activity log by task_id
                            $this->db->select('additional_data,description,date,full_name,reason');
                            $this->db->from(db_prefix() . 'lead_activity_log');
                            $this->db->where('task_id', $task_id);
                            $this->db->where('activity_type', 'task-activity');
                            $this->db->order_by('date', 'DESC');
                            $query = $this->db->get();
                            if ($query->num_rows() > 0) {
                                $activity_list = $query->result();
                                foreach ($activity_list as $activity_data) {
                                    $message = $activity_data->additional_data == 'Rejected'
                                        ? $activity_data->reason . " - Rejected by " . $activity_data->full_name . "."
                                        : $activity_data->description;
                                    $activity_details[] = [
                                        'name' => $activity_data->full_name,
                                        'status' => $activity_data->additional_data,
                                        'description' => $message,
                                        'created_at' => strtotime($activity_data->date),
                                    ];
                                }
                            }
                            $data = $checklist;
                            if (!empty($comma_separated_names)) {
                                $data['item_type_title'] = $comma_separated_names;
                            } else {
                                $data['item_type_title'] = null;
                            }
                            $data['files_list'] = $files_details;
                            $data['activities'] = $activity_details;
                        }
                        $response = [
                            'status' => 200,
                            'message' => 'Success',
                            'data' => $data,
                        ];
                        getresponse($this, $response);
                    } else {
                        $response = array(
                            'status' => 400,
                            'message' => 'No record found.',
                            'data' => null,
                        );
                        getresponse($this, $response);
                    }

                }
            }
        }
    }

    public function getcomments_post()
    {
        $getemail = $this->authmiddleware->verifyToken();
        if (empty($getemail)) {
        } else {
            if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
                $response = array(
                    'status' => 400,
                    'message' => 'Invalid request method.',
                    'data' => array()
                );
                getresponse($this, $response);
            } else {
                $data = $this->Contacts_model->getEmail($getemail);
                $case_id = $this->post('case_id');
                $comment_type = $this->post('type');
                $lead_id = $case_id;
                $profil_url = '';
                $contacts_data = '';
                $get_role = array_column($data, 'role');
                $role_string = implode(',', $get_role);
                if ($role_string == 'client') {
                    $username = '';
                    $userid = '';
                    $profil_url = '';
                    $profile_check = '';
                    $this->db->select('id');
                    $this->db->where('email', $getemail);
                    $this->db->where('is_primary', '1');
                    $query = $this->db->get(db_prefix() . 'contacts');
                    $userdata = $query->row();
                    $user_id = $userdata->id;
                    $leadData = $this->Leads_model->get_lead_id($user_id);
                    $lead_id_parent = $leadData->id;
                    $comments = $this->Comment_model->getCommentsWithUserInfo($user_id, $lead_id);
                    foreach ($comments as &$comment) {
                        if ($comment->role == 'staff') {
                            $this->db->select('*');
                            $this->db->where('staffid', $comment->from_user_id);
                            $query = $this->db->get(db_prefix() . 'staff');
                            $staff_data = $query->row();
                            $username = $staff_data->firstname . ' ' . $staff_data->lastname;
                            $userid = $comment->from_user_id;
                            $profile_check = $staff_data->profile_image;
                            if (!empty($profile_check)) {
                                $profil_url = base_url('uploads/staff_profile_images/' . $staff_data->staffid . '/thumb_' . $staff_data->profile_image);
                            } else {
                                $profil_url = null;
                            }
                        } else {
                            $username = $comment->firstname . ' ' . $comment->lastname;
                            $userid = $comment->id;
                            $this->db->select('file_url');
                            $this->db->where('rel_id', $lead_id_parent);
                            $this->db->where('rel_type', 'profile-doc');
                            $query = $this->db->get(db_prefix() . 'files');
                            $file_data = $query->row();
                            $profil_url = $file_data->file_url;
                        }
                        $comment->created_at = strtotime($comment->created_at);
                        $comment_Data[] = array(
                            'user_id' => $userid,
                            'user_name' => $username,
                            'comment' => $comment->comment_text,
                            'profile_url' => $profil_url,
                            'created_at' => $comment->created_at
                        );
                    }
                } else {
                    // get staff id 
                    $get_staffid = array_column($data, 'staffid');
                    $get_firstname = array_column($data, 'firstname');
                    $get_lastname = array_column($data, 'lastname');
                    $staffid_string = implode(',', $get_staffid);
                    $firstname_string = implode(',', $get_firstname);
                    $lastname_string = implode(',', $get_lastname);
                    $staff_name = $firstname_string . ' ' . $lastname_string;
                    // check if comment enter from client or broker
                    if ($comment_type == 'client') {
                        $type = 'client-to-ld';
                    } elseif ($comment_type == 'ld_team') {
                        $type = 'admin-to-ld';
                    } elseif ($comment_type == 'broker') {
                        $type = 'broker-to-ld';
                    }
                    $this->db->select('*');
                    $this->db->where('lead_id', $lead_id);
                    $this->db->where('type', $type);
                    $this->db->order_by('created_at', 'DESC');
                    $query = $this->db->get(db_prefix() . 'comments');

                    if ($query->num_rows() > 0) {
                        $result = $query->result_array();
                        $comment_array_data = array();
                        foreach ($result as $comment_values) {
                            if ($comment_values['role'] == 'client') {
                                $this->db->select('id,userid,is_primary,firstname,lastname,email,additional_email,phonenumber,datecreated,password,active,role,is_password_changed');
                                $this->db->where('id', $comment_values['from_user_id']);
                                $query_contacts = $this->db->get(db_prefix() . 'contacts');
                                $contacts_data = $query_contacts->row();
                            }
                            // get staff name 
                            $this->db->select('firstname,lastname');
                            $this->db->where('staffid', $comment_values['from_user_id']);
                            $staff_query = $this->db->get(db_prefix() . 'staff');
                            $staff_data = $staff_query->row();
                            $staff_name = $staff_data->firstname . ' ' . $staff_data->lastname;
                            $user_name = ($comment_values['role'] == 'staff' || $comment_values['role'] == 'ld-broker-staff') ? $staff_name : $contacts_data->firstname . ' ' . $contacts_data->lastname;
                            // $user_id_comment = ($comment_values['role'] == 'staff') ? $staffid_string : $contacts_data->id;
                            $user_id_comment = ($comment_values['role'] == 'staff' || $comment_values['role'] == 'ld-broker-staff') ? $comment_values['from_user_id'] : $contacts_data->id;
                            $parent_lead_id = get_lead_parent_id($this, $lead_id);
                            // get the profile url for staff and clients
                            if ($comment_values['role'] == 'staff' || $comment_values['role'] == 'ld-broker-staff') {
                                $this->db->select('staffid,email,firstname,lastname,staff_group,phonenumber,password,datecreated,profile_image,admin,role,active,is_password_changed');
                                $this->db->where('staffid', $comment_values['from_user_id']);
                                $query = $this->db->get(db_prefix() . 'staff');
                                $staff_data = $query->row();
                                $profile_check = $staff_data->profile_image;
                                if (!empty($profile_check)) {
                                    $profil_url = base_url('uploads/staff_profile_images/' . $staff_data->staffid . '/thumb_' . $staff_data->profile_image);
                                } else {
                                    $profil_url = null;
                                }
                            } else {
                                $this->db->select('file_url');
                                $this->db->where('rel_id', $parent_lead_id);
                                $this->db->where('rel_type', 'profile-doc');
                                $query = $this->db->get(db_prefix() . 'files');
                                $file_data = $query->row();
                                $profil_url = $file_data->file_url;
                            }
                            $key = ($comment_values['role'] == 'staff' || $comment_values['role'] == 'ld-broker-staff') ? 'staff_id' : 'user_id';
                            $comment_Data[] = array(
                                // $comment_values['role'] == 'staff' ? 'staff_id' : 'user_id' => $user_id_comment,
                                $key => $user_id_comment,
                                'user_name' => $user_name,
                                'comment' => $comment_values['comment_text'],
                                'created_at' => strtotime($comment_values['created_at']),
                                'profile_url' => $profil_url
                            );

                        }
                    }
                }
                if ($comment_Data) {
                    $response = array(
                        'status' => 200,
                        'message' => 'Comments retrieved successfully.',
                        'data' => $comment_Data,
                    );
                    getresponse($this, $response);
                } else {
                    $response = array(
                        'status' => 200,
                        'message' => 'No comments found.',
                        'data' => null,
                    );
                    getresponse($this, $response);
                }
            }
        }
    }
    public function savecomment_post()
    {
        $getemail = $this->authmiddleware->verifyToken();
        if (empty($getemail)) {
        } else {
            if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
                $response = array(
                    'status' => 400,
                    'message' => 'Invalid request method.',
                    'data' => null,
                );
                getresponse($this, $response);
            } else {
                // get id from contact model

                $lead_id = $this->post('case_id');
                $comment_text = $this->post('comment_text');
                $comment_type = $this->post('type');
                $username = '';
                if (empty($lead_id) || empty($comment_text)) {
                    $response = array(
                        'status' => 400,
                        'message' => 'Credentials are missing.',
                        'data' => null,
                    );
                    getresponse($this, $response);
                } else {
                    // get the groupd id
                    $this->db->select('assign_group,name');
                    $this->db->where('id', $lead_id);
                    $result = $this->db->get(db_prefix() . 'leads');

                    if ($result->num_rows() > 0) {
                        $row = $result->row();
                        $groupname = $row->assign_group;
                        $user_name = $row->name;
                    }
                    /*
                    $group_id = get_group_id_by_using_group_name($this, $groupname);
                    $this->db->select('group_name');
                    $this->db->where('id', $group_id);
                    $query = $this->db->get(db_prefix() . 'group');
                    if ($query->num_rows() > 0) {
                        $result = $query->row();
                        $group_name = $result->group_name;
                    } else {
                        $group_name = null;
                    }
                    $case_group_name = $group_name;
                    */
                    $case_group_name = $groupname;
                    $query_token = $this->Contacts_model->getEmail($getemail);
                    $get_role = array_column($query_token, 'role');
                    $role_string = implode(',', $get_role);
                    if ($role_string == 'client') {
                        $this->db->select('id,firstname,middlename,lastname');
                        $this->db->where('email', $getemail);
                        $this->db->where('is_primary', '1');
                        $query = $this->db->get(db_prefix() . 'contacts');
                        $userdata = $query->row();
                        $user_id = $userdata->id;
                        // $user_id = $userdata->userid;
                        $contact_user_name = $userdata->firstname . ' ' . $userdata->middlename . ' ' . $userdata->lastname;

                        // get lead id using lead helper
                        $leadData = $this->Leads_model->get_lead_id($user_id);
                        $lead_id_for_parent_case = $leadData->id;
                        $username = $leadData->name;
                        // get staff id by group name
                        $this->db->select('staffid');
                        $this->db->from(db_prefix() . 'staff');
                        $this->db->group_start();
                        $this->db->where('staff_group', $case_group_name);
                        $this->db->or_where('role', 4);
                        $this->db->group_end();
                        $staff_query = $this->db->get();
                        $staffIds = array();

                        if ($staff_query->num_rows() > 0) {
                            $staff_id_array = $staff_query->result_array();
                            // Extract staff IDs into an array
                            $staffIds = array_column($staff_id_array, 'staffid');
                        }

                        $data = array(
                            'from_user_id' => $user_id,
                            'to_user_id' => implode(',', $staffIds),
                            'comment_text' => $comment_text,
                            'role' => 'client',
                            'type' => 'client-to-ld',
                            'lead_id' => $lead_id,
                            'created_at' => date('Y-m-d H:i:s'),
                        );

                        $save_comment_id = $this->Comment_model->add_comment($data);

                        // get staff id by group name
                        if (!empty($save_comment_id) && !empty($staffIds)) {
                            foreach ($staffIds as $staffId) {
                                $read_comment_table_data = array(
                                    'comment_id' => $save_comment_id,
                                    'to_user_id' => $staffId,
                                    'from_user_id' => $user_id,
                                    'lead_id' => $lead_id,
                                    'type' => 'client-to-ld',
                                );
                                $this->Comment_model->add_read_comment($read_comment_table_data);

                            }
                        }
                        // send notification
                        $staff_data = get_staff_ids_by_group($this, $groupname);
                        foreach ($staff_data as $get_staff_records) {
                            // notification push code 
                            if (!empty($get_staff_records['staffid'])) {
                                $this->db->select('multiple_cases,client_id');
                                $this->db->where('id', $lead_id);
                                $lead_data_check = $this->db->get(db_prefix() . 'leads');
                                if ($lead_data_check->num_rows() > 0) {
                                    $lead_data = $lead_data_check->row();
                                    if ($lead_data->client_id == 0) {
                                        // get the parnet id of lead
                                        $partent_lead_id = $lead_data->multiple_cases;
                                        $this->db->select('id,multiple_cases,client_id');
                                        $this->db->where('id', $partent_lead_id);
                                        $lead_parent_data_check = $this->db->get(db_prefix() . 'leads')->row();
                                        $client_id = $lead_parent_data_check->client_id;
                                    } else {
                                        $client_id = $lead_data->client_id;
                                    }
                                    $contact_id = get_contact_id_using_client_id($this, $client_id);
                                    $notification_type = get_notification_type(3);
                                    // $values = array(
                                    //     'staff_id' => $get_staff_records['staffid'],
                                    //     'contact_id' => $contact_id,
                                    //     'client_id' => $client_id,
                                    //     'lead_id' => $lead_id,
                                    //     'send_to' => 'staff',
                                    //     'title' => 'New Message Notification',
                                    //     'message' => 'New message from ' . $user_name . '.',
                                    //     'type' => $notification_type,
                                    // );

                                    // add_alerts_user($values);

                                }
                            }
                        }
                        // send email to team and admin when client send message
                        $replay_to_mail = get_all_staff_to_replay_email($this, get_staff_user_id(), $row->assign_group);
                        $_POST['lead_id'] = $lead_id;
                        $subject = get_mail_subject_for_case_stages($this, $lead_id, 1);
                        $_POST['case_url'] = admin_url('cases/index/') . $lead_id;
                        $_POST['generic_email_title'] = '';
                        $_POST['generic_email_content'] = 'Good ' . get_afternoon_and_morning() . '<br> Please note the client has sent a message on this file #' . $lead_id;
                        $_POST['generic_email_back_to_case_url'] = 'Please <a href="' . htmlspecialchars($_POST['case_url'], ENT_QUOTES, 'UTF-8') . '">Click here</a> to access the file.';
                        $html_content_confirmation_email_to_broker = $this->load->view('admin/leads/Email_template/generic_email_template', $_POST, TRUE);

                        // send  notiication in crm to all the team group member and staff
                        $this->db->select('assign_group,assigned');
                        $this->db->where('id', $lead_id);
                        $lead_data_for_get_assign_group = $this->db->get(db_prefix() . 'leads')->row();
                        $current_staff_data = get_staff_ids_by_group($this, $lead_data_for_get_assign_group->assign_group);
                        foreach ($current_staff_data as $staff_notifiy_data) {
                            if ($staff_notifiy_data['staffid']) {
                                $read_comment_data = array(
                                    'comment_id' => $save_comment_id,
                                    'to_user_id' => $staff_notifiy_data['staffid'],
                                    'from_user_id' => $contact_id,
                                    'lead_id' => $lead_id,
                                    'is_read' => '0',
                                );
                                $insert_read_comments = $this->db->insert(db_prefix() . 'read_comments', $read_comment_data);
                                // send notification in the mobile side to staff
                                $values = array(
                                    'staff_id' => $staff_notifiy_data['staffid'],
                                    'contact_id' => $contact_id,
                                    'client_id' => $client_id,
                                    'lead_id' => $lead_id,
                                    'send_to' => 'staff',
                                    'title' => 'New Message Notification',
                                    // 'message' => '' . $stage_name . ' Stage has been completed.',
                                    'message' => $contact_user_name . ' Send a message to ' . $staff_notifiy_data['firstname'] . $staff_notifiy_data['lastname'] . '.',
                                    'type' => $notification_type,
                                    'comment_type' => 'client',
                                );
                                add_alerts_user($values);
                                // send slack notification
                                $slack_message = $contact_user_name . ' Send a message to ' . $staff_notifiy_data['firstname'] . $staff_notifiy_data['lastname'] . '.';

                                // send email to the team
                                send_mailchimp_email($staff_notifiy_data['email'], $subject, $html_content_confirmation_email_to_broker, $replay_to_mail, '', '');

                                // send notification in the crm
                                $this->Leads_model->custom_lead_assigned_member_notification('staff', $lead_id, $staff_notifiy_data['staffid'], $user_id, '', $contact_user_name . 'Send a message to ' . $staff_notifiy_data['firstname'] . $staff_notifiy_data['lastname'] . '.');
                            }
                        }
                        // get the all admin staff ids
                        $admin_ids = get_all_admin_role_staff_ids($this);
                        foreach ($admin_ids as $admin_email) {
                            if ($admin_email['staffid']) {
                                $staff_name_message = get_staff_name_by_id($this, $admin_email['staffid']);
                                // send notification in the mobile side to staff
                                $read_comment_data = array(
                                    'comment_id' => $save_comment_id,
                                    'to_user_id' => $admin_email['staffid'],
                                    'from_user_id' => $contact_id,
                                    'lead_id' => $lead_id,
                                    'is_read' => '0',
                                );
                                $insert_read_comments = $this->db->insert(db_prefix() . 'read_comments', $read_comment_data);
                                $values = array(
                                    'staff_id' => $admin_email['staffid'],
                                    'contact_id' => $contact_id,
                                    'client_id' => $client_id,
                                    'lead_id' => $lead_id,
                                    'send_to' => 'staff',
                                    'title' => 'New Message Notification',
                                    // 'message' => '' . $stage_name . ' Stage has been completed.',
                                    'message' => $contact_user_name . ' Send a message to  ' . $staff_name_message . '.',
                                    'type' => $notification_type,
                                    'comment_type' => 'client',
                                );
                                add_alerts_user($values);
                                // send slack notification
                                $slack_message = $contact_user_name . ' Send a message to  ' . $staff_name_message . '.';
                                // send email to the team
                                send_mailchimp_email($admin_email['email'], $subject, $html_content_confirmation_email_to_broker, $replay_to_mail, '', '');

                                // send notification in the crm
                                $this->Leads_model->custom_lead_assigned_member_notification('staff', $lead_id, $admin_email['staffid'], $user_id, '', $contact_user_name . 'Send a message to  ' . $staff_name_message . '.');
                            }
                        }
                        // send slack notification in ld-channel
                        // $this->slack->sendnotification($slack_message, $lead_id);
                        // get profile image of user
                        $this->db->select('file_url');
                        $this->db->where('rel_id', $lead_id_for_parent_case);
                        $this->db->where('rel_type', 'profile-doc');
                        $query = $this->db->get(db_prefix() . 'files');
                        $file_data = $query->row();
                        // get username of user
                        $this->db->select('name,assign_group');
                        $this->db->where('id', $lead_id);
                        $query = $this->db->get(db_prefix() . 'leads');
                        $userdata = $query->row();
                        $data['name'] = $userdata->name;
                        $data['file_url'] = $file_data->file_url;
                        $data['created_at'] = strtotime($data['created_at']);
                        $response_data = array(
                            'user_id' => $data['from_user_id'],
                            'user_name' => $data['name'],
                            'comment' => $data['comment_text'],
                            'profile_url' => $data['file_url'],
                            'created_at' => $data['created_at']
                        );
                        // add the activity of comments
                        $lead_activity_data = array(
                            'leadid' => $lead_id,
                            'description' => $contact_user_name . ' send a message to the group ( ' . $userdata->assign_group . ' ).',
                            'date' => date('Y-m-d H:i:s'),
                            'full_name' => $contact_user_name
                        );
                        $this->db->insert(db_prefix() . 'lead_activity_log', $lead_activity_data);
                        // Send Slack notification
                        $slack_message = "\n - " . $contact_user_name . " send a message to the group ( " . $userdata->assign_group . " ).";
                        $lead_name = get_lead_name_using_lead_id($this, $lead_id);
                        $lead_split_name = leads_splitFullName($lead_name);
                        $case_split_name = $lead_split_name['lastname'] . ', ' . $lead_split_name['firstname'];
                        $send_notification = $this->slack->sendnotification($slack_message, $lead_id, $userdata->assign_group, $case_split_name, $case_split_name, true);
                    } else {
                        // get the staff id
                        $get_staffid = array_column($query_token, 'staffid');
                        $staffid_string = implode(',', $get_staffid);
                        // get the staff first and last name
                        $get_firstname = array_column($query_token, 'firstname');
                        $get_lastname = array_column($query_token, 'lastname');
                        $firstname_string = implode(',', $get_firstname);
                        $lastname_string = implode(',', $get_lastname);
                        $staff_name = $firstname_string . ' ' . $lastname_string;
                        // Staff comment insert
                        // Get the contact id using lead id with multiple cases handled
                        if ($comment_type == 'client') {
                            $this->db->select('*');
                            $this->db->where('id', $lead_id);
                            $this->db->where('multiple_cases', '0');
                            $lead_query_data = $this->db->get(db_prefix() . 'leads');

                            if ($lead_query_data->num_rows() > 0) {
                                // Get the contact primary id
                                $lead_data = $lead_query_data->row();
                                $client_id = $lead_data->client_id;
                                $username = $lead_data->name;
                                $this->db->select('id,firstname,middlename,lastname');
                                $this->db->where('userid', $client_id);
                                $contact_query_data = $this->db->get(db_prefix() . 'contacts');
                                if ($contact_query_data->num_rows() > 0) {
                                    $contact_data = $contact_query_data->row();
                                    $to_user_id = $contact_data->id;
                                    $to_user_name = $contact_data->firstname . ' ' . $contact_data->middlename . ' ' . $contact_data->lastname;
                                }
                            } else {
                                $this->db->select('*');
                                $this->db->where('id', $lead_id);
                                $lead_query_data = $this->db->get(db_prefix() . 'leads');
                                $lead_data = $lead_query_data->row();
                                $multiple_case_lead_id = $lead_data->multiple_cases;
                                $username = $lead_data->name;
                                // get client id of the parnet lead case 
                                $this->db->select('client_id');
                                $this->db->where('id', $multiple_case_lead_id);
                                $lead_query_data = $this->db->get(db_prefix() . 'leads');
                                $lead_data_parent_case = $lead_query_data->row();
                                $client_id = $lead_data_parent_case->client_id;
                                // Get the contact primary id
                                $this->db->select('*');
                                $this->db->where('userid', $client_id);
                                $contact_query_data = $this->db->get(db_prefix() . 'contacts');
                                $contact_data = $contact_query_data->row();
                                $to_user_id = $contact_data->id;
                                $to_user_name = $contact_data->firstname . ' ' . $contact_data->middlename . ' ' . $contact_data->lastname;
                            }
                        }
                        // Insert record in comments table
                        // check if comment enter from client or broker
                        if ($comment_type == 'client') {
                            $type = 'client-to-ld';
                        } elseif ($comment_type == 'ld_team') {
                            $type = 'admin-to-ld';
                        } elseif ($comment_type == 'broker') {
                            $type = 'broker-to-ld';
                        }
                        $comments_data = array(
                            'to_user_id' => $to_user_id,
                            'from_user_id' => $staffid_string,
                            'lead_id' => $lead_id,
                            'comment_text' => $comment_text,
                            'role' => 'staff',
                            'type' => $type,
                            'created_at' => date('Y-m-d H:i:s'),
                        );
                        $this->db->insert(db_prefix() . 'comments', $comments_data);
                        // // Get the ID of the inserted comment
                        $comment_id = $this->db->insert_id();
                        // get staff profile url
                        $this->db->select('staffid,email,firstname,lastname,staff_group,phonenumber,password,datecreated,profile_image,admin,role,active,is_password_changed');
                        $this->db->where('staffid', $staffid_string);
                        $query = $this->db->get(db_prefix() . 'staff');
                        $staff_data = $query->row();
                        $profile_check = $staff_data->profile_image;
                        if (!empty($profile_check)) {
                            $profile_url = base_url('uploads/staff_profile_images/' . $staff_data->staffid . '/thumb_' . $staff_data->profile_image);
                        } else {
                            $profile_url = null;
                        }
                        // Insert record in read_comment for user 
                        $read_comment_data = array(
                            'comment_id' => $comment_id,
                            'to_user_id' => $to_user_id,
                            'from_user_id' => $staffid_string,
                            'lead_id' => $lead_id,
                            'is_read' => '0',
                        );
                        $insert_read_comments = $this->db->insert(db_prefix() . 'read_comments', $read_comment_data);
                        // add the activity of comments
                        $lead_activity_data = array(
                            'leadid' => $lead_id,
                            'description' => $staff_name . ' send a message to ' . $to_user_name,
                            'date' => date('Y-m-d H:i:s'),
                            'staffid' => $staffid_string,
                            'full_name' => $staff_name
                        );
                        $this->db->insert(db_prefix() . 'lead_activity_log', $lead_activity_data);
                        $response_data = array(
                            'staff_id' => $staffid_string,
                            'user_name' => $staff_name,
                            'comment' => $comment_text,
                            'profile_url' => $profile_url,
                            'created_at' => strtotime(date('Y-m-d H:i:s')),
                        );
                        $save_comment_id = $comment_id;
                    }
                    if (!empty($save_comment_id)) {
                        // Send notification
                        $this->db->select('id,multiple_cases,client_id');
                        $this->db->where('id', $lead_id);
                        $lead_data_check = $this->db->get(db_prefix() . 'leads');
                        if ($lead_data_check->num_rows() > 0) {
                            $lead_data = $lead_data_check->row();
                            if ($lead_data->client_id == 0) {
                                // get the parnet id of lead
                                $partent_lead_id = $lead_data->multiple_cases;
                                $this->db->select('id,multiple_cases,client_id');
                                $this->db->where('id', $partent_lead_id);
                                $lead_parent_data_check = $this->db->get(db_prefix() . 'leads')->row();
                                $client_id = $lead_parent_data_check->client_id;
                            } else {
                                $client_id = $lead_data->client_id;
                            }
                            $to_user_id = get_contact_id_using_client_id($this, $client_id);
                            $notification_type = get_notification_type(3);
                            if ($staffid_string != 0) {
                                if ($comment_type == 'client') {
                                    $values = array(
                                        'staff_id' => $staffid_string,
                                        'contact_id' => $to_user_id,
                                        'client_id' => $client_id,
                                        'lead_id' => $lead_id,
                                        'send_to' => 'client',
                                        'title' => 'New Message Notification',
                                        'message' => $staff_name . ' send a message to ' . $to_user_name,
                                        'type' => $notification_type,
                                        'comment_type' => 'broker',
                                    );
                                    add_alerts_user($values);
                                }
                                // send  notiication in crm to all the team group member and staff
                                $this->db->select('assign_group,assigned');
                                $this->db->where('id', $lead_id);
                                $lead_data_for_get_assign_group = $this->db->get(db_prefix() . 'leads')->row();
                                $current_staff_data = get_staff_ids_by_group($this, $lead_data_for_get_assign_group->assign_group);
                                foreach ($current_staff_data as $staff_notifiy_data) {
                                    if ($staff_notifiy_data['staffid'] != $staffid_string) {
                                        $read_comment_data = array(
                                            'comment_id' => $comment_id,
                                            'to_user_id' => $staff_notifiy_data['staffid'],
                                            'from_user_id' => $staffid_string,
                                            'lead_id' => $lead_id,
                                            'is_read' => '0',
                                        );
                                        $insert_read_comments = $this->db->insert(db_prefix() . 'read_comments', $read_comment_data);
                                        // send notification in the mobile side to staff
                                        $values = array(
                                            'staff_id' => $staff_notifiy_data['staffid'],
                                            'contact_id' => $to_user_id,
                                            'client_id' => $client_id,
                                            'lead_id' => $lead_id,
                                            'send_to' => 'staff',
                                            'title' => 'New Message Notification',
                                            // 'message' => '' . $stage_name . ' Stage has been completed.',
                                            'message' => $staff_name . ' send a message to ' . $to_user_name,
                                            'type' => $notification_type,
                                            'comment_type' => $comment_type,
                                        );
                                        add_alerts_user($values);
                                        // send slack notification
                                        $slack_message = $staff_name . ' send a message to ' . $to_user_name;
                                        // send notification in the crm
                                        $this->Leads_model->custom_lead_assigned_member_notification('staff', $lead_id, $staff_notifiy_data['staffid'], $staffid_string, '', $staff_name . ' send a message to ' . $contact_user_name);
                                    }
                                }
                                // get the all admin staff ids
                                $admin_ids = get_all_admin_role_staff_ids($this);
                                foreach ($admin_ids as $admin_email) {
                                    if ($admin_email['staffid'] != $staffid_string) {
                                        $read_comment_data = array(
                                            'comment_id' => $comment_id,
                                            'to_user_id' => $admin_email['staffid'],
                                            'from_user_id' => $staffid_string,
                                            'lead_id' => $lead_id,
                                            'is_read' => '0',
                                        );
                                        $insert_read_comments = $this->db->insert(db_prefix() . 'read_comments', $read_comment_data);
                                        // send notification in the mobile side to staff
                                        $values = array(
                                            'staff_id' => $admin_email['staffid'],
                                            'contact_id' => $to_user_id,
                                            'client_id' => $client_id,
                                            'lead_id' => $lead_id,
                                            'send_to' => 'staff',
                                            'title' => 'New Message Notification',
                                            // 'message' => '' . $stage_name . ' Stage has been completed.',
                                            'message' => $staff_name . ' send a message to ' . $to_user_name,
                                            'type' => $notification_type,
                                            'comment_type' => $comment_type,
                                        );
                                        add_alerts_user($values);
                                        // send slack notification
                                        $slack_message = $staff_name . ' send a message to ' . $to_user_name;
                                        // send notification in the crm
                                        $this->Leads_model->custom_lead_assigned_member_notification('staff', $lead_id, $admin_email['staffid'], $staffid_string, '', $staff_name . ' send a message to ' . $contact_user_name);
                                    }
                                }
                                // send slack notification in ld-channel
                                // $this->slack->sendnotification($slack_message, $lead_id);
                            }
                        }
                        $response = array(
                            'status' => 200,
                            'message' => 'User comments save successfully.',
                            'data' => $response_data,
                        );
                        getresponse($this, $response);
                    } else {
                        $response = array(
                            'status' => 400,
                            'message' => 'User comments not save successfully.',
                            'data' => null,
                        );
                        getresponse($this, $response);
                    }
                }
            }
        }
    }
    // get the notification counts for apps
    public function unread_notify_count_post()
    {
        $getemail = $this->authmiddleware->verifyToken();
        if (empty($getemail)) {
        } else {
            if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
                $response = array(
                    'status' => 400,
                    'message' => 'Invalid request method.',
                    'data' => null
                );
                getresponse($this, $response);
            } else {
                $data = $this->Contacts_model->getEmail($getemail);
                $get_role = array_column($data, 'role');
                $role_string = implode(',', $get_role);
                $user_id = $this->post('user_id');
                $case_id = $this->post('case_id');
                // $leadData = $this->Leads_model->get_lead_id($user_id);
                // $lead_id = $leadData->id;
                if (!empty($user_id)) {
                    if ($role_string == 'client') {
                        $this->db->select('COUNT(*) as count');
                        $this->db->where('contact_id', $user_id);
                        if (!empty($case_id)) {
                            $this->db->where('lead_id', $case_id);
                        }
                        $this->db->where('send_to', 'client');
                        $this->db->where('is_read', 0);
                        $query = $this->db->get(db_prefix() . 'alerts');
                        if ($query->num_rows() > 0) {
                            $result = $query->row();
                            $total_count = $result->count;
                            $response = [
                                'status' => 200,
                                'message' => 'Total Count',
                                'data' => [
                                    'count' => $total_count,
                                ],
                            ];
                        } else {
                            $response = [
                                'status' => 200,
                                'message' => 'No Counts found',
                                'data' => [
                                    'count' => 0,
                                ],
                            ];
                        }
                        getresponse($this, $response);
                    } else {
                        $this->db->select('COUNT(*) as count');
                        $this->db->where('staff_id', $user_id);
                        $this->db->where('send_to', 'staff');
                        $this->db->where('is_read', 0);
                        $query = $this->db->get(db_prefix() . 'alerts');
                        if ($query->num_rows() > 0) {
                            $result = $query->row();
                            $total_count = $result->count;
                            $response = [
                                'status' => 200,
                                'message' => 'Total Count',
                                'data' => [
                                    'count' => $total_count,
                                ],
                            ];
                        } else {
                            $response = [
                                'status' => 200,
                                'message' => 'No Counts found',
                                'data' => [
                                    'count' => 0,
                                ],
                            ];
                        }
                        getresponse($this, $response);
                    }
                } else {
                    $response = [
                        'status' => 400,
                        'message' => 'Invalid Credentails',
                        'data' => [],
                    ];
                    getresponse($this, $response);
                }
            }
        }

    }
    // read the all notification for app
    public function read_notification_post()
    {
        $getemail = $this->authmiddleware->verifyToken();
        if (empty($getemail)) {
        } else {
            if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
                $response = array(
                    'status' => 400,
                    'message' => 'Invalid request method.',
                    'data' => null
                );
                getresponse($this, $response);
            } else {
                $data = $this->Contacts_model->getEmail($getemail);
                $get_role = array_column($data, 'role');
                $role_string = implode(',', $get_role);
                $user_id = $this->post('user_id');
                $case_id = $this->post('case_id');
                $notification_id = $this->post('notification_id');
                // $leadData = $this->Leads_model->get_lead_id($user_id);
                // $lead_id = $leadData->id;
                if (!empty($user_id)) {
                    if ($role_string == 'client') {
                        $update_notify = array(
                            'is_read' => 1
                        );

                        $this->db->where('contact_id', $user_id);
                        $this->db->where('send_to', 'client');
                        if (!empty($notification_id)) {
                            $this->db->where('id', $notification_id);
                        }
                        if (!empty($case_id)) {
                            $this->db->where('lead_id', $case_id);
                        }
                        $this->db->update(db_prefix() . 'alerts', $update_notify);
                        if ($this->db->affected_rows() > 0) {
                            $this->db->select('COUNT(*) as count');
                            $this->db->where('lead_id', $case_id);
                            $this->db->where('send_to', 'client');
                            $this->db->where('is_read', 0);
                            $query = $this->db->get(db_prefix() . 'alerts');

                            if ($query->num_rows() > 0) {
                                $result = $query->row();
                                $total_count = $result->count;

                                $response = [
                                    'status' => 200,
                                    'message' => 'Unread Count After Update',
                                    'data' => [
                                        'count' => $total_count,
                                    ],
                                ];
                            } else {
                                $response = [
                                    'status' => 200,
                                    'message' => 'No Unread Notifications Found',
                                    'data' => [
                                        'count' => 0,
                                    ],
                                ];
                            }
                        } else {
                            $response = [
                                'status' => 400,
                                'message' => 'Notifications are not updated',
                                'data' => [],
                            ];
                        }
                        getresponse($this, $response);
                    } else {
                        $update_notify = array(
                            'is_read' => 1
                        );
                        if (!empty($notification_id)) {
                            $this->db->where('id', $notification_id);
                        }
                        if (!empty($case_id)) {
                            $this->db->where('lead_id', $case_id);
                        }
                        $this->db->where('staff_id', $user_id);
                        $this->db->where('send_to', 'staff');
                        $this->db->update(db_prefix() . 'alerts', $update_notify);
                        if ($this->db->affected_rows() > 0) {
                            $this->db->select('COUNT(*) as count');
                            $this->db->where('staff_id', $user_id);
                            $this->db->where('send_to', 'staff');
                            $this->db->where('is_read', 0);
                            $query = $this->db->get(db_prefix() . 'alerts');
                            if ($query->num_rows() > 0) {
                                $result = $query->row();
                                $total_rows = $result->count;
                                $response = [
                                    'status' => 200,
                                    'message' => 'Total Count',
                                    'data' => [
                                        'count' => $total_rows,
                                    ],
                                ];
                            } else {
                                $response = [
                                    'status' => 200,
                                    'message' => 'No Counts found',
                                    'data' => [
                                        'count' => 0,
                                    ],
                                ];
                            }
                            getresponse($this, $response);
                        } else {
                            $response = [
                                'status' => 400,
                                'message' => 'Notifications are not updated',
                                'data' => [],
                            ];
                            getresponse($this, $response);
                        }
                    }
                } else {
                    $response = [
                        'status' => 400,
                        'message' => 'Invalid Credentails',
                        'data' => [],
                    ];
                    getresponse($this, $response);
                }
            }
        }

    }
    // Get unread comment api
    public function unreadcomment_post()
    {
        $getemail = $this->authmiddleware->verifyToken();
        if (empty($getemail)) {
        } else {
            if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
                $response = array(
                    'status' => 400,
                    'message' => 'Invalid request method.',
                    'data' => null
                );
                getresponse($this, $response);
            } else {
                $data = $this->Contacts_model->getEmail($getemail);
                $get_role = array_column($data, 'role');
                $role_string = implode(',', $get_role);
                $user_id = $this->post('user_id');
                if (!empty($user_id)) {
                    if ($role_string == 'client') {
                        $leadData = $this->Leads_model->get_lead_id($user_id);
                        $lead_id = $leadData->id;
                        $this->db->select('comment_id');
                        $this->db->where('lead_id', $lead_id);
                        $this->db->where('role', 'staff');
                        $this->db->where('type', 'client-to-ld');
                        $query = $this->db->get(db_prefix() . 'comments');
                        $comment_id_array = array();
                        if ($query->num_rows() > 0) {
                            $comment_id_array = $query->result_array();
                            $total_rows = 0;
                            if (!empty($comment_id_array)) {
                                $comment_ids = array_column($comment_id_array, 'comment_id');
                                $this->db->select('COUNT(*) as count');
                                $this->db->from(db_prefix() . 'read_comments');
                                $this->db->where_in('comment_id', $comment_ids);
                                $this->db->where('lead_id', $lead_id);
                                $this->db->where('to_user_id', $user_id);
                                $this->db->where('is_read', '0');
                                $query_count = $this->db->get();
                                if ($query_count) {
                                    $total_rows = $query_count->row_array();
                                }
                            }
                            $response = [
                                'status' => 200,
                                'message' => 'Comment Count',
                                'data' => $total_rows,
                            ];
                            getresponse($this, $response);
                        } else {
                            $response = [
                                'status' => 200,
                                'message' => 'No comments found',
                                'data' => ['count' => 0],
                            ];
                            getresponse($this, $response);
                        }
                    } else {
                        $response = [
                            'status' => 400,
                            'message' => 'Unauthorized person',
                            'data' => null,
                        ];
                        getresponse($this, $response);
                    }
                }
            }
        }
    }
    // get read comment api
    public function readcomment_post()
    {
        $getemail = $this->authmiddleware->verifyToken();
        if (empty($getemail)) {
        } else {
            if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
                $response = array(
                    'status' => 400,
                    'message' => 'Invalid request method.',
                    'data' => array()
                );
                getresponse($this, $response);
            } else {
                $user_id = $this->post('user_id');
                $leadData = $this->Leads_model->get_lead_id($user_id);
                $lead_id = $leadData->id;
                $update_data = array(
                    'is_read' => '1'
                );
                $data = $this->Contacts_model->getEmail($getemail);
                $get_role = array_column($data, 'role');
                $role_string = implode(',', $get_role);
                if (!empty($user_id)) {
                    if ($role_string == 'client') {
                        $this->db->select('comment_id');
                        $this->db->where('to_user_id', $user_id);
                        $this->db->where('lead_id', $lead_id);
                        $this->db->where('role', 'staff');
                        $this->db->where('type', 'client-to-ld');
                        $query = $this->db->get(db_prefix() . 'comments');
                        $comment_id_array = array();
                        if ($query->num_rows() > 0) {
                            $comment_id_array = $query->result_array();
                            $comment_ids = array_column($comment_id_array, 'comment_id');
                            $comment_ids = array_map('intval', $comment_ids);
                            $this->db->where_in('comment_id', $comment_ids);
                            $this->db->where('lead_id', $lead_id);
                            $this->db->delete(db_prefix() . 'read_comments');
                        }
                        // Count the read comments
                        $this->db->select('COUNT(*) as count');
                        $this->db->from(db_prefix() . 'read_comments');
                        $this->db->where_in('comment_id', $comment_ids);
                        $this->db->where('to_user_id', $user_id);
                        $this->db->where('lead_id', $lead_id);
                        $this->db->where('is_read', '0');
                        $query_count = $this->db->get();
                        if ($query_count) {
                            $total_rows = $query_count->row_array();
                            $response = [
                                'status' => 200,
                                'message' => 'Comment Count',
                                'data' => $total_rows,
                            ];
                            getresponse($this, $response);
                        } else {
                            $response = [
                                'status' => 200,
                                'message' => 'Comment count not found.',
                                'data' => ['count' => 0]
                            ];
                            getresponse($this, $response);
                        }
                    }
                } else {
                    $response = [
                        'status' => 400,
                        'message' => 'Incorrect credentials',
                        'data' => null,
                    ];
                    getresponse($this, $response);
                }
            }
        }
    }
    // User task notes create
    public function usernotes_post()
    {
        $getemail = $this->authmiddleware->verifyToken();
        if (empty($getemail)) {
        } else {
            if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
                $response = array(
                    'status' => 400,
                    'message' => 'Invalid request method.',
                    'data' => null,
                );
                getresponse($this, $response);
            } else {
                $this->form_validation->set_rules('notes_data', 'notes', 'required');

                // Set custom error messages
                $this->form_validation->set_message('required', 'The {field} field is required.');
                if ($this->form_validation->run() == true) {
                    $data = $this->Contacts_model->getEmail($getemail);
                    $task_id = $this->post('task_id');
                    $notes_data = $this->post('notes_data');
                    // get role and set condition
                    $get_role = array_column($data, 'role');
                    $role_string = implode(',', $get_role);
                    if ($role_string == 'client') {
                        // array to string convert the id of contact table
                        $get_contact_id = array_column($data, 'id');
                        $contact_id = implode(',', $get_contact_id);
                        // get lead id using lead helper
                        $leadData = $this->Leads_model->get_lead_id($contact_id);
                        $lead_id = $leadData->id;
                        $notes_data = array(
                            'task_id' => $task_id,
                            'rel_id' => $lead_id,
                            'rel_type' => 'user-notes',
                            'description' => $notes_data,
                            'addedfrom' => $contact_id,
                            'dateadded' => date('Y-m-d H:i:s')
                        );
                        $save = $this->db->insert(db_prefix() . 'notes', $notes_data);
                        $inserted_id = $this->db->insert_id();
                    } else {
                        // get the staff id
                        $get_staffid = array_column($data, 'staffid');
                        $staffid_string = implode(',', $get_staffid);
                        $notes_data = array(
                            'task_id' => $task_id,
                            'rel_id' => $staffid_string,
                            'rel_type' => 'staff-notes',
                            'description' => $notes_data,
                            'addedfrom' => $staffid_string,
                            'dateadded' => date('Y-m-d H:i:s')
                        );
                        $save = $this->db->insert(db_prefix() . 'notes', $notes_data);
                        $inserted_id = $this->db->insert_id();
                    }
                    // change for response 
                    $show_notes_data = array(
                        'id' => (string) $inserted_id,
                        'description' => $notes_data['description'],
                        'created_at' => strtotime($notes_data['dateadded'])
                    );
                    if (!empty($save)) {
                        $response = array(
                            'status' => 200,
                            'message' => 'Data inserted successfully.',
                            'data' => $show_notes_data
                        );
                        getresponse($this, $response);
                    } else {
                        $response = array(
                            'status' => 400,
                            'message' => 'Fail to insert data please try again.',
                            'data' => null
                        );
                        getresponse($this, $response);
                    }
                } else {
                    $errors = array(
                        'notes_data' => form_error('notes_data'),
                    );
                    if (!empty($errors['notes_data'])) {
                        $response = array(
                            'status' => 400,
                            'message' => 'Please correct the errors below!',
                            'data' => null,
                        );
                        if (!empty($errors['notes_data'])) {
                            $response['message'] .= ' ' . $errors['notes_data'];
                        }
                    }
                    getresponse($this, $response);
                }
            }
        }
    }
    // fetch user notes 
    public function getusernotes_post()
    {
        $getemail = $this->authmiddleware->verifyToken();
        if (empty($getemail)) {
        } else {
            if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
                $response = array(
                    'status' => 400,
                    'message' => 'Invalid request method.',
                    'data' => null
                );
                getresponse($this, $response);
            } else {
                $task_id = $this->post('task_id');
                $data = $this->Contacts_model->getEmail($getemail);
                $get_role = array_column($data, 'role');
                $role_string = implode(',', $get_role);
                if ($role_string == 'client') {
                    // get the primary id of table contact
                    $get_contact_id = array_column($data, 'id');
                    $contact_id = implode(',', $get_contact_id);
                    // get lead id using lead helper
                    $leadData = $this->Leads_model->get_lead_id($contact_id);
                    $user_id = $leadData->id;
                    // get all comment 
                    $query = get_user_notes_api($this, $user_id, $task_id, $role_string);
                } else {
                    // get the staff id
                    $get_staffid = array_column($data, 'staffid');
                    $staffid_string = implode(',', $get_staffid);
                    $query = get_user_notes_api($this, $staffid_string, $task_id, $role_string);
                }
                if ($query->num_rows() > 0) {
                    $get_user_notes = $query->result();
                    $fetch_notes = array();

                    foreach ($get_user_notes as $record_task) {
                        $fetch_notes[] = array(
                            'id' => $record_task->id,
                            'description' => $record_task->description,
                            'created_at' => strtotime($record_task->dateadded)
                        );
                    }
                    $response = array(
                        'status' => 200,
                        'message' => 'Data fetch successfully.',
                        'data' => $fetch_notes
                    );
                    getresponse($this, $response);
                } else {
                    $response = array(
                        'status' => 200,
                        'message' => 'No records found.',
                        'data' => null
                    );
                    getresponse($this, $response);
                }
            }
        }
    }
    // Notification save
    public function update_fcm_token_post()
    {
        $getemail = $this->authmiddleware->verifyToken();
        if (empty($getemail)) {
        } else {
            if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
                $response = array(
                    'status' => 400,
                    'message' => 'Invalid request method.',
                    'data' => null
                );
                getresponse($this, $response);
            } else {
                // in the app side pass param platform and in the backend side/database it is called device_name
                // in the app side pass param fcm_token and in the backend side/database it is called device_token
                $device_name = $this->post('platform');
                $device_token = $this->post('fcm_token');
                $data = $this->Contacts_model->getEmail($getemail);
                $get_role = array_column($data, 'role');
                $role_string = implode(',', $get_role);
                if ($role_string == 'client') {
                    $get_user_id = array_column($data, 'id');
                    $user_id = implode(',', $get_user_id);
                    if (!empty($user_id)) {
                        $data = array(
                            'device_name' => $device_name,
                            'device_token' => $device_token,
                        );
                        $this->db->where('id', $user_id);
                        $this->db->update(db_prefix() . 'contacts', $data);
                        $user_data = array(
                            'user_id' => $user_id,
                            'platform' => $device_name,
                            'fcm_token' => $device_token,
                        );
                        $response = array(
                            'status' => 200,
                            'message' => 'Notification save successfully.',
                            'data' => $user_data,
                        );
                    } else {
                        $response = array(
                            'status' => 200,
                            'message' => 'User is not exist in our record.',
                            'data' => null,
                        );
                    }
                    getresponse($this, $response);
                } else {
                    $get_staff_id = array_column($data, 'staffid');
                    $staff_id = implode(',', $get_staff_id);
                    if (!empty($staff_id)) {
                        $data = array(
                            'device_name' => $device_name,
                            'device_token' => $device_token,
                        );
                        $this->db->where('staffid', $staff_id);
                        $this->db->update(db_prefix() . 'staff', $data);
                        $user_data = array(
                            'user_id' => $staff_id,
                            'platform' => $device_name,
                            'fcm_token' => $device_token,
                        );
                        $response = array(
                            'status' => 200,
                            'message' => 'Notification save successfully.',
                            'data' => $user_data,
                        );
                    } else {
                        $response = array(
                            'status' => 200,
                            'message' => 'User is not exist in our record.',
                            'data' => null,
                        );
                    }
                    getresponse($this, $response);
                }

            }
        }
    }
    public function get_notifications_post()
    {
        $getemail = $this->authmiddleware->verifyToken();
        if (empty($getemail)) {
        } else {
            if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
                $response = array(
                    'status' => 400,
                    'message' => 'Invalid request method.',
                    'data' => null
                );
                getresponse($this, $response);
            } else {
                $page = $this->input->post('page');
                $per_page = $this->input->post('per_page');
                $data = $this->Contacts_model->getEmail($getemail);
                $get_role = array_column($data, 'role');
                $role_string = implode(',', $get_role);
                if ($role_string == 'client') {
                    $get_user_id = array_column($data, 'id');
                    $user_id = implode(',', $get_user_id);
                    // Set pagination configuration
                    $config['base_url'] = '';
                    $config['total_rows'] = $this->db->where('contact_id', $user_id)->where('send_to', 'client')->count_all_results('tblalerts');
                    $config['per_page'] = $per_page;
                    $config['uri_segment'] = 3;

                    // Initialize pagination
                    $this->pagination->initialize($config);

                    // Get current page number
                    $page = ($page !== null && $page >= 0) ? $page : 0;
                    $offset = $page * $per_page;

                    $this->db->select('*')->from('tblalerts')->where('contact_id', $user_id)->where('send_to', 'client')->order_by("id", "desc")->limit($per_page, $offset);
                    $notifications = $this->db->get()->result();

                    $notifications_data = [];

                    foreach ($notifications as $key => $alert) {
                        // Set properties in $notifications_data array
                        $notifications_data[$key] = new stdClass();
                        $notifications_data[$key]->notification_id = $alert->id;
                        $notifications_data[$key]->user_id = $alert->contact_id;
                        // $notifications_data[$key]->case_id = get_lead_parent_id($this, $alert->contact_id);
                        $notifications_data[$key]->case_id = $alert->lead_id;
                        $notifications_data[$key]->task_id = $alert->task_id;
                        $notifications_data[$key]->title = $alert->title;
                        $notifications_data[$key]->message = $alert->message;
                        $notifications_data[$key]->type = $alert->type;
                        $notifications_data[$key]->comment_type = $alert->comment_type;
                        $notifications_data[$key]->is_read = $alert->is_read;
                        $notifications_data[$key]->created_at = strtotime($alert->created_at);
                        $notifications_data[$key]->checklist_type = $alert->checklist_type;
                    }
                    $response = array(
                        'status' => 200,
                        'message' => 'success.',
                        'data' => $notifications_data
                    );
                    getresponse($this, $response);
                } else {
                    $get_staff_id = array_column($data, 'staffid');
                    $staff_id = implode(',', $get_staff_id);
                    // Set pagination configuration
                    $config['base_url'] = '#';
                    $config['total_rows'] = $this->db->where('staff_id', $staff_id)->where('send_to', 'staff')->count_all_results('tblalerts'); // Get total number of notifications
                    $config['per_page'] = $per_page;
                    $config['uri_segment'] = 3;

                    // Initialize pagination
                    $this->pagination->initialize($config);

                    // Calculate the offset based on the current page
                    $page = ($page !== null && $page >= 0) ? $page : 0;
                    $offset = $page * $config['per_page'];

                    $this->db->select('*')->from('tblalerts')->where('staff_id', $staff_id)->where('send_to', 'staff')->order_by("id", "desc")->limit($config['per_page'], $offset);
                    $notifications = $this->db->get()->result();

                    foreach ($notifications as $key => $alert) {
                        // Set properties in $notifications_data array
                        $notifications_data[$key] = new stdClass();
                        $notifications_data[$key]->notification_id = $alert->id;
                        $notifications_data[$key]->user_id = $alert->contact_id;
                        // $notifications_data[$key]->case_id = get_lead_parent_id($this, $alert->contact_id);
                        $notifications_data[$key]->case_id = $alert->lead_id;
                        $notifications_data[$key]->task_id = $alert->task_id;
                        $notifications_data[$key]->title = $alert->title;
                        $notifications_data[$key]->message = $alert->message;
                        $notifications_data[$key]->type = $alert->type;
                        $notifications_data[$key]->comment_type = $alert->comment_type;
                        $notifications_data[$key]->is_read = $alert->is_read;
                        $notifications_data[$key]->created_at = strtotime($alert->created_at);
                        $notifications_data[$key]->checklist_type = $alert->checklist_type;
                    }
                    $response = array(
                        'status' => 200,
                        'message' => 'success.',
                        'data' => $notifications_data
                    );
                    getresponse($this, $response);
                }
            }
        }
    }

    // Example usage

    public function test_notification_post()
    {
        // Device token received from the client
        $device_token = $this->input->post('device_token');

        $deviceToken = 'YOUR_DEVICE_TOKEN'; // Replace with the actual device token
        $projectId = 'legal-direct'; // Your Firebase project ID
        $title = 'Test Notification';
        $body = 'This is a test message using FCM v1 API.';

        $response = $this->Leads_model->sendFCMNotification($device_token, $title, $body);
        echo $response;
    }

}