<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Str;

class Order extends Model
{
    protected $fillable = [
        'order_number', 'name', 'address', 'mobile', 'note',
        'payment_method', 'payment_phone', 'payment_trx_id',
        'shipping_area', 'shipping_charge', 'subtotal', 'total', 'status',
    ];

    protected $casts = [
        'subtotal'        => 'decimal:2',
        'shipping_charge' => 'decimal:2',
        'total'           => 'decimal:2',
    ];

    protected static function boot()
    {
        parent::boot();
        static::creating(function ($order) {
            if (empty($order->order_number)) {
                $order->order_number = 'ORD-' . strtoupper(Str::random(10));
            }
        });
    }

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

    public function trackingUpdates()
    {
        return $this->hasMany(TrackingUpdate::class)->orderBy('created_at', 'desc');
    }

    public function getStatusBadgeAttribute()
    {
        $badges = [
            'pending'    => 'warning',
            'confirmed'  => 'info',
            'processing' => 'primary',
            'shipped'    => 'secondary',
            'delivered'  => 'success',
            'cancelled'  => 'danger',
        ];
        return $badges[$this->status] ?? 'secondary';
    }
}
