<?php
namespace App\Models\Compras;

class ProveedorTipoModel extends \App\Models\BaseModel
{
    protected $table = "lg_proveedores_tipos";

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

    const SORTABLE = [
        1 => "t1.id",
        2 => "t1.nombre",
        3 => "t1.created_at",
        4 => "t1.updated_at",
    ];

    protected $allowedFields = ["nombre"];
    protected $returnType = "App\Entities\Compras\ProveedorTipoEntity";

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

    protected $createdField = "created_at";

    protected $updatedField = "updated_at";

    public static $labelField = "nombre";

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

    protected $validationMessages = [
        "nombre" => [
            "max_length" => "LgProveedoresTipos.validation.nombre.max_length",
            "required" => "LgProveedoresTipos.validation.nombre.required",
        ],
    ];

    /**
     * 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.created_at AS created_at, t1.updated_at AS updated_at");

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


    public function getTipoId(string $tipo = ""){
        
        $builder = $this->db
            ->table($this->table . " t1")
            ->select("t1.id AS id")
            ->where("t1.nombre", $tipo);

        $rows = $builder->get()->getResultObject();
        if(sizeof($rows)>0)
            return intval($rows[0]->id);
        else
            return -1;
    }
}
