<?php
namespace App\Models\Configuracion;

class PapelImpresionModel extends \App\Models\BaseModel
{
    protected $table = "lg_papel_impresion";

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

    const SORTABLE = [
        0 => "t1.nombre",
        1 => "t2.nombre",
        2 => "t1.gramaje",
        3 => "t1.interior",
        4 => "t1.bn",
        5 => "t1.color",
        6 => "t1.cubierta",
        7 => "t1.use_for_tapa_dura",
        8 => "t1.sobrecubierta",
        9 => "t1.guardas",
        10 => "t1.inkjet",
        11 => "t1.rotativa",
        12 => "t1.isActivo",
        13 => "t1.use_in_client",
    ];


    protected $allowedFields = [
        "papel_generico_id",
        "nombre",
        "defecto",
        "referencia",
        "mano",
        "espesor",
        "gramaje",
        "precio_tonelada",
        "interior",
        "bn",
        "color",
        "cubierta",
        "sobrecubierta",
        "guardas",
        "inkjet",
        "rotativa",
        "isActivo",
        "use_in_client",
        "use_for_tapa_dura",
        "deleted_at",
        "is_deleted",
        "user_updated_id",
    ];
    protected $returnType = "App\Entities\Configuracion\PapelImpresion";

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

    protected $createdField = "created_at";

    protected $updatedField = "updated_at";

    public static $labelField = "nombre";

    protected $validationRules = [
        "espesor" => [
            "label" => "PapelImpresion.espesor",
            "rules" => "required|decimal",
        ],
        "gramaje" => [
            "label" => "PapelImpresion.gramaje",
            "rules" => "required|decimal",
        ],
        "mano" => [
            "label" => "PapelImpresion.mano",
            "rules" => "required|decimal",
        ],
        "nombre" => [
            "label" => "PapelImpresion.nombre",
            "rules" => "trim|required|max_length[255]",
        ],
        "precio_tonelada" => [
            "label" => "PapelImpresion.precioTonelada",
            "rules" => "required|decimal",
        ],
        "referencia" => [
            "label" => "PapelImpresion.referencia",
            "rules" => "trim|max_length[13]",
        ],
    ];

    protected $validationMessages = [
        "espesor" => [
            "decimal" => "PapelImpresion.validation.espesor.decimal",
            "required" => "PapelImpresion.validation.espesor.required",
        ],
        "gramaje" => [
            "decimal" => "PapelImpresion.validation.gramaje.decimal",
            "required" => "PapelImpresion.validation.gramaje.required",
        ],
        "mano" => [
            "decimal" => "PapelImpresion.validation.mano.decimal",
            "required" => "PapelImpresion.validation.mano.required",
        ],
        "nombre" => [
            "max_length" => "PapelImpresion.validation.nombre.max_length",
            "required" => "PapelImpresion.validation.nombre.required",
        ],
        "precio_tonelada" => [
            "decimal" => "PapelImpresion.validation.precio_tonelada.decimal",
            "required" => "PapelImpresion.validation.precio_tonelada.required",
        ],
        "referencia" => [
            "max_length" => "PapelImpresion.validation.referencia.max_length",
            //"required" => "PapelImpresion.validation.referencia.required",
        ],
    ];

    public function findAllWithPapelGenerico(string $selcols = "*", int $limit = null, int $offset = 0)
    {
        $sql =
            "SELECT t1." .
            $selcols .
            ",  t2.nombre AS papel_generico_id FROM " .
            $this->table .
            " t1  LEFT JOIN lg_papel_generico t2 ON t1.papel_generico_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(string $search = "", $generico_id = -1)
    {
        $builder = $this->db
            ->table($this->table . " t1")
            ->select(
                "t1.id AS id, t1.nombre AS nombre, t1.defecto AS defecto, t1.referencia AS referencia, t1.mano AS mano, 
                t1.espesor AS espesor, t1.gramaje AS gramaje, t1.interior AS interior, t1.precio_tonelada AS precio_tonelada, 
                t1.bn AS bn, t1.color AS color, t1.cubierta AS cubierta, t1.use_for_tapa_dura AS use_for_tapa_dura,
                t1.sobrecubierta AS sobrecubierta, t1.guardas AS guardas, 
                t1.inkjet AS inkjet, t1.rotativa AS rotativa, 
                t1.isActivo AS isActivo, t2.nombre AS papel_generico_id,
                t1.use_in_client AS use_in_client"
            );

        $builder->join("lg_papel_generico t2", "t1.papel_generico_id = t2.id", "left");
        $builder->where("t1.is_deleted", 0);
        if ($generico_id > 0) {
            $builder->where("t1.papel_generico_id", $generico_id);
        }

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

    public function getIdPapelesImpresion($maquina_id = -1, $tarifas = [])
    {
        $builder = $this->db
            ->table($this->table . " t1")
            ->select(
                "'" . $maquina_id . "'" . " as maquina_id, t1.id AS papel_impresion_id, '0' as active"
            );

        $builder->where("t1.is_deleted", 0);
        $builder->where("t1.isActivo", 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 .= "`t1`.`cubierta`=1";
                else if ($tarifa->uso == 'sobrecubierta')
                    $where_str .= "`t1`.`sobrecubierta`=1";
                else {
                    if ($tarifa->tipo == 'negro' || $tarifa->tipo == 'negrohq')
                        $where_str .= "`t1`.`bn`=1 ";
                    else
                        $where_str .= "`t1`.`color`=1 ";
                }
            }
            $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("t1.bn", 2);
        }

        return $builder;
    }

    /**
     * @param null $papel_generico_id
     * @param null $gramaje
     * @param mixed $options
     *                  array con las opciones para bn,color,cubierta,sobrecubierta,rotativa
     * @param mixed $is_activo=true
     * 
     * @return [type]
     */
    public function getIdPapelesImpresionForPresupuesto($papel_generico_id = null, $gramaje = null, $options = [])
    {
        $bn = array_key_exists('bn', $options) ? $options['bn'] : null;
        $color = array_key_exists('color', $options) ? $options['color'] : null;
        $cubierta = array_key_exists('cubierta', $options) ? $options['cubierta'] : null;
        $sobrecubierta = array_key_exists('sobrecubierta', $options) ? $options['sobrecubierta'] : null;
        $guardas = array_key_exists('guardas', $options) ? $options['guardas'] : null;
        $rotativa = array_key_exists('rotativa', $options) ? $options['rotativa'] : null;

        $builder = $this->db
            ->table($this->table . " t1")
            ->distinct("t1.id")
            ->select(
                "t1.id AS id, t1.nombre AS nombre, t1.papel_generico_id AS papel_generico_id, 
                t1.gramaje as gramaje, t1.espesor AS espesor, t1.precio_tonelada AS precio_tonelada, t1.rotativa AS rotativa"
            );

        $builder->where("t1.is_deleted", 0);
        $builder->where("t1.isActivo", 1);

        $builder->where("t1.papel_generico_id", $papel_generico_id);
        $builder->where("t1.gramaje", $gramaje);

        if (!is_null($bn)) {
            $builder->where("t1.bn", $bn);
        }
        if (!is_null($color)) {
            $builder->where("t1.color", $color);
        }
        if (!is_null($cubierta)) {
            $builder->where("t1.cubierta", $cubierta);
        }
        if (!is_null($sobrecubierta)) {
            $builder->where("t1.sobrecubierta", $sobrecubierta);
        }
        if (!is_null($guardas)) {
            $builder->where("t1.guardas", $guardas);
        }
        if (!is_null($rotativa)) {
            $builder->where("t1.rotativa", $rotativa);
        }

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

    //tipo: negro, negrohq, color, colorhq
    //uso: interior, rotativa, cubierta, sobrecubierta
    public function getPapelesImpresionForMenu(
        $papel_generico = null,
        $gramaje = null,
        $tipo = null,
        $uso = "",
        $tapaDura = false,
        $forInkjet = false
    ) {

        $builder = $this->db
            ->table($this->table . " t1")
            ->distinct("t1.id")
            ->join("lg_papel_generico t2", "t1.papel_generico_id = t2.id", "left")
            ->join("lg_maquina_papel_impresion t3", "t1.id = t3.papel_impresion_id", "left")
            ->join("lg_maquinas t4", "t3.maquina_id = t4.id", "left")
            ->join("lg_maquinas_tarifas_impresion t5", "t4.id = t5.maquina_id", "left")
            ->select(
                "t1.id AS id, t1.nombre AS nombre"
            );

        $builder->where("t1.is_deleted", 0);
        $builder->where("t1.isActivo", 1);
        $builder->where("t2.is_deleted", 0);
        $builder->where("t3.active", 1);
        $builder->where("t4.is_deleted", 0);
        $builder->where("t4.tipo", 'impresion');
        $builder->where("t5.is_deleted", 0);
        $builder->where("t5.tipo", $tipo);

        $builder->where("t2.id", $papel_generico);
        $builder->where("t1.gramaje", $gramaje);

        if ($uso == 'cubierta') {
            if ($tapaDura)
                $builder->where("t1.use_for_tapa_dura", 1);
            $builder->where("t1.cubierta", 1);
        } else if ($uso == 'sobrecubierta')
            $builder->where("t1.sobrecubierta", 1);
        else if ($uso == 'guardas')
            $builder->where("t1.guardas", 1);
        else {
            $builder->where("t1.interior", 1);
            if ($tipo == 'negro' || $tipo == 'negrohq')
                $builder->where("t1.bn", 1);
            else if ($tipo == 'color' || $tipo == 'colorhq')
                $builder->where("t1.color", 1);
        }
        if ($uso == 'rotativa') {
            $builder->where("t1.rotativa", 1);
            $builder->where("t4.is_rotativa", 1);
        } else
            $builder->where("t1.rotativa", 0);

        if ($forInkjet)
            $builder->where("t1.inkjet", 1);

        return $builder;
    }

    public function getNombre($id)
    {
        $builder = $this->db
            ->table($this->table . " t1")
            ->select(
                "t1.nombre AS text"
            );

        $builder->where("t1.id", $id);

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

    public function getPapelGenericoCode($papel_id = 0)
    {
        $builder = $this->db
            ->table($this->table . " t1")
            ->select("t2.code AS code")
            ->join("lg_papel_generico t2", "t1.papel_generico_id = t2.id", "left")
            ->where("t1.id", $papel_id)
            ->where("t1.is_deleted", 0)
            ->where("t1.isActivo", 1)
            ->where("t2.is_deleted", 0);

        $result = $builder->get()->getResultObject();
        if (count($result) > 0) {
            return $result[0]->code;
        } else
            return "";
    }

    public function getPapelGenericoNombre($papel_id = 0)
    {
        $builder = $this->db
            ->table($this->table . " t1")
            ->select("t2.nombre AS nombre")
            ->join("lg_papel_generico t2", "t1.papel_generico_id = t2.id", "left")
            ->where("t1.id", $papel_id)
            ->where("t1.is_deleted", 0)
            ->where("t1.isActivo", 1)
            ->where("t2.is_deleted", 0);

        $result = $builder->get()->getResultObject();
        if (count($result) > 0) {
            return $result[0]->nombre;
        } else
            return "";
    }

    public function querySelect(?string $query)
    {
        $q =  $this->builder()->select([
            "id",
            "nombre as name",
        ]);
        if ($query) {
            $q->orLike("nombre", $query);
        }
        return $q;
    }

}
