<?php

namespace App\Models;

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

class DeliveryNote extends Model
{
    use HasFactory;

    public const STATUS_DRAFT = 'draft';
    public const STATUS_PRINTED = 'printed';
    public const STATUS_DELIVERED = 'delivered';
    public const STATUS_RECEIVED = 'received';
    public const STATUS_CANCELLED = 'cancelled';

    protected $fillable = [
        'number', 'order_id', 'vehicle_id', 'recipient_name', 'recipient_phone', 'recipient_address',
        'driver_name', 'driver_phone', 'vehicle_name', 'plate_number', 'delivery_date', 'status', 'notes', 'created_by',
    ];

    protected $casts = ['delivery_date' => 'date'];

    protected static function booted(): void
    {
        static::creating(function (DeliveryNote $deliveryNote) {
            if (empty($deliveryNote->number)) {
                $deliveryNote->number = static::generateNumber();
            }
        });
    }

    public static function generateNumber(): string
    {
        $prefix = 'SJ/' . now()->format('Y/m') . '/';
        $lastNumber = static::query()->where('number', 'like', $prefix . '%')->orderByDesc('id')->value('number');
        $next = 1;
        if ($lastNumber && preg_match('/(\d+)$/', $lastNumber, $matches)) {
            $next = ((int) $matches[1]) + 1;
        }
        return $prefix . str_pad((string) $next, 4, '0', STR_PAD_LEFT);
    }

    public function order() { return $this->belongsTo(Order::class); }
    public function vehicle() { return $this->belongsTo(Vehicle::class); }
    public function creator() { return $this->belongsTo(User::class, 'created_by'); }

    public function getStatusLabelAttribute(): string
    {
        return match ($this->status) {
            self::STATUS_DRAFT => 'Draft',
            self::STATUS_PRINTED => 'Sudah Dicetak',
            self::STATUS_DELIVERED => 'Dikirim',
            self::STATUS_RECEIVED => 'Diterima',
            self::STATUS_CANCELLED => 'Dibatalkan',
            default => ucfirst((string) $this->status),
        };
    }

    public function markPrinted(): void
    {
        if ($this->status === self::STATUS_DRAFT) {
            $this->forceFill(['status' => self::STATUS_PRINTED])->save();
        }
    }
}
