<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\Category;
use App\Models\Product;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;

class HomeApiController extends Controller
{
    /**
     * Get all data required to render the homepage in a single request.
     */
    public function index()
    {
        // Cache the entire homepage payload for 5 minutes (300 seconds)
        $data = Cache::remember('home_data_payload', 300, function () {
            // Helper function to format products with Spatie media URLs and convert to array
            $formatProduct = function ($product) {
                $imageUrl = $product->getFirstMediaUrl('images', 'webp') 
                    ?: ($product->getFirstMediaUrl('images') 
                    ?: '/images/placeholder.jpg');
                
                $allImages = $product->getMedia('images')->map(function ($media) {
                    return [
                        'url' => $media->getUrl(),
                        'webp' => $media->hasGeneratedConversion('webp') ? $media->getUrl('webp') : null,
                    ];
                })->toArray();
                
                $arr = $product->toArray();
                $arr['image_url'] = $imageUrl;
                $arr['all_images'] = $allImages;
                
                // Add is_best_selling flag dynamically based on keywords to match mockup design
                $bestSellingKeywords = ['ghee', 'mustard', 'oil'];
                $isBestSelling = false;
                foreach ($bestSellingKeywords as $keyword) {
                    if (stripos($product->name, $keyword) !== false) {
                        $isBestSelling = true;
                        break;
                    }
                }
                $arr['is_best_selling'] = $isBestSelling;
                
                return $arr;
            };

            // 1. Fetch Categories
            $categories = Category::where('is_visible', true)
                ->with('media')
                ->orderBy('name')
                ->get()
                ->map(function ($category) {
                    $imageUrl = $category->getFirstMediaUrl('image', 'webp')
                        ?: ($category->getFirstMediaUrl('image')
                        ?: null);
                    
                    $arr = $category->toArray();
                    $arr['image_url'] = $imageUrl;
                    return $arr;
                })
                ->values()
                ->toArray();

            // 2. Fetch Latest Products (10 items)
            $latestProducts = Product::where('is_visible', true)
                ->with(['variants', 'media', 'category'])
                ->orderByDesc('created_at')
                ->limit(10)
                ->get()
                ->map($formatProduct)
                ->values()
                ->toArray();

            // 3. Fetch Featured Products (4 items)
            $featuredProducts = Product::where('is_visible', true)
                ->where('is_featured', true)
                ->with(['variants', 'media', 'category'])
                ->orderByDesc('created_at')
                ->limit(4)
                ->get()
                ->map($formatProduct)
                ->values()
                ->toArray();

            // 4. Fetch all visible products for these categories in a single query
            $categoryIds = array_column($categories, 'id');
            $allProducts = Product::where('is_visible', true)
                ->whereIn('category_id', $categoryIds)
                ->with(['variants', 'media', 'category'])
                ->orderByDesc('created_at')
                ->get();

            // Group the products in PHP memory
            $groupedProducts = $allProducts->groupBy('category_id');

            $categorySections = [];
            foreach ($categories as $category) {
                $catProducts = $groupedProducts->get($category['id']);
                
                if ($catProducts && $catProducts->count() > 0) {
                    $productsList = $catProducts->take(5)->map($formatProduct)->values()->toArray();
                    
                    $categorySections[] = [
                        'category' => $category,
                        'products' => $productsList
                    ];
                }
            }

            return [
                'categories' => $categories,
                'latestProducts' => $latestProducts,
                'featuredProducts' => $featuredProducts,
                'categorySections' => $categorySections
            ];
        });

        return response()->json($data);
    }
}
