<?php

namespace App\Models;

use Illuminate\Contracts\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;

class Produk extends Model
{
    use HasFactory;
    protected $fillable = [
        'kategori_id',
        'satuan_id',
        'kd_produk',
        'nm_produk',
        'berat',
        'harga_beli',
        'harga_jual',
        'diskon',
        'ktr_produk',
        'link_produk',
        'gambar',
    ];

    public function satuan(): BelongsTo
    {
        return $this->belongsTo(Satuan::class);
    }

    public function kategori(): BelongsTo
    {
        return $this->belongsTo(Kategori::class);
    }

    public function scopePencarian(Builder $query): void
    {
        $query->where('nm_produk', 'like', '%' . request('cari') . '%')
            ->orWhere('kd_produk', 'like', '%' . request('cari') . '%')
            ->orWhere('berat', 'like', '%' . request('cari') . '%')
            ->orWhere('harga_jual', 'like', '%' . request('cari') . '%')
            ->orWhere('harga_beli', 'like', '%' . request('cari') . '%')
            ->orwhereHas('satuan', function ($query) {
                $query->where('nm_satuan', 'like', '%' .  request('cari') . '%');
            })->orwhereHas('kategori', function ($query) {
                $query->where('nm_kategori', 'like', '%' .  request('cari') . '%');
            });
    }
}
