<?php

namespace App\Models;

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

class WayToPay extends Model
{
    use HasFactory;
    protected $table = "tbl_way_to_pay";

    protected $fillable = [
        'iderp',
        'name',
        'agenda',
        'days',
        'SII_fmapago',
        'status'
    ];

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

    # 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 scopeName($query, $name, $id = null)
    {
        return $query->when($id, fn ($query) => $query->where('id', '<>', $id))->where('name', $name);
    }

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

        #Filtro de id erp
        $query->when(
            request('iderp'),
            fn ($query) => $query->where('name', request('iderp'))
        );

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

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

        // $query->when(request('status'), fn ($query, $status) => $query->where('status', $status), 1);
    }
}
