<?php

namespace App\Models\Configuracion;

class MaquinaModel extends \App\Models\BaseModel
{
    protected $table = "lg_maquinas";

    /**
     * Whether primary key uses auto increment.
     *
     * @var bool
     */
    protected $useAutoIncrement = true;

    const SORTABLE = [
        0 => "t1.id",
        1 => "t1.nombre",
        2 => "t1.tipo",
        3 => "t1.ancho_impresion",
        4 => "t1.alto_impresion",
        5 => "t1.min",
        6 => "t1.max",    ];

    protected $allowedFields = [
        "nombre",
        "is_padre",
        "tipo",
        "velocidad",
        "ancho",
        "alto",
        "ancho_impresion",
        "alto_impresion",
        "alto_click",
        "padre_id",
        "min",
        "max",
        "duracion_jornada",
        "orden_planning",
        "is_rotativa",
        "precio_tinta_negro",
        "is_inkjet",
        "precio_tinta_color",
        "precio_tinta_cg",
        "velocidad_corte",
        "precio_hora_corte",
        "metrosxminuto",
        "forzar_num_formas_horizontales_cubierta",
        "forzar_num_formas_verticales_cubierta",
        "observaciones",
        "deleted_at",
        "is_deleted",
        "user_created_id",
        "user_updated_id"
    ];
    protected $returnType = "App\Entities\Configuracion\Maquina";

    protected $useTimestamps = true;
    protected $useSoftDeletes = false;

    protected $createdField = "created_at";

    public static $labelField = "nombre";

    protected $validationRules = [
        "alto" => [
            "label" => "Maquinas.alto",
            "rules" => "required|decimal|greater_than[0]",
        ],
        "alto_click" => [
            "label" => "Maquinas.altoClick",
            "rules" => "required|decimal|greater_than[0]",
        ],
        "alto_impresion" => [
            "label" => "Maquinas.altoImpresion",
            "rules" => "required|decimal|greater_than[0]",
        ],
        "ancho" => [
            "label" => "Maquinas.ancho",
            "rules" => "required|decimal|greater_than[0]",
        ],
        "ancho_impresion" => [
            "label" => "Maquinas.anchoImpresion",
            "rules" => "required|decimal|greater_than[0]",
        ],
        "duracion_jornada" => [
            "label" => "Maquinas.duracionJornada",
            "rules" => "required|integer",
        ],
        "forzar_num_formas_horizontales_cubierta" => [
            "label" => "Maquinas.forzarNumFormasHorizontalesPortada",
            "rules" => "integer|permit_empty",
        ],
        "forzar_num_formas_verticales_cubierta" => [
            "label" => "Maquinas.forzarNumFormasVerticalesPortada",
            "rules" => "integer|permit_empty",
        ],
        "max" => [
            "label" => "Maquinas.max",
            "rules" => "required|integer",
        ],
        "metrosxminuto" => [
            "label" => "Maquinas.metrosxminuto",
            "rules" => "max_length[31]",
        ],
        "min" => [
            "label" => "Maquinas.min",
            "rules" => "required|integer",
        ],
        "nombre" => [
            "label" => "Maquinas.nombre",
            "rules" => "trim|required|max_length[255]",
        ],
        "observaciones" => [
            "label" => "Maquinas.observaciones",
            "rules" => "trim|max_length[16313]",
        ],
        "orden_planning" => [
            "label" => "Maquinas.ordenPlanning",
            "rules" => "required|integer",
        ],
        "precio_hora_corte" => [
            "label" => "Maquinas.precioHoraCorte",
            "rules" => "decimal",
        ],
        "precio_tinta_cg" => [
            "label" => "Maquinas.precioTintaColor",
            "rules" => "decimal",
        ],
        "precio_tinta_color" => [
            "label" => "Maquinas.precioTintaColor",
            "rules" => "decimal",
        ],
        "precio_tinta_negro" => [
            "label" => "Maquinas.precioTintaNegro",
            "rules" => "decimal",
        ],
        "tipo" => [
            "label" => "Maquinas.tipo",
            "rules" => "required|in_list[impresion,manipulado,acabado]",
        ],
        "velocidad" => [
            "label" => "Maquinas.velocidad",
            "rules" => "required|decimal",
        ],
        "velocidad_corte" => [
            "label" => "Maquinas.velocidadCorte",
            "rules" => "decimal",
        ],
    ];

    protected $validationMessages = [
        "alto" => [
            "decimal" => "Maquinas.validation.alto.decimal",
        ],
        "alto_click" => [
            "decimal" => "Maquinas.validation.alto_click.decimal",
            "required" => "Maquinas.validation.alto_click.required",
        ],
        "alto_impresion" => [
            "decimal" => "Maquinas.validation.alto_impresion.decimal",
            "required" => "Maquinas.validation.alto_impresion.required",
        ],
        "ancho" => [
            "decimal" => "Maquinas.validation.ancho.decimal",
        ],
        "ancho_impresion" => [
            "decimal" => "Maquinas.validation.ancho_impresion.decimal",
            "required" => "Maquinas.validation.ancho_impresion.required",
        ],
        "duracion_jornada" => [
            "integer" => "Maquinas.validation.duracion_jornada.integer",
            "required" => "Maquinas.validation.duracion_jornada.required",
        ],
        "forzar_num_formas_horizontales_cubierta" => [
            "integer" => "Maquinas.validation.forzar_num_formas_horizontales_cubierta.integer",
        ],
        "forzar_num_formas_verticales_cubierta" => [
            "integer" => "Maquinas.validation.forzar_num_formas_verticales_cubierta.integer",
        ],
        "max" => [
            "integer" => "Maquinas.validation.max.integer",
            "required" => "Maquinas.validation.max.required",
        ],
        "metrosxminuto" => [
            "max_length" => "Maquinas.validation.metrosxminuto.max_length",
            "required" => "Maquinas.validation.metrosxminuto.required",
        ],
        "min" => [
            "integer" => "Maquinas.validation.min.integer",
            "required" => "Maquinas.validation.min.required",
        ],
        "nombre" => [
            "max_length" => "Maquinas.validation.nombre.max_length",
            "required" => "Maquinas.validation.nombre.required",
        ],
        "observaciones" => [
            "max_length" => "Maquinas.validation.observaciones.max_length",
            //"required" => "Maquinas.validation.observaciones.required",
        ],
        "orden_planning" => [
            "integer" => "Maquinas.validation.orden_planning.integer",
            "required" => "Maquinas.validation.orden_planning.required",
        ],
        "precio_hora_corte" => [
            "decimal" => "Maquinas.validation.precio_hora_corte.decimal",
            "required" => "Maquinas.validation.precio_hora_corte.required",
        ],
        "precio_tinta_color" => [
            "decimal" => "Maquinas.validation.precio_tinta_color.decimal",
            "required" => "Maquinas.validation.precio_tinta_color.required",
        ],
        "precio_tinta_negro" => [
            "decimal" => "Maquinas.validation.precio_tinta_negro.decimal",
            "required" => "Maquinas.validation.precio_tinta_negro.required",
        ],
        "tipo" => [
            "in_list" => "Maquinas.validation.tipo.in_list",
            "required" => "Maquinas.validation.tipo.required",
        ],
        "velocidad" => [
            "decimal" => "Maquinas.validation.velocidad.decimal",
            "required" => "Maquinas.validation.velocidad.required",
        ],
        "velocidad_corte" => [
            "decimal" => "Maquinas.validation.velocidad_corte.decimal",
            "required" => "Maquinas.validation.velocidad_corte.required",
        ],
    ];

    public function findAllWithMaquinas(string $selcols = "*", int $limit = null, int $offset = 0)
    {
        $sql =
            "SELECT t1." .
            $selcols .
            ",  t2.nombre AS padre FROM " .
            $this->table .
            " t1  LEFT JOIN lg_maquinas t2 ON t1.padre_id = t2.id";
        if (!is_null($limit) && intval($limit) > 0) {
            $sql .= " LIMIT " . $limit;
        }

        if (!is_null($offset) && intval($offset) > 0) {
            $sql .= " OFFSET " . $offset;
        }

        $query = $this->db->query($sql);
        $result = $query->getResultObject();
        return $result;
    }

    public function getIdMaquinasForPapelImpresion($papel_impresion_id, $rotativa , $inkjet)
    {
        $builder = $this->db
            ->table($this->table . " t1")
            ->select(
                "'" . $papel_impresion_id . "'" . " as papel_impresion_id, t1.id AS maquina_id, '0' as active"
            );
        $builder->where("t1.is_rotativa", $rotativa);
        //$builder->where("t1.is_inkjet", $inkjet);

        return $builder;
    }

    public function getVelocidad($maquina_id){
        $builder = $this->db
            ->table($this->table . " t1")
            ->select(
                "t1.velocidad as velocidad"
            );
        $builder->where("t1.id", $maquina_id);

        $resultObject = $builder->get()->getResultObject();

        if(count($resultObject)>0)
            return $resultObject[0]->velocidad;
        else{
            return -1;
        }
    }

    /**
     * Get resource data.
     *
     * @param string $search
     *
     * @return \CodeIgniter\Database\BaseBuilder
     */
    public function getResource($search = [])
    {
        $builder = $this->db
            ->table($this->table . " t1")
            ->select(
                "t1.id AS id, t1.nombre AS nombre, t1.is_padre AS is_padre, t1.tipo AS tipo, t1.velocidad AS velocidad, t1.ancho AS ancho, t1.alto AS alto, t1.ancho_impresion AS ancho_impresion, t1.alto_impresion AS alto_impresion, t1.alto_click AS alto_click, t1.min AS min, t1.max AS max, t1.duracion_jornada AS duracion_jornada, 
                t1.orden_planning AS orden_planning, t1.is_rotativa AS is_rotativa, t1.precio_tinta_negro AS precio_tinta_negro, 
                t1.is_inkjet AS is_inkjet, t1.precio_tinta_color AS precio_tinta_color, t1.precio_tinta_cg AS precio_tinta_cg, t1.velocidad_corte AS velocidad_corte, 
                t1.precio_hora_corte AS precio_hora_corte, t1.metrosxminuto AS metrosxminuto, 
                t1.forzar_num_formas_horizontales_cubierta AS forzar_num_formas_horizontales_cubierta, 
                t1.forzar_num_formas_verticales_cubierta AS forzar_num_formas_verticales_cubierta, 
                t1.observaciones AS observaciones, t2.nombre AS padre"
            );
        $builder->join("lg_maquinas t2", "t1.padre_id = t2.id", "left");

        //JJO
        $builder->where("t1.is_deleted", 0);

        if (empty($search))
            return $builder;
        else {
            $builder->groupStart();
            foreach ($search as $col_search) {
                $column = self::SORTABLE[$col_search[0]];
                $value = $col_search[2];
                $builder->where("LOWER(CONVERT($column USING utf8)) COLLATE utf8_general_ci LIKE", "%" . strtolower($value) . "%");
            }
            $builder->groupEnd();
            return $builder;
        }
    }

    public function getMaquinaImpresionForPresupuesto($is_rotativa, $tarifa_tipo, $uso_tarifa , $tirada, $papel_impresion_id = -1)
    {
        /*
        1.-> tarifa_Tipo impresion
	        2.-> Maquina
		        3.-> Papeles impresion asociados a esa maquina
			        4.-> papeles genericos que aparecen en esos papeles impresion
        */
        $builder = $this->db
            ->table($this->table . " t1")
            ->distinct('t1.id')
            ->select(
                "t1.id AS id, t1.id AS maquina_id, t1.nombre AS maquina, t1.nombre AS nombre, t1.ancho_impresion AS ancho_impresion,
                t1.alto_impresion AS alto_impresion, t1.ancho AS ancho, t1.alto AS alto,
                t1.is_rotativa AS is_rotativa, t1.is_inkjet AS is_inkjet, t1.alto_click AS alto_click, t1.velocidad AS velocidad, 
                t1.precio_tinta_negro AS precio_tinta_negro, t1.precio_tinta_color AS precio_tinta_color, t1.precio_tinta_cg AS precio_tinta_cg, 
                t1.velocidad_corte AS velocidad_corte, t1.precio_hora_corte AS precio_hora_corte,
                t1.forzar_num_formas_horizontales_cubierta AS forzar_num_formas_horizontales_cubierta,
                t1.forzar_num_formas_verticales_cubierta AS forzar_num_formas_verticales_cubierta"
            )
            ->join("lg_maquinas_tarifas_impresion t2", "t1.id = t2.maquina_id", "left")            
            ->join("lg_maquina_papel_impresion t3", "t1.id = t3.maquina_id", "left")
            
            
            ->where("t1.is_deleted", 0)
            ->where("t1.tipo", "impresion")
            ->where("t1.is_rotativa", $is_rotativa)
            ->where("t2.is_deleted", 0)
            ->where("t3.papel_impresion_id", $papel_impresion_id)
            ->where("t3.active", 1)
            ->where("t1.min <=", $tirada)
            ->where("t1.max >=", $tirada);

            if(is_array($tarifa_tipo)){
                foreach($tarifa_tipo as $tarifa){
                    $builder->where("EXISTS (SELECT * FROM lg_maquinas_tarifas_impresion t2 WHERE t1.id=t2.maquina_id AND t2.tipo='{$tarifa}' AND t2.uso='{$uso_tarifa}' AND t2.is_deleted=0)"); 
                }    
            }
            else{
                $builder->where("t2.tipo", $tarifa_tipo);
                $builder->where("t2.uso", $uso_tarifa);
            }

        return $builder;

    }

    public function getNombre($id){
        $builder = $this->db
            ->table($this->table . " t1")
            ->select(
                "t1.nombre AS text");
            
        $builder->where("t1.id", $id);
        
        return $builder->orderBy("t1.id", "asc")->get()->getResultObject();
    }

    /**
     * Query for select2
     *
     * @param string|null $q Query param from select2 ajax request
     * @param string|null $type Tipo de maquina impresion,manipulado,acabado
     * @return array 
     */
    public function getSelectQuery(?string $q = null, ?string $type = null) : array
    {
        $query = $this->builder()->select(["id","nombre","tipo as description"])
        ->where("deleted_at",null);
        if($q){
            $query->like("nombre",$q);
        }
        if($type){
            $query->where("tipo",$type);
        }
        return $query->get()->getResultArray();
    }
}
