<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;

class Shipment extends Model
{
    use HasFactory;

    protected $fillable = [
        'order_confirmation_id',
        'shipment_number',
        'shipment_date',
        'vessel_flight_no',
        'bill_of_lading',
        'port_of_loading',
        'port_of_discharge',
        'etd',
        'eta',
        'status',
        'remarks',
        'created_by'
    ];

    protected $casts = [
        'shipment_date' => 'date',
        'etd' => 'date',
        'eta' => 'date',
    ];

    protected static function boot()
    {
        parent::boot();

        static::creating(function ($shipment) {
            if (empty($shipment->shipment_number)) {
                $shipment->shipment_number = static::generateShipmentNumber();
            }
        });
    }

    public static function generateShipmentNumber(): string
    {
        $lastShipment = static::latest('id')->first();
        $nextNumber = $lastShipment ? $lastShipment->id + 1 : 1;
        return 'SHIP-' . date('Y') . '-' . str_pad($nextNumber, 5, '0', STR_PAD_LEFT);
    }

    public function orderConfirmation(): BelongsTo
    {
        return $this->belongsTo(OrderConfirmation::class);
    }

    public function cartonDetails(): HasMany
    {
        return $this->hasMany(CartonDetail::class);
    }

    public function bookingInvoice(): HasMany
    {
        return $this->hasMany(BookingInvoice::class);
    }

    public function finalShipment(): HasMany
    {
        return $this->hasMany(FinalShipment::class);
    }

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

    public function getStatusBadgeColorAttribute(): string
    {
        return match($this->status) {
            'draft' => 'secondary',
            'booked' => 'primary',
            'in_transit' => 'warning',
            'delivered' => 'success',
            'cancelled' => 'danger',
            default => 'secondary',
        };
    }

    public function getTotalCartonsAttribute(): int
    {
        return $this->cartonDetails->count();
    }

    public function getTotalQuantityAttribute(): int
    {
        return $this->cartonDetails->sum('quantity');
    }

    public function getTotalWeightAttribute(): float
    {
        return $this->cartonDetails->sum('gross_weight');
    }
}