<?php

namespace App\Models;

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

class ItemSupplier extends Model
{
    use LogsActivity;

    protected $table = 'item_suppliers';

    protected $fillable = [
        'item_id',
        'contact_id',
        'is_primary',
        'lead_time_days',
        'min_order_qty',
        'last_price',
    ];

    protected $casts = [
        'is_primary' => 'boolean',
        'lead_time_days' => 'integer',
        'min_order_qty' => 'decimal:4',
        'last_price' => 'decimal:4',
    ];

    // Relationships
    public function item(): BelongsTo
    {
        return $this->belongsTo(Item::class);
    }

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

    // Scopes
    public function scopePrimary($query)
    {
        return $query->where('is_primary', true);
    }

    public function scopeForItem($query, $itemId)
    {
        return $query->where('item_id', $itemId);
    }

    public function scopeForContact($query, $contactId)
    {
        return $query->where('contact_id', $contactId);
    }

    // Helper methods
    public function getFormattedLastPriceAttribute()
    {
        return $this->last_price ? format_currency($this->last_price) : '-';
    }

    public function getFormattedMinOrderQtyAttribute()
    {
        return $this->min_order_qty ? number_format($this->min_order_qty, 4) : '-';
    }

    public function getActivitylogOptions(): LogOptions
    {
        return LogOptions::defaults()
            ->useLogName('item_supplier')
            ->logFillable()
            ->logOnlyDirty()
            ->dontSubmitEmptyLogs();
    }
}
