<?php

namespace App\Models\Chat;

use App\Entities\Chat\ChatDepartmentUserEntity;
use App\Models\Usuarios\UserModel;
use CodeIgniter\Model;

class ChatDeparmentUserModel extends Model
{
    protected $table            = 'chat_department_users';
    protected $primaryKey       = 'id';
    protected $useAutoIncrement = true;
    protected $returnType       = ChatDepartmentUserEntity::class;
    protected $useSoftDeletes   = true;
    protected $protectFields    = true;
    protected $allowedFields    = [
        "chat_department_id",
        "user_id",
        "pedido_id",
        "factura_id",
        "presupuesto_id",
        "orden_trabajo_id",

    ];

    protected bool $allowEmptyInserts = false;
    protected bool $updateOnlyChanged = true;

    protected array $casts = [];
    protected array $castHandlers = [];

    // Dates
    protected $useTimestamps = false;
    protected $dateFormat    = 'datetime';
    protected $createdField  = 'created_at';
    protected $updatedField  = 'updated_at';
    protected $deletedField  = 'deleted_at';

    // Validation
    protected $validationRules      = [];
    protected $validationMessages   = [];
    protected $skipValidation       = false;
    protected $cleanValidationRules = true;

    // Callbacks
    protected $allowCallbacks = true;
    protected $beforeInsert   = [];
    protected $afterInsert    = [];
    protected $beforeUpdate   = [];
    protected $afterUpdate    = [];
    protected $beforeFind     = [];
    protected $afterFind      = [];
    protected $beforeDelete   = [];
    protected $afterDelete    = [];

    public function getChatDepartmentUser(int $user_id)
    {
        return $this->db->table($this->table . " t1")
            ->select("chat_departments.*")
            ->join("chat_departments", "t1.chat_department_id = chat_departments.id", "left")
            ->where("t1.user_id", $user_id)
            ->where("t1.deleted_at", null)
            ->get()->getResultObject();
    }
    public function datatableQuery(int $chat_department_id)
    {
        return $this->builder()->select(
            [
                'users.id as userId',
                'CONCAT(users.first_name," ",users.last_name) as userFullName',
                'users.username'
            ]
        )
            ->join('users', 'users.id = chat_department_users.user_id', 'left')
            ->join('chat_departments', 'chat_departments.id = chat_department_users.chat_department_id', 'left')
            ->where('chat_departments.id', $chat_department_id)
            ->where('chat_department_users.pedido_id', null)
            ->where('chat_department_users.presupuesto_id', null)
            ->where('chat_department_users.factura_id', null)
            ->where('chat_department_users.deleted_at', null);
    }
    public function querySelectUsersNotInDepartment(int $chat_department_id, ?string $q): array
    {
        $query =  $this->builder()->select([
            'users.id as userId',
        ])
            ->join('users', 'users.id = chat_department_users.user_id', 'left')
            ->join('chat_departments', 'chat_departments.id = chat_department_users.chat_department_id', 'left')
            ->where('chat_departments.id', $chat_department_id)
            ->where('chat_department_users.deleted_at', null);

        $usersInDepartment = array_map(fn($q) => $q->userId, $query->get()->getResultObject());
        $userModel = model(UserModel::class);
        $queryUser = $userModel->builder()->select([
            'id',
            'CONCAT(first_name," ",last_name) as name',
            'username as description',
        ])
            ->where('cliente_id',null)
            ->where('deleted_at', null);
        if ($usersInDepartment) {
            $queryUser->whereNotIn("id", $usersInDepartment);
        }
        if ($q) {
            $queryUser->like('CONCAT(first_name," ",last_name)', $q);
        }
        return $queryUser->get()->getResultArray();
    }
}
