<?php

namespace App\Models\Presupuestos;

class BuscadorModel extends \App\Models\BaseModel
{
    protected $table = "presupuestos";

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

    const SORTABLE = [
        0 => "t1.id",
        1 => "t1.created_at",
        2 => "t7.codigo",
        3 => "t2.nombre",
        4 => "t3.first_name",
        5 => "t1.titulo",
        6 => "t5.nombre",
        7 => "t1.inc_rei",
        8 => "t1.paginas",
        9 => "t1.tirada",
        10 => "t1.total_presupuesto",
        11 => "t6.estado",
    ];

    /* protected $allowedFields = [
        "cliente_id",
        "user_created_id",
        "user_update_id",
        "tipo_impresion_id",
        "tipologia_id",
        "pais_id",
        "estado_id",
        "inc_rei",
        "causa_cancelacion",
        "retractilado",
        "retractilado5",
        "guardas",
        "faja_color",
        "recoger_en_taller",
        "ferro",
        "ferro_digital",
        "marcapaginas",
        "prototipo",
        "papel_formato_id",
        "papel_formato_personalizado",
        "papel_formato_ancho",
        "papel_formato_alto",
        "titulo",
        "autor",
        "coleccion",
        "numero_edicion",
        "isbn",
        "referencia_cliente",
        "paginas",
        "tirada",
        "solapas",
        "solapas_ancho",
        "cosido",
        "sobrecubiertas",
        "sobrecubiertas_ancho",
        "merma",
        "merma_cubierta",
        "comentarios_cliente",
        "comentarios_safekat",
        "comentarios_pdf",
        "comentarios_tarifa",
        "comentarios_produccion",
        "lomo",
        "total_presupuesto",
        "envios_recoge_cliente",
        "tirada_alternativa_json_data",
        "aprobado_user_id",
        "aprobado_at",
        "comparador_json_data",
        "is_deleted",
        "comp_tipo_impresion",
        "pos_paginas_color",
        "total_coste_papel",
        "total_margen_papel",
        "total_margenPercent_papel",
        "total_coste_impresion",
        "total_margen_impresion",
        "total_margenPercent_impresion",
        "total_coste_servicios",
        "total_margen_servicios",
        "total_margenPercent_servicios",
        "total_coste_envios",
        "total_margen_envios",
        "total_costes",
        "total_margenes",
        "total_antes_descuento",
        "total_descuento",
        "total_descuentoPercent",
        "total_presupuesto",
        "total_precio_unidad",
    ];
    */
    protected $returnType = "App\Entities\Presupuestos\PresupuestoEntity";

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

    protected $createdField = "created_at";
    protected $updatedField = "updated_at";

    public static $labelField = "titulo";



    /**
     * Get resource data.
     *
     * @param string $search
     *
     * @return \CodeIgniter\Database\BaseBuilder
     */
    public function getResource($search = [])
    {
        $builder = $this->db
            ->table($this->table . " t1")
            ->select(
                "t1.id AS id, t1.created_at AS fecha, t7.codigo as codigo, t2.nombre AS cliente, 
                CONCAT(t3.first_name, ' ', t3.last_name) AS comercial, t1.titulo AS titulo,
                t5.nombre AS pais, t1.inc_rei AS inc_rei, t1.paginas AS paginas, t1.tirada AS tirada,
                t1.total_presupuesto AS total_presupuesto, t1.total_presupuesto AS total_presupuesto, 
                t6.estado AS estado"
            );
        $builder->join("clientes t2", "t1.cliente_id = t2.id", "left");
        $builder->join("users t3", "t2.comercial_id = t3.id", "left");
        $builder->join("lg_paises t5", "t1.pais_id = t5.id", "left");
        $builder->join("presupuesto_estados t6", "t1.estado_id = t6.id", "left");
        $builder->join("tipos_presupuestos t7", "t1.tipo_impresion_id = t7.id", "left");

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

        
        if (empty($search))
            return $builder;
        else {
            $builder->groupStart();
            foreach ($search as $col_search) {
                if ($col_search[0] != 1)
                    $builder->like(self::SORTABLE[$col_search[0]], $col_search[2]);
                else {
                    $dates = explode(" ", $col_search[2]);
                    $builder->where(self::SORTABLE[$col_search[0]] . ">=", $dates[0]);
                    $builder->where(self::SORTABLE[$col_search[0]] . "<=", $dates[1]);
                }
            }
            $builder->groupEnd();
            return $builder;
        }

    }



}
