<?php
namespace App\Models\Tarifas\Acabados;

use function PHPUnit\Framework\isNan;
use function PHPUnit\Framework\isNull;

class TarifaAcabadoLineaModel extends \App\Models\BaseModel
{
    protected $table = "tarifa_acabado_lineas";

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

    const SORTABLE = [
        0 => "t3.nombre",
        1 => "t1.tirada_min",
        2 => "t1.precio_max",
        3 => "t1.tirada_max",
        4 => "t1.precio_min",
        5 => "t1.margen",
    ];

    protected $allowedFields = [
        "proveedor_id",
        "tirada_min",
        "tirada_max",
        "precio_min",
        "precio_max",
        "margen",
        "user_created_id",
        "is_deleted",
    ];
    protected $returnType = "App\Entities\Tarifas\TarifaAcabadoLinea";

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

    protected $createdField = "created_at";

    protected $updatedField = "updated_at";

    public static $labelField = "tarifa_acabado_id";

    protected $validationRules = [
        "is_deleted" => [
            "label" => "TarifaAcabadoLineas.isDeleted",
            "rules" => "required|integer",
        ],
        "precio_max" => [
            "label" => "TarifaAcabadoLineas.precioMax",
            "rules" => "required|decimal",
        ],
        "precio_min" => [
            "label" => "TarifaAcabadoLineas.precioMin",
            "rules" => "required|decimal",
        ],
        "tirada_max" => [
            "label" => "TarifaAcabadoLineas.tiradaMax",
            "rules" => "required|integer",
        ],
        "tirada_min" => [
            "label" => "TarifaAcabadoLineas.tiradaMin",
            "rules" => "required|integer",
        ],
        "user_created_id" => [
            "label" => "TarifaAcabadoLineas.userCreatedId",
            "rules" => "required|integer",
        ],
    ];

    protected $validationMessages = [
        "is_deleted" => [
            "integer" => "TarifaAcabadoLineas.validation.is_deleted.integer",
            "required" => "TarifaAcabadoLineas.validation.is_deleted.required",
        ],
        "precio_max" => [
            "decimal" => "TarifaAcabadoLineas.validation.precio_max.decimal",
            "required" => "TarifaAcabadoLineas.validation.precio_max.required",
        ],
        "precio_min" => [
            "decimal" => "TarifaAcabadoLineas.validation.precio_min.decimal",
            "required" => "TarifaAcabadoLineas.validation.precio_min.required",
        ],
        "tirada_max" => [
            "integer" => "TarifaAcabadoLineas.validation.tirada_max.integer",
            "required" => "TarifaAcabadoLineas.validation.tirada_max.required",
        ],
        "tirada_min" => [
            "integer" => "TarifaAcabadoLineas.validation.tirada_min.integer",
            "required" => "TarifaAcabadoLineas.validation.tirada_min.required",
        ],
        "margen" => [
            "integer" => "TarifaAcabadoLineas.validation.margen.integer",
            "required" => "TarifaAcabadoLineas.validation.margen.required",
        ],
        "user_created_id" => [
            "integer" => "TarifaAcabadoLineas.validation.user_created_id.integer",
            "required" => "TarifaAcabadoLineas.validation.user_created_id.required",
        ],
    ];

    public function findAllWithTarifaAcabado(string $selcols = "*", int $limit = null, int $offset = 0)
    {
        $sql =
            "SELECT t1." .
            $selcols .
            ",  t2.id AS tarifa_acabado FROM " .
            $this->table .
            " t1  LEFT JOIN lg_tarifa_acabado t2 ON t1.tarifa_acabado_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;
    }

    /**
     * Get resource data.
     *
     * @param string $search
     *
     * @return \CodeIgniter\Database\BaseBuilder
     */
    public function getResource($search = [], $tarifa_acabado_id = -1)
    {
        $builder = $this->db
            ->table($this->table . " t1")
            ->select(
                "t1.id AS id, t1.proveedor_id AS proveedor_id, t3.nombre AS proveedor_nombre, t1.tirada_min AS tirada_min, t1.tirada_max AS tirada_max, t1.precio_min AS precio_min, t1.precio_max AS precio_max, t1.margen AS margen, t2.id AS tarifa_acabado"
            );

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

        $builder->join("lg_tarifa_acabado t2", "t1.tarifa_acabado_id = t2.id", "left");
        $builder->join("lg_proveedores t3", "t1.proveedor_id = t3.id", "left");

        
        if (empty($search))
            return $builder;
        else {
            $filterEnabled = 0;
            
            foreach ($search as $col_search) {
                if($col_search[0] != 0){
                    if(strlen($col_search[2]) > 1){
                        $values = explode(",",$col_search[2]);
                        $min_val = floatval($values[0]);
                        $max_val = floatval($values[1]);
                        if(!is_nan($min_val) && !is_null($min_val) && strlen($values[0]) > 0){
                            if($filterEnabled == 0){
                                $builder->groupStart();
                                $filterEnabled = 1;
                            }
                            $builder->where(self::SORTABLE[$col_search[0]] . " >=", $min_val);
                        }
                        if(!is_nan($max_val) && !is_null($max_val) && strlen($values[1]) > 0){
                            if($filterEnabled == 0){
                                $builder->groupStart();
                                $filterEnabled = 1;
                            }
                            $builder->where(self::SORTABLE[$col_search[0]] . " <", $max_val);
                        }
                    }
                }
                else{
                    if(strlen($col_search[2]) > 1){
                        $values = explode(",",$col_search[2]);
                        if(count($values) > 1){
                            foreach ($values as $value) {
                                if($filterEnabled == 0){
                                    $builder->groupStart();
                                    $filterEnabled = 1;
                                }
                                $builder->orWhere("t1.proveedor_id", $value);
                            }
                        }
                        else{
                            if($filterEnabled == 0){
                                $builder->groupStart();
                                $filterEnabled = 1;
                            }
                            $builder->where("t1.proveedor_id", $col_search[2]);
                        }
                    }
                }
                
            }
            if($filterEnabled == 1){
                $builder->groupEnd();
            }
            

            return $builder;
        }
    }

    public function findLineasForTarifaAcabado(int $tarifaacabado_id){
        
        $builder = $this->db
            ->table($this->table )
            ->select("*")
            ->where("tarifa_acabado_id", $tarifaacabado_id);


        return $builder;        

    }

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

        if(floatval($data["tirada_min"])>= floatval($data["tirada_max"])){
            return lang('TarifaAcabadoLineas.validation.error_tirada_range');
        }

        $rows = $this->db
            ->table($this->table)
            ->select("id, tirada_min, tirada_max")
            ->where("is_deleted", 0)
            ->where("tarifa_acabado_id", $id_tarifa_acabado)
            ->where("proveedor_id", $data["proveedor_id"])
            ->get()->getResultObject();


        foreach ($rows as $row) {
            if (!is_null($id_linea)){
                if($row->id == $id_linea){
                    continue;
                }
            }
            if(check_overlap(floatval($data["tirada_min"]), floatval($data["tirada_max"]),
                                $row->tirada_min, $row->tirada_max)){
                    return lang('TarifaAcabadoLineas.validation.error_tirada_overlap');
            }
        }

        return "";
    }
}
