<?php

namespace App\Modules\Production\Models;

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

class ProductionOrder extends Model
{
    use HasFactory, LogsActivity;

    protected $fillable = [
        'code',
        'product_id',
        'warehouse_id',
        'output_quantity',
        'output_batch_number',
        'output_box_count',
        'production_date',
        'expiry_date',
        'user_id',
        'status',
        'remark',
    ];

    protected $casts = [
        'production_date' => 'date',
        'expiry_date' => 'date',
        'output_quantity' => 'decimal:2',
    ];

    public function getActivitylogOptions(): LogOptions
    {
        return LogOptions::defaults()
            ->logOnly([
                'code',
                'status',
                'output_quantity',
                'output_batch_number',
                'production_date',
                'remark'
            ])
            ->logOnlyDirty()
            ->dontSubmitEmptyLogs()
            ->setDescriptionForEvent(fn(string $eventName) => "生產工單已{$this->getEventDescription($eventName)}");
    }

    protected function getEventDescription($eventName): string
    {
        return match ($eventName) {
            'created' => '建立',
            'updated' => '更新',
            'deleted' => '刪除',
            default => $eventName,
        };
    }

    public static function generateCode()
    {
        $prefix = 'PO' . now()->format('Ymd');
        $lastOrder = self::where('code', 'like', $prefix . '%')->latest()->first();
        if ($lastOrder) {
            $lastSequence = intval(substr($lastOrder->code, -3));
            $sequence = str_pad($lastSequence + 1, 3, '0', STR_PAD_LEFT);
        } else {
            $sequence = '001';
        }
        return $prefix . $sequence;
    }

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