<?php

namespace App\Modules\Procurement\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;

class PurchaseReturn extends Model
{
    use HasFactory, SoftDeletes;
    use \Spatie\Activitylog\Traits\LogsActivity;

    public const STATUS_DRAFT = 'draft';
    public const STATUS_COMPLETED = 'completed';
    public const STATUS_CANCELLED = 'cancelled';

    protected $fillable = [
        'code',
        'vendor_id',
        'warehouse_id',
        'user_id',
        'return_date',
        'status',
        'total_amount',
        'tax_amount',
        'grand_total',
        'remarks',
    ];

    protected $casts = [
        'return_date' => 'date',
        'total_amount' => 'decimal:2',
        'tax_amount' => 'decimal:2',
        'grand_total' => 'decimal:2',
    ];

    public function getActivitylogOptions(): \Spatie\Activitylog\LogOptions
    {
        return \Spatie\Activitylog\LogOptions::defaults()
            ->logAll()
            ->logOnlyDirty()
            ->dontSubmitEmptyLogs();
    }
    
    public function tapActivity(\Spatie\Activitylog\Contracts\Activity $activity, string $eventName)
    {
        // 活動紀錄名稱解析 (依 activity-logging.md)
        $properties = $activity->properties instanceof \Illuminate\Support\Collection 
            ? $activity->properties->toArray() 
            : $activity->properties;

        $snapshot = $properties['snapshot'] ?? [];
        $snapshot['return_no'] = $this->code;
        $snapshot['warehouse_name'] = $this->warehouse?->name;
        $properties['snapshot'] = $snapshot;

        $resolver = function (&$data) {
            if (empty($data) || !is_array($data)) return;
            
            foreach (['user_id', 'created_by', 'updated_by'] as $f) {
                if (isset($data[$f]) && is_numeric($data[$f])) {
                    $data[$f] = \App\Modules\Core\Models\User::find($data[$f])?->name;
                }
            }
            if (isset($data['vendor_id']) && is_numeric($data['vendor_id'])) {
                $data['vendor_id'] = Vendor::find($data['vendor_id'])?->name;
            }
            // Strict Mode: Warehouse relation may not be available directly here if it's across modules, 
            // but we might need it for display.
        };

        if (isset($properties['attributes'])) $resolver($properties['attributes']);
        if (isset($properties['old'])) $resolver($properties['old']);

        $activity->properties = $properties;
    }

    public function items()
    {
        return $this->hasMany(PurchaseReturnItem::class);
    }
    
    public function vendor()
    {
        return $this->belongsTo(Vendor::class);
    }

    public function user()
    {
        return $this->belongsTo(\App\Modules\Core\Models\User::class);
    }
}
