<?php
namespace App\Models\Configuracion;

use CodeIgniter\Database\RawSql;

class MaquinasPapelesImpresionModel extends \App\Models\BaseModel
{
    protected $table = "lg_maquina_papel_impresion";

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

    const SORTABLE = [
        0 => "t1.active",
        1 => "t4.nombre",
        2 => "t3.nombre",
        3 => "t3.gramaje",
        4 => "t3.bn",
        5 => "t3.color",
        6 => "t3.cubierta",
        7 => "t3.sobrecubierta",
        8 => "t3.rotativa",
    ];

    const SORTABLE_2 = [
        0 => "t1.active",
        1 => "t2.nombre",
        2 => "t2.ancho",
        3 => "t2.alto",
        4 => "t2.ancho_impresion",
        5 => "t2.alto_impresion",

        
    ];

    protected $allowedFields = ["maquina_id", "papel_impresion_id", "active"];
    protected $returnType = "App\Entities\Configuracion\MaquinasPapelesImpresionEntity";


    /**
     * Get resource data.
     *
     * @param string $search
     *
     * @return \CodeIgniter\Database\BaseBuilder
     */
    public function getResource(string $search = "", $isRotativa = 0, $tarifas = [], $maquina_id = -1)
    {
        $builder = $this->db
            ->table($this->table . " t1")
            ->select(
                "t1.maquina_id AS maquina_id, t1.papel_impresion_id AS papel_impresion_id, t1.active AS active, t2.nombre AS maquina,
                 t3.nombre AS papel_impresion, t3.gramaje AS gramaje, , t3.bn AS bn, t3.color AS color, t3.cubierta AS cubierta, , t3.sobrecubierta AS sobrecubierta,
                 t3.rotativa AS rotativa, t4.nombre as papel_generico"
            )
            ->join("lg_papel_impresion t3", "t1.papel_impresion_id = t3.id", "left")
            ->join("lg_maquinas t2", "t1.maquina_id = t2.id", "left")
            ->join("lg_papel_generico t4", "t3.papel_generico_id = t4.id", "left");
            
        $builder->where("t1.maquina_id", $maquina_id);
        $builder->where("t2.is_deleted", 0);
        $builder->where("t3.is_deleted", 0);
        $builder->where("t4.is_deleted", 0);
        $builder->where("t3.isActivo", 1);

        $builder->where("t3.rotativa", $isRotativa);

        $isFirst = true;
        $where_str = "(";
        //Si hay tarifas...
        if (!empty($tarifas)){
            foreach ($tarifas as $tarifa){
                
                if (!$isFirst)
                    $where_str .= ' OR ';
                else{
                    $isFirst = false;
                }
                if ($tarifa->uso == 'cubierta')
                    $where_str .= "t3.cubierta=1";
                else if ($tarifa->uso == 'sobrecubierta')
                    $where_str .= "t3.sobrecubierta=1";
                else{
                    if ($tarifa->tipo == 'negro' || $tarifa->tipo == 'negrohq')
                        $where_str .= "t3.bn=1";       
                    else
                        $where_str .= "t3.color=1";
                }
            }
            $where_str .= ")";
            $builder->where(new RawSql($where_str));
        }
        // si no hay tarifas no hay que devolver nada
        else{
            // Se pone una condicion que no se puede dar
            $builder->where("t3.bn", 2);
        }
        

        return empty($search)
            ? $builder
            : $builder
                ->groupStart()
                ->like("t2.nombre", $search)
                ->orLike("t3.nombre", $search)
                ->groupEnd();
    }

    /**
     * Get resource data for Papeles impresion.
     *
     * @param string $search
     *
     * @return \CodeIgniter\Database\BaseBuilder
     */
    public function getResource_maquinas(string $search = "", $papel_id = -1, $isRotativa = -1)
    {
        $builder = $this->db
            ->table($this->table . " t1")
            ->select(
                "t1.maquina_id AS maquina_id, t1.papel_impresion_id AS papel_impresion_id, t1.active AS active, t2.nombre AS maquina,
                t2.ancho AS ancho, t2.alto AS alto, t2.ancho_impresion AS anchoimpresion, t2.alto_impresion AS altoimpresion"
            )
            ->join("lg_maquinas t2", "t1.maquina_id = t2.id", "left")
            ->join("lg_papel_impresion t3", "t1.papel_impresion_id = t3.id", "left");
            
        $builder->where("t1.papel_impresion_id", $papel_id);
        $builder->where("t2.is_deleted", 0);
        $builder->where("t2.is_rotativa", $isRotativa);
        $builder->where("t3.is_deleted", 0);
        $builder->where("t3.isActivo", 1);


        return empty($search)
            ? $builder
            : $builder
                ->groupStart()
                ->like("t2.nombre", $search)
                ->groupEnd();
    }


    public function getInitData($isRotativa = 0, $isInkjet=0, $tarifas = [], $maquina_id = -1)
    {
        $builder = $this->db
            ->table($this->table . " t1")
            ->select(
                "t1.*"
            );

        $builder->join("lg_papel_impresion t2", "t1.papel_impresion_id = t2.id", "left");
        
        $builder->where("t1.maquina_id", $maquina_id);
        $builder->where("t2.is_deleted", 0);
        $builder->where("t2.isActivo", 1);
        $builder->where("t2.rotativa", $isRotativa);
        //$builder->where("t2.inkjet", $isInkjet);
        $builder->where("t1.active", 1);
        
        $isFirst = true;
        $where_str = "(";
        //Si hay tarifas...
        if (!empty($tarifas)){
            foreach ($tarifas as $tarifa){
                if (!$isFirst)
                    $where_str .= ' OR ';
                else{
                    $isFirst = false;
                }
                if ($tarifa->uso == 'cubierta')
                    $where_str .= "`t2`.`cubierta`=1";
                else if ($tarifa->uso == 'sobrecubierta')
                    $where_str .= "`t2`.`sobrecubierta`=1";
                else{
                    if ($tarifa->tipo == 'negro' || $tarifa->tipo == 'negrohq')
                        $where_str .= "`t2`.`bn`=1 ";       
                    else
                        $where_str .= "`t2`.`color`=1 ";
                }
            }
            $where_str .= ")";
            $builder->where($where_str);
        }
        // si no hay tarifas no hay que devolver nada
        else{
            // Se pone una condicion que no se puede dar
            $builder->where("t2.bn", 2);
        }
       
        return $builder;
    }


    // Funcion para obtener todas las máquinas seleccionadas para un papel
    public function getInitSelectedMachines($papel_impresion_id= -1, $isRotativa=false, $isInkjet=false)
    {
        $builder = $this->db
            ->table($this->table . " t1")
            ->select(
                "t1.*"
            );

        $builder->join("lg_maquinas t2", "t1.maquina_id = t2.id", "left");

        $builder->where("t1.papel_impresion_id", $papel_impresion_id);
        $builder->where("t1.active", 1);

        // Se aplican las condiciones que tienen que cumplir
        $builder->where("t2.is_rotativa", $isRotativa);
        //$builder->where("t2.is_inkjet", $isInkjet);
        
        return $builder;
    }

    // Borrar todas las filas para un papel impresion determinado
    public function deleteForPapelImpresion($papel_impresion_id= -1){
        $this->db
            ->table($this->table . " t1")
            ->where("papel_impresion_id", $papel_impresion_id)
            ->delete();
    }


    // Funcion para consultar los papeles activos con un gramaje 
    // determinado seleccionados para una máquina
    public function getPapelActivo($maquina_id=-1, $gramaje=-1){
        $builder = $this->db
            ->table($this->table . " t1")
            ->select(
                "t1.*"
            );
        $builder->join("lg_papel_impresion t2", "t1.papel_impresion_id = t2.id", "left");

        $builder->where('t1.active', 1);
        $builder->where('t1.maquina_id', $maquina_id);
        $builder->where('t2.gramaje', $gramaje);

        return $builder;
    }


    // Funcion que borra todos los registros de una máquina determinada
    public function deleteRows($maquina_id = -1){
        $this->db
            ->table($this->table . " t1")
            ->where("maquina_id", $maquina_id)
            ->delete();
    }


    // Funcion que inserta valores en la tabla
    public function insertRows($values = []){
        if (!empty($values)){
            $this->db->table($this->table)->insertBatch($values);
        }
    }

    // Funcion que actualiza valores en la tabla  
    public function updateRows($values = []){
        if (!empty($values)){
            foreach($values as $value){
                $builder = $this->db->table($this->table)->where('maquina_id', $value['maquina_id']);
                $builder->where('papel_impresion_id', $value['papel_impresion_id']);
                $builder->update($value);
            }
            
        }
    }
}
