<?php

namespace App\Modules\Inventory\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Spatie\Activitylog\Traits\LogsActivity;
use Spatie\Activitylog\LogOptions;


class Product extends Model
{
    use HasFactory, LogsActivity, SoftDeletes;

    protected $fillable = [
        'code',
        'barcode',
        'name',
        'external_pos_id',
        'category_id',
        'brand',
        'specification',
        'base_unit_id',
        'large_unit_id',
        'conversion_rate',
        'purchase_unit_id',
        'location',
        'cost_price',
        'price',
        'member_price',
        'wholesale_price',
        'is_active',
    ];

    protected $casts = [
        'conversion_rate' => 'decimal:4',
        'is_active' => 'boolean',
    ];

    /**
     * 取得該商品所屬的分類。
     */
    public function category(): BelongsTo
    {
        return $this->belongsTo(Category::class);
    }

    public function baseUnit(): BelongsTo
    {
        return $this->belongsTo(Unit::class, 'base_unit_id');
    }

    public function largeUnit(): BelongsTo
    {
        return $this->belongsTo(Unit::class, 'large_unit_id');
    }

    public function purchaseUnit(): BelongsTo
    {
        return $this->belongsTo(Unit::class, 'purchase_unit_id');
    }



    public function inventories(): \Illuminate\Database\Eloquent\Relations\HasMany
    {
        return $this->hasMany(Inventory::class);
    }

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

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

    public function tapActivity(\Spatie\Activitylog\Contracts\Activity $activity, string $eventName)
    {
        $properties = $activity->properties;
        $attributes = $properties['attributes'] ?? [];
        $snapshot = $properties['snapshot'] ?? [];
        
        // 處理分類名稱快照
        if (isset($attributes['category_id'])) {
            $category = Category::find($attributes['category_id']);
            $snapshot['category_name'] = $category ? $category->name : null;
        }
        
        // 處理單位名稱快照
        $unitFields = ['base_unit_id', 'large_unit_id', 'purchase_unit_id'];
        foreach ($unitFields as $field) {
            if (isset($attributes[$field])) {
                $unit = Unit::find($attributes[$field]);
                $nameKey = str_replace('_id', '_name', $field);
                $snapshot[$nameKey] = $unit ? $unit->name : null;
            }
        }
        
        // 始終對自身名稱進行快照以便於上下文顯示（這樣日誌總是顯示 "可樂"）
        $snapshot['name'] = $this->name;

        $properties['attributes'] = $attributes;
        $properties['snapshot'] = $snapshot;
        $activity->properties = $properties;
    }

    public function warehouses(): \Illuminate\Database\Eloquent\Relations\BelongsToMany
    {
        return $this->belongsToMany(Warehouse::class, 'inventories')
            ->withPivot(['quantity', 'safety_stock', 'location'])
            ->withTimestamps();
    }
}
