<?php

namespace App\Models;

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

class DeliveryNote extends Model
{
    use HasFactory;

    protected $fillable = [
        'delivery_note_number',
        'order_id',
        'supplier_id',
        'status',
        'delivery_method',
        'tracking_number',
        'courier_name',
        'delivery_address',
        'delivery_city',
        'delivery_postal_code',
        'recipient_name',
        'recipient_phone',
        'dispatched_at',
        'delivered_at',
        'notes',
        'delivery_instructions',
    ];

    protected $casts = [
        'dispatched_at' => 'datetime',
        'delivered_at' => 'datetime',
    ];

    public function order()
    {
        return $this->belongsTo(Order::class);
    }

    public function supplier()
    {
        return $this->belongsTo(Supplier::class);
    }

    public static function generateDeliveryNoteNumber(): string
    {
        $prefix = 'DN';
        $date = now()->format('Ymd');
        $lastNote = self::whereDate('created_at', today())->latest()->first();
        $sequence = $lastNote ? ((int) substr($lastNote->delivery_note_number, -4)) + 1 : 1;
        return $prefix . $date . str_pad($sequence, 4, '0', STR_PAD_LEFT);
    }

    public function markAsDispatched(?string $trackingNumber = null, ?string $courierName = null): void
    {
        $this->update([
            'status' => 'dispatched',
            'dispatched_at' => now(),
            'tracking_number' => $trackingNumber,
            'courier_name' => $courierName,
        ]);
    }

    public function markAsDelivered(): void
    {
        $this->update([
            'status' => 'delivered',
            'delivered_at' => now(),
        ]);
    }
}
