<?php
namespace App\Models\Tarifas;

class TarifaManipuladoModel extends \App\Models\BaseModel
{
    protected $table = "lg_tarifa_manipulado";

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

    const SORTABLE = [
        0 => "t1.nombre",
        1 => "precio_min",
        2 => "importe_fijo",
        3 => "t1.mostrar_en_presupuesto",
    ];

    protected $allowedFields = [
        "nombre",
        "precio_min",
        "code",
        "comment",
        "importe_fijo",
        "mostrar_en_presupuesto",
        "deleted_at",
        "is_deleted",
        "user_created_id",
        "user_updated_id",
        "mostrar_en_presupuesto_cliente"
    ];
    protected $returnType = "App\Entities\Tarifas\TarifaManipuladoEntity";

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

    protected $createdField = "created_at";

    protected $updatedField = "updated_at";

    public static $labelField = "nombre";

    protected $validationRules = [
        "nombre" => [
            "label" => "Tarifamanipulado.nombre",
            "rules" => "trim|required|max_length[255]",
        ],

        "precio_min" => [
            "label" => "Tarifamanipulado.precioMin",
            "rules" => "required|decimal",
        ],
        "importe_fijo" => [
            "label" => "Tarifamanipulado.importeFijo",
            "rules" => "required|decimal",
        ],
    ];

    protected $validationMessages = [
        "nombre" => [
            "max_length" => "Tarifamanipulado.validation.nombre.max_length",
            "required" => "Tarifamanipulado.validation.nombre.required",
        ],
        "precio_min" => [
            "required" => "Tarifamanipulado.validation.precio_min.required",
            "decimal" => "Tarifamanipulado.validation.precio_min.decimal",
        ],
        "importe_fijo" => [
            "required" => "Tarifamanipulado.validation.importe_fijo.required",
            "decimal" => "Tarifamanipulado.validation.importe_fijo.decimal",
        ],
    ];

    /**
     * Get resource data.
     *
     * @param string $search
     *
     * @return \CodeIgniter\Database\BaseBuilder
     */
    public function getResource(string $search = "")
    {
        $builder = $this->db->table($this->table . " t1")->select("t1.id AS id,t1.code AS code, t1.nombre AS nombre, t1.precio_min AS precio_min, t1.importe_fijo AS importe_fijo
        ,t1.mostrar_en_presupuesto AS mostrar_en_presupuesto,t1.mostrar_en_presupuesto_cliente AS mostrar_en_presupuesto_cliente");

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

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

    public function getServiciosManipuladoSelector()
    {
        /*
            Todos los servicios de manipulado activas que se pueden usar en presupuestos
        */
        $builder = $this->db
            ->table($this->table . " t1")
            ->select(
                "t1.id as value, t1.nombre AS label"
            )
            ->where("t1.is_deleted", 0)
            ->where("t1.mostrar_en_presupuesto", 1);

        return $builder->orderBy("t1.nombre", "asc")->get()->getResultObject();
    }

    public function getTarifaPresupuestoManipulado($tarifa_id, $tirada)
    {

        $builder = $this->db
            ->table($this->table . " t1")
            ->select(
                "t1.id AS tarifa_manipulado_id, t1.nombre AS tarifa_manipulado_nombre, t1.precio_min AS tarifa_precio_min, t1.importe_fijo AS tarifa_importe_fijo,
                t2.id AS tarifa_linea_id, t2.tirada_min AS tirada_min, t2.tirada_max AS tirada_max, 
                t2.precio_min AS precio_min, t2.precio_max AS precio_max, t2.margen AS margen"
            )
            ->join("tarifa_manipulado_lineas t2", "t1.id = t2.tarifa_manipulado_id", "left")
            ->where("t1.is_deleted", 0)
            //->where("t1.mostrar_en_presupuesto", 1)
            ->where("t2.is_deleted", 0);

        // check if tarifa_id is an array
        if (is_array($tarifa_id)) {
            // check if tarifa_id['id'] exists
            $builder->where('t1.id', array_key_exists('id', $tarifa_id)? $tarifa_id['id']:$tarifa_id['tarifa_id']);
        } else {
            $builder->where('t1.id', $tarifa_id);
        }

        $builder->where('t2.tirada_min <=', $tirada);
        $builder->where('t2.tirada_max >=', $tirada);

        return $builder->get()->getResultObject();
    }

    public function getNombreTarifaManipulado($id = -1)
    {
        /*
            Todos los servicios de encuadernacion activas que se pueden usar en presupuestos
        */
        $builder = $this->db
            ->table($this->table . " t1")
            ->select(
                "t1.nombre AS nombre"
            );
        $builder->where("t1.is_deleted", 0);
        if (is_array($id)) {
            $builder->where("t1.id", $id['id']);
        } else
            $builder->where("t1.id", $id);


        return $builder->orderBy("t1.nombre", "asc")->get()->getResultObject();
    }
}
