<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    /**
     * Run the migrations.
     */
    public function up(): void
    {
        if (!Schema::hasTable('meal_plans')) {
            Schema::create('meal_plans', function (Blueprint $table) {
                $table->id();
                $table->foreignId('client_id')->constrained()->onDelete('cascade');
                $table->string('name');
                $table->text('description')->nullable();
                $table->enum('goal_type', ['lose', 'maintain', 'gain'])->default('maintain');
                $table->integer('goal_percentage')->default(0); // -15%, 0%, +15%
                $table->decimal('target_calories', 8, 2)->nullable();
                $table->decimal('target_proteins', 6, 2)->nullable();
                $table->decimal('target_carbs', 6, 2)->nullable();
                $table->decimal('target_fats', 6, 2)->nullable();
                $table->boolean('is_active')->default(true);
                $table->timestamps();
                
                $table->index('client_id');
            });
        }

        if (!Schema::hasTable('meal_items')) {
            Schema::create('meal_items', function (Blueprint $table) {
                $table->id();
                $table->foreignId('meal_plan_id')->constrained()->onDelete('cascade');
                $table->foreignId('food_id')->constrained()->onDelete('cascade');
                $table->enum('meal_type', [
                    'breakfast',
                    'lunch', 
                    'dinner',
                    'snack',
                    'mid_morning_snack',
                    'mid_afternoon_snack',
                    'pre_workout',
                    'post_workout',
                    'meal_1',
                    'meal_2',
                    'meal_3'
                ]);
                $table->decimal('quantity', 8, 2)->default(100); // grams
                $table->decimal('proteins', 6, 2)->default(0);
                $table->decimal('carbs', 6, 2)->default(0);
                $table->decimal('fats', 6, 2)->default(0);
                $table->decimal('calories', 8, 2)->default(0);
                $table->integer('order')->default(0);
                $table->timestamps();
                
                $table->index('meal_plan_id');
                $table->index('meal_type');
            });
        }
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        Schema::dropIfExists('meal_items');
        Schema::dropIfExists('meal_plans');
    }
};
