<?php

namespace App\Modules\Inventory\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Spatie\Activitylog\Traits\LogsActivity;
use Spatie\Activitylog\LogOptions;
use App\Modules\Core\Models\User;

class StoreRequisition extends Model
{
    use HasFactory, LogsActivity;

    protected $fillable = [
        'doc_no',
        'store_warehouse_id',
        'supply_warehouse_id',
        'status',
        'remark',
        'reject_reason',
        'created_by',
        'approved_by',
        'submitted_at',
        'approved_at',
        'transfer_order_id',
    ];

    protected $casts = [
        'submitted_at' => 'datetime',
        'approved_at' => 'datetime',
    ];

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

    /**
     * 自定義日誌屬性，解析 ID 為名稱
     */
    public function tapActivity(\Spatie\Activitylog\Models\Activity $activity, string $eventName)
    {
        $properties = $activity->properties->toArray();

        // 基本單據資訊快照
        $properties['snapshot'] = [
            'doc_no' => $this->doc_no,
            'store_warehouse_name' => $this->storeWarehouse?->name,
            'supply_warehouse_name' => $this->supplyWarehouse?->name,
            'status' => $this->status,
        ];

        // 移除雜訊欄位
        if (isset($properties['attributes'])) {
            unset($properties['attributes']['updated_at']);
        }
        if (isset($properties['old'])) {
            unset($properties['old']['updated_at']);
        }

        $activity->properties = collect($properties);
    }

    /**
     * 自動產生單號 SR-YYYYMMDD-XX
     */
    protected static function boot()
    {
        parent::boot();

        static::creating(function ($model) {
            if (empty($model->doc_no)) {
                $today = date('Ymd');
                $prefix = 'SR-' . $today . '-';

                $lastDoc = static::where('doc_no', 'like', $prefix . '%')
                    ->orderBy('doc_no', 'desc')
                    ->first();

                if ($lastDoc) {
                    $lastNumber = substr($lastDoc->doc_no, -2);
                    $nextNumber = str_pad((int)$lastNumber + 1, 2, '0', STR_PAD_LEFT);
                } else {
                    $nextNumber = '01';
                }

                $model->doc_no = $prefix . $nextNumber;
            }
        });
    }

    // ===== 關聯 =====

    /**
     * 申請倉庫
     */
    public function storeWarehouse(): BelongsTo
    {
        return $this->belongsTo(Warehouse::class, 'store_warehouse_id');
    }

    /**
     * 供貨倉庫（審核時填入）
     */
    public function supplyWarehouse(): BelongsTo
    {
        return $this->belongsTo(Warehouse::class, 'supply_warehouse_id');
    }

    /**
     * 叫貨明細
     */
    public function items(): HasMany
    {
        return $this->hasMany(StoreRequisitionItem::class);
    }

    /**
     * 申請人
     */
    public function createdBy(): BelongsTo
    {
        return $this->belongsTo(User::class, 'created_by');
    }

    /**
     * 審核人
     */
    public function approvedBy(): BelongsTo
    {
        return $this->belongsTo(User::class, 'approved_by');
    }

    /**
     * 關聯調撥單
     */
    public function transferOrder(): BelongsTo
    {
        return $this->belongsTo(InventoryTransferOrder::class, 'transfer_order_id');
    }
}
