<?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 Order extends Model
{
    use HasFactory;

    protected $fillable = [
        'order_number',
        'user_id',
        'vehicle_id',
        'auction_vehicle_id',
        'bid_id',
        'order_type',
        'total_amount_bdt',
        'paid_amount_bdt',
        'due_amount_bdt',
        'hammer_price_jpy',
        'status',
        'vessel_name',
        'voyage_number',
        'bl_number',
        'container_number',
        'shipping_line',
        'port_of_loading',
        'port_of_discharge',
        'etd_japan',
        'eta_chittagong',
        'customs_cleared_date',
        'registration_date',
        'delivery_date',
        'assigned_reg_number',
        'delivery_address',
        'internal_notes',
    ];

    protected function casts(): array
    {
        return [
            'total_amount_bdt' => 'decimal:2',
            'paid_amount_bdt' => 'decimal:2',
            'due_amount_bdt' => 'decimal:2',
            'hammer_price_jpy' => 'decimal:2',
            'etd_japan' => 'date',
            'eta_chittagong' => 'date',
            'customs_cleared_date' => 'date',
            'registration_date' => 'date',
            'delivery_date' => 'date',
        ];
    }

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

    public function customer(): BelongsTo
    {
        return $this->belongsTo(Customer::class, 'user_id', 'user_id');
    }

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

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

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

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

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

    public function statusHistory(): HasMany
    {
        return $this->hasMany(OrderStatusHistory::class)->orderBy('occurred_at', 'desc');
    }

    // 12-Step Import Tracking Definition
    public static function trackingSteps(): array
    {
        return [
            'auction_won' => ['title' => 'Auction Won', 'icon' => 'trophy', 'desc' => 'Vehicle successfully secured at Japanese auction'],
            'payment_pending' => ['title' => 'Payment Pending', 'icon' => 'credit-card', 'desc' => 'Invoice issued, awaiting booking deposit'],
            'payment_received' => ['title' => 'Payment Received', 'icon' => 'check-circle', 'desc' => 'Funds verified and confirmed by accounts'],
            'japan_processing' => ['title' => 'Japan Processing', 'icon' => 'building', 'desc' => 'Yard inspection, deregistration, export certificate'],
            'preparing_shipment' => ['title' => 'Preparing Shipment', 'icon' => 'package', 'desc' => 'Vehicle moved to port yard and booked on vessel'],
            'shipped' => ['title' => 'Shipped', 'icon' => 'ship', 'desc' => 'Vessel departed Japan for Chittagong Port'],
            'arrived_chittagong' => ['title' => 'Arrived Chittagong', 'icon' => 'anchor', 'desc' => 'Vessel berthed and vehicle unloaded at port yard'],
            'customs_processing' => ['title' => 'Customs Assessment', 'icon' => 'file-text', 'desc' => 'C&F filing, assessment and duty assessment'],
            'customs_cleared' => ['title' => 'Customs Cleared', 'icon' => 'check-square', 'desc' => 'Duty paid, customs gate release order received'],
            'registration' => ['title' => 'BRTA Registration', 'icon' => 'shield', 'desc' => 'BRTA inspection, retro-reflective plate assignment'],
            'ready_for_delivery' => ['title' => 'Ready for Delivery', 'icon' => 'sparkles', 'desc' => 'Vehicle detailed, serviced, ready at Gulshan showroom'],
            'delivered' => ['title' => 'Delivered', 'icon' => 'key', 'desc' => 'Handed over to proud owner'],
        ];
    }

    public function getCurrentStepIndexAttribute(): int
    {
        $keys = array_keys(self::trackingSteps());
        $index = array_search($this->status, $keys);
        return $index !== false ? $index : 0;
    }

    public function getCarTitleAttribute(): string
    {
        if ($this->vehicle) {
            return $this->vehicle->full_name;
        }
        if ($this->auctionVehicle) {
            return $this->auctionVehicle->full_name;
        }
        return "Import Vehicle #{$this->order_number}";
    }

    public function getCarImageAttribute(): string
    {
        if ($this->vehicle && $this->vehicle->main_image) {
            return $this->vehicle->main_image;
        }
        if ($this->auctionVehicle && $this->auctionVehicle->main_image) {
            return $this->auctionVehicle->main_image;
        }
        return 'https://images.unsplash.com/photo-1549399542-7e3f8b79c341?w=800&q=80';
    }

    public function getStatusBadgeClassAttribute(): string
    {
        return match ($this->status) {
            'delivered' => 'bg-emerald-100 text-emerald-800 border-emerald-300 dark:bg-emerald-950/70 dark:text-emerald-300',
            'shipped', 'arrived_chittagong', 'customs_processing', 'customs_cleared' => 'bg-blue-100 text-blue-800 border-blue-300 dark:bg-blue-950/70 dark:text-blue-300',
            'ready_for_delivery' => 'bg-teal-100 text-teal-800 border-teal-300 dark:bg-teal-950/70 dark:text-teal-300',
            'cancelled' => 'bg-rose-100 text-rose-800 border-rose-300 dark:bg-rose-950/70 dark:text-rose-300',
            default => 'bg-amber-100 text-amber-800 border-amber-300 dark:bg-amber-950/70 dark:text-amber-300',
        };
    }
}
