<?php

namespace App\Models\Chat;

use App\Entities\Chat\ChatEntity;
use App\Models\ChatNotification;
use App\Models\ChatUser;
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 CodeIgniter\Model;
use CodeIgniter\Database\BaseBuilder;
use Config\OrdenTrabajo;

class ChatModel extends Model
{
    protected $table            = 'chats';
    protected $primaryKey       = 'id';
    protected $useAutoIncrement = true;
    protected $returnType       = ChatEntity::class;
    protected $useSoftDeletes   = true;
    protected $protectFields    = true;
    protected $allowedFields    = [
        "pedido_id",
        "chat_department_id",
        "presupuesto_id",
        "factura_id",
        "orden_trabajo_id",
        "title"
    ];

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

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

    // Dates
    protected $useTimestamps = true;
    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 getChat(int $chat_id): array
    {
        return $this->db->table('chats')
            ->select(
                [
                    "chats.*",
                    "chat_messages.created_at as messageCreatedAt",
                    "chat_messages.message as messageText",
                ]
            )
            ->join("chat_messages", "chats.id = chat_messages.chat_id", "left")
            ->orderBy("created_at", "desc")
            ->where("chats.id", $chat_id)
            ->get()->getResultObject();
    }
    public function getChatPresupuesto(int  $chat_department_id, int $presupuesto_id)
    {
        return $this->builder()->where("presupuesto_id", $presupuesto_id)->where("chat_department_id", $chat_department_id)->get()->getFirstRow();
    }
    public function getChatPedido(int  $chat_department_id, int $pedido_id)
    {
        return $this->builder()->where("pedido_id", $pedido_id)->where("chat_department_id", $chat_department_id)->get()->getFirstRow();
    }
    public function getChatFactura(int  $chat_department_id, int $factura_id)
    {
        return $this->builder()->where("factura_id", $factura_id)->where("chat_department_id", $chat_department_id)->get()->getFirstRow();
    }
    public function getChatOrdenTrabajo(int  $chat_department_id, int $orden_trabajo_id)
    {
        return $this->builder()->where("orden_trabajo_id", $orden_trabajo_id)->where("chat_department_id", $chat_department_id)->get()->getFirstRow();
    }

    public function createChatPresupuesto(int $chat_department_id, int $presupuesto_id): int
    {
        $model = model(PresupuestoModel::class);
        $chatDeparmentModel = model(ChatDeparmentModel::class);
        $presupuesto = $model->find($presupuesto_id);
        return $this->insert([
            "title" => $presupuesto->titulo . "[" . $chatDeparmentModel->getDisplay($chat_department_id) . "]",
            "presupuesto_id" => $presupuesto_id,
            "chat_department_id" => $chat_department_id
        ]);
    }
    public function createChatPedido(int $chat_department_id, int $pedido_id): int
    {

        $model = model(PedidoModel::class);
        $chatDeparmentModel = model(ChatDeparmentModel::class);
        $pedido = $model->getPedidoClientePresupuesto($pedido_id);
        return $this->insert([
            "title" => "Pedido " . $pedido->titulo . "[" . $chatDeparmentModel->getDisplay($chat_department_id) . "]",
            "pedido_id" => $pedido_id,
            "chat_department_id" => $chat_department_id
        ]);
    }
    public function createChatFactura(int $chat_department_id, int $factura_id): int
    {


        $model = model(FacturaModel::class);
        $chatDeparmentModel = model(ChatDeparmentModel::class);
        $factura = $model->find($factura_id);
        return $this->insert([
            "title" => "Factura " . $factura->numero . "[" . $chatDeparmentModel->getDisplay($chat_department_id) . "]",
            "factura_id" => $factura_id,
            "chat_department_id" => $chat_department_id
        ]);
    }
    public function createChatOrdenTrabajo(int $chat_department_id, int $orden_trabajo_id): int
    {
        $model = model(OrdenTrabajoModel::class);
        $chatDeparmentModel = model(ChatDeparmentModel::class);
        $ot = $model->find($orden_trabajo_id);
        return $this->insert([
            "title" => "[OT]".$ot->id . "[" . $chatDeparmentModel->getDisplay($chat_department_id) . "]",
            "orden_trabajo_id" => $orden_trabajo_id,
            "chat_department_id" => $chat_department_id
        ]);
    }
    public function createChatSingle(): int
    {
        return $this->insert(["chat_department_id" => null]);
    }
    public function existChatPresupuesto(int $chat_department_id, int $presupuesto_id): bool
    {
        $countChatPresupuesto = $this->builder()
            ->where("presupuesto_id", $presupuesto_id)
            ->where("chat_department_id", $chat_department_id)
            ->countAllResults();
        return $countChatPresupuesto > 0;
    }
    public function existChatPedido(int $chat_department_id, int $pedido_id): bool
    {
        $countChatPresupuesto = $this->builder()
            ->where("pedido_id", $pedido_id)
            ->where("chat_department_id", $chat_department_id)
            ->countAllResults();
        return $countChatPresupuesto > 0;
    }
    public function existChatFactura(int $chat_department_id, int $factura_id): bool
    {
        $countChatPresupuesto = $this->builder()
            ->where("factura_id", $factura_id)
            ->where("chat_department_id", $chat_department_id)
            ->countAllResults();
        return $countChatPresupuesto > 0;
    }

    public function getChatPedidosChat(): array
    {
        $query = $this->db->table("chats")
            ->select([
                "chats.id as chatId",
                "chats.pedido_id as pedidoId",
                "chats.chat_department_id as chatDepartmentId",
                "chat_departments.display as chatDisplay",
                "pedidos.id as title"
            ])
            ->join("chat_departments", "chat_departments.id = chats.chat_department_id", "left")
            ->join("pedidos", "pedidos.id = chats.pedido_id", "left")
            ->get()->getResultObject();
        return $query;
    }

    public function getChatPresupuestosChat(): array
    {
        $query = $this->db->table("chats")
            ->select([
                "chats.id as chatId",
                "chats.pedido_id as pedidoId",
                "chats.chat_department_id as chatDepartmentId",
                "chat_departments.display as chatDisplay",
                "presupuestos.titulo as title"
            ])
            ->join("chat_departments", "chat_departments.id = chats.chat_department_id", "left")
            ->join("presupuestos", "presupuestos.id = chats.pedido_id", "left")
            ->get()->getResultObject();
        return $query;
    }
    public function getChatFacturasChat(): array
    {
        $query = $this->db->table("chats")
            ->select([
                "chats.id as chatId",
                "chats.pedido_id as pedidoId",
                "chats.chat_department_id as chatDepartmentId",
                "chat_departments.display as chatDisplay",
                "facturas.numero as title"
            ])
            ->join("chat_departments", "chat_departments.id = chats.chat_department_id", "left")
            ->join("facturas", "facturas.id = chats.pedido_id", "left")
            ->get()->getResultObject();
        return $query;
    }
    public function getChatSingleChat(): array
    {
        $query = $this->db->table("chats")
            ->select([
                "chats.id as chatId",
                "chats.chat_department_id as chatDepartmentId",
                "chat_departments.display as chatDisplay",
                "facturas.numero as title"
            ])
            ->join("chat_departments", "chat_departments.id = chats.chat_department_id", "left")
            ->join("facturas", "facturas.id = chats.pedido_id", "left")
            ->get()->getResultObject();
        return $query;
    }
    public function getClienteChatPedidos(array $pedidos): array
    {
        $q = $this->db->table("chats")
            ->select([
                "chats.id as chatId",
                "chats.pedido_id as pedidoId",
                "chats.chat_department_id as chatDepartmentId",
                "chat_departments.display as chatDisplay",
                "pedidos.id as title"
            ])
            ->join("chat_departments", "chat_departments.id = chats.chat_department_id", "left")
            ->join("pedidos", "pedidos.id = chats.pedido_id", "left")
            ->where('chats.chat_department_id is NOT NULL', NULL, FALSE);
        if (count($pedidos) > 0) {
            $q->whereIn("pedidos.id", $pedidos);
        } else {
            return [];
        }
        $results = $q->get()->getResultObject();
        $chatMessageModel = model(ChatMessageModel::class);
        $count = 0;
        foreach ($results as $row) {
            $messages = $chatMessageModel->get_chat_messages($row->chatId);
            foreach ($messages as $key => $message) {
                if ($message->sender_id != auth()->user()->id && $message->viewed == false) {
                    $count++;
                }
            }
            $row->uri = "/pedidos/edit/" . $row->pedidoId . "#accordionChatPedido";
            $row->unreadMessages = $count;
        }
        return $results;
    }
    public function getClienteChatFacturas(array $facturas): array
    {
        $q = $this->db->table("chats")
            ->select([
                "chats.id as chatId",
                "chats.factura_id as facturaId",
                "chats.chat_department_id as chatDepartmentId",
                "chat_departments.display as chatDisplay",
                "facturas.numero as title"
            ])
            ->join("chat_departments", "chat_departments.id = chats.chat_department_id", "left")
            ->join("facturas", "facturas.id = chats.factura_id", "left")
            ->where('chats.chat_department_id is NOT NULL', NULL, FALSE);

        if (count($facturas) > 0) {
            $q->whereIn("facturas.id", $facturas);
        } else {
            return [];
        }
        $results = $q->get()->getResultObject();
        $chatMessageModel = model(ChatMessageModel::class);
        $count = 0;
        foreach ($results as $row) {
            $messages = $chatMessageModel->get_chat_messages($row->chatId);
            foreach ($messages as $key => $message) {
                if ($message->sender_id != auth()->user()->id && $message->viewed == false) {
                    $count++;
                }
            }
            $row->uri = "/factura/edit/" . $row->facturaId . "#accordionChatFactura";
            $row->unreadMessages = $count;
        }
        return $results;
    }
    public function getClienteChatPresupuestos(array $presupuestos): array
    {
        $q = $this->db->table("chats")
            ->select([
                "chats.id as chatId",
                "chats.presupuesto_id as presupuestoId",
                "chats.chat_department_id as chatDepartmentId",
                "chat_departments.display as chatDisplay",
                "presupuestos.titulo as title"
            ])
            ->join("chat_departments", "chat_departments.id = chats.chat_department_id", "left")
            ->join("presupuestos", "presupuestos.id = chats.presupuesto_id", "left")
            ->where('chats.chat_department_id is NOT NULL', NULL, FALSE);

        if (count($presupuestos) > 0) {
            $q->whereIn("presupuestos.id", $presupuestos);
        } else {
            return [];
        }
        $results = $q->get()->getResultObject();
        $chatMessageModel = model(ChatMessageModel::class);
        $count = 0;
        foreach ($results as $row) {
            $messages = $chatMessageModel->get_chat_messages($row->chatId);
            foreach ($messages as $key => $message) {
                if ($message->sender_id != auth()->user()->id && $message->viewed == false) {
                    $count++;
                }
            }
            $row->uri = "/presupuestocliente/edit/" . $row->presupuestoId . "#accordionChatPresupuesto";
            $row->unreadMessages = $count;
        }

        return $results;
    }
    public function getChatDepartmentNotifications()
    {
        $q = $this->builder()
            ->select([
                "chats.id as chatId",
                "chats.chat_department_id as chatDepartmentId",
                "chats.pedido_id as pedidoId",
                "chats.presupuesto_id as presupuestoId",
                "chats.factura_id as facturaId",
                "chats.orden_trabajo_id as ordenTrabajoId",
                "chats.title as chatDisplay",
                "COUNT(chat_notifications.id) as unreadMessages"
            ])
            ->join("chat_messages", "chat_messages.chat_id = chats.id", "left")
            ->join("chat_notifications", "chat_notifications.chat_message_id = chat_messages.id", "left")
            ->where("chat_notifications.user_id", auth()->user()->id)
            ->where("chat_notifications.viewed", false)
            ->where("chats.chat_department_id is NOT NULL", NULL, FALSE)
            ->groupBy('chats.id');

        $rows = $q->get()->getResultObject();
        $auth_user = auth()->user();
        $rows_new = [];
        foreach ($rows as $row) {
            if ($row->presupuestoId) {
                // $row->model = $presupuestoModel->find($row->presupuestoId);
                if ($auth_user->cliente_id) {
                    $row->uri = "/presupuestocliente/edit/" . $row->presupuestoId . "#accordionChatPresupuesto";
                } else {
                    $row->uri = "/presupuestoadmin/edit/" . $row->presupuestoId . "#accordionChatPresupuesto";
                }
                $row->title = $row->presupuestoId;

                $row->avatar = "PRE";
                $rows_new[] = $row;
            } elseif ($row->pedidoId) {
                // $row->model = $pedidoModel->find($row->pedidoId);
                $row->uri = "/pedidos/edit/" . $row->pedidoId . "#accordionChatPedido";
                $row->title = $row->pedidoId;

                $row->avatar = "P";
                $rows_new[] = $row;
            } elseif ($row->facturaId) {
                // $row->model = $facturaModel->find($row->facturaId);
                $row->uri = "/chat/factura/" . $row->facturaId . "#accordionChatFactura";
                $row->avatar = "F";

                $row->title = $row->facturaId;
                $rows_new[] = $row;
            }
            elseif ($row->ordenTrabajoId) {
                // $row->model = $facturaModel->find($row->facturaId);
                $row->uri = "/chat/ot/" . $row->ordenTrabajoId . "#accordionChatOrdenTrabajo";
                $row->avatar = "OT";
                $row->title = $row->ordenTrabajoId;
                $rows_new[] = $row;
            }
        }
        return $rows_new;
    }
    public function getChatInternalNotifications()
    {
        $q = $this->builder()
            ->select([
                "chats.id as chatId",
                "chats.chat_department_id as chatDepartmentId",
                "chats.pedido_id as pedidoId",
                "chats.presupuesto_id as presupuestoId",
                "chats.orden_trabajo_id as ordenTrabajoId",
                "chats.factura_id as facturaId",
                "chats.title as chatDisplay",
                "COUNT(chat_messages.id) as unreadMessages"

            ])
            ->join("chat_messages", "chat_messages.chat_id = chats.id", "left")
            ->join("chat_notifications", "chat_notifications.chat_message_id = chat_messages.id", "left")
            ->where("chat_notifications.user_id", auth()->user()->id)
            ->where("chat_notifications.viewed", false)
            ->where("chats.chat_department_id", null)
            ->groupBy('chats.id');

        $auth_user = auth()->user();
        $rows = $q->get()->getResultObject();
        $rows_new = [];
        foreach ($rows as $row) {
            if ($row->presupuestoId) {
                if ($auth_user->cliente_id) {
                    $row->uri = "/presupuestocliente/edit/" . $row->presupuestoId . "#accordionChatPresupuesto";
                } else {
                    $row->uri = "/presupuestoadmin/edit/" . $row->presupuestoId . "#accordionChatPresupuesto";
                }
                $row->title = $row->presupuestoId;
                $row->chatDisplay .= "[INTERNAL]";
                $row->avatar = "PRE";
                $rows_new[] = $row;
            } elseif ($row->pedidoId) {
                $row->uri = "/pedidos/edit/" . $row->pedidoId . "#accordionChatFactura";
                $row->title = $row->pedidoId;
                $row->chatDisplay .= "[INTERNAL]";
                $row->avatar = "P";
                $rows_new[] = $row;
            } elseif ($row->facturaId) {
                $row->uri = "/factura/edit/" . $row->facturaId . "#accordionChatFactura";
                $row->avatar = "F";
                $row->chatDisplay .= "[INTERNAL]";
                $row->title = $row->facturaId;
                $rows_new[] = $row;
            }
            elseif ($row->ordenTrabajoId) {
                $row->uri = "/produccion/ordentrabajo/edit/" . $row->ordenTrabajoId . "#accordionChatOrdenTrabajo";
                $row->avatar = "OT";
                $row->chatDisplay .= "[INTERNAL]";
                $row->title = $row->ordenTrabajoId;
                $rows_new[] = $row;
            }
        }
        return $rows_new;
    }
    public function getChatDirectMessageNotifications()
    {
        $chatMessageModel = model(ChatMessageModel::class);
        $chatNotificationModel = model(ChatNotification::class);

        $q = $this->db->table("chats")
            ->select([
                "chats.id as chatId",
                "chats.title as chatDisplay",
                "COUNT(chat_notifications.user_id) as unreadMessages"
            ])
            ->join("chat_messages", "chat_messages.chat_id = chats.id", "left")
            ->join("chat_notifications", "chat_notifications.chat_message_id = chat_messages.id", "left")
            ->where("chats.presupuesto_id", null)
            ->where("chats.chat_department_id", null)
            ->where("chats.pedido_id", null)
            ->where("chats.factura_id", null)
            ->where("chats.orden_trabajo_id", null)
            ->where("chat_notifications.viewed", false)
            ->where("chat_notifications.user_id", auth()->user()->id);
        $rows = $q->get()->getResultObject();
        $rows_new = [];
        foreach ($rows as $row) {
            if ($row->chatId) {
                $row->model = [];
                $row->uri = "/chat/direct/" . $row->chatId;
                $row->avatar = "MD";
                $row->title = "MD";
                // $row->chatDisplay = $this->getSenderIdFromChatMessage($row->chatId)?->username ?? "Unknown";
                $rows_new[] = $row;
            }
        }
        return $rows_new;
    }
    public function getChatInternalHebraPresupuesto(int $chat_id, int $presupuesto_id): array
    {

        $data = [];
        $query =  $this->builder()->select([
            "chats.id as chatId",
            "chat_messages.message",
            "users.username as senderUserName",
            "chat_messages.created_at",
            "CONCAT(users.first_name,' ',users.last_name) as senderFullName",
        ])
            ->join("chat_messages", "chat_messages.chat_id = chats.id", "left")
            ->join("users", "users.id = chat_messages.sender_id", "left")
            ->where("chats.id", $chat_id)
            ->where("chats.presupuesto_id", $presupuesto_id);
        $data["chatId"] = $chat_id;
        $data["messages"] = $query->get()->getResultObject();
        $data["chatTitle"] = "Presupuesto" . "[" . $presupuesto_id . "] - ";
        $data["chatTitle"] .= $this->find($chat_id)->title;
        $data["users"] = $this->getChatUsers($chat_id);
        return $data;
    }
    public function getChatInternalHebraPedido($chat_id, $pedido_id)
    {
        $data = [];
        $query =  $this->builder()->select([
            "chats.id as chatId",
            "chat_messages.message",
            "users.username as senderUserName",
            "chat_messages.created_at",
            "CONCAT(users.first_name,' ',users.last_name) as senderFullName",
        ])
            ->join("chat_messages", "chat_messages.chat_id = chats.id", "left")
            ->join("users", "users.id = chat_messages.sender_id", "left")
            ->where("chats.id", $chat_id)
            ->where("chats.pedido_id", $pedido_id);
        $data["chatId"] = $chat_id;
        $data["messages"] = $query->get()->getResultObject();
        $data["chatTitle"] = "Pedido" . "[" . $pedido_id . "] - ";
        $data["chatTitle"] .= $this->find($chat_id)->title;
        $data["users"] = $this->getChatUsers($chat_id);
        return $data;
    }
    public function getChatInternalHebraFactura($chat_id, $factura_id)
    {
        $data = [];
        $query =  $this->builder()->select([
            "chats.id as chatId",
            "chat_messages.message",
            "users.username as senderUserName",
            "chat_messages.created_at",
            "CONCAT(users.first_name,' ',users.last_name) as senderFullName",
        ])
            ->join("chat_messages", "chat_messages.chat_id = chats.id", "left")
            ->join("users", "users.id = chat_messages.sender_id", "left")
            ->where("chats.id", $chat_id)
            ->where("chats.factura_id", $factura_id);
        $data["chatId"] = $chat_id;
        $data["messages"] = $query->get()->getResultObject();
        $data["chatTitle"] = "Factura" . "[" . $factura_id . "] - ";
        $data["chatTitle"] .= $this->find($chat_id)->title;
        $data["users"] = $this->getChatUsers($chat_id);
        return $data;
    }
    public function getChatInternalHebraOrdenTrabajo($chat_id, $orden_trabajo_id)
    {
        $data = [];
        $query =  $this->builder()->select([
            "chats.id as chatId",
            "chat_messages.message",
            "users.username as senderUserName",
            "chat_messages.created_at",
            "CONCAT(users.first_name,' ',users.last_name) as senderFullName",
        ])
            ->join("chat_messages", "chat_messages.chat_id = chats.id", "left")
            ->join("users", "users.id = chat_messages.sender_id", "left")
            ->where("chats.id", $chat_id)
            ->where("chats.orden_trabajo_id", $orden_trabajo_id);
        $data["chatId"] = $chat_id;
        $data["messages"] = $query->get()->getResultObject();
        $data["chatTitle"] = "OT" . "[" . $orden_trabajo_id . "] - ";
        $data["chatTitle"] .= $this->find($chat_id)->title;
        $data["users"] = $this->getChatUsers($chat_id);
        return $data;
    }
    public function getChatUsers(int $chat_id)
    {
        $query = $this->builder()->select([
            "users.username",
            "CONCAT(users.first_name,' ',users.last_name) as userFullName",
        ])
            ->join("chat_users", "chat_users.chat_id = chats.id")
            ->join("users", "users.id = chat_users.user_id", "left")
            ->where("chats.id", $chat_id);
        return $query->get()->getResultObject();
    }
    public function getPresupuestoHebras($presupuesto_id): array
    {
        $data = [];
        $chats = $this->builder()->select("chats.id as chatId")
            ->where("chats.chat_department_id", null)
            ->where("chats.presupuesto_id", $presupuesto_id)->get()->getResultObject();
        foreach ($chats as $chat) {
            $data[$chat->chatId] = $this->getChatInternalHebraPresupuesto($chat->chatId, $presupuesto_id);
        }
        return $data;
    }
    public function getPedidoHebras($pedido_id): array
    {
        $data = [];
        $chats = $this->builder()->select("chats.id as chatId")
            ->where("chats.chat_department_id", null)
            ->where("chats.pedido_id", $pedido_id)->get()->getResultObject();
        foreach ($chats as $chat) {
            $data[$chat->chatId] = $this->getChatInternalHebraPedido($chat->chatId, $pedido_id);
        }
        return $data;
    }
    public function getFacturaHebras($factura_id): array
    {
        $data = [];
        $chats = $this->builder()->select("chats.id as chatId")
            ->where("chats.chat_department_id", null)
            ->where("chats.factura_id", $factura_id)->get()->getResultObject();
        foreach ($chats as $chat) {
            $data[$chat->chatId] = $this->getChatInternalHebraFactura($chat->chatId, $factura_id);
        }
        return $data;
    }
    public function getOrdenTrabajoHebras($orden_trabajo_id): array
    {
        $data = [];
        $chats = $this->builder()->select("chats.id as chatId")
            ->where("chats.chat_department_id", null)
            ->where("chats.orden_trabajo_id", $orden_trabajo_id)->get()->getResultObject();
        foreach ($chats as $chat) {
            $data[$chat->chatId] = $this->getChatInternalHebraOrdenTrabajo($chat->chatId, $orden_trabajo_id);
        }
        return $data;
    }
    public function countUnreadMessagePresupuesto(int $presupuesto_id): int|string
    {
        return $this->builder()->select()
            ->join("chat_messages", "chat_messages.chat_id = chats.id", "left")
            ->join("chat_notifications", "chat_notifications.chat_message_id = chat_messages.id", "left")
            ->where("chats.presupuesto_id", $presupuesto_id)
            ->where("chat_notifications.viewed", false)
            ->where("chat_notifications.user_id", auth()->user()->id)
            ->countAllResults();
    }
    public function countUnreadMessagePedido($pedido_id): int|string
    {
        return $this->builder()->select()
            ->join("chat_messages", "chat_messages.chat_id = chats.id", "left")
            ->join("chat_notifications", "chat_notifications.chat_message_id = chat_messages.id", "left")
            ->where("chats.pedido_id", $pedido_id)
            ->where("chat_notifications.viewed", false)
            ->where("chat_notifications.user_id", auth()->user()->id)
            ->countAllResults();
    }
    public function countUnreadMessageFactura($factura_id): int|string
    {
        return $this->builder()->select()
            ->join("chat_messages", "chat_messages.chat_id = chats.id", "left")
            ->join("chat_notifications", "chat_notifications.chat_message_id = chat_messages.id", "left")
            ->where("chats.factura_id", $factura_id)
            ->where("chat_notifications.viewed", false)
            ->where("chat_notifications.user_id", auth()->user()->id)->countAllResults();
    }
    public function countUnreadMessageOrdenTrabajo($orden_trabajo_id): int|string
    {
        return $this->builder()->select()
            ->join("chat_messages", "chat_messages.chat_id = chats.id", "left")
            ->join("chat_notifications", "chat_notifications.chat_message_id = chat_messages.id", "left")
            ->where("chats.orden_trabajo_id", $orden_trabajo_id)
            ->where("chat_notifications.viewed", false)
            ->where("chat_notifications.user_id", auth()->user()->id)->countAllResults();
    }
    public function countUnreadMessageDirectos(int $chat_id): int|string
    {
        return $this->builder()->select()
            ->join("chat_messages", "chat_messages.chat_id = chats.id", "left")
            ->join("chat_notifications", "chat_notifications.chat_message_id = chat_messages.id", "left")
            ->where("chats.presupuesto_id", null)
            ->where("chats.pedido_id", null)
            ->where("chats.factura_id", null)
            ->where("chats.chat_department_id", null)
            ->where("chat_messages.chat_id", $chat_id)
            ->where("chat_notifications.viewed", false)
            ->where("chat_notifications.user_id", auth()->user()->id)->countAllResults();
    }
    public function getSenderIdFromChatMessage(int $chat_id)
    {
        $first_message =  $this->builder()->select()
            ->join("chat_messages", "chat_messages.chat_id = chats.id", "left")
            ->where("chats.presupuesto_id", null)
            ->where("chats.pedido_id", null)
            ->where("chats.factura_id", null)
            ->where("chats.orden_trabajo_id", null)
            ->where("chats.id", $chat_id)
            ->where("chat_messages.receiver_id", auth()->user()->id)->get()->getFirstRow();
        $userModel = model(UserModel::class);
        return $userModel->find($first_message->sender_id);
    }
    public function getOpenChatCliente(int $user_id): array
    {
        $q = $this->builder()->distinct()->select([
            "users.*"
        ])
            ->join("chat_messages", "chat_messages.chat_id = chats.id", "left")
            ->join("users", "users.id = chat_messages.sender_id", "left")
            ->where("chat_messages.receiver_id", $user_id);

        return $q->get()->getResultObject();
    }
    public function getChatDepartmentMessagesCount(int $chat_id, int $chat_department_id): int
    {
        $q = $this->builder()->select([
            "chat_messages.id"
        ])
            ->join("chat_messages", "chat_messages.chat_id = chats.id", 'left')
            ->where("chats.chat_department_id", $chat_department_id)
            ->where("chats.id", $chat_id)
            ->countAllResults();
        return $q;
    }
    public function getChatFirstUser(int $chat_id): object
    {
        $q = $this->builder()->select([
            "users.id",
            "CONCAT(users.first_name,' ',users.last_name) as userFullName",
        ])
            ->join("chat_messages", "chat_messages.chat_id = chats.id", 'left')
            ->join("users", "users.id = chat_messages.sender_id", "left")
            ->where("chats.id", $chat_id)
            ->where("chat_messages.deleted_at", null)
            ->orderBy("chat_messages.created_at", 'ASC');
        return $q->get()->getFirstRow();
    }

    /**
     * Check if all messages of a chat sent to an user have been viewed.
     *
     * @param integer $chat_id 
     * @param integer $user_id
     * @return boolean True : All messages readed
     */
    public function isMessageChatViewed(int $chat_message_id): bool
    {
        $q = $this->builder()->select(["chat_notifications.id as cnId"])
            ->join("chat_messages", "chat_messages.chat_id = chats.id", 'left')
            ->join("chat_notifications", "chat_notifications.chat_message_id = chat_messages.id", 'left')
            ->where("chat_messages.id", $chat_message_id)
            ->where("chat_notifications.viewed", false);
        $unread_messages_count = $q->countAllResults();
        if ($unread_messages_count > 0) {
            $result = false;
        } else {
            $result = true;
        }
        return $result;
    }
    /**
     * Return users who did not read the message.
     *
     * @param integer $chat_id 
     * @return array True : All messages readed
     */
    public function getUsersNotificationNotViewedFromChat(int $chat_message_id): array
    {
        $q = $this->builder()->distinct()->select(
            [
                "CONCAT(users.first_name,' ',users.last_name) as userFullName",
                "users.username as userName",
                "chat_notifications.viewed"
            ]

        )
            ->join("chat_messages", "chat_messages.chat_id = chats.id", 'left')
            ->join("chat_notifications", "chat_notifications.chat_message_id = chat_messages.id", 'left')
            ->join("users", "users.id = chat_notifications.user_id", 'left')
            ->where("chat_messages.id", $chat_message_id)
            ->where("chat_notifications.deleted_at", null)
            ->get()->getResultArray();
        return $q;
    }
    public function getUsersNotificationViewedFromChat(int $chat_message_id): array
    {
        $q = $this->builder()->distinct()->select(
            [
                "CONCAT(users.first_name,' ',users.last_name) as userFullName",
                "users.username as userName",
                "chat_notifications.viewed"
            ]

        )
            ->join("chat_messages", "chat_messages.chat_id = chats.id", 'left')
            ->join("chat_notifications", "chat_notifications.chat_message_id = chat_messages.id", 'left')
            ->join("users", "users.id = chat_notifications.user_id", 'left')
            ->where("chat_messages.id", $chat_message_id)
            ->where("chat_notifications.deleted_at", null)
            ->where('chat_notifications.viewed', true)
            ->get()->getResultArray();
        return $q;
    }
    public function getQueryDatatable(): BaseBuilder
    {
        $query = $this->builder()
            ->select([
                "chats.id",
                "cm.id as chatMessageId",
                "u.id as userId",
                "cm.message",
                "chats.created_at",
                "
                (
                    SELECT cm2.updated_at
                    FROM chat_messages cm2
                    WHERE cm2.chat_id = chats.id
                    ORDER BY cm2.updated_at DESC LIMIT 1
                ) as updated_at",
                "CONCAT(u.first_name,' ',u.last_name) as creator",
                "chats.title as title",
            ])
            ->join("presupuestos", "presupuestos.id = chats.presupuesto_id", 'left')
            ->join("chat_messages cm", "chats.id = cm.chat_id", "left")
            ->join("users u", "u.id = cm.sender_id", 'left')
            ->groupStart()
            ->orWhere("chats.presupuesto_id is NOT NULL", NULL, FALSE)
            ->orWhere("chats.pedido_id is NOT NULL", NULL, FALSE)
            ->orWhere("chats.factura_id is NOT NULL", NULL, FALSE)
            ->groupEnd();

        if (auth()->user()->inGroup("admin") == false) {
            $query->where('presupuestos.cliente_id', auth()->user()->cliente_id)
                ->where("chats.chat_department_id is NOT NULL", NULL, FALSE);
        }
        return $query->groupBy('chatMessageId');
    }
    public function getQueryDatatableMessagePresupuesto(int $user_id): BaseBuilder
    {
        $query = $this->builder()
            ->select([
                "chats.id",
                "cm.id as chatMessageId",
                "u.id as userId",
                "cm.message",
                "chats.created_at",
                "
                (
                    SELECT cm2.updated_at
                    FROM chat_messages cm2
                    WHERE cm2.chat_id = chats.id
                    ORDER BY cm2.updated_at DESC LIMIT 1
                ) as updated_at",
                "CONCAT(u.first_name,' ',u.last_name) as creator",
                "CONCAT('[',chats.title,']',' ',presupuestos.titulo) as title",
            ])
            ->join("presupuestos", "presupuestos.id = chats.presupuesto_id", 'left')
            ->join("chat_messages cm", "chats.id = cm.chat_id", "left")
            ->join("users u", "u.id = cm.sender_id", 'left')
            ->where("chats.presupuesto_id is NOT NULL", NULL, FALSE);

        if (auth()->user()->inGroup("cliente-administrador","cliente")) {
            $query->where('presupuestos.cliente_id', auth()->user()->cliente_id)
                ->where("chats.chat_department_id is NOT NULL", NULL, FALSE);
        }
        return $query->groupBy('chatMessageId');
    }
    public function getQueryDatatableMessagePedido(int $user_id): BaseBuilder
    {
        $query = $this->builder()
            ->select([
                "chats.id",
                "cm.id as chatMessageId",
                "u.id as userId",
                "cm.message",
                "chats.created_at",
                "
            (
                SELECT cm2.updated_at
                FROM chat_messages cm2
                WHERE cm2.chat_id = chats.id
                ORDER BY cm2.updated_at DESC LIMIT 1
            ) as updated_at",
                "CONCAT(u.first_name,' ',u.last_name) as creator",
                "CONCAT('[',chats.title,']',' ',presupuestos.titulo) as title",
            ])
            ->join("pedidos_linea", "pedidos_linea.pedido_id = chats.pedido_id", 'left')
            ->join("chat_messages cm", "chats.id = cm.chat_id", "left")
            ->join("users u", "u.id = cm.sender_id", 'left')
            ->join("presupuestos", "presupuestos.id = pedidos_linea.presupuesto_id", 'left')
            ->where("chats.pedido_id is NOT NULL", NULL, FALSE);

        if (auth()->user()->inGroup("cliente-administrador","cliente")) {
            $query->where('presupuestos.cliente_id', auth()->user()->cliente_id)
                ->where("chats.chat_department_id is NOT NULL", NULL, FALSE);
        }
        return $query->groupBy('chatMessageId');
    }
    public function getQueryDatatableMessageFactura(int $user_id): BaseBuilder
    {
        $query = $this->builder()
            ->select([
                "chats.id",
                "cm.id as chatMessageId",
                "u.id as userId",
                "cm.message",
                "chats.created_at",
                "
            (
                SELECT cm2.updated_at
                FROM chat_messages cm2
                WHERE cm2.chat_id = chats.id
                ORDER BY cm2.updated_at DESC LIMIT 1
            ) as updated_at",
                "CONCAT(u.first_name,' ',u.last_name) as creator",
                "chats.title",
            ])
            ->join("chat_messages cm", "chats.id = cm.chat_id", "left")
            ->join("users u", "u.id = cm.sender_id", 'left')
            ->join("facturas", "facturas.id = chats.factura_id", "left")
            ->where("chats.factura_id is NOT NULL", NULL, FALSE);

            if (auth()->user()->inGroup("cliente-administrador","cliente")) {
                $query->where('facturas.cliente_id', auth()->user()->cliente_id)
                    ->where("chats.chat_department_id is NOT NULL", NULL, FALSE);
            }
        return $query->groupBy('chatMessageId');
    }
    public function getQueryDatatableMessageOrdenTrabajo(int $user_id): BaseBuilder
    {
        $query = $this->builder()
            ->select([
                "chats.id",
                "cm.id as chatMessageId",
                "u.id as userId",
                "cm.message",
                "chats.created_at",
                "
            (
                SELECT cm2.updated_at
                FROM chat_messages cm2
                WHERE cm2.chat_id = chats.id
                ORDER BY cm2.updated_at DESC LIMIT 1
            ) as updated_at",
                "CONCAT(u.first_name,' ',u.last_name) as creator",
                "chats.title",
            ])
            ->join("chat_messages cm", "chats.id = cm.chat_id", "left")
            ->join("users u", "u.id = cm.sender_id", 'left')
            ->join("ordenes_trabajo", "ordenes_trabajo.id = chats.orden_trabajo_id", "left")
            ->where("chats.orden_trabajo_id is NOT NULL", NULL, FALSE);

            if (auth()->user()->inGroup("cliente-administrador","cliente")) {
                $query->where('facturas.cliente_id', auth()->user()->cliente_id)
                    ->where("chats.chat_department_id is NOT NULL", NULL, FALSE);
            }
        return $query->groupBy('chatMessageId');
    }
    public function createNewDirectChat(string $title, string $message, array $users)
    {
        $chatMessageModel = model(ChatMessageModel::class);
        $chatNotificationModel = model(ChatNotification::class);
        $chatUserModel = model(ChatUser::class);
        $auth_user_id = auth()->user()->id;
        $chat_id = $this->insert(["title" => $title]);
        $chat_message_id = $chatMessageModel->insert([
            "chat_id" => $chat_id,
            "sender_id" => $auth_user_id,
            "receiver_id" => null,
            "message" => $message
        ]);
        $chatUserModel->insert(["chat_id" => $chat_id, "user_id" => $auth_user_id]);
        foreach ($users as $key => $user_id) {
            $chatUserModel->insert(["chat_id" => $chat_id, "user_id" => $user_id]);
            $chatNotificationModel->insert(["chat_message_id" => $chat_message_id, "user_id" => $user_id]);
        }
    }

    /**
     * Obtain users and messages from `chat_id`
     *
     * @param integer $chat_id
     * @return array 
     * [
     * "chat" => object,
     * "messages" => array ,
     * "users" => array
     * ]
     */
    public function getChatDirect(int $chat_id): array
    {
        $auth_user = auth()->user()->id;
        $chat = $this->find($chat_id);
        $chatNotificationModel = model(ChatNotification::class);
        $query = $this->builder()->select([
            "users.*",
        ])
            ->join("chat_users", "chat_users.chat_id = chats.id")
            ->join("users", "users.id = chat_users.user_id", "left")
            ->where("chats.id", $chat_id);
        $users = $query->get()->getResultObject();
        $query = $this->builder()->select([
            "chat_messages.*",
            "users.first_name as sender_first_name",
            "users.last_name as sender_last_name",

        ])
            ->join("chat_messages", "chat_messages.chat_id = chats.id", "left")
            ->join("users", "chat_messages.sender_id = users.id", "left")
            ->where("chats.id", $chat_id);

        $messages = $query->get()->getResultObject();
        $validatedMessages = [];
        foreach ($messages as $key => $message) {
            $message->viewed = $chatNotificationModel->isChatMessageViewed($message->id);
            if ($auth_user == $message->sender_id) {
                $message->pos = 'right';
                $validatedMessages[] = $message;
            } else {
                $message->pos = 'left';
                $validatedMessages[] = $message;
            }
        }
        $data = [
            "chat" => $chat,
            "users" => $users,
            "messages" => $validatedMessages
        ];
        return $data;
    }
    public function setAsViewedChatUserNotifications(int $chat_id, int $user_id)
    {
        $query = $this->builder()
            ->select("chat_notifications.id as notificationId")
            ->join('chat_messages', 'chat_messages.chat_id = chats.id', 'left')
            ->join('chat_notifications', 'chat_notifications.chat_message_id = chat_messages.id', 'left')
            ->where('chat_notifications.user_id', $user_id)
            ->where('chat_messages.chat_id', $chat_id)
            ->get()->getResultObject();
        $chat_messages_ids = array_map(fn($q) => $q->notificationId, $query);
        $chatNotificationModel = model(ChatNotification::class);
        if ($chat_messages_ids) {
            $chatNotificationModel->setNotificationsAsViewed($chat_messages_ids);
        }
    }
    public function setAsViewedChatUserMessages(int $chat_id, int $user_id)
    {
        $this->db->table("chat_messages")
            ->where('chat_id', $chat_id)
            ->where('sender_id !=', $user_id)
            ->update(["viewed" => true]);
    }
    public function setAsUnviewedChatUserNotifications(int $chat_id, int $user_id)
    {
        $query = $this->builder()
            ->select("chat_notifications.id as notificationId")
            ->join('chat_messages', 'chat_messages.chat_id = chats.id', 'left')
            ->join('chat_notifications', 'chat_notifications.chat_message_id = chat_messages.id', 'left')
            ->where('chat_notifications.user_id', $user_id)
            ->where('chat_messages.chat_id', $chat_id)
            ->get()->getResultObject();
        $chat_messages_ids = array_map(fn($q) => $q->notificationId, $query);
        $chatNotificationModel = model(ChatNotification::class);
        if ($chat_messages_ids) {
            $chatNotificationModel->setNotificationsAsUnViewed($chat_messages_ids);
        }
    }

    public function setAsUnviewedChatUserMessages(int $chat_id, int $user_id)
    {
        $this->db->table("chat_messages")
            ->where('chat_id', $chat_id)
            ->where('sender_id !=', $user_id)
            ->update(["viewed" => false]);
    }
    public function createNotificationsToNewChatUser($chat_id, $user_id)
    {
        $query = $this->builder()
            ->select("chat_messages.id")
            ->join('chat_messages', 'chat_messages.chat_id = chats.id', 'left')
            ->where('chat_messages.chat_id', $chat_id)
            ->get()->getResultObject();
        $chat_notifications = array_map(fn($q) => ["chat_message_id" => $q->id, "user_id" => $user_id], $query);
        $chatNotificationModel = model(ChatNotification::class);
        $chatNotificationModel->insertBatch($chat_notifications);
    }
}
