<?php

namespace App\Models\Chat;

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

class ChatDeparmentModel extends Model
{
    protected $table            = 'chat_departments';
    protected $primaryKey       = 'id';
    protected $useAutoIncrement = true;
    protected $returnType       = ChatDepartmentEntity::class;
    protected $useSoftDeletes   = true;
    protected $protectFields    = true;
    protected $allowedFields    = [
        "name",
        "display",
        "description",
        "type"
    ];

    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 getChatDepartments(string $type = "general"): array
    {
        $userModel = model(UserModel::class);
        $chatModel = model(ChatModel::class);

        $query = $this->builder()
            ->select(
                [

                    'chat_departments.id',
                    'chat_departments.name',
                    'chat_departments.display',
                    'chat_department_users.user_id',
                ]
            )
            ->join(
                "chat_department_users",
                "chat_department_users.chat_department_id = chat_departments.id",
                'left'
            )
            ->join(
                "users",
                "chat_department_users.user_id = users.id",
                'left'
            )
            ->where("chat_departments.type", $type);


        // if (auth()->user()->cliente_id == null) {
        //     $query->where("chat_department_users.user_id", auth()->user()->id);
        // }

        $results = $query->get()->getResultArray();
        // Create the desired structure
        $departments = [];
        foreach ($results as $row) {
            $departmentName = $row['name'];
            // If the department is not yet added to the array, initialize it
            if (!isset($departments[$departmentName])) {

                $departments[$departmentName] = [
                    'id' => $row['id'],
                    'name' => $row['name'],
                    'display' => $row['display'],
                    'users' => [] // Initialize users as an empty array
                ];
            }

            // If user_id is not null, add the user to the department's 'users' array
            if ($row['user_id']) {
                $departments[$departmentName]['users'][] = $userModel->find($row["user_id"]);
            }
        }
        return $departments;
    }

    public function getChatDeparmentUserQuery(int $chat_deparment_id)
    {
        $query = $this
            ->select(
                [
                    "users.*"
                ]
            )
            ->join(
                "chat_department_users",
                "chat_department_users.chat_department_id = chat_departments.id",
                'left'
            )
            ->join(
                "users",
                "chat_department_users.user_id = users.id",
                'left'
            )
            ->where("chat_department_users.chat_department_id", $chat_deparment_id)
            ->where("chat_department_users.deleted_at",null)
            ->where("users.deleted_at",null);
        return $query;
    }
    public function getChatDepartmentUsers(int $chat_deparment_id)
    {
        $result = $this->getChatDeparmentUserQuery($chat_deparment_id)
            ->where('chat_department_users.presupuesto_id',null)
            ->where('chat_department_users.pedido_id',null)
            ->where('chat_department_users.factura_id',null)
            ->where('chat_department_users.orden_trabajo_id',null)
            ->get();
            
        return $result->getResultObject() ?: [];
    }
    public function getChatDeparmentPresupuestoUsers(int $chat_deparment_id, int $presupuesto_id)
    {
        $result = $this->getChatDeparmentUserQuery($chat_deparment_id)
            ->where('chat_department_users.presupuesto_id', $presupuesto_id)
            ->get()->getResultObject();
        return $result;
    }
    public function getChatDeparmentPedidoUsers(int $chat_deparment_id, int $pedido_id)
    {
        $result = $this->getChatDeparmentUserQuery($chat_deparment_id)
            ->where('chat_department_users.pedido_id', $pedido_id)
            ->get()->getResultObject();
        return $result;
    }
    public function getChatDeparmentFacturaUsers(int $chat_deparment_id, int $factura_id)
    {
        $result = $this->getChatDeparmentUserQuery($chat_deparment_id)
            ->where('chat_department_users.factura_id', $factura_id)
            ->get()->getResultObject();
        return $result;
    }
    public function getChatDeparmentOrdenTrabajoUsers(int $chat_deparment_id, int $orden_trabajo_id)
    {
        $result = $this->getChatDeparmentUserQuery($chat_deparment_id)
            ->where('chat_department_users.orden_trabajo_id', $orden_trabajo_id)
            ->get()->getResultObject();
        return $result;
    }
    public function getDisplay(int $chat_deparment_id): string
    {
        return $this->find($chat_deparment_id)->display;
    }
    public function getChatDepartmentSelect(?string $query)
    {
        $q =  $this->builder()->select([
            "id",
            "display as name",
            "description"
        ]);
        if ($query) {
            $q->orLike("display", $query)
                ->orLike("name", $query);
        }
        return $q;
    }
    public function datatableQuery()
    {
        return $this->select(['id','display','description'])->where('deleted_at',null);
    }

    public function getModelChatDepartments(string $modelFk,int $modelId) : array
    {
        $query = $this->builder()->select([
            'chat_departments.id',
            'chat_departments.name',
            'chat_departments.display',
            'COUNT(chat_messages.id) as countMessages'
        ])
        ->join('chats','chats.chat_department_id = chat_departments.id','left')
        ->join('chat_messages','chat_messages.chat_id = chats.id','left')
        ->where($modelFk,$modelId)
        ->groupBy('chat_departments.name');
        return $query->get()->getResultArray() ?? [];

    }
}
