<?php

namespace Database\Seeders;

use Illuminate\Database\Seeder;
use App\Models\MenuItemRecipe;
use App\Models\PosMenuItem;
use App\Models\Item;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class MenuItemRecipeSeeder extends Seeder
{
    /**
     * Run the database seeds.
     * 
     * This seeder imports recipes for Azan Shinwari restaurant (id=1), branch (id=2)
     * The recipes are imported from a sample file for Bismillah Restaurant (2nd branch)
     * but saved for Azan Shinwari restaurant.
     */
    public function run()
    {
        $restaurantId = 1; // Azan Shinwari restaurant
        $branchId = 2; // Branch ID 2

        // Sample recipe data structure
        // Format: ['menu_item_name', 'inventory_item_name', quantity, 'unit', 'details', sort_order]
        // Note: Update this array with actual data from your sample file
        $recipes = [
            // Example recipes - replace with actual data from your sample file
            // ['Chicken Biryani', 'Chicken', 500, 'g', 'Boneless chicken pieces', 1],
            // ['Chicken Biryani', 'Basmati Rice', 250, 'g', 'Long grain rice', 2],
            // ['Chicken Biryani', 'Onions', 100, 'g', 'Sliced onions', 3],
            // Add more recipes here from your sample file
        ];

        if (empty($recipes)) {
            $this->command->warn('No recipes to import. Please add recipe data to the $recipes array in MenuItemRecipeSeeder.php');
            return;
        }

        $imported = 0;
        $skipped = 0;
        $errors = [];

        DB::beginTransaction();

        try {
            foreach ($recipes as $index => $recipe) {
                try {
                    $menuItemName = trim($recipe[0] ?? '');
                    $inventoryItemName = trim($recipe[1] ?? '');
                    $quantity = isset($recipe[2]) ? (float) $recipe[2] : 0;
                    $unit = isset($recipe[3]) ? trim($recipe[3] ?? '') : '';
                    $details = isset($recipe[4]) ? trim($recipe[4] ?? '') : null;
                    $sortOrder = isset($recipe[5]) ? (int) $recipe[5] : 0;

                    if (empty($menuItemName) || empty($inventoryItemName)) {
                        $skipped++;
                        $errors[] = "Row " . ($index + 1) . ": Menu Item Name or Inventory Item Name is missing";
                        continue;
                    }

                    if ($quantity <= 0) {
                        $skipped++;
                        $errors[] = "Row " . ($index + 1) . ": Quantity must be greater than 0";
                        continue;
                    }

                    // Find menu item by name (case-insensitive) for the specified branch
                    $menuItem = PosMenuItem::whereRaw('LOWER(name) = ?', [strtolower($menuItemName)])
                        ->where('restaurant_id', $restaurantId)
                        ->where('branch_id', $branchId)
                        ->first();

                    if (!$menuItem) {
                        $skipped++;
                        $errors[] = "Row " . ($index + 1) . ": Menu item '{$menuItemName}' not found for restaurant {$restaurantId}, branch {$branchId}";
                        continue;
                    }

                    // Find inventory item by name (case-insensitive)
                    $inventoryItem = Item::whereRaw('LOWER(name) = ?', [strtolower($inventoryItemName)])
                        ->first();

                    if (!$inventoryItem) {
                        $skipped++;
                        $errors[] = "Row " . ($index + 1) . ": Inventory item '{$inventoryItemName}' not found";
                        continue;
                    }

                    // Convert unit: g -> gram, kg -> kilogram
                    $unit = strtolower(trim($unit));
                    if ($unit === 'g') {
                        $unit = 'gram';
                    } elseif ($unit === 'kg'|| $unit === 'kilogram') {
                        $unit = 'kg';
                    }

                    // Check if recipe already exists
                    $existing = MenuItemRecipe::where('menu_item_id', $menuItem->id)
                        ->where('inventory_item_id', $inventoryItem->id)
                        ->first();

                    if ($existing) {
                        $skipped++;
                        $errors[] = "Row " . ($index + 1) . ": Recipe for '{$menuItemName}' with '{$inventoryItemName}' already exists";
                        continue;
                    }

                    // Create recipe
                    MenuItemRecipe::create([
                        'menu_item_id' => $menuItem->id,
                        'inventory_item_id' => $inventoryItem->id,
                        'quantity' => round($quantity, 2),
                        'unit' => $unit,
                        'details' => $details,
                        'sort_order' => $sortOrder,
                        'restaurant_id' => $restaurantId,
                    ]);

                    $imported++;
                } catch (\Exception $e) {
                    $skipped++;
                    $errors[] = "Row " . ($index + 1) . ": " . $e->getMessage();
                    Log::error('Error importing recipe row in seeder: ' . $e->getMessage());
                }
            }

            DB::commit();

            $this->command->info("Recipe import completed!");
            $this->command->info("Imported: {$imported} recipes");
            if ($skipped > 0) {
                $this->command->warn("Skipped: {$skipped} rows");
                if (!empty($errors)) {
                    $this->command->error("Errors:");
                    foreach ($errors as $error) {
                        $this->command->error("  - {$error}");
                    }
                }
            }
        } catch (\Exception $e) {
            DB::rollBack();
            Log::error('Error in MenuItemRecipeSeeder: ' . $e->getMessage());
            $this->command->error('Failed to import recipes: ' . $e->getMessage());
        }
    }
}

