<?php
namespace App\Models\Tarifas;

class TarifaEncuadernacionLineaModel extends \App\Models\BaseModel
{
    protected $table = "tarifa_encuadernacion_lineas";

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

    const SORTABLE = [
        0 => "t1.id",
        1 => "t1.dimensiones_id",
        2 => "t1.paginas_libro_min",
        3 => "t1.paginas_libro_max",
        4 => "t1.precio_min",
        5 => "t1.precio_max",
        6 => "t1.total_min",
        7 => "t1.margen",
    ]; 

    protected $allowedFields = [
        "tirada_encuadernacion_id",
        "paginas_libro_min",
        "paginas_libro_max",
        "dimensiones_id",
        "precio_min",
        "precio_max",
        "tirada_min",
        "tirada_max",
        "margen",
        "total_min",
        "user_created_id",
        "is_deleted",

    ];
    protected $returnType = "App\Entities\Tarifas\TarifaEncuadernacionLinea";

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

    protected $createdField = "created_at";

    protected $updatedField = "updated_at";

    public static $labelField = "tirada_encuadernacion_id";

    protected $validationRules = [
        "precio_max" => [
            "label" => "TarifaEncuadernacionLineas.precioMax",
            "rules" => "required|decimal",
        ],
        "precio_min" => [
            "label" => "TarifaEncuadernacionLineas.precioMin",
            "rules" => "required|decimal",
        ],
        "tirada_max" => [
            "label" => "TarifaEncuadernacionLineas.tiradaMax",
            "rules" => "required|decimal",
        ],
        "tirada_min" => [
            "label" => "TarifaEncuadernacionLineas.tiradaMin",
            "rules" => "required|decimal",
        ],
        "total_min" => [
            "label" => "TarifaEncuadernacionLineas.precioMin",
            "rules" => "required|decimal",
        ],
        "paginas_libro_max" => [
            "label" => "TarifaEncuadernacionLineas.paginasMax",
            "rules" => "required|decimal",
        ],
        "paginas_libro_min" => [
            "label" => "TarifaEncuadernacionLineas.paginasMin",
            "rules" => "required|decimal",
        ],
        "margen" => [
            "label" => "TarifaEncuadernacionLineas.margen",
            "rules" => "required|decimal",
        ],
    ];

    protected $validationMessages = [
        "precio_max" => [
            "decimal" => "TarifaEncuadernacionLineas.validation.precio_max.decimal",
            "required" => "TarifaEncuadernacionLineas.validation.precio_max.required",
        ],
        "precio_min" => [
            "decimal" => "TarifaEncuadernacionLineas.validation.precio_min.decimal",
            "required" => "TarifaEncuadernacionLineas.validation.precio_min.required",
        ],
        "tirada_max" => [
            "decimal" => "TarifaEncuadernacionLineas.validation.tirada_max.decimal",
            "required" => "TarifaEncuadernacionLineas.validation.tirada_max.required",
        ],
        "tirada_min" => [
            "decimal" => "TarifaEncuadernacionLineas.validation.tirada_min.decimal",
            "required" => "TarifaEncuadernacionLineas.validation.tirada_min.required",
        ],
        "total_min" => [
            "decimal" => "TarifaEncuadernacionLineas.validation.precio_min.decimal",
            "required" => "TarifaEncuadernacionLineas.validation.precio_min.required",
        ],
        "paginas_libro_max" => [
            "decimal" => "TarifaEncuadernacionLineas.validation.paginas_libro_max.decimal",
            "required" => "TarifaEncuadernacionLineas.validation.paginas_libro_max.required",
        ],
        "paginas_libro_min" => [
            "decimal" => "TarifaEncuadernacionLineas.validation.paginas_libro_min.decimal",
            "required" => "TarifaEncuadernacionLineas.validation.paginas_libro_min.required",
        ],
        "margen" => [
            "decimal" => "TarifaEncuadernacionLineas.validation.margen.decimal",
            "required" => "TarifaEncuadernacionLineas.validation.margen.required",
        ],
    ];

    /**
     * Get resource data.
     *
     * @param string $search
     *
     * @return \CodeIgniter\Database\BaseBuilder
     */
    public function getResource(string $search = "", $tirada_encuadernacion_id = -1)
    {
        $builder = $this->db
            ->table($this->table . " t1")
            ->select(
                "t1.id AS id, t1.tirada_encuadernacion_id AS tirada_encuadernacion_id, t1.paginas_libro_min AS paginas_libro_min, t1.paginas_libro_max AS paginas_libro_max, t1.precio_min AS precio_min, t1.precio_max AS precio_max, t1.tirada_min AS tirada_min, 
                t1.tirada_max AS tirada_max, t1.total_min as total_min, t1.margen AS margen, t2.id AS tarifa_encuadernacion, t3.id AS dimensiones_id, t3.ancho_min, t3.ancho_max, , t3.alto_min, t3.alto_max, t3.descripcion as descripcion"
            );
        //JJO
        $builder->where('tirada_encuadernacion_id', $tirada_encuadernacion_id);    
        $builder->where("t1.is_deleted", 0);

        $builder->join("tarifa_encuadernacion_tiradas    t2", "t1.tirada_encuadernacion_id = t2.id", "left");
        $builder->join("tarifa_encuadernacion_dimensiones    t3", "t1.dimensiones_id = t3.id", "left");
        


        return empty($search)
            ? $builder
            : $builder
                ->groupStart()
                ->like("t1.id", $search)
                ->orLike("t1.tirada_encuadernacion_id", $search)
                ->orLike("t1.paginas_libro_min", $search)
                ->orLike("t1.paginas_libro_max", $search)
                ->orLike("t1.precio_min", $search)
                ->orLike("t1.precio_max", $search)
                ->orLike("t1.tirada_min", $search)
                ->orLike("t1.tirada_max", $search)
                ->groupEnd();
    }

    public function checkIntervals($data = [], $id_linea = null, $tirada_encuadernacion_id = null){
        
        helper('general');

        if(floatval($data["paginas_libro_min"])>= floatval($data["paginas_libro_max"])){
            return lang('TarifaEncuadernacionLineas.validation.error_paginas_range');
        }

        $rows = $this->db
            ->table($this->table)
            ->select("id, paginas_libro_min, paginas_libro_max, dimensiones_id")
            ->where("is_deleted", 0)
            ->where("tirada_encuadernacion_id", $tirada_encuadernacion_id)
            ->get()->getResultObject();


        foreach ($rows as $row) {
            if (!is_null($id_linea)){
                if($row->id == $id_linea){
                    continue;
                }
            }
            if($data['dimensiones_id'] == $row->dimensiones_id){
                if(check_overlap(floatval($data["paginas_libro_min"]), floatval($data["paginas_libro_max"]),
                                    $row->paginas_libro_min, $row->paginas_libro_max)){
                        return lang('TarifaEncuadernacionLineas.validation.error_paginas_overlap');
                }
            }
        }

        return "";
    }

    public function removeAllEncuadernacionLineas($tiradaId = -1, $datetime = null, $delete_flag=1){
        
        $builder = $this->db
            ->table($this->table)
            ->set(['deleted_at' =>  $datetime->format('Y-m-d H:i:s'),
                    'is_deleted' => $delete_flag])
            ->where('tirada_encuadernacion_id',$tiradaId)
            ->update();

        return $builder;
    }
    

    public function removeAllEncuadernacionLineasForTarifa($tarifaId = -1, $datetime = null, $delete_flag=1){
        
        $builder = $this->db
            ->table($this->table . " t1")
            ->select('t1.id')
            ->join("tarifa_encuadernacion_tiradas t2", "t1.tirada_encuadernacion_id = t2.id", "left")
            ->join("tarifa_encuadernacion t3", "t2.tarifa_encuadernacion_id = t3.id", "left")
            ->where("t3.id", $tarifaId);
            
                
        $ids = $builder->get()->getResultArray();
        foreach($ids as $id){
            $builder = $this->db
                ->table($this->table . " t1")
                ->set(["t1.deleted_at" =>  $datetime->format('Y-m-d H:i:s'),
                    "t1.is_deleted" => $delete_flag])
                ->where('t1.id', $id["id"])
                ->update();
        }
    }
}
