<?php

namespace App\Models\Configuracion;

class PapelGenericoModel extends \App\Models\BaseModel
{
    protected $table = "lg_papel_generico";

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

    const SORTABLE = [
        //0 => "t1.id",
        0 => "t1.nombre",
        1 => "t1.code",
        2 => "t1.code_ot",
        3 => "t1.show_in_client",
        4 => "t1.show_in_client_special",
    ];

    protected $allowedFields = ["nombre", "code", "code_ot", "show_in_client", "show_in_client_special", "deleted_at", "is_deleted", "activo"];
    protected $returnType = "App\Entities\Configuracion\PapelGenerico";

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

    protected $createdField = "created_at";

    protected $updatedField = "updated_at";

    public static $labelField = "nombre";

    protected $validationRules = [
        "code" => [
            "label" => "PapelGenericoes.code",
            "rules" => "trim|max_length[5]",
        ],
        "code_ot" => [
            "label" => "PapelGenericoes.codeOt",
            "rules" => "trim|max_length[5]",
        ],
        "nombre" => [
            "label" => "PapelGenericoes.nombre",
            "rules" => "trim|required|max_length[255]",
        ],
    ];

    protected $validationMessages = [
        "code" => [
            "max_length" => "PapelGenericoes.validation.code.max_length",
        ],
        "code_ot" => [
            "max_length" => "PapelGenericoes.validation.code_ot.max_length",
        ],
        "nombre" => [
            "max_length" => "PapelGenericoes.validation.nombre.max_length",
            "required" => "PapelGenericoes.validation.nombre.required",
        ],
    ];


    public function getIdFromCode(string $code = "")
    {
        $builder = $this->db
            ->table($this->table . " t1")
            ->select(
                "t1.id AS id, t1.nombre AS nombre"
            )
            ->where("t1.code", $code)
            ->where("t1.is_deleted", 0);
        $data = $builder->get()->getFirstRow();
        // se convierte a de stdClass a array
        $data = json_decode(json_encode($data), true);
        return $data;
    }


    public function getCodeFromId($id = 0)
    {
        $builder = $this->db
            ->table($this->table . " t1")
            ->select(
                "t1.code AS code"
            )
            ->where("t1.id", $id)
            ->where("t1.is_deleted", 0);
        $data = $builder->get()->getFirstRow();
        // se convierte a de stdClass a array
        $data = json_decode(json_encode($data), true);
        return $data;
    }

    public function getNombre($id = 0)
    {
        $builder = $this->db
            ->table($this->table . " t1")
            ->select(
                "t1.nombre AS nombre"
            )
            ->where("t1.id", $id)
            ->where("t1.is_deleted", 0);
        $data = $builder->get()->getFirstRow();
        // se convierte a de stdClass a array
        $data = json_decode(json_encode($data), true);
        return $data;
    }

    /**
     * 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.nombre AS nombre, 
                t1.code AS code, 
                t1.code_ot AS code_ot, 
                t1.activo AS activo,
                t1.show_in_client AS show_in_client, 
                t1.show_in_client_special AS show_in_client_special"
            )
            ->where("is_deleted", 0);

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


    public function getPapelForComparador(
        $tipo,
        $is_cubierta = false,
        $is_sobrecubierta = false,
        $rotativa = false,
        $is_guardas = false,
        $tapa_dura = false,
        $POD = false,
        $ancho = 0,
        $alto = 0,
        $tirada = 0,
    ) {
        /*
        1.-> Tipo impresion
            2.-> Maquina
                3.-> Papeles impresion asociados a esa maquina
                    4.-> papeles genericos que aparecen en esos papeles impresion
        */

        if ($POD == true && ($tipo == 'color' || $tipo == 'negro')) {
            if ($tipo == 'color')
                $tipo = 'colorhq';
            else if ($tipo == 'negro')
                $tipo = 'negrohq';
        }

        $builder = $this->db
            ->table($this->table . " t1")
            ->select(
                "t1.id as id, t1.nombre AS nombre",
                // for debug, t2.nombre AS nombre_papel_impresion, t4.nombre AS maquina_nombre, t5.uso AS tarifa_uso, t5.tipo AS tarifa_tipo"
            )
            ->join("lg_papel_impresion t2", "t2.papel_generico_id = t1.id", "inner")
            ->join("lg_maquina_papel_impresion t3", "t3.papel_impresion_id = t2.id", "inner")
            ->join("lg_maquinas t4", "t3.maquina_id = t4.id", "inner")
            ->join("lg_maquinas_tarifas_impresion t5", "t5.maquina_id = t4.id", "inner")

            ->where("t1.is_deleted", 0)
            ->where("t1.show_in_client", 1)
            ->where("t2.is_deleted", 0)
            ->where("t2.isActivo", 1)
            ->where("t3.active", 1)
            ->where("t4.is_deleted", 0)
            ->where("t4.tipo", "impresion")
            ->where("t4.min <= ", $tirada)
            ->where("t4.max >= ", $tirada)
            ->where("t5.is_deleted", 0)
            ->where("t5.tipo", $tipo)
            ->distinct('t1.id');

        // Validación adicional para asegurar que t1.id esté presente en las combinaciones con t3.active = 1
        $builder->whereIn("t1.id", function ($subQuery) {
            $subQuery->select("t1_inner.id")
                ->from("lg_papel_generico t1_inner")
                ->join("lg_papel_impresion t2_inner", "t2_inner.papel_generico_id = t1_inner.id", "inner")
                ->join("lg_maquina_papel_impresion t3_inner", "t3_inner.papel_impresion_id = t2_inner.id", "inner")
                ->where("t3_inner.active", 1);
        });

        $builder->groupStart()
            ->groupStart()
            ->where("t4.ancho_impresion >", $ancho)
            ->where("t4.alto_impresion >", $alto)
            ->groupEnd()
            ->orGroupStart()
            ->where("t4.ancho_impresion >", $alto)
            ->where("t4.alto_impresion >", $ancho)
            ->groupEnd()
            ->orGroupStart()
            ->where("t4.ancho_impresion >", $alto)
            ->where("t4.is_rotativa", 1)
            ->groupEnd()
            ->groupEnd();

        if ($is_cubierta == true) {
            $builder->where("t2.cubierta", 1);
            $builder->where("t5.uso", 'cubierta');
            if ($tapa_dura == true) {
                $builder->where("t2.use_for_tapa_dura", 1);
            }
        } else if ($is_sobrecubierta == true) {
            $builder->where("t2.sobrecubierta", 1);
            $builder->where("t5.uso", 'sobrecubierta');
        } else if ($is_guardas == true) {
            $builder->where("t2.guardas", 1);
        } else {
            $builder->where("t2.interior", 1);
            $builder->where("t5.uso", 'interior');
            if ($tipo == 'negro' || $tipo == 'negrohq')
                $builder->where("t2.bn", 1);
            else if ($tipo == 'color' || $tipo == 'colorhq')
                $builder->where("t2.color", 1);
        }

        if ($tipo == 'colorhq' || $tipo == 'negrohq') {
            $builder->where("t2.rotativa", 0);
        } else if ($rotativa && $POD == false) {
            $builder->where("t2.rotativa", 1);
        } else if ($POD) {
            $builder->where("t2.rotativa", 0);
        }

        //$query = $this->db->getLastQuery();
        return $builder;
    }

    public function getGramajeForComparador(
        $tipo,
        $selected_papel_id,
        $is_cubierta = false,
        $is_sobrecubierta = false,
        $rotativa = false,
        $is_guardas = false,
        $tapa_dura = false,
        $POD = false,
        $ancho = 0,
        $alto = 0,
        $tirada = 0
    ) {
        if ($POD == true && ($tipo == 'color' || $tipo == 'negro')) {
            if ($tipo == 'color')
                $tipo = 'colorhq';
            else if ($tipo == 'negro')
                $tipo = 'negrohq';
        }


        $builder = $this->db
            ->table($this->table . " t1")
            ->select(
                "t2.gramaje as id, t2.gramaje as nombre",
                // for debug, t2.nombre AS nombre_papel_impresion, t4.nombre AS maquina_nombre, t5.uso AS tarifa_uso, t5.tipo AS tarifa_tipo"
            )
            ->join("lg_papel_impresion t2", "t2.papel_generico_id = t1.id", "inner")
            ->join("lg_maquina_papel_impresion t3", "t3.papel_impresion_id = t2.id", "inner")
            ->join("lg_maquinas t4", "t3.maquina_id = t4.id", "inner")
            ->join("lg_maquinas_tarifas_impresion t5", "t5.maquina_id = t4.id", "inner")

            ->where("t1.id", $selected_papel_id)
            ->where("t1.is_deleted", 0)
            ->where("t1.show_in_client", 1)
            ->where("t2.is_deleted", 0)
            ->where("t2.isActivo", 1)
            ->where("t3.active", 1)
            ->where("t4.is_deleted", 0)
            ->where("t4.min <= ", $tirada)
            ->where("t4.max >= ", $tirada)
            ->where("t4.tipo", "impresion")
            ->where("t5.is_deleted", 0)
            ->where("t5.tipo", $tipo)
            ->distinct('t2.gramaje');

        // Validación adicional para asegurar que t1.id esté presente en las combinaciones con t3.active = 1
        $builder->whereIn("t1.id", function ($subQuery) {
            $subQuery->select("t1_inner.id")
                ->from("lg_papel_generico t1_inner")
                ->join("lg_papel_impresion t2_inner", "t2_inner.papel_generico_id = t1_inner.id", "inner")
                ->join("lg_maquina_papel_impresion t3_inner", "t3_inner.papel_impresion_id = t2_inner.id", "inner")
                ->where("t3_inner.active", 1);
        });

        $builder->groupStart()
            ->groupStart()
            ->where("t4.ancho_impresion >", $ancho)
            ->where("t4.alto_impresion >", $alto)
            ->groupEnd()
            ->orGroupStart()
            ->where("t4.ancho_impresion >", $alto)
            ->where("t4.alto_impresion >", $ancho)
            ->groupEnd()
            ->orGroupStart()
            ->where("t4.ancho_impresion >", $alto)
            ->where("t4.is_rotativa", 1)
            ->groupEnd()
            ->groupEnd();

        if ($is_cubierta == true) {
            $builder->where("t2.cubierta", 1);
            $builder->where("t5.uso", 'cubierta');
            if ($tapa_dura == true) {
                $builder->where("t2.use_for_tapa_dura", 1);
            }
        } else if ($is_sobrecubierta == true) {
            $builder->where("t2.sobrecubierta", 1);
            $builder->where("t5.uso", 'sobrecubierta');
        } else if ($is_guardas == true) {
            $builder->where("t2.guardas", 1);
        } else {
            $builder->where("t2.interior", 1);
            $builder->where("t5.uso", 'interior');
            if ($tipo == 'negro' || $tipo == 'negrohq')
                $builder->where("t2.bn", 1);
            else if ($tipo == 'color' || $tipo == 'colorhq')
                $builder->where("t2.color", 1);
        }

        if ($tipo == 'colorhq' || $tipo == 'negrohq') {
            $builder->where("t2.rotativa", 0);
        } else if ($rotativa && $POD == false) {
            $builder->where("t2.rotativa", 1);
        } else if ($POD) {
            $builder->where("t2.rotativa", 0);
        }

        //$query = $this->db->getLastQuery();
        return $builder;
    }

    //tipo: negro, negrohq, color, colorhq
    //uso: interior, rotativa, cubierta, sobrecubierta
    public function getGramajeLineasPresupuesto($papel_generico_id = 0, $tipo = "", $uso = "")
    {
        $builder = $this->db
            ->table($this->table . " t1")
            ->select(
                "t2.gramaje AS text"
            )
            ->join("lg_papel_impresion t2", "t2.papel_generico_id = t1.id", "left")
            ->join("lg_maquina_papel_impresion t3", "t3.papel_impresion_id = t2.id", "left")
            ->join("lg_maquinas t4", "t3.maquina_id = t4.id", "left")
            ->join("lg_maquinas_tarifas_impresion t5", "t5.maquina_id = t4.id", "left")

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

        $uso_tarifa = 'interior';

        if ($uso == 'cubierta') {
            $uso_tarifa = 'cubierta';
            $builder->where("t2.cubierta", 1);
        } else if ($uso == 'sobrecubierta') {
            $uso_tarifa = 'sobrecubierta';
            $builder->where("t2.sobrecubierta", 1);
        } else {
            if ($tipo == 'negro' || $tipo == 'negrohq')
                $builder->where("t2.bn", 1);
            else if ($tipo == 'color' || $tipo == 'colorhq')
                $builder->where("t2.color", 1);
        }

        if ($uso == 'rotativa')
            $builder->where("t2.rotativa", 1);
        else
            $builder->where("t2.rotativa", 0);

        $builder->where("t5.uso", $uso_tarifa);


        $values = $builder->orderBy("t2.gramaje", "asc")->get()->getResultObject();
        $id = 1;
        foreach ($values as $value) {
            $value->id = $id;
            $id++;
        }
        $values_array = array_map(function ($value) {
            return $value->text;
        }, $values);
        $unique_values = array_unique($values_array);
        return array_values(array_intersect_key($values, $unique_values));
    }


    public function getPapelCliente(
        $tipo,
        $is_cubierta = false,
        $is_sobrecubierta = false,
        $is_guardas = false,
        $selected_papel_id = null,
        $tapa_dura = null,
        $papel_especial = false,
        $POD = null,
        $ancho = 0,
        $alto = 0,
        $tirada = 0
    ) {
        /*
        1.-> Tipo impresion
            2.-> Maquina
                3.-> Papeles impresion asociados a esa maquina
                    4.-> papeles genericos que aparecen en esos papeles impresion
        */

        if ($POD == true && ($tipo == 'color' || $tipo == 'negro')) {
            if ($tipo == 'color')
                $tipo = 'colorhq';
            else if ($tipo == 'negro')
                $tipo = 'negrohq';
        }

        if ($selected_papel_id != null) {
            $builder = $this->db
                ->table($this->table . " t1")
                ->select(
                    "t2.gramaje as gramaje",
                    // for debug, t2.nombre AS nombre_papel_impresion, t4.nombre AS maquina_nombre, t5.uso AS tarifa_uso, t5.tipo AS tarifa_tipo"
                )
                ->join("lg_papel_impresion t2", "t2.papel_generico_id = t1.id", "inner")
                ->join("lg_maquina_papel_impresion t3", "t3.papel_impresion_id = t2.id", "inner")
                ->join("lg_maquinas t4", "t3.maquina_id = t4.id", "inner")
                ->join("lg_maquinas_tarifas_impresion t5", "t5.maquina_id = t4.id", "inner")

                ->where("t1.id", $selected_papel_id)
                ->where("t1.is_deleted", 0)
                ->where("t1.show_in_client", 1)
                ->where("t2.is_deleted", 0)
                ->where("t2.isActivo", 1)
                ->where("t2.use_in_client", 1)
                ->where("t3.active", 1)
                ->where("t4.is_deleted", 0)
                ->where("t4.min <= ", $tirada)
                ->where("t4.max >= ", $tirada)
                ->where("t4.tipo", "impresion")
                ->where("t5.is_deleted", 0)
                ->where("t5.tipo", $tipo)
                ->distinct('t2.gramaje');
        } else {
            $builder = $this->db
                ->table($this->table . " t1")
                ->select(
                    "t1.id as id, t1.nombre AS nombre",
                    // for debug, t2.nombre AS nombre_papel_impresion, t4.nombre AS maquina_nombre, t5.uso AS tarifa_uso, t5.tipo AS tarifa_tipo"
                )
                ->join("lg_papel_impresion t2", "t2.papel_generico_id = t1.id", "inner")
                ->join("lg_maquina_papel_impresion t3", "t3.papel_impresion_id = t2.id", "inner")
                ->join("lg_maquinas t4", "t3.maquina_id = t4.id", "inner")
                ->join("lg_maquinas_tarifas_impresion t5", "t5.maquina_id = t4.id", "inner")

                ->where("t1.is_deleted", 0)
                ->where("t1.show_in_client", 1)
                ->where("t2.is_deleted", 0)
                ->where("t2.isActivo", 1)
                ->where("t2.use_in_client", 1)
                ->where("t3.active", 1)
                ->where("t4.is_deleted", 0)
                ->where("t4.min <= ", $tirada)
                ->where("t4.max >= ", $tirada)
                ->where("t4.tipo", "impresion")
                ->where("t5.is_deleted", 0)
                ->where("t5.tipo", $tipo)
                ->distinct('t1.id');
        }
        // Validación adicional para asegurar que t1.id esté presente en las combinaciones con t3.active = 1
        $builder->whereIn("t1.id", function ($subQuery) {
            $subQuery->select("t1_inner.id")
                ->from("lg_papel_generico t1_inner")
                ->join("lg_papel_impresion t2_inner", "t2_inner.papel_generico_id = t1_inner.id", "inner")
                ->join("lg_maquina_papel_impresion t3_inner", "t3_inner.papel_impresion_id = t2_inner.id", "inner")
                ->where("t3_inner.active", 1);
        });

        $builder->groupStart()
            ->groupStart()
            ->where("t4.ancho_impresion >", $ancho)
            ->where("t4.alto_impresion >", $alto)
            ->groupEnd()
            ->orGroupStart()
            ->where("t4.ancho_impresion >", $alto)
            ->where("t4.alto_impresion >", $ancho)
            ->groupEnd()
            ->orGroupStart()
            ->where("t4.ancho_impresion >", $alto)
            ->where("t4.is_rotativa", 1)
            ->groupEnd()
            ->groupEnd();

        if ($is_cubierta == true) {
            $builder->where("t2.cubierta", 1);
            $builder->where("t5.uso", 'cubierta');
            if ($tapa_dura == true) {
                $builder->where("t2.use_for_tapa_dura", 1);
            }
        } else if ($is_sobrecubierta == true) {
            $builder->where("t2.sobrecubierta", 1);
            $builder->where("t5.uso", 'sobrecubierta');
        } else if ($is_guardas == true) {
            $builder->where("t2.guardas", 1);
            $builder->where("t5.uso", 'interior');
        } else {
            $builder->where("t2.interior", 1);
            $builder->where("t5.uso", 'interior');
            if ($tipo == 'negro' || $tipo == 'negrohq')
                $builder->where("t2.bn", 1);
            else if ($tipo == 'color' || $tipo == 'colorhq')
                $builder->where("t2.color", 1);
        }

        if ($papel_especial == true) {
            $builder->where("t1.show_in_client_special", 1);
        } else {
            $builder->where("t1.show_in_client_special", 0);
        }

        if ($tipo == 'colorhq' || $tipo == 'negrohq') {
            $builder->where("t2.rotativa", 0);
        } else {
            if ($POD == false) {
                $builder->where("t2.rotativa", 1);
            } else if ($POD == true) {
                $builder->where("t2.rotativa", 0);
            }
        }


        if ($selected_papel_id != null)
            $data = $builder->orderBy("t2.gramaje", "asc")->get()->getResultObject();
        else
            $data = $builder->orderBy("t1.nombre", "asc")->get()->getResultObject();
        $query = $this->db->getLastQuery();
        return $data;
    }
}
