<?php

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

/**
 * @since  2.3.3
 * Get available staff permissions, modules can use the filter too to hook permissions
 * @param  array  $data additional data passed from view role.php and member.php
 * @return array
 */
function get_all_staff($ci)
{
    $ci->db->select('staffid,firstname,lastname');
    $staff_data = $ci->db->get(db_prefix() . 'staff')->result_array();
    return $staff_data ?? null;
}
function get_all_staff_name_email_by_group_for_porfile($ci, $leads_group)
{
    if (empty($leads_group)) {
        return null;
    }
    $ci->db->select('firstname, lastname, email');
    $ci->db->where('staff_group', $leads_group);
    $assign_group_data = $ci->db->get(db_prefix() . 'staff');
    $data['get_staff_name_by_group'] = array();
    if ($assign_group_data->num_rows() > 0) {
        $get_staff_data = $assign_group_data->result_array();
        $get_staff_name_by_group = array_map(function ($item) {
            return $item['firstname'] . ' ' . $item['lastname'] . ' (' . $item['email'] . ') ';
        }, $get_staff_data);
    }
    return $get_staff_name_by_group ?? null;
}
function get_all_staff_name_email_by_group_for_cc($ci, $id, $leads_group)
{
    // add the broker email in cc 
    if (!empty($leads_group)) {
        $ci->db->select('staffid, firstname, lastname, email');
        // $ci->db->where('staff_group', $leads_group);
        $ci->db->where("FIND_IN_SET('$leads_group', staff_group) >", 0); 
        $assign_group_data = $ci->db->get(db_prefix() . 'staff');
        if ($assign_group_data->num_rows() > 0) {
            $get_staff_data = $assign_group_data->result_array();
            $get_staff_name_by_group = implode(',', array_map(function ($item) {
                return $item['email'];
            }, $get_staff_data));
        }
    }
    return $get_staff_name_by_group ?: null;

}
// get the all broker/addedfrom email
function get_all_staff_name_email_by_addedfrom_for_to($ci, $id, $admin_broker_email_add)
{
    // get the broker ids 
    $ci->db->select('addedfrom');
    $ci->db->where('id', $id);
    $lead_data = $ci->db->get(db_prefix() . 'leads')->row();
    $addedfrom_ids = explode(',', $lead_data->addedfrom);
    // add the broker email in to 
    if (!empty($addedfrom_ids)) {
        $ci->db->select('staffid, firstname, lastname, email');
        $ci->db->where_in('staffid', $addedfrom_ids);
        $assign_group_data = $ci->db->get(db_prefix() . 'staff');
        if ($assign_group_data->num_rows() > 0) {
            $get_staff_data = $assign_group_data->result_array();
            $get_staff_name_by_group = implode(',', array_map(function ($item) {
                return $item['email'];
            }, $get_staff_data));
        }
    }
    return $get_staff_name_by_group ?: '';

}
function get_all_staff_against_brokerage_id_for_to_email($ci, $brokerage_id){
    if(empty($brokerage_id)){
        return null;
    }
    $ci->db->select('staffid, firstname, lastname, brokerage_ids, email');
    $ci->db->where('brokerage_ids', $brokerage_id);
    $query = $ci->db->get(db_prefix() . 'staff');
    if ($query->num_rows() > 0) {
        $get_staff_data =  $query->result_array();
        $get_staff_details_by_brokerageid = implode(',', array_map(function ($item) {
            return $item['email'];
        }, $get_staff_data));
    }
    return $get_staff_details_by_brokerageid ?: null;
}

function get_all_staff_name_by_groups($ci, $leads_group)
{
    if(empty($leads_group)){
        return null;
    }
    $ci->db->select('firstname, lastname');
    $ci->db->where('staff_group', $leads_group);
    $assign_group_data = $ci->db->get(db_prefix() . 'staff');
    $data['get_staff_name_by_group'] = array();
    if ($assign_group_data->num_rows() > 0) {
        $get_staff_data = $assign_group_data->result_array();
        $get_staff_name_by_group = array_map(function ($item) {
            return $item['firstname'] . ' ' . $item['lastname'];
        }, $get_staff_data);
    }
    return $get_staff_name_by_group;
}
function get_all_staff_ids_by_group_name($ci, $group_name)
{
    if (empty($group_name)) {
        return array();
    }
    $ci->db->select('staff_group, staffid, firstname, lastname,email');
    $ci->db->where('staff_group', $group_name);
    $query = $ci->db->get(db_prefix() . 'staff');
    $data = $query->result_array();
    return ($data) ? $data : array();
}
function get_staff_email_by_staffid($ci, $staffid)
{
    if (empty($staffid)) {
        return array();
    }
    $ci->db->select('staff_group, staffid, firstname, lastname,email');
    $ci->db->where('staffid', $staffid);
    $query = $ci->db->get(db_prefix() . 'staff');
    $data = $query->row();
    return ($data) ? $data : array();
}
function get_multiple_broker_details_using_addedfrom($ci, $staffid)
{
    if (empty($staffid)) {
        return array();
    }
    $id_array = explode(',', $staffid);
    $ci->db->select('staff_group, staffid, firstname, lastname, email');
    $ci->db->where_in('staffid', $id_array);
    $query = $ci->db->get(db_prefix() . 'staff');
    $data = $query->result_array();
    return ($data) ? $data : array();
}
// get the staff admin id
function get_all_admin_role_staff_ids($ci)
{
    // get the admin staff ids to send the notification
    $ci->db->select('staffid,email');
    $ci->db->where('role', 4);
    $staff_ids = $ci->db->get(db_prefix() . 'staff')->result_array();
    return $staff_ids ?? '';
}
// get all admin broker list
function get_all_admin_broker_role_staff_ids($ci, $brokerage_id = ''){
    $ci->db->select('staffid,email,firstname,lastname');
    $ci->db->where('role', 6);
    if(!empty($brokerage_id)){
        $ci->db->where('brokerage_ids', $brokerage_id);
    }
    $staff_ids = $ci->db->get(db_prefix() . 'staff')->result_array();
    return $staff_ids ?? '';
}
function get_broker_parent_ids($ci)
{
    // Select relevant fields from the staff table
    $ci->db->select('staffid, firstname, lastname, email');
    $ci->db->where('broker_agent_id', 0);
    $ci->db->where('role', 2);
    $query = $ci->db->get(db_prefix() . 'staff');
    $data = $query->result_array();

    // Prepare the data in a key-value pair format: staffid => "firstname lastname"
    $broker_parent_id = array();
    if (!empty($data)) {
        foreach ($data as $row) {
            // Combine firstname and lastname for display
            $fullName = $row['firstname'] . ' ' . $row['lastname'];
            // Use staffid as the key and full name as the value
            $broker_parent_id[$row['staffid']] = $fullName;
        }
    }

    return $broker_parent_id;
}
function get_client_staff_type_using_email($ci, $email) {
    $result = [
        'role_type' => '',
        'id' => null,
        'email' => null,
    ];

    // Check in staff table
    $ci->db->select('staffid, email, firstname, lastname');
    $ci->db->where('email', $email);
    $staff = $ci->db->get(db_prefix() . 'staff')->row();
    if (!empty($staff)) {
        $result['role_type'] = 'staff';
        $result['id'] = $staff->staffid;
        $result['email'] = $staff->email;
        $result['firstname'] = $staff->firstname ?? '';
        $result['lastname'] = $staff->lastname ?? '';
        return $result;
    }

    // Check in leads table
    $ci->db->select('id, email');
    $ci->db->where('email', $email);
    $lead = $ci->db->get(db_prefix() . 'leads')->row();
    if (!empty($lead)) {

        $primary_name = explode(' ', $lead->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];
            }

        $result['role_type'] = 'client';
        $result['id'] = $lead->id;
        $result['email'] = $lead->email;
        $result['firstname'] = $firstname ?? '';
        $result['middlename'] = $middlename ?? '';
        $result['lastname'] = $lastname ?? '';
        return $result;
    }

    // Check in leads_borrow table
    $ci->db->select('id, borrow_firstname, borrow_middlename, borrow_lastname, borrow_email');
    $ci->db->where('borrow_email', $email);
    $borrow = $ci->db->get(db_prefix() . 'leads_borrow')->row();
    if (!empty($borrow)) {
        $result['role_type'] = 'client-borrow';
        $result['id'] = $borrow->id;
        $result['email'] = $borrow->borrow_email;
        $result['firstname'] = $borrow->borrow_firstname ?? '';
        $result['middlename'] = $borrow->borrow_middlename ?? '';
        $result['lastname'] = $borrow->borrow_lastname ?? '';
        return $result;
    }

    return $result;
}

function get_client_staff_data_using_type_id($ci, $id, $type){
    $result = [
        'role_type' => '',
        'id' => null,
        'email' => null,
    ];

    if($type == "staff"){
        // Check in staff table
        $ci->db->select('staffid, email, firstname, lastname, profile_image');
        $ci->db->where('staffid', $id);
        $staff = $ci->db->get(db_prefix() . 'staff')->row();
        if (!empty($staff)) {
            $result['role_type'] = 'staff';
            $result['id'] = $staff->staffid;
            $result['email'] = $staff->email;
            $result['firstname'] = $staff->firstname ?? '';
            $result['middlename'] = '';
            $result['lastname'] = $staff->lastname ?? '';
            $result['profile_image'] = $staff->profile_image ?? '';
            return $result;
        }
    }

    if($type == "client"){
        // Check in leads table
        $ci->db->select('id, email, name');
        $ci->db->where('id', $id);
        $lead = $ci->db->get(db_prefix() . 'leads')->row();
        if (!empty($lead)) {
            $primary_name = explode(' ', $lead->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];
            }

            $result['role_type'] = 'client';
            $result['id'] = $lead->id;
            $result['email'] = $lead->email;
            $result['firstname'] = $firstname ?? '';
            $result['middlename'] = $middlename ?? ''; 
            $result['lastname'] = $lastname ?? '';
            return $result;
        }
    }

    if($type == "client-borrow"){
        // Check in leads_borrow table
        $ci->db->select('id, borrow_firstname, borrow_middlename, borrow_lastname, borrow_email');
        $ci->db->where('id', $id);
        $borrow = $ci->db->get(db_prefix() . 'leads_borrow')->row();
        if (!empty($borrow)) {
            $result['role_type'] = 'client-borrow';
            $result['id'] = $borrow->id;
            $result['email'] = $borrow->borrow_email;
            $result['firstname'] = $borrow->borrow_firstname ?? '';
            $result['middlename'] = $borrow->borrow_middlename ?? '';
            $result['lastname'] = $borrow->borrow_lastname ?? '';

            return $result;
        }
    }

    return $result;
}

function get_broker_agent_staffid($ci, $staffid)
{
    if(empty($staffid)){
        return null;
    }
    $ci->db->select('staffid, broker_agent_id, role');
    $ci->db->where('staffid', $staffid);
    $query = $ci->db->get(db_prefix() . 'staff');
    $staff_row = $query->row();

    $staff_broker_agent_id = '';

    // Check if staff exists and has a role of 2
    if ($staff_row && $staff_row->role == 2) {
        if ($staff_row->broker_agent_id == 0) {
            // If broker_agent_id is 0, use the staffid as the broker_agent_id
            $staff_broker_agent_id = $staff_row->staffid;
        } else {
            // Otherwise, use the existing broker_agent_id
            $staff_broker_agent_id = $staff_row->broker_agent_id;
        }
    }

    return $staff_broker_agent_id;
}
// get the brokage data
function get_brokerage_data($ci)
{
    $ci->db->select('*');
    $query = $ci->db->get(db_prefix() . 'brokerage');
    if ($query && $query->num_rows() > 0) {
        $brokerage_data = $query->result_array();
        return $brokerage_data;
    } else {
        return array();
    }
}
function get_laywer_firm_data($ci)
{
    $ci->db->select('*');
    $query = $ci->db->get(db_prefix() . 'laywer_firm');
    if ($query && $query->num_rows() > 0) {
        $laywer_firm_data = $query->result_array();
        return $laywer_firm_data;
    } else {
        return array();
    }
}
function get_brokerage_dropdown_data($ci)
{
    $ci->db->select('id, name, mandatory');
    $query = $ci->db->get(db_prefix() . 'brokerage');
    if ($query && $query->num_rows() > 0) {
        return $query->result_array();
    } else {
        return array();
    }
}
function get_available_staff_permissions($data = [])
{
    $viewGlobalName = _l('permission_view') . '(' . _l('permission_global') . ')';

    $allPermissionsArray = [
        'view_own' => _l('permission_view_own'),
        'view' => $viewGlobalName,
        'create' => _l('permission_create'),
        'edit' => _l('permission_edit'),
        'delete' => _l('permission_delete'),
    ];

    $withoutViewOwnPermissionsArray = [
        'view' => $viewGlobalName,
        'create' => _l('permission_create'),
        'edit' => _l('permission_edit'),
        'delete' => _l('permission_delete'),
    ];

    $withNotApplicableViewOwn = array_merge(['view_own' => ['not_applicable' => true, 'name' => _l('permission_view_own')]], $withoutViewOwnPermissionsArray);

    $corePermissions = [

        'email_templates' => [
            'name' => _l('email_templates'),
            'capabilities' => [
                'view' => $viewGlobalName,
                'edit' => _l('permission_edit'),
            ],
        ],

        'reports' => [
            'name' => _l('reports'),
            'capabilities' => [
                'view' => $viewGlobalName,
                'view-timesheets' => _l('permission_view_timesheet_report'),
            ],
        ],
        'roles' => [
            'name' => _l('roles'),
            'capabilities' => $withoutViewOwnPermissionsArray,
        ],
        'settings' => [
            'name' => _l('settings'),
            'capabilities' => [
                'view' => $viewGlobalName,
                'edit' => _l('permission_edit'),
            ],
        ],
        'staff' => [
            'name' => _l('staff'),
            'capabilities' => $withoutViewOwnPermissionsArray,
        ],

    ];

    $addLeadsPermission = true;
    if (isset($data['staff_id']) && $data['staff_id']) {
        $is_staff_member = is_staff_member($data['staff_id']);
        if (!$is_staff_member) {
            $addLeadsPermission = false;
        }
    }

    if ($addLeadsPermission) {
        $corePermissions['leads'] = [
            'name' => 'Cases',
            'capabilities' => [
                'view' => $viewGlobalName,
                'delete' => _l('permission_delete'),
            ],
            'help' => [
                'view' => _l('help_leads_permission_view'),
            ],
        ];
    }

    return hooks()->apply_filters('staff_permissions', $corePermissions, $data);
}
/**
 * Get staff by ID or current logged in staff
 * @param  mixed $id staff id
 * @return mixed
 */
function get_staff($id = null)
{
    if (empty($id) && isset($GLOBALS['current_user'])) {
        return $GLOBALS['current_user'];
    }

    // Staff not logged in
    if (empty($id)) {
        return null;
    }

    if (!class_exists('staff_model', false)) {
        get_instance()->load->model('staff_model');
    }

    return get_instance()->staff_model->get($id);
}

/**
 * Return staff profile image url
 * @param  mixed $staff_id
 * @param  string $type
 * @return string
 */
function staff_profile_image_url($staff_id, $type = 'small')
{
    $url = base_url('assets/images/user-placeholder.webp');

    if ((string) $staff_id === (string) get_staff_user_id() && isset($GLOBALS['current_user'])) {
        $staff = $GLOBALS['current_user'];
    } else {
        $CI = &get_instance();
        $CI->db->select('profile_image')
            ->where('staffid', $staff_id);

        $staff = $CI->db->get(db_prefix() . 'staff')->row();
    }

    if ($staff) {
        if (!empty($staff->profile_image)) {
            $profileImagePath = 'uploads/staff_profile_images/' . $staff_id . '/' . $type . '_' . $staff->profile_image;
            if (file_exists($profileImagePath)) {
                $url = base_url($profileImagePath);
            }
        }
    }

    return $url;
}

/**
 * Staff profile image with href
 * @param  boolean $id        staff id
 * @param  array   $classes   image classes
 * @param  string  $type
 * @param  array   $img_attrs additional <img /> attributes
 * @return string
 */
function staff_profile_image($id, $classes = ['staff-profile-image'], $type = 'small', $img_attrs = [])
{
    $url = base_url('assets/images/user-placeholder.webp');

    $id = trim($id);

    $_attributes = '';
    foreach ($img_attrs as $key => $val) {
        $_attributes .= $key . '=' . '"' . html_escape($val) . '" ';
    }

    $blankImageFormatted = '<img loading="lazy" src="' . $url . '" ' . $_attributes . ' class="' . implode(' ', $classes) . '" />';

    if ((string) $id === (string) get_staff_user_id() && isset($GLOBALS['current_user'])) {
        $result = $GLOBALS['current_user'];
    } else {
        $CI = &get_instance();
        $result = $CI->app_object_cache->get('staff-profile-image-data-' . $id);

        if (!$result) {
            $CI->db->select('profile_image,firstname,lastname');
            $CI->db->where('staffid', $id);
            $result = $CI->db->get(db_prefix() . 'staff')->row();
            $CI->app_object_cache->add('staff-profile-image-data-' . $id, $result);
        }
    }

    if (!$result) {
        return $blankImageFormatted;
    }

    if ($result && $result->profile_image !== null) {
        $profileImagePath = 'uploads/staff_profile_images/' . $id . '/' . $type . '_' . $result->profile_image;
        if (file_exists($profileImagePath)) {
            $profile_image = '<img loading="lazy" ' . $_attributes . ' src="' . base_url($profileImagePath) . '" class="' . implode(' ', $classes) . '" />';
        } else {
            return $blankImageFormatted;
        }
    } else {
        $profile_image = '<img loading="lazy" src="' . $url . '" ' . $_attributes . ' class="' . implode(' ', $classes) . '" />';
    }

    return $profile_image;
}

/**
 * Get staff full name
 * @param  string $userid Optional
 * @return string Firstname and Lastname
 */
function staff_sms_content($template, $staff_id, $merge_fields = [])
{
    $CI = &get_instance();
    if (!class_exists('staff_merge_fields', false)) {
        $CI->load->library('merge_fields/staff_merge_fields');
    }
    if (!class_exists('other_merge_fields', false)) {
        $CI->load->library('merge_fields/other_merge_fields');
    }
    $merge_fields = array_merge($merge_fields, $CI->other_merge_fields->format());
    $merge_fields = array_merge($merge_fields, $CI->staff_merge_fields->format($staff_id));
    foreach ($merge_fields as $key => $val) {
        foreach (['message', 'fromname', 'subject'] as $section) {
            $template->{$section} = stripos($template->{$section}, $key) !== false
                ? str_replace($key, $val, $template->{$section})
                : str_replace($key, '', $template->{$section});
        }
    }
    return $template;
}
function get_staff_full_name_using_lead_addedfrom($ci, $id)
{
    if(empty($id)){
        return '';
    }
    // Convert the comma-separated $id string into an array
    $id_array = explode(',', $id);
    $ci->db->select('firstname, lastname');
    $ci->db->where_in('staffid', $id_array);
    $staff_data = $ci->db->get(db_prefix() . 'staff')->result();

    if ($staff_data) {
        $staff_names = [];
        foreach ($staff_data as $staff) {
            $staff_names[] = $staff->firstname . ' ' . $staff->lastname;
        }
        $staff_name_string = implode(', ', $staff_names);
        return $staff_name_string;
    } else {
        return '';
    }
}
function get_staff_full_name($userid = '')
{
    $tmpStaffUserId = get_staff_user_id();
    if ($userid == '' || $userid == $tmpStaffUserId) {
        if (isset($GLOBALS['current_user'])) {
            return $GLOBALS['current_user']->firstname . ' ' . $GLOBALS['current_user']->lastname;
        }
        $userid = $tmpStaffUserId;
    }

    $CI = &get_instance();

    $staff = $CI->app_object_cache->get('staff-full-name-data-' . $userid);

    if (!$staff) {
        $CI->db->where('staffid', $userid);
        $staff = $CI->db->select('firstname,lastname')->from(db_prefix() . 'staff')->get()->row();
        $CI->app_object_cache->add('staff-full-name-data-' . $userid, $staff);
    }

    return html_escape($staff ? $staff->firstname . ' ' . $staff->lastname : '');
}
function get_staff_role($ci, $roleid)
{
    $role_name = '';
    $ci->db->select('name');
    $ci->db->where('roleid', $roleid);
    $role_data = $ci->db->get(db_prefix() . 'roles');

    if ($role_data->num_rows() > 0) {
        $role_row = $role_data->row();
        $role_name = $role_row->name;
        return $role_name;
    } else {
        return null;
    }
}
function get_current_staff_role($ci, $staffid)
{
    if(empty($staffid)){
        return null;
    }
    $ci->db->select('role');
    $ci->db->where('staffid', $staffid);
    $role_data = $ci->db->get(db_prefix() . 'staff');
    if ($role_data->num_rows() > 0) {
        $role_row = $role_data->row();
        $roleid = $role_row->role;
        return $roleid;
    } else {
        return null;
    }
}
function get_current_staff_brokerage_id($ci, $staffid){
    if(empty($staffid)){
        return null;
    }
    $ci->db->select('brokerage_ids');
    $ci->db->where('staffid', $staffid);
    $role_data = $ci->db->get(db_prefix() . 'staff');
    if ($role_data->num_rows() > 0) {
        $role_row = $role_data->row();
        $brokerage_id = $role_row->brokerage_ids;
        return $brokerage_id;
    } else {
        return null;
    }
}
// get the brokerage id is mandatroy or not
function get_brokerage_mandatory_details($ci, $brokerage_id){
    if(empty($brokerage_id)){
        return 0;
    }
    $ci->db->select('mandatory');
    $ci->db->where('id', $brokerage_id);
    $mandatory_data = $ci->db->get(db_prefix() . 'brokerage');
    if ($mandatory_data->num_rows() > 0) {
        $mandatory_row = $mandatory_data->row();
        $mandatory = $mandatory_row->mandatory;
        return $mandatory;
    } else {
        return 0;
    }

}
function get_brokerage_name_using_brokerage_id($ci, $brokerage_id){
    if(empty($brokerage_id)){
        return '';
    }
    $ci->db->select('name');
    $ci->db->where('id', $brokerage_id);
    $brokerage_data = $ci->db->get(db_prefix() . 'brokerage');
    if ($brokerage_data->num_rows() > 0) {
        $row = $brokerage_data->row();
        return $row->name;
    } else {
        return '';
    }
}
// get the color of brokerage
function get_brokerage_color_using_brokerage_id($ci, $brokerage_id){
    if (empty($brokerage_id)) {
        return null;
    }
    $ci->db->select('color');
    $ci->db->from(db_prefix() . 'brokerage');
    $ci->db->where('id', $brokerage_id);
    $data = $ci->db->get()->row();
    return $data->color ?? '';
}
// get the group color by name
function get_groups_color_by_group_name($ci, $group_name){
    if (empty($group_name)) {
        return null;
    }
    $ci->db->select('group_color as color');
    $ci->db->from(db_prefix() . 'group');
    $ci->db->where('group_name', $group_name);
    $data = $ci->db->get()->row();
    return $data->color ?? '';
}
function get_groups_color_by_group_id($ci, $group_id){
    if (empty($group_id)) {
        return null;
    }
    $ci->db->select('group_color as color');
    $ci->db->from(db_prefix() . 'group');
    $ci->db->where('id', $group_id);
    $data = $ci->db->get()->row();
    return $data->color ?? '';
}
function get_all_staff_against_brokerage_id($ci, $brokerage_id) {
    if(empty($brokerage_id)){
        return null;
    }
    $ci->db->select('staffid, firstname, lastname, brokerage_ids, email');
    $ci->db->where('brokerage_ids', $brokerage_id);
    $query = $ci->db->get(db_prefix() . 'staff');
    if ($query->num_rows() > 0) {
        return $query->result_array();
    } else {
        return null;
    }
}

function get_staff_data_by_id($ci, $staffid)
{
    if(empty($staffid)){
        return null;
    }
    $ci->db->select('*');
    $ci->db->where('staffid', $staffid);
    $staff_data = $ci->db->get(db_prefix() . 'staff');
    if ($staff_data->num_rows() > 0) {
        $staff_row = $staff_data->row();
        return $staff_row;
    } else {
        return null;
    }
}

function get_staff_role_id($ci, $role_name)
{
    $role_id = '';
    $ci->db->select('roleid');
    $ci->db->where('name', $role_name);
    $role_data = $ci->db->get(db_prefix() . 'roles');

    if ($role_data->num_rows() > 0) {
        $role_row = $role_data->row();
        $role_id = $role_row->roleid;
        return $role_id;
    } else {
        return null;
    }
}
// get the all ld-team staff record
function get_ld_team_staff_record($ci){
    $ci->db->select('staffid,email,firstname,lastname,datecreated,profile_image,staff_group');
    $ci->db->where('role', '1');
    $ci->db->where('active', '1');
    $ld_staff = $ci->db->get(db_prefix() . 'staff')->result_array();
    return $ld_staff ?? null;
}
function get_group_name_of_staff($ci, $id)
{
    if(empty($id)){
        return '';
    }
    $staffgroup = '';

    $ci->db->select('staff_group');
    $ci->db->where('staffid', $id);
    $staff_data = $ci->db->get(db_prefix() . 'staff');

    if ($staff_data->num_rows() > 0) {
        $staff_row_data = $staff_data->row();
        $staffgroup = $staff_row_data->staff_group;
    } else {
        $staffgroup = '';
    }
    return $staffgroup;
}

function get_staff_profile_url($staffid, $staff_profile_image)
{
    $profile_image = empty($staff_profile_image) ? null : base_url('uploads/staff_profile_images/' . $staffid . '/thumb_' . $staff_profile_image);
    return $profile_image;
}

/**
 * Get staff default language
 * @param  mixed $staffid
 * @return mixed
 */
function get_staff_default_language($staffid = '')
{
    if (!is_numeric($staffid)) {
        // checking for current user if is admin
        if (isset($GLOBALS['current_user'])) {
            return $GLOBALS['current_user']->default_language;
        }

        $staffid = get_staff_user_id();
    }
    $CI = &get_instance();
    $CI->db->select('default_language');
    $CI->db->from(db_prefix() . 'staff');
    $CI->db->where('staffid', $staffid);
    $staff = $CI->db->get()->row();
    if ($staff) {
        return $staff->default_language;
    }

    return '';
}

function get_staff_recent_search_history($staff_id = null)
{
    $recentSearches = get_staff_meta($staff_id ? $staff_id : get_staff_user_id(), 'recent_searches');

    if ($recentSearches == '') {
        $recentSearches = [];
    } else {
        $recentSearches = json_decode($recentSearches);
    }

    return $recentSearches;
}

function update_staff_recent_search_history($history, $staff_id = null)
{
    $totalRecentSearches = hooks()->apply_filters('total_recent_searches', 5);
    $history = array_reverse($history);
    $history = array_unique($history);
    $history = array_splice($history, 0, $totalRecentSearches);

    update_staff_meta($staff_id ? $staff_id : get_staff_user_id(), 'recent_searches', json_encode($history));

    return $history;
}


/**
 * Check if user is staff member
 * In the staff profile there is option to check IS NOT STAFF MEMBER eq like contractor
 * Some features are disabled when user is not staff member
 * @param  string  $staff_id staff id
 * @return boolean
 */
function is_staff_member($staff_id = '')
{
    $CI = &get_instance();
    if ($staff_id == '') {
        if (isset($GLOBALS['current_user'])) {
            return $GLOBALS['current_user']->is_not_staff === '0';
        }
        $staff_id = get_staff_user_id();
    }

    $CI->db->where('staffid', $staff_id)
        ->where('is_not_staff', 0);

    return $CI->db->count_all_results(db_prefix() . 'staff') > 0 ? true : false;
}