<?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',
        'product_id',
        'product_name',
        'quantity',
        'unit_price',
        'total_price',
        'options',
        'inner_options',
        'special_instructions',
        'cup_size_id',
        'flavors',
        'total_weight_grams',
    ];

    protected $casts = [
        'quantity' => 'integer',
        'unit_price' => 'decimal:2',
        'total_price' => 'decimal:2',
        'options' => 'array',
        'inner_options' => 'array',
        'flavors' => 'array',
        'total_weight_grams' => 'decimal:2',
    ];

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

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

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

    public function batchDeductions()
    {
        return $this->hasMany(BatchDeduction::class);
    }

    public function calculateTotalPrice(): float
    {
        return $this->unit_price * $this->quantity;
    }

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

        static::saving(function ($item) {
            $item->total_price = $item->calculateTotalPrice();
        });

        static::saved(function ($item) {
            $item->order->calculateTotals();
        });

        static::deleted(function ($item) {
            $item->order->calculateTotals();
        });
    }
}
