<?php

namespace App\Controllers\Chat;

use App\Controllers\BaseController;
use App\Models\Chat\ChatDeparmentModel;
use App\Models\Chat\ChatDeparmentUserModel;
use App\Models\Chat\ChatMessageModel;
use App\Models\Chat\ChatModel;
use App\Models\ChatNotification;
use App\Models\ChatUser;
use App\Models\Clientes\ClienteModel;
use App\Models\Facturas\FacturaModel;
use App\Models\OrdenTrabajo\OrdenTrabajoModel;
use App\Models\Pedidos\PedidoModel;
use App\Models\Presupuestos\PresupuestoModel;
use App\Models\Usuarios\UserModel;
use App\Services\ChatService;
use App\Services\MessageService;
use CodeIgniter\HTTP\ResponseInterface;
use CodeIgniter\HTTP\RequestInterface;
use CodeIgniter\Log\Logger;
use Psr\Log\LoggerInterface;
use Hermawan\DataTables\DataTable;
use CodeIgniter\I18n\Time;
use CodeIgniter\Validation\Validation;

class ChatController extends BaseController
{
    protected ChatDeparmentModel $chatDeparmentModel;
    protected ChatDeparmentUserModel $chatDeparmentUserModel;
    protected ChatModel $chatModel;
    protected ChatMessageModel $chatMessageModel;
    protected UserModel $userModel;
    protected ClienteModel $clienteModel;
    protected ChatUser $chatUserModel;
    protected ChatNotification $chatNotificationModel;
    protected Validation $validation;
    protected ChatService $chatService;
    protected array $viewData;
    protected static $viewPath = 'themes/vuexy/form/mensajes/';


    public function initController(
        RequestInterface $request,
        ResponseInterface $response,
        LoggerInterface $logger
    ) {
        parent::initController($request, $response, $logger);

        // Add your code here.
        $this->chatDeparmentModel = model(ChatDeparmentModel::class);
        $this->chatDeparmentUserModel = model(ChatDeparmentUserModel::class);
        $this->chatModel = model(ChatModel::class);
        $this->chatMessageModel = model(ChatMessageModel::class);
        $this->userModel = model(UserModel::class);
        $this->clienteModel = model(ClienteModel::class);
        $this->chatUserModel = model(ChatUser::class);
        $this->chatNotificationModel = model(ChatNotification::class);
        $this->validation = service("validation");
        $this->chatService = service("chat");

    }
    public function index() {}
    public function get_chat_departments(string $model,int $modelId)
    {

        $data = $this->chatService->getChatDepartments($model,$modelId);

        return $this->response->setJSON($data);
    }
    public function get_chat_department_select()
    {
        $query = $this->chatDeparmentModel->getChatDepartmentSelect($this->request->getGet("q"));
        return $this->response->setJSON($query->get()->getResultObject());
    }
    public function get_chat_presupuesto(int $chat_department_id, int $presupuesto_id)
    {

        $data = [
            "department" => $this->chatDeparmentModel->find($chat_department_id),
            "chat" => null,
            "messages" => null,
            "count" => 0,
        ];
        $chat = $this->chatModel->getChatPresupuesto($chat_department_id, $presupuesto_id);
        if ($chat) {
            $data["messages"] = $this->chatMessageModel->get_chat_messages($chat->id);
            $this->chatMessageModel->set_chat_department_messages_as_read($chat->id);
            $this->chatModel->setAsViewedChatUserNotifications($chat->id, auth()->user()->id);

            $data["count"] = count($data["messages"]);
        }
        $data["chat"] = $chat;
        return $this->response->setJSON($data);
    }
    public function get_chat_pedido(int $chat_department_id, int $pedido_id)
    {

        $data = [
            "department" => $this->chatDeparmentModel->find($chat_department_id),
            "chat" => null,
            "messages" => null,
            "count" => 0,
        ];
        $chat = $this->chatModel->getChatPedido($chat_department_id, $pedido_id);
        if ($chat) {
            $data["messages"] = $this->chatMessageModel->get_chat_messages($chat->id);
            $this->chatMessageModel->set_chat_department_messages_as_read($chat->id);
            $this->chatModel->setAsViewedChatUserNotifications($chat->id, auth()->user()->id);

            $data["count"] = count($data["messages"]);
        }
        $data["chat"] = $chat;
        return $this->response->setJSON($data);
    }
    public function get_chat_factura(int $chat_department_id, int $factura_id)
    {

        $data = [
            "department" => $this->chatDeparmentModel->find($chat_department_id),
            "chat" => null,
            "messages" => null,
            "count" => 0,
        ];
        $chat = $this->chatModel->getChatFactura($chat_department_id, $factura_id);
        if ($chat) {
            $data["messages"] = $this->chatMessageModel->get_chat_messages($chat->id);
            $this->chatMessageModel->set_chat_department_messages_as_read($chat->id);
            $this->chatModel->setAsViewedChatUserNotifications($chat->id, auth()->user()->id);
            $data["count"] = count($data["messages"]);
        }
        $data["chat"] = $chat;
        return $this->response->setJSON($data);
    }
    public function get_chat_orden_trabajo(int $chat_department_id, int $orden_trabajo_id)
    {

        $data = [
            "department" => $this->chatDeparmentModel->find($chat_department_id),
            "chat" => null,
            "messages" => null,
            "count" => 0,
        ];
        $chat = $this->chatModel->getChatOrdenTrabajo($chat_department_id, $orden_trabajo_id);
        if ($chat) {
            $data["messages"] = $this->chatMessageModel->get_chat_messages($chat->id);
            $this->chatMessageModel->set_chat_department_messages_as_read($chat->id);
            $this->chatModel->setAsViewedChatUserNotifications($chat->id, auth()->user()->id);
            $data["count"] = count($data["messages"]);
        }
        $data["chat"] = $chat;
        return $this->response->setJSON($data);
    }
    public function get_chat_direct_view($chat_id)
    {
        $chat = $this->chatModel->find($chat_id);
        $this->viewData['breadcrumb'] = [
            ['title' => lang("Chat.chat"), 'route' => route_to("mensajeriaView"), 'active' => false],
            ['title' => $chat->title, 'route' => 'javascript:void(0);', 'active' => true]
        ];
        $this->viewData["chatId"] = $chat_id;
        $auth_user = auth()->user();
        $this->chatModel->setAsViewedChatUserNotifications($chat_id, $auth_user->id);
        $this->chatModel->setAsUnviewedChatUserMessages($chat_id, $auth_user->id);

        return view(static::$viewPath . 'messageChat', $this->viewData);
    }
    public function get_chat_presupuesto_view($chat_id)
    {
        $chat = $this->chatModel->find($chat_id);
        $this->viewData['breadcrumb'] = [
            ['title' => lang("Chat.chat"), 'route' => route_to("mensajeriaView"), 'active' => false],
            ['title' => $chat->title, 'route' => 'javascript:void(0);', 'active' => true]
        ];
        $this->viewData["modelId"] = $chat->presupuesto_id;
        $this->viewData["type"] = "presupuesto";
        $auth_user = auth()->user();
        $this->chatModel->setAsViewedChatUserNotifications($chat_id, $auth_user->id);
        $this->chatModel->setAsUnviewedChatUserMessages($chat_id, $auth_user->id);

        if ($chat->chat_department_id) {
            return view(static::$viewPath . 'messageChatPresupuesto', $this->viewData);
        } else {
            return view(static::$viewPath . 'messageChatInternal', $this->viewData);
        }
    }
    public function get_chat_pedido_view($chat_id)
    {
        $chat = $this->chatModel->find($chat_id);
        $this->viewData['breadcrumb'] = [
            ['title' => lang("Chat.chat"), 'route' => route_to("mensajeriaView"), 'active' => false],
            ['title' => $chat->title, 'route' => 'javascript:void(0);', 'active' => true]
        ];
        $this->viewData["modelId"] = $chat->pedido_id;
        $this->viewData["type"] = "pedido";
        $auth_user = auth()->user();
        $this->chatModel->setAsViewedChatUserNotifications($chat_id, $auth_user->id);
        $this->chatModel->setAsUnviewedChatUserMessages($chat_id, $auth_user->id);
        if ($chat->chat_department_id) {
            return view(static::$viewPath . 'messageChatPedido', $this->viewData);
        } else {
            return view(static::$viewPath . 'messageChatInternal', $this->viewData);
        }
    }
    public function get_chat_factura_view($chat_id)
    {
        $chat = $this->chatModel->find($chat_id);
        $this->viewData['breadcrumb'] = [
            ['title' => lang("Chat.chat"), 'route' => route_to("mensajeriaView"), 'active' => false],
            ['title' => $chat->title, 'route' => 'javascript:void(0);', 'active' => true]
        ];
        $this->viewData["modelId"] = $chat->factura_id;
        $this->viewData["type"] = "factura";
        $auth_user = auth()->user();
        $this->chatModel->setAsViewedChatUserNotifications($chat_id, $auth_user->id);
        $this->chatModel->setAsUnviewedChatUserMessages($chat_id, $auth_user->id);

        if ($chat->chat_department_id) {
            return view(static::$viewPath . 'messageChatFactura', $this->viewData);
        } else {
            return view(static::$viewPath . 'messageChatInternal', $this->viewData);
        }
    }
    public function get_chat(int $chat_id)
    {

        $data = $this->chatModel->getChat($chat_id);
        return $this->response->setJSON($data);
    }
    public function store_message($model)
    {
        $data = $this->request->getPost();
        $chatMessageEntity = $this->chatService->storeChatMessage($data["chat_department_id"],$model,$data["model_id"],$data);
        return $this->response->setJSON($chatMessageEntity);

    }

    public function store_chat_message_single()
    {
        $data = $this->request->getPost();

        $existChat = $this->chatMessageModel->get_chat_contact_messages($data["receiver_id"]);
        if (count($existChat) > 0) {
            $chatId = $existChat[0]->chat_id;
        } else {
            $chatId = $this->chatModel->createChatSingle();
        }
        $chat_message_id = $this->chatMessageModel->insert(
            [
                "chat_id" => $chatId,
                "sender_id" => auth()->user()->id,
                "message" => $data["message"],
                "receiver_id" => $data["receiver_id"],
            ]
        );
        $this->chatNotificationModel->insert(["chat_message_id" => $chat_message_id, "user_id" => $data["receiver_id"]]);
        $dataResponse = $this->chatMessageModel->find($chat_message_id);
        return $this->response->setJSON($dataResponse);
    }
    public function get_chat_internal_contacts()
    {
        $auth_user = auth()->user();
        if ($auth_user->cliente_id) {
            $users = $this->chatModel->getOpenChatCliente($auth_user->id);
        } else {
            $users = $this->userModel->builder()
                ->whereNotIn("id", [$auth_user->id])
                ->where("deleted_at", null)
                ->get()->getResultObject();
        }
        foreach ($users as $user) {
            $user->unreadMessages = $this->chatMessageModel->get_chat_messages_count($user->id);
        }
        usort($users, fn($a, $b) => $a->unreadMessages < $b->unreadMessages);
        return $this->response->setJSON($users);
    }
    public function get_chat_internal_contact(int $user_id)
    {
        $auth_user = auth()->user();
        // if ($auth_user->cliente_id) {
        //     return $this->response->setJSON([]);
        // }
        $users = $this->userModel->builder()
            ->where("deleted_at", null)
            ->where("id", $user_id)
            ->get()->getFirstRow();
        return $this->response->setJSON($users);
    }
    public function get_chat_internal_messages(int $user_id)
    {
        $conversation = $this->chatMessageModel->get_chat_contact_messages($user_id);

        return $this->response->setJSON($conversation);
    }
    public function get_chat_cliente()
    {
        $cliente_id = auth()->user()->cliente_id;
        $response = $this->chatService->getAuthUserNotifications();
        return $this->response->setJSON($response);
    }

    public function get_chat_department_presupuesto_users(int $chat_department_id, int $presupuesto_id)
    {
        $data = $this->chatDeparmentModel->find($chat_department_id)->withUsers($presupuesto_id, 'presupuesto');
        return $this->response->setJSON($data);
    }
    public function get_chat_department_pedido_users(int $chat_department_id, $pedido_id)
    {
        $data = $this->chatDeparmentModel->find($chat_department_id)->withUsers($pedido_id, 'pedido');
        return $this->response->setJSON($data);
    }
    public function get_chat_department_factura_users(int $chat_department_id, $factura_id)
    {
        $data = $this->chatDeparmentModel->find($chat_department_id)->withUsers($factura_id, 'factura');
        return $this->response->setJSON($data);
    }
    public function get_chat_department_orden_trabajo_users(int $chat_department_id, $orden_trabajo_id)
    {
        $data = $this->chatDeparmentModel->find($chat_department_id)->withUsers($orden_trabajo_id, 'ot');
        return $this->response->setJSON($data);
    }
    public function get_chat_users_internal()
    {
        $query = $this->userModel->builder()->select(
            [
                "id",
                "CONCAT(first_name,' ',last_name,'(',username,')') as name"
            ]
        )->where("cliente_id", null)
            ->where("deleted_at", null)
            ->whereNotIn("id", [auth()->user()->id]);
        if ($this->request->getGet("q")) {
            $query->groupStart()
                ->orLike("users.username", $this->request->getGet("q"))
                ->orLike("CONCAT(first_name,' ',last_name)", $this->request->getGet("q"))
                ->groupEnd();
        }

        return $this->response->setJSON($query->get()->getResultObject());
    }
    public function get_chat_users_all()
    {
        $query = $this->userModel->builder()->select(
            [
                "id",
                "CONCAT(first_name,' ',last_name,'(',username,')') as name"
            ]
        )
            ->where("deleted_at", null)
            ->whereNotIn("id", [auth()->user()->id]);
        if ($this->request->getGet("q")) {
            $query->groupStart()
                ->orLike("users.username", $this->request->getGet("q"))
                ->orLike("CONCAT(first_name,' ',last_name)", $this->request->getGet("q"))
                ->groupEnd();
        }

        return $this->response->setJSON($query->get()->getResultObject());
    }
    public function get_presupuesto_client_users(int $presupuesto_id)
    {
        $pm = model(PresupuestoModel::class);
        $p = $pm->find($presupuesto_id);
        $cm = model(ClienteModel::class);
        $clienteContactos = $cm->querySelectClienteContacto($p->cliente_id,$this->request->getGet('q'));
        return $this->response->setJSON($clienteContactos);
    }
    public function get_pedido_client_users(int $pedido_id)
    {
        $pm = model(PedidoModel::class);
        $p = $pm->find($pedido_id);
        $cm = model(ClienteModel::class);
        $clienteContactos = $cm->querySelectClienteContacto($p->cliente()->id,$this->request->getGet('q'));
        return $this->response->setJSON($clienteContactos);
    }
    public function get_factura_client_users(int $factura_id)
    {
        $fm = model(FacturaModel::class);
        $f = $fm->find($factura_id);
        $cm = model(ClienteModel::class);
        $clienteContactos = $cm->querySelectClienteContacto($f->cliente_id,$this->request->getGet('q'));
        return $this->response->setJSON($clienteContactos);
    }
    public function get_orden_trabajo_client_users(int $orden_trabajo_id)
    {
        $otm = model(OrdenTrabajoModel::class);
        $ot = $otm->find($orden_trabajo_id);
        $cm = model(ClienteModel::class);
        $cliente = $ot->pedido()->cliente();
        $clienteContactos = $cm->querySelectClienteContacto($cliente->id,$this->request->getGet('q'));
        return $this->response->setJSON($clienteContactos);
    }
    public function store_hebra(string $model)
    {
        $auth_user = auth()->user();
        $bodyData = $this->request->getPost();
        $status = $this->chatService->storeHebra($model,$bodyData['modelId'],$bodyData);
        return $this->response->setJSON(["message" => "Hebra creada correctamente", "status" => $status]);
    }

    public function update_hebra($chat_id)
    {
        $bodyData = $this->request->getPost();
        $chatMessageId =  $this->chatMessageModel->insert([
            "chat_id" => $chat_id,
            "message" => $bodyData["message"],
            "sender_id" => auth()->user()->id
        ]);
        $actualUsers = $this->chatUserModel->builder()->select("user_id")->where("chat_id", $chat_id)->get()->getResultArray();
        $actualUsersArray = array_map(fn($x) => $x["user_id"], $actualUsers);

        if (isset($bodyData["users"])) {
            foreach ($bodyData["users"] as $userId) {
                if (in_array($userId, $actualUsersArray) == false) {
                    $chatUserData = ["user_id" => $userId, "chat_id" => $chat_id];
                    $this->chatUserModel->insert($chatUserData);
                }
                $this->chatNotificationModel->insert(
                    ["chat_message_id" => $chatMessageId, "user_id" => $userId]
                );
            }
        }
        return $this->response->setJSON(["message" => "Hebra actualizada correctamente", "status" => true]);
    }
    public function get_hebra(string $model,int $modelId)
    {
        $data = $this->chatService->getHebras($model,$modelId);
        return $this->response->setJSON($data);
    }


    public function datatable_messages()
    {
        $auth_user_id = auth()->user()->id;
        $isAdmin = auth()->user()->inGroup('admin');
        $query = $this->chatModel->getQueryDatatable();
        return DataTable::of($query)
            ->edit('created_at', fn($q) => Time::createFromFormat('Y-m-d H:i:s', $q->created_at)->format("d/m/Y H:i"))
            ->edit('updated_at', fn($q) => Time::createFromFormat('Y-m-d H:i:s', $q->updated_at)->format("d/m/Y H:i"))
            ->edit("creator",fn($q) => $q->userId == $auth_user_id ? '<span class="badge text-bg-success w-100">'.lang("App.me").'</span>' : $q->creator)
            ->add("viewed", fn($q) =>  $this->chatModel->isMessageChatViewed($q->id, $auth_user_id))
            ->add("action", fn($q) => [
                "type" => "direct",
                "modelId" => $q->id,
                "isAdmin" => $isAdmin,
                "chatMessageId" => $q->chatMessageId,
                "lang" => [
                    "view_chat" => lang('Chat.view_chat'),
                    "view_by_alt_message" => lang('Chat.view_by_alt_message')
                ]
            ])
            ->toJson(true);
    }
    public function datatable_presupuesto_messages()
    {
        $auth_user_id = auth()->user()->id;
        $isAdmin = auth()->user()->inGroup('admin');
        $query = $this->chatModel->getQueryDatatableMessagePresupuesto($auth_user_id);
        return DataTable::of($query)
            ->edit('created_at', fn($q) => $q->created_at ? Time::createFromFormat('Y-m-d H:i:s', $q->created_at)->format("d/m/Y H:i") : "")
            ->edit('updated_at', fn($q) => $q->updated_at ? Time::createFromFormat('Y-m-d H:i:s', $q->updated_at)->format("d/m/Y H:i") : "")
            ->add("viewed", fn($q) =>  $this->chatModel->isMessageChatViewed($q->chatMessageId))
            ->edit("creator",fn($q) => $q->userId == $auth_user_id ? '<span class="badge text-bg-success w-100">'.lang("App.me").'</span>' : $q->creator)
            ->add("action", fn($q) => ["type" => "presupuesto", "modelId" => $q->id, "isAdmin" => $isAdmin,"chatMessageId" => $q->chatMessageId, "lang" => [
                "view_chat" => lang('Chat.view_chat'),
                "view_by_alt_message" => lang('Chat.view_by_alt_message')
            ]])
            ->toJson(true);
    }
    public function datatable_pedido_messages()
    {
        $auth_user_id = auth()->user()->id;
        $isAdmin = auth()->user()->inGroup('admin');
        $query = $this->chatModel->getQueryDatatableMessagePedido($auth_user_id);
        return DataTable::of($query)
            ->edit('created_at', fn($q) => $q->created_at ? Time::createFromFormat('Y-m-d H:i:s', $q->created_at)->format("d/m/Y H:i") : "")
            ->edit('updated_at', fn($q) => $q->updated_at ? Time::createFromFormat('Y-m-d H:i:s', $q->updated_at)->format("d/m/Y H:i") : "")
            ->edit("creator",fn($q) => $q->userId == $auth_user_id ? '<span class="badge text-bg-success w-100">'.lang("App.me").'</span>' : $q->creator)
            ->add("viewed", fn($q) =>  $this->chatModel->isMessageChatViewed($q->chatMessageId))
            ->add("action", fn($q) => ["type" => "pedido", "modelId" => $q->id, "isAdmin" => $isAdmin,"chatMessageId" => $q->chatMessageId, "lang" => [
                "view_chat" => lang('Chat.view_chat'),
                "view_by_alt_message" => lang('Chat.view_by_alt_message')
            ]])

            ->toJson(true);
    }
    public function datatable_factura_messages()
    {
        $auth_user_id = auth()->user()->id;
        $isAdmin = auth()->user()->inGroup('admin');
        $query = $this->chatModel->getQueryDatatableMessageFactura($auth_user_id);
        return DataTable::of($query)
            ->edit('created_at', fn($q) => $q->created_at ? Time::createFromFormat('Y-m-d H:i:s', $q->created_at)->format("d/m/Y H:i") : "")
            ->edit('updated_at', fn($q) => $q->updated_at ? Time::createFromFormat('Y-m-d H:i:s', $q->updated_at)->format("d/m/Y H:i") : "")
            ->edit("creator",fn($q) => $q->userId == $auth_user_id ? '<span class="badge text-bg-success w-100">'.lang("App.me").'</span>' : $q->creator)
            ->add("viewed", fn($q) =>  $this->chatModel->isMessageChatViewed($q->chatMessageId))
            ->add("action", fn($q) => ["type" => "factura", "modelId" => $q->id, "isAdmin" => $isAdmin,"chatMessageId" => $q->chatMessageId, "lang" => [
                "view_chat" => lang('Chat.view_chat'),
                "view_by_alt_message" => lang('Chat.view_by_alt_message')
            ]])

            ->toJson(true);
    }
    public function get_notifications_not_viewed_from_message(int $chat_message_id)
    {
        $unviewedNotifications = $this->chatModel->getUsersNotificationNotViewedFromChat($chat_message_id);
        // $viewedNotifications = $this->chatModel->getUsersNotificationViewedFromChat($chat_message_id);

        return $this->response->setJSON(
            [
                "data" => [
                    "notifications" => $unviewedNotifications,
                ],
                "chat_message_id" => $chat_message_id
            ]
        );
    }
    public function store_new_direct_message()
    {
        $bodyData = $this->request->getPost();
        $rules = [
            "title" => "required|string",
            "message" => "required|string",
            "users" => "required",

        ];
        if (!$this->validate($rules)) {
            return $this->response->setStatusCode(400)->setJSON([
                'message' => lang('App.global_alert_save_error'),
                'status' => 'error',
                'errors' => $this->validator->getErrors(),
            ]);
        }
        $this->chatModel->createNewDirectChat(...$bodyData);
        return $this->response->setJSON(["message" => lang("Chat.new_message_ok"), "status" => true]);
    }
    public function store_new_direct_message_client()
    {
        $bodyData = $this->request->getPost();
        $rules = [
            "title" => "required|string",
            "message" => "required|string",
            "chat_department_id" => "required",

        ];
        if (!$this->validate($rules)) {
            return $this->response->setStatusCode(400)->setJSON([
                'message' => lang('App.global_alert_save_error'),
                'status' => 'error',
                'errors' => $this->validator->getErrors(),
            ]);
        }
        $users = $this->chatDeparmentModel->getChatDepartmentUsers($bodyData["chat_department_id"]);
        $bodyData["users"] = array_map(fn($q) => $q->id, $users);
        dd(1);
        $this->chatModel->createNewDirectChat(...$bodyData);
        return $this->response->setJSON(["message" => lang("Chat.new_message_ok"), "status" => true]);
    }
    public function get_chat_direct($chat_id)
    {
        $chatData = $this->chatModel->getChatDirect($chat_id);
        return $this->response->setJSON($chatData);
    }
    public function get_chat_direct_select_users($chat_id)
    {
        $chat_users_id = $this->chatUserModel->getChatUserArrayId($chat_id);

        $query = $this->userModel->builder()->select(
            [
                "id",
                "CONCAT(first_name,' ',last_name,'(',username,')') as name"
            ]
        )
            ->where("deleted_at", null)
            ->whereNotIn("id", $chat_users_id);
        if ($this->request->getGet("q")) {
            $query->groupStart()
                ->orLike("users.username", $this->request->getGet("q"))
                ->orLike("CONCAT(first_name,' ',last_name)", $this->request->getGet("q"))
                ->groupEnd();
        }

        return $this->response->setJSON($query->get()->getResultObject());
    }
    public function store_chat_direct_users($chat_id)
    {
        $bodyData = $this->request->getPost();
        $chat_users = [];
        foreach ($bodyData["users"] as $user_id) {
            $chat_users[] = ["chat_id" => $chat_id, "user_id" => $user_id];
            if ($bodyData["notification"]) {
                $this->chatModel->createNotificationsToNewChatUser($chat_id, $user_id);
            }
        }
        $this->chatUserModel->insertBatch($chat_users);
        return $this->response->setJSON(["message" => "ok", "status" => true]);
    }
    public function store_chat_direct_message(int $chat_id)
    {
        $bodyData = $this->request->getPost();
        $auth_user = auth()->user();
        $bodyData["sender_id"] =  $auth_user->id;
        $chat_message_id = $this->chatMessageModel->insert($bodyData);
        $users_id = $this->chatUserModel->getChatUserArrayId($chat_id);
        foreach ($users_id as $user_id) {
            if ($user_id != $auth_user->id) {
                $this->chatNotificationModel->insert(["chat_message_id" => $chat_message_id, "user_id" => $user_id]);
            }
        };
        $message = $this->chatMessageModel->get_chat_message($chat_message_id);
        return $this->response->setJSON($message);
    }
    public function update_chat_direct_message_unread($chat_id)
    {
        $this->chatModel->setAsUnviewedChatUserNotifications($chat_id, auth()->user()->id);
        return $this->response->setJSON(["message" => "ok", "status" => true]);
    }
    public function store_chat_error_message()
    {
        $bodyData = $this->request->getPost();
        $messageService = service('messages');
        $r = $messageService->createErrorMessagePresupuesto("Error", $bodyData['presupuesto_id']);
        return $this->response->setJSON(["message" => "ok", "data" => $r]);
    }
    public function delete_user_from_department($chat_department_id)
    {
        $data = $this->request->getRawInput();
        $user_id = auth()->user()->id;
        $adminExist = $this->chatDeparmentUserModel->where('chat_department_id', $chat_department_id)
            ->where('user_id', $user_id)
            ->where('pedido_id', null)
            ->where('factura_id', null)
            ->where('presupuesto_id', null)->countAllResults();
        if ($adminExist) {
            return $this->response->setJSON(["message" => lang('Chat.exit_admin_chat_wrong'), "status" => false]);
        }
        $chatDepartmentUserEntity = $this->chatDeparmentUserModel->where('chat_department_id', $chat_department_id)->where('user_id', $user_id)->where($data['model_fk'], $data['model_id_fk']);
        if ($chatDepartmentUserEntity->countAllResults() > 0) {
            $deleted = $this->chatDeparmentUserModel->where('chat_department_id', $chat_department_id)->where('user_id', $user_id)->delete(purge: true);
            return $this->response->setJSON(["message" => lang('Chat.exit_chat_ok'), "status" => true]);
        } else {
            return $this->response->setJSON(["message" => lang('Chat.exit_chat_wrong'), "status" => false]);
        }
    }
    public function delete_user_admin_from_department($chat_department_id, $user_id)
    {
        $this->chatDeparmentUserModel->where('chat_department_id', $chat_department_id)->where('user_id', $user_id)->delete();
        return $this->response->setJSON(["message" => lang('Chat.user_deleted_ok'), "status" => true]);
    }
    public function subscribe_to_chat_deparment()
    {
        $data = $this->request->getPost();
        $user_id = auth()->user()->id;
        $adminExist = $this->chatDeparmentUserModel->where('chat_department_id', $data['chat_department_id'])
            ->where('user_id', $user_id)
            ->where('pedido_id', null)
            ->where('factura_id', null)
            ->where('presupuesto_id', null)->countAllResults();
        if ($adminExist) {
            return $this->response->setJSON(["message" => lang('Chat.subscribe_chat_wrong'), "status" => false]);
        }
        $chatDepartmentUserEntity = $this->chatDeparmentUserModel->where('chat_department_id', $data['chat_department_id'])->where('user_id', $user_id)->where($data['model_fk'], $data['model_id_fk']);
        if ($chatDepartmentUserEntity->countAllResults() > 0) {
            return $this->response->setJSON(["message" => lang('Chat.subscribe_chat_wrong'), "status" => false]);
        } else {
            $this->chatDeparmentUserModel->insert(["chat_department_id" => $data["chat_department_id"], "user_id" => $user_id, $data['model_fk'] => $data['model_id_fk']]);
            return $this->response->setJSON(["message" => lang('Chat.subscribe_chat_ok'), "status" => true]);
        }
    }
    public function subscribe_admin_to_department()
    {
        $data = $this->request->getPost();
        if ($data['user_id']) {

            $this->chatDeparmentUserModel
                ->insert(
                    [
                        "chat_department_id" => $data["chat_department_id"],
                        "user_id" => $data["user_id"],
                    ]
                );
            return $this->response->setJSON(["message" => lang('Chat.subscribe_admin_chat_ok'), "status" => true]);
        } else {
            return $this->response->setStatusCode(422)->setJSON(["message" => lang('Chat.subscribe_admin_chat_wrong'), "status" => false]);
        }
    }
    public function config_view()
    {
        $this->viewData['breadcrumb'] = [
            ['title' => lang("App.menu_configuration"), 'route' => 'javascript:void(0);', 'active' => false],
            ['title' => lang("App.menu_config_messages"), 'route' => route_to("configMessagesIndex"), 'active' => true]
        ];

        return view('themes/vuexy/form/configuracion/messages/configView', $this->viewData);
    }
    public function chat_department_edit($chat_department_id)
    {
        $chatDepartment =  $this->chatDeparmentModel->find($chat_department_id);
        $this->viewData['breadcrumb'] = [
            ['title' => lang("App.menu_configuration"), 'route' => 'javascript:void(0);', 'active' => false],
            ['title' => lang("App.menu_config_messages"), 'route' => route_to("configMessagesIndex"), 'active' => false],
            ['title' => $chatDepartment->display, 'route' => route_to("chatDepartmentEditView", $chat_department_id), 'active' => true]

        ];
        $this->viewData["chat_department"] = $chatDepartment;
        return view('themes/vuexy/form/configuracion/messages/editChatDepartmentForm', $this->viewData);
    }
    public function chat_department_datatable()
    {
        $q = $this->chatDeparmentModel->datatableQuery();
        return DataTable::of($q)
            ->add('action', fn($r) => $r->id)
            ->toJson(true);
    }
    public function chat_department_user_datatable(int $chat_department_id)
    {
        $q = $this->chatDeparmentUserModel->datatableQuery($chat_department_id);
        $datatable = DataTable::of($q);
        if (auth()->user()->inGroup('admin')) {
            $datatable->add('action', fn($r) => $r->userId);
        }
        return $datatable->toJson(true);
    }
    public function select_users_not_in_chat_department(int $chat_department_id)
    {
        $paramQuery = $this->request->getGet("q");
        $data = $this->chatDeparmentUserModel->querySelectUsersNotInDepartment($chat_department_id, $paramQuery);
        return $this->response->setJSON($data);
    }
    public function store_chat_department()
    {
        $data = $this->request->getPost();
        $validated = $this->validation->run($data, 'chat_department');
        if ($validated) {
            $dataValidated = $this->validation->getValidated();
            $dataValidated['name'] = newUUID();
            $this->chatDeparmentModel->insert($dataValidated);
            return $this->response->setJSON(["message" => lang('App.global_alert_save_success'), "status" => true, "data" => $dataValidated]);
        } else {
            return $this->response->setStatusCode(422)->setJSON(["message" => lang('App.global_alert_save_success'), "status" => false, "errors" => $this->validation->getErrors()]);
        }
        return $this->response->setJSON(["message" => lang('App.global_alert_save_success'), "status" => true]);
    }
    public function update_chat_department(int $chat_department_id)
    {
        $data = $this->request->getPost();
        $validated = $this->validation->run($data, 'chat_department');
        if ($validated) {
            $dataValidated = $this->validation->getValidated();
            $this->chatDeparmentModel->update($chat_department_id, $dataValidated);
            return $this->response->setJSON(["message" => lang('App.global_alert_save_success'), "status" => true, "data" => $dataValidated]);
        } else {
            return $this->response->setStatusCode(422)->setJSON(["message" => lang('App.global_alert_save_success'), "status" => false, "errors" => $this->validation->getErrors()]);
        }
    }
    public function delete_chat_department($chat_department_id)
    {
        if (auth()->user()->inGroup('admin')) {
            $this->chatDeparmentModel->delete($chat_department_id);
            return $this->response->setJSON(["message" => lang('App.user_alert_delete'), "status" => true]);
        } else {
            return $this->response->setStatusCode(403)->setJSON(["message" => lang('App.user_alert_forbidden'), "status" => false]);
        }
    }
}
