<?php

namespace App\Models;

use CodeIgniter\Model;

class UserModel extends Model
{
    protected $table = 'm_users'; // Table name
    protected $primaryKey = 'user_id'; // Primary key

    // Fields that can be mass assigned
    protected $allowedFields = ['first_name','last_name','password','email','mobile_no','alternate_mobile_no','date_of_birth','address','gender','postal_code','country_code','employee_code','role_id','department_id','group_id','first_approver','first_approver_email','second_approver','second_approver_email','third_approver','third_approver_email','fourth_approver','fourth_approver_email','user_type','passport_number','place_of_issue','passport_document','passport_firstname','passport_middlename','passport_lastname','nationality','date_of_issue','date_of_expiry','created_on','created_by','updated_on','updated_by','is_active','org_id', 'temp_password', 'forex_pre_paid_card_number', 'emergency_contact_number', 'd_seat_preference', 'd_meal_preference', 'i_seat_preference', 'i_meal_preference', 'agent_supported_service_ids', 'd_additonalInfo', 'i_additonalInfo', 'forex_expiry_date', 'delegated_to_user_id', 'delegation_start_date', 'delegation_end_date','last_login_at','company_name','failed_attempts','lock_until','current_token'];

    // Specify the return type of the results
    protected $returnType = 'array';

    // Enable timestamps (if you wish to handle created_at and updated_at automatically)
    protected $useTimestamps = false; // Set true if using CI4 timestamp features

    // Custom method example (e.g., fetching active users)
    public function getUsers($org_id, $active, $role)
    {

        $data = $this->select('m_users.*, C.country_name ,  Dep.name as department_value , R.value as role_value, G.name as group_name')
                    ->join('m_country C', 'C.country_code = m_users.country_code ', 'left')
                    ->join('m_department Dep', 'Dep.department_id = m_users.department_id ', 'left')
                    ->join('m_role R', 'R.id = m_users.role_id', 'left')
                    ->join('m_group G', 'G.group_id = m_users.group_id', 'left')
                    ->whereIn('m_users.is_active', $active)
                    ->where('m_users.org_id', $org_id)
                    ->whereIn('m_users.role_id',$role)
                    ->orderBy('user_id', 'asc')
                    ->findAll();

        return $data;
    }

    public function getRole($id)
    {
        return $this->db->table('m_role')->select('value')->where('id',$id)->get()->getRow()->value;

    }


    public function getRolesList()
    {
        $roles = $this->db->table('m_role')->select('id, value')->get()->getResultArray();

        $cleaned = [];

        foreach ($roles as $role) {
            // Remove special characters and spaces, convert to lowercase
            $key = strtolower(preg_replace('/[^a-zA-Z0-9]/', '', $role['value']));
            $cleaned[$key] = $role['id'];
        }

        return $cleaned;
    }




    public function getGroupsList()
    {
        $groups = $this->db->table('m_group')->select('group_id, name')->get()->getResultArray();

        $cleaned = [];

        foreach ($groups as $group) {
            $name = strtolower(preg_replace('/[^a-zA-Z0-9]/', '', $group['name']));
            
            $cleaned[$name] = $group['group_id'];
        }

        return $cleaned;
    }





public function updateApprover(string $approverType, array $insertedIds)
{
    if (empty($insertedIds)) {
        return;
    }

    // Allowed types
    $validTypes = [
        'first'       => ['column' => 'first_approver', 'email' => 'first_approver_email'],
        'second'      => ['column' => 'second_approver', 'email' => 'second_approver_email'],
        'third'       => ['column' => 'third_approver', 'email' => 'third_approver_email'],
        'fourth' => ['column' => 'fourth_approver', 'email' => 'fourth_approver_email']
    ];

    $column = $validTypes[$approverType]['column'];
    $emailCol = $validTypes[$approverType]['email'];

    $placeholders = implode(',', array_fill(0, count($insertedIds), '?'));

    $sql = "
        UPDATE m_users AS target
        JOIN m_users AS ref ON ref.email = target.{$emailCol}
        SET target.{$column} = ref.user_id
        WHERE target.user_id IN ($placeholders)
    ";

    $this->db->query($sql, $insertedIds);

    log_message('info', "users {$approverType} approver updation count: " . $this->db->affectedRows());
}



    public function userExists($email){

        $result = $this->db->table('m_users mu')->select('mu.*')->where('mu.email',$email)->get()->getResultArray();

       return empty($result) ? false : true;

    }







}
