<?php

namespace Modules\Inventory\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
use Modules\Accounts\Models\Traits\HasAccount;
use Modules\Inventory\Models\Traits\HasAmcContracts;
use Illuminate\Database\Eloquent\Builder;

class Supplier extends Model
{
    use HasAccount,
        HasAmcContracts,
        SoftDeletes;

    /**
     * The attributes that are mass assignable.
     */
    protected $fillable = [
        'name',
        'phone',
        'address',
        'account_id',
        'status',
    ];

    public function scopeSearch(Builder $query, ?string $search): Builder
    {
        if (blank($search)) {
            return $query;
        }
        $like = "%{$search}%";

        return $query->where(function ($q) use ($like) {
            $q->where('name', 'LIKE', $like)
                ->orWhere('phone', 'LIKE', $like)
                ->orWhereHas('account', function ($q) use ($like) {
                    $q->where('account_name', 'LIKE', $like);
                });
        });
    }
}
