<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\HasOne;

class TypeSale extends Model
{
    use HasFactory;

    protected $table = "tbl_type_sale";
    protected $fillable = [
        'name',
        'status',
        'idcompany'
    ];

    protected $hidden = [
        'created_at',
        'updated_at'
    ];

    #Relaciones
    public function company(): HasOne
    {
        return $this->hasOne(Company::class, 'id', 'idcompany');   
    }

    # Query scopes
    public function scopeActiveForID($query, $id)
    {
        return $query->where('id', $id)->where('status', 1);
    }

    public function scopeActive($query)
    {
        return $query->where('status', 1);
    }

    public function scopeCompany($query)
    {
        return $query->when(
            request('idcompany'),
            fn ($query) => $query->where('idcompany', request('idcompany'))
        );
    }

    # Filtros
    public function scopeTypeSaleFilters($query)
    {
        #Filtro de Buscador
        $query->when(
            request('search'),
            fn ($query) => $query->where('name', 'LIKE', '%' . request('search') . '%')
        );

        #Filtro de name
        $query->when(
            request('name'),
            fn ($query) => $query->where('name', 'LIKE', '%' . request('name') . '%')
        );

        #Filtro de idcompany
        $query->company();

        #Filtro de estados
        $query->when(
            request('status'),
            fn ($query) => $query->where('status', request('status'))
        );
    }
}
