<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Spatie\Activitylog\Traits\LogsActivity;
use Spatie\Activitylog\LogOptions;

class Vendor extends Model
{
    use LogsActivity;

    protected $fillable = [
        'code',
        'name',
        'short_name',
        'tax_id',
        'owner',
        'contact_name',
        'tel',
        'phone',
        'email',
        'address',
        'remark'
    ];
    public function products(): BelongsToMany
    {
        return $this->belongsToMany(Product::class, 'product_vendor')
                    ->withPivot('last_price')
                    ->withTimestamps();
    }

    public function purchaseOrders(): HasMany
    {
        return $this->hasMany(PurchaseOrder::class);
    }

    public function getActivitylogOptions(): LogOptions
    {
        return LogOptions::defaults()
            ->logAll()
            ->logOnlyDirty()
            ->dontSubmitEmptyLogs();
    }

    public function tapActivity(\Spatie\Activitylog\Contracts\Activity $activity, string $eventName)
    {
        $properties = $activity->properties;
        
        // Store name in 'snapshot' for context, keeping 'attributes' clean
        $snapshot = $properties['snapshot'] ?? [];
        // Only set name if it's not already set (e.g. by controller for specific context like supply product)
        if (!isset($snapshot['name'])) {
            $snapshot['name'] = $this->name;
        }
        $properties['snapshot'] = $snapshot;

        $activity->properties = $properties;
    }
}
