<?php

namespace App\Modules\Inventory\Models;

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

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

    public const STATUS_DRAFT = 'draft';
    public const STATUS_PENDING_AUDIT = 'pending_audit';
    public const STATUS_COMPLETED = 'completed';
    public const STATUS_REJECTED = 'rejected';

    protected $fillable = [
        'code',
        'type',
        'warehouse_id',
        'purchase_order_id',
        'vendor_id',
        'received_date',
        'status',
        'remarks',
        'user_id',
    ];

    protected $casts = [
        'received_date' => 'date:Y-m-d',
    ];

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

    public function tapActivity(\Spatie\Activitylog\Contracts\Activity $activity, string $eventName)
    {
        $properties = $activity->properties instanceof \Illuminate\Support\Collection 
            ? $activity->properties->toArray() 
            : $activity->properties;

        $snapshot = $properties['snapshot'] ?? [];
        $snapshot['doc_no'] = $this->code;
        $snapshot['warehouse_name'] = $this->warehouse?->name;
        
        if (!isset($snapshot['vendor_name']) && $this->vendor_id) {
            $vendor = app(\App\Modules\Procurement\Contracts\ProcurementServiceInterface::class)
                ->getVendorsByIds([$this->vendor_id])->first();
            $snapshot['vendor_name'] = $vendor?->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(\App\Modules\Core\Contracts\CoreServiceInterface::class)->getUser($data[$f])?->name;
                }
            }
            if (isset($data['warehouse_id']) && is_numeric($data['warehouse_id'])) {
                $data['warehouse_id'] = \App\Modules\Inventory\Models\Warehouse::find($data['warehouse_id'])?->name;
            }
            if (isset($data['vendor_id']) && is_numeric($data['vendor_id'])) {
                $vendor = app(\App\Modules\Procurement\Contracts\ProcurementServiceInterface::class)
                    ->getVendorsByIds([$data['vendor_id']])->first();
                $data['vendor_id'] = $vendor?->name;
            }
        };

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

        $activity->properties = $properties;
    }

    public function items()
    {
        return $this->hasMany(GoodsReceiptItem::class);
    }
    
    // Strict Mode: relationships to Warehouse is allowed (same module).
    public function warehouse()
    {
        return $this->belongsTo(Warehouse::class);
    }
    
    // Strict Mode: cross-module relationship to Vendor/User/PurchaseOrder is restricted.
    // They are accessed via IDs or Services.
}
