<?php

namespace App\Http\Controllers\API\V1;

use App\Http\Controllers\Controller;
use App\Models\Advertisement;
use App\Models\Category;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class HomeController extends Controller
{
    public function index(Request $request): JsonResponse
    {
        // Get authenticated user for targeted ads (optional)
        $user = $request->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();

        // Build categories response with products
        $categoriesData = $rootCategories->map(function ($category) {
            // Get all category IDs (parent + children)
            $categoryIds = [$category->id];
            if ($category->children) {
                $categoryIds = array_merge($categoryIds, $category->children->pluck('id')->toArray());
            }

            // Get products from this category and all subcategories (limit to 8)
            $products = \App\Models\Product::query()
                ->whereIn('category_id', $categoryIds)
                ->orderBy('created_at', 'desc')
                ->limit(8)
                ->get();

            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,
                '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,
                    ];
                }),
                'products' => $products->map(function ($product) {
                    return [
                        'id' => $product->id,
                        'name_en' => $product->name_en,
                        'name_ar' => $product->name_ar,
                        'image_url' => $product->image_url,
                        'video_url' => $product->video_url,
                        'price' => (string) $product->price,
                        'discount_price' => $product->discount_price ? (string) $product->discount_price : null,
                        'currency' => $product->currency,
                    ];
                }),
            ];
        });

        // 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,
                ];
            });

        return response()->json([
            'categories' => $categoriesData,
            'advertisements' => $advertisements,
        ]);
    }
}
