<?php
namespace App\Models\Tarifas;

class TarifaEncuadernacionLineaHorasModel extends \App\Models\BaseModel
{
    protected $table = "tarifa_encuadernacion_lineas_horas";

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

    const SORTABLE = [
        0 => "t1.id",
        1 => "t1.tiempo_min",
        2 => "t1.tiempo_max",
        3 => "t1.precio_hora",
        4 => "t1.total_min",
        5 => "t1.margen",
    ];

    protected $allowedFields = [
        "tirada_encuadernacion_id",
        "tiempo_min",
        "tiempo_max",
        "precio_hora",
        "total_min",
        "margen",
        "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 = [
        "tiempo_max" => [
            "label" => "TarifaEncuadernacionLineas.tiempoMax",
            "rules" => "required|decimal",
        ],
        "tiempo_min" => [
            "label" => "TarifaEncuadernacionLineas.tiempoMin",
            "rules" => "required|decimal",
        ],
        "precio_hora" => [
            "label" => "TarifaEncuadernacionLineas.precioHora",
            "rules" => "required|decimal",
        ],
        "total_min" => [
            "label" => "TarifaEncuadernacionLineas.precioHora",
            "rules" => "required|decimal",
        ],
        "margen" => [
            "label" => "TarifaEncuadernacionLineas.margen",
            "rules" => "required|decimal",
        ],
    ];

    protected $validationMessages = [
        "tiempo_min" => [
            "decimal" => "TarifaEncuadernacionLineas.validation.precio_max.decimal",
            "required" => "TarifaEncuadernacionLineas.validation.precio_max.required",
        ],
        "tiempo_max" => [
            "decimal" => "TarifaEncuadernacionLineas.validation.precio_min.decimal",
            "required" => "TarifaEncuadernacionLineas.validation.precio_min.required",
        ],
        "precio_hora" => [
            "decimal" => "TarifaEncuadernacionLineas.validation.tirada_max.decimal",
            "required" => "TarifaEncuadernacionLineas.validation.tirada_max.required",
        ],
        "total_min" => [
            "decimal" => "TarifaEncuadernacionLineas.validation.tirada_max.decimal",
            "required" => "TarifaEncuadernacionLineas.validation.tirada_max.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.tiempo_min AS tiempo_min, 
                t1.tiempo_max AS tiempo_max, t1.precio_hora AS precio_hora, t1.total_min AS total_min, t1.margen AS margen, 
                t2.id AS tarifa_encuadernacion"
            );
        //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");
        

        return empty($search)
            ? $builder
            : $builder
                ->groupStart()
                ->like("t1.id", $search)
                ->orLike("t1.tirada_encuadernacion_id", $search)
                ->orLike("t1.tiempo_min", $search)
                ->orLike("t1.tiempo_max", $search)
                ->orLike("t1.precio_hora", $search)
                ->orLike("t1.margen", $search)
                ->groupEnd();
    }

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

        if(floatval($data["tiempo_min"])>= floatval($data["tiempo_max"])){
            return lang('TarifaEncuadernacionLineas.validation.error_tiempo_range');
        }

        $rows = $this->db
            ->table($this->table)
            ->select("id, tiempo_min, tiempo_max")
            ->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(check_overlap_with_extremos(floatval($data["tiempo_min"]), floatval($data["tiempo_max"]),
                                $row->tiempo_min, $row->tiempo_max)){
                    return lang('TarifaEncuadernacionLineas.validation.error_tiempo_overlap');
            }
            
        }

        return "";
    }

    public function removeAllEncuadernacionLineasHoras($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 removeAllEncuadernacionLineasHorasForTarifa($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();
        }
    }
}
