<?php

namespace App\Models;

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

class OrderItem extends Model
{
    use HasFactory;

    protected $fillable = [
        'order_id',
        'menu_item_id',
        'item_name',
        'item_price',
        'quantity',
        'total_price',
        'variants',
        'addons',
        'special_instructions',
        'status',
        'kitchen_station',
        'sent_to_kitchen_at',
        'started_preparing_at',
        'ready_at',
        'served_at',
    ];

    protected $casts = [
        'item_price' => 'decimal:2',
        'total_price' => 'decimal:2',
        'variants' => 'array',
        'addons' => 'array',
        'sent_to_kitchen_at' => 'datetime',
        'started_preparing_at' => 'datetime',
        'ready_at' => 'datetime',
        'served_at' => 'datetime',
    ];

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

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

    public function getFormattedVariantsAttribute(): string
    {
        if (!$this->variants) {
            return '';
        }

        return collect($this->variants)
            ->map(fn($value, $key) => "$key: $value")
            ->implode(', ');
    }

    public function getFormattedAddonsAttribute(): string
    {
        if (!$this->addons) {
            return '';
        }

        return collect($this->addons)
            ->map(fn($addon) => $addon['name'] ?? $addon)
            ->implode(', ');
    }

    public function getTotalPriceWithAddonsAttribute(): float
    {
        $basePrice = $this->total_price;
        
        if ($this->addons) {
            $addonPrice = collect($this->addons)
                ->sum(fn($addon) => ($addon['price'] ?? 0) * $this->quantity);
            
            return $basePrice + $addonPrice;
        }

        return $basePrice;
    }
}