<?php

namespace App\Http\Controllers\API;

use App\Http\Controllers\Controller;
use App\Http\Requests\FoodicsOrderRequest;
use App\Models\FoodicsOrderToken;
use App\Models\FoodicsUnit;
use Illuminate\Support\Facades\DB;
use GuzzleHttp\Client;
use GuzzleHttp\Exception\RequestException;
use Illuminate\Support\Facades\Log;
use App\Models\MiddlewareData;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Http;

class FoodicsAutomationController extends Controller
{
    public function index(FoodicsOrderRequest $request)
    {
        $brandTokens = $this->getBrandsToken('all', null);

        if (count($brandTokens) > 0) {
            foreach ($brandTokens as $brand) {
                $this->processDataSets($brand);
            }
        }
        echo "Done";
    }

    private function processDataSets(array $brand)
    {
        $apiUrl = env('FOODICS_API_URL');
        $company_id = $brand['company_id'];
        $brand_id = $brand['brand_id'];
        $access_token = $brand['access_token'];

        $dataSets = [
            [
                'endpoint' => '/inventory_item_categories',
                'queryParams' => 'filter[is_deleted]=false',
                'actionType' => 'create_ingredient_category'
            ],
            [
                'endpoint' => '/categories',
                'queryParams' => 'filter[is_deleted]=false',
                'actionType' => 'create_menu_category'
            ],
            [
                'endpoint' => '/inventory_items',
                'queryParams' => 'filter[with_ingredients]=false&filter[is_deleted]=false&include=category,suppliers',
                'actionType' => 'create_ingredient'
            ],
            [
                'endpoint' => '/inventory_items',
                'queryParams' => 'filter[with_ingredients]=true&filter[is_deleted]=false&include=category,ingredients',
                'actionType' => 'create_sub_recipe'
            ],
            [
                'endpoint' => '/products',
                'queryParams' => 'filter[is_deleted]=false&include=category,ingredients',
                'actionType' => 'create_recipe'
            ],
        ];

        foreach ($dataSets as $dataSet) {
            $url = "{$apiUrl}{$dataSet['endpoint']}";
            parse_str($dataSet['queryParams'], $queryParams);
            $dataItems = $this->fetchData($access_token, $url, $queryParams, $dataSet['actionType']);
            $this->saveData($company_id, $brand_id, $dataItems, $dataSet['actionType']);
        }
    }

    public function getBrandsToken($mode = 'all', $brand_id = null)
    {
        if ($mode == 'all') {
            $foodicsTokens = $this->getTokensFromAPI();
        } else {
            $foodicsTokens = $this->getTokensFromAPI('brand_id', $brand_id);
        }
        return $foodicsTokens;
    }

    public function getTokensFromAPI($column = null, $value = null)
    {
        $data = FoodicsOrderToken::getAccessToken(true, $column, $value);

        if (isset($data['data']) && !empty($data['data'])) {
            foreach ($data['data'] as &$item) {
                $branchIds = array_map(function ($shop) {
                    return $shop['foodics_branch_id'];
                }, $item['shops']);
                $item['branch_ids'] = implode(',', $branchIds);
            }
            return $data['data'];
        } else {
            return [];
        }
    }

    private function fetchData($access_token, $url, $queryParams = null, $actionType = null)
    {
        $client = new Client(['timeout' => 10.0]);
        $headers = [
            'Authorization' => 'Bearer ' . $access_token,
            'Accept' => 'application/json',
            'Content-Type' => 'application/json'
        ];

        $allItems = [];

        // Build base query string
        $baseQueryString = $queryParams ? http_build_query($queryParams) : '';
        $currentPageUrl = $url . ($baseQueryString ? '?' . $baseQueryString : '');

        try {
            do {
                Log::channel('foodics')->info("➡️ Requesting URL: {$currentPageUrl}");

                $res = $client->get($currentPageUrl, ['headers' => $headers]);
                $body = json_decode($res->getBody(), true);

                Log::channel('foodics')->debug("Raw response: " . json_encode($body));

                $data = $body['data'] ?? [];

                if (!empty($data)) {
                    Log::channel('foodics')->info("✅ Fetched " . count($data) . " items.");
                    $allItems = array_merge($allItems, $data);
                } else {
                    Log::channel('foodics')->warning("⚠️ No items found on this page.");
                }

                // Prepare next page URL
                $nextPage = $body['links']['next'] ?? null;

                if ($nextPage) {
                    // Ensure original query params are added again (if not already)
                    $parsedUrl = parse_url($nextPage);
                    parse_str($parsedUrl['query'] ?? '', $nextParams);

                    // Merge preserved query params with next page param
                    $finalParams = array_merge($queryParams ?? [], $nextParams);
                    $currentPageUrl = $url . '?' . http_build_query($finalParams);
                } else {
                    $currentPageUrl = null;
                    Log::channel('foodics')->info("⛔ No more pages to fetch.");
                }
            } while ($currentPageUrl);

            // Remove duplicates by ID
            $uniqueItems = [];
            foreach ($allItems as $item) {
                $uniqueItems[$item['id']] = $item;
            }

            $uniqueItems = array_values($uniqueItems);
            Log::channel('foodics')->info("🎉 Total unique items fetched " . $actionType . ": " . count($uniqueItems));
            #Log::channel('foodics')->info(json_encode($uniqueItems, JSON_PRETTY_PRINT));

            return $uniqueItems;
        } catch (\Exception $e) {
            Log::channel('foodics')->error("❌ Error during fetch: " . $e->getMessage());
            return ['error' => $e->getMessage()];
        }
    }

    private function saveData($company_id, $brand_id, $items, $dataType)
    {
        DB::beginTransaction();

        try {
            $data = [];

            $itemIds = array_map(fn($item) => $item['id'], $items);

            $existingItems = MiddlewareData::where('brand_id', $brand_id)
                ->where('data_type', $dataType)
                ->whereIn('foodics_id', $itemIds)
                ->pluck('foodics_id')
                ->toArray();

            foreach ($items as $item) {
                if (!in_array($item['id'], $existingItems)) {
                    $data[] = [
                        'company_id' => $company_id,
                        'brand_id' => $brand_id,
                        'foodics_id' => $item['id'],
                        'data_type' => $dataType,
                        'response' => json_encode($item, JSON_PRETTY_PRINT),
                    ];
                }
            }

            if (!empty($data)) {
                MiddlewareData::upsert($data, ['foodics_id'], ['response']);
            }

            DB::commit();
            # Log::channel('foodics')->info("Items and categories saved successfully.");
        } catch (\Exception $e) {
            DB::rollback();
            Log::channel('foodics')->error("Error saving data: " . $e->getMessage());
        }
    }

    public function generateData(FoodicsOrderRequest $request)
    {

        $type = $request->input('type');

        if ($type == 'inventory') {
            $this->typeInventory();
        } elseif ($type == 'recipe') {
            $this->typeRecipe();
        } elseif ($type == 'sub_recipe') {
            $this->typeSubRecipe();
        } elseif ($type == 'create_ingredient_category') {
            $this->typeIngredientCategory();
        } elseif ($type == 'create_menu_category') {
            $this->typeMenuCategory();
        } else {
            echo "no jobs";
        }
    }

    public function typeRecipe()
    {
        // Ensure the automation folder exists
        $folderPath = public_path('automation');
        if (!file_exists($folderPath)) {
            mkdir($folderPath, 0755, true); // Create folder with proper permissions
        }

        // Fetch all data grouped by brand_id
        $ingredients = MiddlewareData::where('data_type', 'create_recipe')
            ->where('status', 'default')
            //->where('brand_id', 255)
            ->get()
            ->groupBy('brand_id');

        if ($ingredients->isEmpty()) {
            return response()->json(['message' => 'No recipe found.'], 404);
        }

        foreach ($ingredients as $brandId => $brandIngredients) {
            // Create a folder for each brand_id
            $brandFolderPath = $folderPath . '/' . $brandId;
            if (!file_exists($brandFolderPath)) {
                mkdir($brandFolderPath, 0755, true); // Create folder with proper permissions
            }

            // CSV file path using brand_id in the brand folder
            $filename = "brand_{$brandId}_recipe.csv";
            $filenameSummary = "brand_{$brandId}_recipe_summary.csv";
            $filepath = $brandFolderPath . '/' . $filename;
            $filepathSummary = $brandFolderPath . '/' . $filenameSummary;

            // Prepare CSV header
            $header = [
                'MenuCategory',
                'RecipeName',
                'Ingredients',
                'IngredientQty',
                'Unit',
                'Yield',
                'UnitOfSubRecipe',
                'CookingMethod',
                'PrepTime',
                'Description',
                'Serving'
            ];

            $headerSummary = [
                'MenuCategory',
                'RecipeName',
                'Ingredients',
                'IngredientQty',
                'Unit',
                'Yield',
                'UnitOfSubRecipe',
                'CookingMethod',
                'PrepTime',
                'Description',
                'Serving',
                'image',
                'price'
            ];

            // Open file for writing
            $file = fopen($filepath, 'w');
            $fileSummary = fopen($filepathSummary, 'w');
            fputcsv($file, $header);
            fputcsv($fileSummary, $headerSummary);

            foreach ($brandIngredients as $ingredient) {
                $data = json_decode($ingredient['response'], true);

                if (empty($data) || !isset($data['ingredients'])) {
                    continue; // Skip if no ingredients
                }

                $menuCategory = $data['category']['name'] ?? '';
                $recipeName = $data['name'] ?? '';
                $unitOfSubRecipe = $data['ingredient_unit'] ?? '';
                $price = $data['price'] ?? 0;
                $image = $data['image'] ?? '';
                #$unitOfSubRecipe = config('general_units.' . $unitOfSubRecipeFoodics);

                // Write the first row with MenuCategory and RecipeName
                fputcsv($file, [
                    $menuCategory,
                    $recipeName,
                    '', // Empty Ingredients column for the first row
                    '', // Empty IngredientQty column
                    '', // Empty Unit column
                    '', // Empty Yield column
                    $unitOfSubRecipe,
                    '', // Empty CookingMethod
                    '', // Empty PrepTime
                    '', // Empty Description
                    mt_rand(0, 9), // Empty Serving
                ]);

                fputcsv($fileSummary, [
                    $menuCategory,
                    $recipeName,
                    '', // Empty Ingredients column for the first row
                    '', // Empty IngredientQty column
                    '', // Empty Unit column
                    '', // Empty Yield column
                    $unitOfSubRecipe,
                    '', // Empty CookingMethod
                    '', // Empty PrepTime
                    '', // Empty Description
                    mt_rand(0, 9), // Empty Serving
                    $image,
                    $price,
                ]);

                foreach ($data['ingredients'] as $ingredientData) {
                    $ingredientName = $ingredientData['name'] ?? '';
                    $ingredientQty = $ingredientData['pivot']['quantity'] ?? 0;
                    $unitFoodics = $ingredientData['ingredient_unit'] ?? '';
                    #  $unit = config('general_units.' . $unitFoodics);
                    $unit = $this->unit_coversion("recipe", $unitFoodics);
                    $yield = $ingredientData['pivot']['yield_percentage'] ?? 100;

                    // Write subsequent rows for each ingredient
                    fputcsv($file, [
                        '', // Empty MenuCategory for subsequent rows
                        '', // Empty RecipeName for subsequent rows
                        $ingredientName,
                        $ingredientQty,
                        $unit,
                        '',
                        '', // Empty UnitOfSubRecipe for subsequent rows
                        '', // Empty CookingMethod
                        '', // Empty PrepTime
                        '', // Empty Description
                        '', // Empty Serving
                    ]);

                    fputcsv($fileSummary, [
                        '', // Empty MenuCategory for subsequent rows
                        '', // Empty RecipeName for subsequent rows
                        $ingredientName,
                        $ingredientQty,
                        $unit,
                        '',
                        '', // Empty UnitOfSubRecipe for subsequent rows
                        '', // Empty CookingMethod
                        '', // Empty PrepTime
                        '', // Empty Description
                        '', // Empty Serving
                    ]);
                }
            }

            fclose($file);
            fclose($fileSummary);

            // **Log File Creation**
            Log::channel('foodics')->info("CSV file created for brand {$brandId}: {$filepath}");

            // **Automatically Call postData and Log Response**
            $response = $this->postData($brandId, 'recipe', $filepath);

            // Log API response
            Log::channel('foodics')->info("API response for brand {$brandId}:", ['response' => $response]);

            $responses[$brandId] = $response;

            // Update status to 'processed' for the current brand_id
            MiddlewareData::where('data_type', 'create_recipe')
                ->where('status', 'default')
                ->where('brand_id', $brandId)
                ->update(['status' => 'processed']);
        }

        return response()->json([
            'message'  => 'CSV files created and data posted successfully.',
            'responses' => $responses
        ]);
    }

    public function typeSubRecipe()
    {
        // Ensure the automation folder exists
        $folderPath = public_path('automation');
        if (!file_exists($folderPath)) {
            mkdir($folderPath, 0755, true); // Create folder with proper permissions
        }

        // Fetch all data grouped by brand_id
        $ingredients = MiddlewareData::where('data_type', 'create_sub_recipe')
            ->where('status', 'default')
            ->get()
            ->groupBy('brand_id');

        if ($ingredients->isEmpty()) {
            return response()->json(['message' => 'No sub_recipe found.'], 404);
        }

        foreach ($ingredients as $brandId => $brandIngredients) {
            // Create a folder for each brand_id
            $brandFolderPath = $folderPath . '/' . $brandId;
            if (!file_exists($brandFolderPath)) {
                mkdir($brandFolderPath, 0755, true); // Create folder with proper permissions
            }

            // CSV file path using brand_id in the brand folder
            $filename = "brand_{$brandId}_sub_recipe.csv";
            $filenameSummary = "brand_{$brandId}_sub_recipe_summary.csv";
            $filepath = $brandFolderPath . '/' . $filename;
            $filepathSummary = $brandFolderPath . '/' . $filenameSummary;

            // Prepare CSV header
            $header = [
                'MenuCategory',
                'RecipeName',
                'Ingredients',
                'IngredientQty',
                'Unit',
                'Yield',
                'UnitOfSubRecipe',
                'CookingMethod',
                'PrepTime',
                'Description',
                'Serving'
            ];

            $headerSummary = [
                'MenuCategory',
                'RecipeName',
                'Ingredients',
                'IngredientQty',
                'Unit',
                'Yield',
                'UnitOfSubRecipe',
                'CookingMethod',
                'PrepTime',
                'Description',
                'Serving',
                'sku',
                'cost'
            ];

            // Open file for writing
            $file = fopen($filepath, 'w');
            $fileSummary = fopen($filepathSummary, 'w');
            fputcsv($file, $header);
            fputcsv($fileSummary, $headerSummary);

            foreach ($brandIngredients as $ingredient) {
                $data = json_decode($ingredient['response'], true);

                if (empty($data) || !isset($data['ingredients'])) {
                    continue; // Skip if no ingredients
                }

                $menuCategory = $data['category']['name'] ?? 'N/A';
                $recipeName = $data['name'] ?? 'N/A';
                $unitOfSubRecipeFoodics = $data['ingredient_unit'] ?? 'N/A';
                $unitOfSubRecipe = $this->unit_coversion("sub_recipe", $unitOfSubRecipeFoodics);
                $cost = $data['cost'] ?? 0;
                $sku = $data['sku'] ?? 0;
                # $unitOfSubRecipe = config('general_units.' . $unitOfSubRecipeFoodics);

                // Write the first row with MenuCategory, RecipeName, and Yield
                fputcsv($file, [
                    $menuCategory,
                    $recipeName,
                    '', // Empty Ingredients column for the first row
                    '', // Empty IngredientQty column
                    '', // Empty Unit column
                    0, // Yield value only on the recipe row
                    $unitOfSubRecipe,
                    '', // Empty CookingMethod
                    '', // Empty PrepTime
                    '', // Empty Description
                    '', // Empty Serving
                ]);

                fputcsv($fileSummary, [
                    $menuCategory,
                    $recipeName,
                    '', // Empty Ingredients column for the first row
                    '', // Empty IngredientQty column
                    '', // Empty Unit column
                    0, // Yield value only on the recipe row
                    $unitOfSubRecipe,
                    '', // Empty CookingMethod
                    '', // Empty PrepTime
                    '', // Empty Description
                    '', // Empty Serving
                    $sku,
                    $cost,
                ]);

                foreach ($data['ingredients'] as $ingredientData) {
                    $ingredientName = $ingredientData['name'] ?? 'N/A';
                    $ingredientQty = $ingredientData['pivot']['quantity'] ?? 0;
                    $unitFoodics = $ingredientData['ingredient_unit'] ?? 'N/A';
                    $unit = $this->unit_coversion("sub_recipe", $unitFoodics);
                    #dd($unit);
                    # $unit = config('general_units.' . $unitFoodics);

                    // Write subsequent rows for each ingredient without Yield
                    fputcsv($file, [
                        '', // Empty MenuCategory for subsequent rows
                        '', // Empty RecipeName for subsequent rows
                        $ingredientName,
                        $ingredientQty,
                        $unit,
                        '', // No Yield for ingredients
                        '', // Empty UnitOfSubRecipe for subsequent rows
                        '', // Empty CookingMethod
                        '', // Empty PrepTime
                        '', // Empty Description
                        '', // Empty Serving
                    ]);

                    // Write subsequent rows for each ingredient without Yield
                    fputcsv($fileSummary, [
                        '', // Empty MenuCategory for subsequent rows
                        '', // Empty RecipeName for subsequent rows
                        $ingredientName,
                        $ingredientQty,
                        $unit,
                        '', // No Yield for ingredients
                        '', // Empty UnitOfSubRecipe for subsequent rows
                        '', // Empty CookingMethod
                        '', // Empty PrepTime
                        '', // Empty Description
                        '', // Empty Serving
                    ]);
                }
            }

            fclose($file);
            fclose($fileSummary);

            // **Log File Creation**
            Log::channel('foodics')->info("CSV file created for brand {$brandId}: {$filepath}");

            // **Automatically Call postData and Log Response**
            $response = $this->postData($brandId, 'sub_recipe', $filepath);

            // Log API response
            Log::channel('foodics')->info("API response for brand {$brandId}:", ['response' => $response]);

            $responses[$brandId] = $response;

            // Update status to 'processed' for the current brand_id
            MiddlewareData::where('data_type', 'create_sub_recipe')
                ->where('status', 'default')
                ->where('brand_id', $brandId)
                ->update(['status' => 'processed']);
        }

        return response()->json([
            'message'  => 'CSV files created and data posted successfully.',
            'responses' => $responses
        ]);
    }

    public function typeInventory()
    {
        $folderPath = public_path('automation');
        if (!file_exists($folderPath)) {
            mkdir($folderPath, 0755, true);
        }

        $ingredients = MiddlewareData::where('data_type', 'create_ingredient')
            ->where('status', 'default')
            ->get()
            ->groupBy('brand_id');

        if ($ingredients->isEmpty()) {
            Log::channel('foodics')->info('No ingredients found for inventory generation.');
            return response()->json(['message' => 'No ingredients found.'], 404);
        }

        $responses = [];

        foreach ($ingredients as $brandId => $brandIngredients) {
            $brandFolderPath = "{$folderPath}/{$brandId}";
            if (!file_exists($brandFolderPath)) {
                mkdir($brandFolderPath, 0755, true);
            }

            $filename = "brand_{$brandId}_inventory.csv";
            $filenameSummary = "brand_{$brandId}_inventory_summary.csv";
            $filepath = "{$brandFolderPath}/{$filename}";
            $filepathSummary = "{$brandFolderPath}/{$filenameSummary}";

            $header = [
                'Item Name',
                'UOM',
                'Item Category',
                'Storage Waste %',
                'Calories (kcal)',
                'Carbs (g)',
                'Proteins (g)',
                'Fats (g)',
                'Alg-Milk',
                'Alg-Egg',
                'Alg-Fish',
                'Alg-Shellfish',
                'Alg-Treenuts',
                'Alg-Peanuts',
                'Alg-Soybean',
                'Alg-Gluten',
                'Product Code'
            ];
            $headerSummary = [
                'Item Name',
                'UOM',
                'Item Category',
                'Storage Waste %',
                'Calories (kcal)',
                'Carbs (g)',
                'Proteins (g)',
                'Fats (g)',
                'Alg-Milk',
                'Alg-Egg',
                'Alg-Fish',
                'Alg-Shellfish',
                'Alg-Treenuts',
                'Alg-Peanuts',
                'Alg-Soybean',
                'Alg-Gluten',
                'Product Code',
                'sku',
                'cost',
                'suppliers'
            ];

            $file = fopen($filepath, 'w');
            $fileSummary = fopen($filepathSummary, 'w');
            fputcsv($file, $header);
            fputcsv($fileSummary, $headerSummary);

            foreach ($brandIngredients as $ingredient) {

                $data = json_decode($ingredient['response'], true);

                $unitOfIngredientFoodics = $data['storage_unit'] ?? 'N/A';
                $cost = $data['cost'] ?? 0;
                $sku = $data['sku'] ?? 0;
                $unit = config('general_units.' . $unitOfIngredientFoodics);
                //$supplierNames = array_filter(array_column($data['suppliers'], 'name'));
                //$commaSeparatedNames = !empty($supplierNames) ? implode(', ', $supplierNames) : '';
                $suppliers = $data['suppliers'] ?? [];
                $supplierNames = array_map(function ($supplier) {
                    return "{$supplier['name']}|{$supplier['code']}|{$supplier['contact_name']}";
                }, $suppliers);
                $commaSeparatedNames = !empty($supplierNames) ? implode(', ', $supplierNames) : '';


                $row = [
                    $data['name'] ?? 'N/A',
                    $unit,
                    $data['category']['name'] ?? 'N/A',
                    0,
                    0,
                    0,
                    0,
                    0,
                    'No',
                    'No',
                    'No',
                    'No',
                    'No',
                    'No',
                    'No',
                    'No',
                    ''
                ];

                $rowSummary = [
                    $data['name'] ?? 'N/A',
                    $unit,
                    $data['category']['name'] ?? 'N/A',
                    0,
                    0,
                    0,
                    0,
                    0,
                    'No',
                    'No',
                    'No',
                    'No',
                    'No',
                    'No',
                    'No',
                    'No',
                    '',
                    $sku,
                    $cost,
                    $commaSeparatedNames
                ];

                fputcsv($file, $row);
                fputcsv($fileSummary, $rowSummary);
            }

            fclose($file);
            fclose($fileSummary);

            // **Log File Creation**
            Log::channel('foodics')->info("CSV file created for brand {$brandId}: {$filepath}");

            // **Automatically Call postData and Log Response**
            $response = $this->postData($brandId, 'marketlist', $filepath);

            // Log API response
            Log::channel('foodics')->info("API response for brand {$brandId}:", ['response' => $response]);

            $responses[$brandId] = $response;

            // Update status to 'processed' for the current brand_id
            MiddlewareData::where('data_type', 'create_ingredient')
                ->where('status', 'default')
                ->where('brand_id', $brandId)
                ->update(['status' => 'processed']);
        }

        return response()->json([
            'message'  => 'CSV files created and data posted successfully.',
            'responses' => $responses
        ]);
    }

    public function typeIngredientCategory()
    {
        // Ensure the automation folder exists
        $folderPath = public_path('automation');
        if (!file_exists($folderPath)) {
            mkdir($folderPath, 0755, true); // Create folder with proper permissions
        }

        // Fetch all data grouped by brand_id
        $categories = MiddlewareData::where('data_type', 'create_ingredient_category')
            ->where('status', 'default')
            ->get()
            ->groupBy('brand_id');

        if ($categories->isEmpty()) {
            return response()->json(['message' => 'No ingredient categories found.'], 404);
        }

        $responses = [];

        foreach ($categories as $brandId => $brandCategories) {
            // Create a folder for each brand_id
            $brandFolderPath = $folderPath . '/' . $brandId;
            if (!file_exists($brandFolderPath)) {
                mkdir($brandFolderPath, 0755, true); // Create folder with proper permissions
            }

            // CSV file path using brand_id in the brand folder
            $filename = "brand_{$brandId}_ingredient_category.csv";
            $filepath = $brandFolderPath . '/' . $filename;

            // Prepare CSV header
            $header = ['Name'];

            // Open file for writing
            $file = fopen($filepath, 'w');
            fputcsv($file, $header);

            foreach ($brandCategories as $category) {
                $data = json_decode($category['response'], true);

                if (empty($data) || !isset($data['name'])) {
                    continue; // Skip if no name
                }

                // Write the row with the category name
                fputcsv($file, [$data['name']]);
            }

            fclose($file);

            // **Log File Creation**
            Log::channel('foodics')->info("CSV file created for brand {$brandId}: {$filepath}");

            // **Automatically Call postData and Log Response**
            $response = $this->postData($brandId, 'ingredient_category', $filepath);

            // Log API response
            Log::channel('foodics')->info("API response for brand {$brandId}:", ['response' => $response]);

            $responses[$brandId] = $response;

            // Update status to 'processed' for the current brand_id
            MiddlewareData::where('data_type', 'create_ingredient_category')
                ->where('status', 'default')
                ->where('brand_id', $brandId)
                ->update(['status' => 'processed']);
        }

        return response()->json([
            'message'  => 'CSV files created and data posted successfully.',
            'responses' => $responses
        ]);
    }

    public function typeMenuCategory()
    {
        // Ensure the automation folder exists
        $folderPath = public_path('automation');
        if (!file_exists($folderPath)) {
            mkdir($folderPath, 0755, true); // Create folder with proper permissions
        }

        // Fetch all data grouped by brand_id
        $categories = MiddlewareData::where('data_type', 'create_menu_category')
            ->where('status', 'default')
            ->get()
            ->groupBy('brand_id');

        if ($categories->isEmpty()) {
            return response()->json(['message' => 'No menu categories found.'], 404);
        }

        $responses = [];

        foreach ($categories as $brandId => $brandCategories) {
            // Create a folder for each brand_id
            $brandFolderPath = $folderPath . '/' . $brandId;
            if (!file_exists($brandFolderPath)) {
                mkdir($brandFolderPath, 0755, true); // Create folder with proper permissions
            }

            // CSV file path using brand_id in the brand folder
            $filename = "brand_{$brandId}_menu_category.csv";
            $filepath = $brandFolderPath . '/' . $filename;

            // Prepare CSV header
            $header = ['Name'];

            // Open file for writing
            $file = fopen($filepath, 'w');
            fputcsv($file, $header);

            foreach ($brandCategories as $category) {
                $data = json_decode($category['response'], true);

                if (empty($data) || !isset($data['name'])) {
                    continue; // Skip if no name
                }

                // Write the row with the category name
                fputcsv($file, [$data['name']]);
            }

            fclose($file);

            // **Log File Creation**
            Log::channel('foodics')->info("CSV file created for brand {$brandId}: {$filepath}");

            // **Automatically Call postData and Log Response**
            $response = $this->postData($brandId, 'recipe_category', $filepath);

            // Log API response
            Log::channel('foodics')->info("API response for brand {$brandId}:", ['response' => $response]);

            $responses[$brandId] = $response;

            // Update status to 'processed' for the current brand_id
            MiddlewareData::where('data_type', 'create_menu_category')
                ->where('status', 'default')
                ->where('brand_id', $brandId)
                ->update(['status' => 'processed']);
        }

        return response()->json([
            'message'  => 'CSV files created and data posted successfully.',
            'responses' => $responses
        ]);
    }

    public function postData($brand_id, $type, $filePath, $module = 'company')
    {
        // Check if file exists
        if (!file_exists($filePath)) {
            Log::channel('foodics')->error("File not found for brand {$brand_id}: {$filePath}");
            return [
                'status' => false,
                'message' => 'File not found',
                'path' => $filePath
            ];
        }

        try {
            $fileContents = file_get_contents($filePath);
            if ($fileContents === false) {
                Log::channel('foodics')->error("Unable to read file for brand {$brand_id}: {$filePath}");
                return [
                    'status' => false,
                    'message' => 'Unable to read file',
                    'path' => $filePath
                ];
            }

            $response = Http::attach('file', $fileContents, basename($filePath))
                ->asMultipart()
                ->post(env('CHEFADMIN_URL') . '/api/foodics/import', [
                    'brand_id' => $brand_id,
                    'type'     => $type,
                    'module'   => $module,
                ]);

            return $response->json();
        } catch (\Exception $e) {
            Log::channel('foodics')->error("Error processing file for brand {$brand_id}: " . $e->getMessage());
            return [
                'status' => false,
                'message' => 'Error processing file: ' . $e->getMessage(),
                'path' => $filePath
            ];
        }
    }

    public function healthData(Request $request)
    {
        $brand_id = $request->brand_id;

        // File paths
        $inventoryCsv = public_path("automation/$brand_id/brand_" . $brand_id . "_inventory_summary.csv");
        $subRecipeCsv = public_path("automation/$brand_id/brand_" . $brand_id . "_sub_recipe_summary.csv");
        $recipeCsv = public_path("automation/$brand_id/brand_" . $brand_id . "_recipe_summary.csv");

        // Check if files exist
        if (!file_exists($inventoryCsv) || !file_exists($subRecipeCsv) || !file_exists($recipeCsv)) {
            return response()->json([
                'status' => false,
                'message' => 'One or more required files are missing.',
                'missing_files' => [
                    'inventory_csv' => file_exists($inventoryCsv) ? 'present' : 'missing',
                    'sub_recipe_csv' => file_exists($subRecipeCsv) ? 'present' : 'missing',
                    'recipe_csv' => file_exists($recipeCsv) ? 'present' : 'missing',
                ],
            ], 404);
        }

        // Command to execute
        $cmd = "curl --location " . env('CHEFADMIN_URL') . "'/api/process-health-check' "
            . "--form 'inventory_csv=@\"$inventoryCsv\"' "
            . "--form 'sub_recipe_csv=@\"$subRecipeCsv\"' "
            . "--form 'recipe_csv=@\"$recipeCsv\"'";

        // Execute the command
        $output = shell_exec($cmd);
        $response = json_decode($output, true);

        return response()->json(['status' => true, 'data' => $response], 200);
    }

    public function unit_coversion($method, $unit)
    {
        $units = FoodicsUnit::where('foodics_unit', $unit)->first();

        if ($method === "sub_recipe" || $method === "recipe") {
            return $units->converted_unit;
        }
    }
}
