<?php

namespace App\Modules\Procurement\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Spatie\Activitylog\Traits\LogsActivity;
use Spatie\Activitylog\LogOptions;
use Spatie\Activitylog\Contracts\Activity;

class ShippingOrder extends Model
{
    use HasFactory, LogsActivity;

    protected $fillable = [
        'doc_no',
        'customer_name',
        'warehouse_id',
        'status',
        'shipping_date',
        'total_amount',
        'tax_amount',
        'grand_total',
        'remarks',
        'created_by',
        'posted_by',
        'posted_at',
    ];

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

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

    public function tapActivity(Activity $activity, string $eventName)
    {
        $snapshot = $activity->properties['snapshot'] ?? [];
        $snapshot['doc_no'] = $this->doc_no;
        $snapshot['customer_name'] = $this->customer_name;
        
        $activity->properties = $activity->properties->merge([
            'snapshot' => $snapshot
        ]);
    }

    public function items()
    {
        return $this->hasMany(ShippingOrderItem::class);
    }
    
    /**
     * 自動產生單號
     */
    protected static function boot()
    {
        parent::boot();

        static::creating(function ($model) {
            if (empty($model->doc_no)) {
                $today = date('Ymd');
                $prefix = 'SHP-' . $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;
            }
        });
    }
}
