<?php

namespace App\Models\Supplier;

use Carbon\Carbon;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;

class Supplier extends Model
{
    use SoftDeletes;
    protected $table = 'proveedor';
    protected $primaryKey = 'idProveedor';

    protected $fillable = [
        "ruc",
        "razonSocial",
        "direccion",
        "telefono",
        "email",
        "paginaWeb",
        "tipoDocumento",
        "documentoRepresentante",
        "nombreRepresentante",
        "idCategoriaProveedor",
        "state"
    ];

    public function setCreatedAtAttribute($value)
    {
        date_default_timezone_set('America/Lima');
        $this->attributes["created_at"] = Carbon::now();
    }

    public function setUpdatedAtAttribute($value)
    {
        date_default_timezone_set("America/Lima");
        $this->attributes["updated_at"] = Carbon::now();
    }

    public function categoria()
    {
        return $this->belongsTo(SupplierCategory::class, 'idCategoriaProveedor', 'idCategoriaProveedor');
    }

    public function scopeFilterMultiple($query, $search, $idCategoriaProveedor, $state)
    {
        if ($search) {
            $query->where("razonSocial", "like", "%" . $search . "%")
                  ->orWhere("ruc", "like", "%" . $search . "%");
        }
        if ($idCategoriaProveedor) {
            $query->where("idCategoriaProveedor", $idCategoriaProveedor);
        }
        if ($state) {
            $query->where("state", $state);
        }
        return $query;
    }
}
