<?php

namespace App\Models\Soporte;


class TicketModel extends \App\Models\BaseModel
{

    protected $table = 'tickets';
    protected $primaryKey = 'id';
    protected $allowedFields = ['usuario_id', 'user_soporte_id', 'seccion_id', 'categoria_id', 'estado_id', 'prioridad', 'titulo', 'descripcion', 'created_at', 'updated_at'];

    protected $useTimestamps = true;

    protected $returnType = "App\Entities\Soporte\TicketEntity";

    const SORTABLE = [
        0 => "t1.id",
        1 => "t1.categoria_id",
        2 => "t1.seccion_id",
        3 => "t1.estado_id",
        4 => "t1.prioridad",
        5 => "t1.titulo",
        6 => "t1.usuario_id",
        7 => "t1.usuario_soporte_id",
        8 => "t1.created_at",
    ];

    protected $validationRules = [
        "titulo" => [
            "label" => "Tickets.asunto",
            "rules" => "trim|required|max_length[255]",
        ],
        "descripcion" => [
            "label" => "Tickets.descripcion",
            "rules" => "trim|required",
        ],
    ];

    protected $validationMessages = [
        "titulo" => [
            "max_length" => "Tickets.validation.titulo.max_length",
            "required" => "Tickets.validation.titulo.required",
        ],
        "descripcion" => [
            "decimal" => "Tickets.validation.descripcion.decimal",
            "required" => "Tickets.validation.descripcion.required",
        ],
    ];

    public function getEstados()
    {
        $values = $this->db->table('tickets_estados')->get()->getResultArray();

        for ($i = 0; $i < count($values); $i++) {
            $values[$i]['text'] = lang("Tickets." . $values[$i]['keyword']);
        }

        return $values;
    }

    public function getCategorias()
    {
        $values = $this->db->table('tickets_categorias')->get()->getResultArray();

        for ($i = 0; $i < count($values); $i++) {
            $values[$i]['text'] = lang("Tickets." . $values[$i]['keyword']);
        }

        return $values;
    }

    public function getSecciones()
    {
        $values = $this->db->table('tickets_secciones')->get()->getResultArray();

        for ($i = 0; $i < count($values); $i++) {
            $values[$i]['text'] = lang("Tickets." . $values[$i]['keyword']);
        }

        return $values;
    }

    public function getTickets($id = null)
    {
        if ($id === null) {
            return $this->select('tickets.*, users.nombre as usuario, categorias.nombre as categoria, estados.nombre as estado')
                ->join('users', 'users.id = tickets.usuario_id')
                ->join('categorias', 'categorias.id = tickets.categoria_id')
                ->join('estados', 'estados.id = tickets.estado_id')
                ->findAll();
        }

        return $this->find($id);
    }

    public function getResource($search = [], $user_id = null)
    {
        $builder = $this->db
            ->table($this->table . " t1")
            ->select(
                "t1.id as id, t1.usuario_id AS usuario_id, CONCAT(t2.first_name, ' ', t2.last_name) AS usuario,
                t1.user_soporte_id AS user_soporte_id, CONCAT(t6.first_name, ' ', t6.last_name) AS user_soporte,
                t1.categoria_id AS categoria_id, t3.keyword AS categoria, 
                t1.seccion_id AS seccion_id, t5.keyword AS seccion, 
                t1.estado_id AS estado_id, t4.keyword AS estado,
                t1.prioridad AS prioridad, t1.titulo AS titulo, t1.created_at AS created_at
                "
            );

        $builder->join("users t2", "t1.usuario_id = t2.id", "left");
        $builder->join("users t6", "t1.user_soporte_id = t6.id", "left");
        $builder->join("tickets_categorias t3", "t1.categoria_id = t3.id", "left");
        $builder->join("tickets_estados t4", "t1.estado_id = t4.id", "left");
        $builder->join("tickets_secciones t5", "t1.seccion_id = t5.id", "left");

        if ($user_id !== null)
            $builder->where("t1.usuario_id", $user_id);

        if (empty($search))
            return $builder;
        else {
            $builder->groupStart();
            foreach ($search as $col_search) {
                if ($col_search[1] == "seccion_id") {
                    $id = $this->getIdFromKeyword("tickets_secciones", $col_search[2]);
                    $builder->where("t1." . $col_search[1], $id);
                } else if ($col_search[1] == "categoria_id") {
                    $id = $this->getIdFromKeyword("tickets_categorias", $col_search[2]);
                    $builder->where("t1." . $col_search[1], $id);
                } else if ($col_search[1] == "estado_id") {
                    $id = $this->getIdFromKeyword("tickets_estados", $col_search[2]);
                    $builder->where("t1." . $col_search[1], $id);
                } else if ($col_search[1] == "prioridad") {
                    $builder->where("t1." . $col_search[1], $col_search[2]);
                } else if ($col_search[1] == "created_at") {
                    $dates = explode(" ", $col_search[2]);
                    $builder->where("t1." . $col_search[1] . ">=", $dates[0]);
                    $builder->where("t1." . $col_search[1] . "<=", $dates[1]);
                }  else if ($col_search[1] == "usuario_id") {
                    $builder->like("t2.first_name", $col_search[2]);
                    $builder->orLike("t2.last_name", $col_search[2]);
                } else if ($col_search[1] == "user_soporte_id") {
                    $builder->like("t6.first_name", $col_search[2]);
                    $builder->orLike("t6.last_name", $col_search[2]);
                }
                else
                    $builder->like("t1." . $col_search[1], $col_search[2]);
            }
            $builder->groupEnd();
            return $builder;

        }
    }

    private function getIdFromKeyword($table, $keyword)
    {
        $subquery = $this->db->table($table)
            ->select('id')
            ->where('keyword', $keyword)
            ->get()
            ->getRow();
        return $subquery->id;
    }
}
