<?php

namespace App\Models;

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

class Shipment extends Model
{
    use HasFactory;

    protected $fillable = [
        'shipment_id',
        'origin',
        'destination',
        'total_ctn',
        'total_qty',
        'total_ttl_qty',
        'total_amount',
        'total_cbm',
        'total_ttl_cbm',
        'total_kg',
        'total_ttl_kg',
        'status',
        'shipment_date',
        'meta',
    ];

    protected $casts = [
        'meta' => 'array',
        'shipment_date' => 'date',
    ];

    // ---------------------------
    // RELATIONSHIPS
    // ---------------------------

    public function items()
    {
        return $this->hasMany(ShipmentItem::class);
    }

    public function orders()
    {
        return $this->belongsToMany(Order::class, 'shipment_items', 'shipment_id', 'order_id');
    }

    // ---------------------------
    // STATUS CONSTANTS
    // ---------------------------

    const STATUS_PENDING     = 'pending';
    const STATUS_IN_TRANSIT  = 'in_transit';
    const STATUS_DISPATCHED  = 'dispatched';
    const STATUS_DELIVERED   = 'delivered';

    public static function statusOptions()
    {
        return [
            self::STATUS_PENDING     => 'Pending',
            self::STATUS_IN_TRANSIT  => 'In Transit',
            self::STATUS_DISPATCHED  => 'Dispatched',
            self::STATUS_DELIVERED   => 'Delivered',
        ];
    }

    // ---------------------------
    // HELPERS
    // ---------------------------

    public function totalOrdersCount()
    {
        return $this->items()->count();
    }

    public function statusLabel()
    {
        return self::statusOptions()[$this->status] ?? ucfirst($this->status);
    }
}
