<?php

namespace App\Models;

use App\Traits\Blameable;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;

class Produk extends Model
{
    use HasFactory, Blameable, SoftDeletes;

    protected $table = 'produks';

    protected $fillable = [
        'kategori_produk_id',
        'kode_produk',
        'nama_produk',
        'varian_produk',
        'deskripsi_produk',
        'harga_produk',
        'stok_produk',
        'stok_promo',
        'tgl_start_promo',
        'tgl_end_promo',
        'tersedia',
        'gambar_produk',
        'urutan',
    ];

    // full path to reach image from storage folder and check if image exists or not
    public function getGambarProdukAttribute($value)
    {
        $storage = storage_path('app/public/produk/' . $this->kategori_produk_id . '/' . $value);
        if (file_exists($storage)) {
            return asset('storage/produk/' . $this->kategori_produk_id . '/' . $value);
        } else {
            return asset('assets/images/menu_image.jpeg');
        }
    }

    public function kategori_produk()
    {
        return $this->belongsTo(KategoriProduk::class, 'kategori_produk_id');
    }

    public function kelompokKategori()
    {
        return $this->belongsToMany(KelompokKategori::class, KelompokKategoriPivot::class, 'produk_id', 'kelompok_kategori_id');
    }
}