<?php

namespace App\Http\Controllers\API\V1;

use App\Http\Controllers\Controller;
use App\Http\Resources\HomeProductResource;
use App\Models\Advertisement;
use App\Models\Category;
use App\Models\Product;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;

class HomeController extends Controller
{
    public function index(Request $request): JsonResponse
    {
        // Get authenticated user for targeted ads (optional) - eager load profile
        $user = $request->user()?->load('profile');

        // Create cache key based on user and locale
        $cacheKey = 'home_page_'.($user ? $user->id : 'guest').'_'.app()->getLocale();

        $data = Cache::remember($cacheKey, now()->addMinutes(15), function () use ($user) {
            // Get all root categories (parent_id is null)
            $rootCategories = Category::query()
                ->whereNull('parent_id')
                ->where('status', 'active')
                ->with(['children' => function ($query) {
                    $query->where('status', 'active');
                }])
                ->orderBy('id', 'asc')
                ->get();

            // Collect only subcategory IDs (exclude parent categories)
            $subcategoryIds = $rootCategories->pluck('children.*.id')
                ->flatten()
                ->filter()
                ->unique()
                ->values()
                ->toArray();

            // Fetch all products from subcategories only - grouped by category_id
            $allProducts = collect();
            if (! empty($subcategoryIds)) {
                $allProducts = Product::query()
                    ->whereIn('category_id', $subcategoryIds)
                    ->inRandomOrder()
                    ->get()
                    ->groupBy('category_id');
            }

            // Build categories response with products
            $categoriesData = $rootCategories->map(function ($category) use ($allProducts) {
                // Get only subcategory IDs (exclude parent)
                $categoryIds = [];
                if ($category->children) {
                    $categoryIds = $category->children->pluck('id')->toArray();
                }

                // Collect products from subcategories only
                $products = collect();
                foreach ($categoryIds as $categoryId) {
                    if (isset($allProducts[$categoryId])) {
                        $products = $products->concat($allProducts[$categoryId]);
                    }
                }

                // Shuffle and limit to 8 products per category
                $products = $products->shuffle()->take(8);

                return [
                    'id' => $category->id,
                    'name_en' => $category->name_en,
                    'name_ar' => $category->name_ar,
                    'slug' => $category->slug,
                    'description_en' => $category->description_en,
                    'description_ar' => $category->description_ar,
                    'image' => $category->image,
                    'icon' => $category->icon,
                    'status' => $category->status,
                    'meta_title' => $category->meta_title,
                    'meta_description' => $category->meta_description,
                    'subcategories' => $category->children->map(function ($child) {
                        return [
                            'id' => $child->id,
                            'name_en' => $child->name_en,
                            'name_ar' => $child->name_ar,
                            'slug' => $child->slug,
                            'icon' => $child->icon,
                        ];
                    }),
                    'products' => HomeProductResource::collection($products),
                ];
            });

            // Get advertisements (targeted if user is authenticated)
            $adsQuery = Advertisement::query()->active();

            if ($user && $user->profile) {
                // Filter by user's gender
                if ($user->profile->gender === 'male') {
                    $adsQuery->whereIn('targeted_audience', ['male', 'all']);
                } elseif ($user->profile->gender === 'female') {
                    $adsQuery->whereIn('targeted_audience', ['female', 'all']);
                }

                // Filter by user's language preference from settings
                $languagePreference = $user->profile->settings['language'] ?? 'both';
                if ($languagePreference === 'ar') {
                    $adsQuery->whereIn('targeted_language', ['ar', 'both']);
                } elseif ($languagePreference === 'en') {
                    $adsQuery->whereIn('targeted_language', ['en', 'both']);
                }
            }

            $advertisements = $adsQuery
                ->orderBy('sort_order', 'asc')
                ->orderBy('created_at', 'desc')
                ->get()
                ->map(function ($ad) {
                    return [
                        'id' => $ad->id,
                        'title' => $ad->title_en,
                        'title_ar' => $ad->title_ar,
                        'image_url' => $ad->image,
                        'link' => $ad->url,
                    ];
                });

            // Convert to array for proper serialization
            return [
                'categories' => $categoriesData->toArray(),
                'advertisements' => $advertisements->toArray(),
            ];
        });

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