<?php

namespace App\Models;

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

class MealItem extends Model
{
    use HasFactory;

    protected $fillable = [
        'diet_plan_id',
        'meal_plan_id', // Keep for backwards compatibility during migration
        'food_id',
        'meal_type',
        'quantity',
        'unit',
        'proteins',
        'carbs',
        'fats',
        'calories',
        'order',
    ];

    protected $casts = [
        'quantity' => 'decimal:2',
        'proteins' => 'decimal:2',
        'carbs' => 'decimal:2',
        'fats' => 'decimal:2',
        'calories' => 'decimal:2',
    ];

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

    /**
     * Legacy relationship for backwards compatibility
     */
    public function mealPlan(): BelongsTo
    {
        return $this->belongsTo(MealPlan::class);
    }

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

    /**
     * Recalculate macros based on quantity.
     */
    public function recalculateMacros(): void
    {
        if ($this->food) {
            $macros = $this->food->calculateMacros($this->quantity);
            $this->proteins = $macros['proteins'];
            $this->carbs = $macros['carbs'];
            $this->fats = $macros['fats'];
            $this->calories = $macros['calories'];
        }
    }
}
