<?php

namespace App\Models;

use CodeIgniter\Model;

class Users extends Model
{
    /**
     * table users name
     * @var string
     */
    protected $table = 'users';
    protected $allowedFields = ['username', 'password', 'email', 'firstname', 'lastname', 'phone', 'gender', 'store_id'];

    /**
     * function used when user try to login
     * @param string $email
     * @param string $password
     * @return array|bool|object
     */
    public function attempt(string $email, string $password, $isOutside = null)
    {
        $user = $this->select('users.*, groups.id as group_id, groups.group_name, groups.permission')
            ->join('user_group', 'user_group.user_id = users.id', 'left')
            ->join('groups', 'groups.id = user_group.group_id', 'left')
            ->where('users.email', $email)
            ->first();

        // Verify password
        if ($isOutside != null) {
            if ($user) {
                return $user; // Return user details with group info
            }
        } else {
            if ($user && password_verify($password, $user['password'])) {
                return $user; // Return user details with group info
            }
        }

        return false; // Return false if authentication fails
    }


    /**
     * get user by id
     * @param int $userId
     * @return array|object|null
     */
    public function getUserData(int $userId = null)
    {
        if ($userId) {
            return $this->where('id', $userId)->first();
        }

        return $this->where('id !=', 1)->findAll();
    }

    public function getUsersByGroup()
    {
        return $this->select('users.*')
            ->join('user_group', 'user_group.user_id = users.id')
            ->join('groups', 'user_group.group_id = groups.id')
            ->where('groups.group_name', 'COMMERCIALE')
            ->findAll(); // Get all matching users
    }
    public function getSecurityAgents()
    {
        return $this->select('users.id, users.firstname, users.lastname, CONCAT(users.firstname, " ", users.lastname) as full_name')
            ->join('user_group', 'user_group.user_id = users.id', 'left')
            ->join('groups', 'groups.id = user_group.group_id', 'left')
            ->where('groups.group_name', 'SECURITE')
            ->where('users.active', 1) // Uniquement les utilisateurs actifs
            ->orderBy('users.firstname', 'ASC')
            ->findAll();
    }

    /**
     * ✅ MÉTHODE GÉNÉRIQUE : Récupérer les utilisateurs par groupe
     */
    public function getUsersByGroupName($groupName)
    {
        return $this->select('users.id, users.firstname, users.lastname, users.email, users.store_id, CONCAT(users.firstname, " ", users.lastname) as full_name, groups.group_name')
            ->join('user_group', 'user_group.user_id = users.id', 'left')
            ->join('groups', 'groups.id = user_group.group_id', 'left')
            ->where('groups.group_name', strtoupper($groupName))
            ->where('users.active', 1)
            ->orderBy('users.firstname', 'ASC')
            ->findAll();
    }

    /**
     * get grouped user by id
     * @param mixed $userId
     * @return array|null
     */
    public function getUserGroup($userId = null)
    {
        if ($userId) {
            $userGroup = $this->db->table('user_group')->where('user_id', $userId)->get()->getRowArray();

            if ($userGroup) {
                $groupId = $userGroup['group_id'];
                return $this->db->table('groups')->where('id', $groupId)->get()->getRowArray();
            }
        }

        return null;
    }

    public function getUsers()
    {
        return $this->select('users.*, groups.id as group_id, groups.group_name, groups.permission')
            ->join('user_group', 'user_group.user_id = users.id', 'left')
            ->join('groups', 'groups.id = user_group.group_id', 'left')
            ->where('groups.group_name', \strtoupper('MECANICIEN'))
            ->findAll(); // Returns all users
    }

    /**
     * create users
     * @param mixed $data
     * @param mixed $groupId
     * @return bool
     */
    public function create($data = '', $groupId = null)
    {
        if ($data && $groupId) {
            $this->db->table('users')->insert($data);
            $userId = $this->db->insertID();

            $groupData = [
                'user_id' => $userId,
                'group_id' => $groupId
            ];

            $this->db->table('user_group')->insert($groupData);

            return true;
        }

        return false;
    }

    /**
     * edit users
     * @param mixed $data
     * @param mixed $id
     * @param mixed $groupId
     * @return bool
     */
    public function edit($data = [], $id = null, $groupId = null)
    {
        if ($id) {
            $this->db->table('users')->where('id', $id)->update($data);

            if ($groupId) {
                $this->db->table('user_group')->where('user_id', $id)->update(['group_id' => $groupId]);
            }

            return true;
        }

        return false;
    }

    /**
     * Assigner un utilisateur à un magasin
     * 
     * @param int|null $userid  ID de l'utilisateur
     * @param int|null $storeid ID du magasin
     * @return bool Résultat de l'opération (true si success, false sinon)
     */
    public function assignToStore($userid = null, $storeid = null)
    {
        // Vérifie si l'utilisateur et le magasin sont fournis
        if (!is_null($userid) && !is_null($storeid)) {
            // Mise à jour du champ store_id pour l'utilisateur spécifié
            // die(var_dump($this->db->table('users')
            // ->where('id', $userid)
            // ->update(['store_id' => $storeid])));
            $this->db->table('users')
                ->where('id', $userid)
                ->update(['store_id' => $storeid]);

            return true;
        }

        // Si $userid ou $storeid est null, l'opération échoue
        return false;
    }


    /**
     * delete users
     * @param mixed $id
     * @return bool
     */
    public function deletes($id)
    {
        if ($id) {
            $this->db->table('users')->where('id', $id)->delete();
            return true;
        }

        return false;
    }

    // To count the total number of users
    public function countTotalUsers()
    {
        return $this->countAllResults();
    }

    public function getUserWithGroupName(int $userId = null)
{
    if ($userId === null) {
        return null;
    }

    $builder = $this->db
        ->table('users AS u')
        ->select([
            'g.group_name AS group_name',
        ])
        ->join('user_group AS ug', 'ug.user_id = u.id')
        ->join('groups AS g', 'g.id = ug.group_id')
        ->where('u.id', $userId);

    return $builder->get()->getRowArray(); // ✅ Il faut retourner les données
}
public function getUserDataForAssign(int $userId)
{
    $builder = $this->db->table('users u');
    $builder->select('u.id, u.firstname, u.lastname, u.store_id, s.name as store_name, g.group_name');
    $builder->join('stores s', 's.id = u.store_id', 'left');
    $builder->join('user_group ug', 'ug.user_id = u.id', 'left');
    $builder->join('groups g', 'g.id = ug.group_id', 'left');
    $builder->where('u.id', $userId);
    $query = $builder->get();
    return $query->getRowArray();
}


}
