<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\Category;
use App\Models\Products;
use App\Models\Banner;
use App\Models\SubCategory;
use App\Models\Country;
use App\Models\HomeSection;
use Carbon\Carbon;

class HomeController extends Controller
{

    public function categories(Request $request)
    {
        try {
            $request->validate([
                'country_code' => 'nullable|string'
            ]);

            // 1️⃣ Get requested country
            $country = null;
            if ($request->country_code) {
                $country = Country::where('country_code', $request->country_code)->first();
            }

            // 2️⃣ Fallback to India
            if (!$country) {
                $country = Country::where('country_code', 'IN')->first();
            }

            // 3️⃣ Get categories linked to country with subcategories
            $categories = $country
                ? $country->categories()
                ->with(['subCategories' => function ($q) {
                    $q->where('is_active', 1)
                        ->select('id as subcategory_id', 'category_id', 'name', 'image');
                }])
                ->select('categories.id', 'categories.name', 'categories.image')
                ->get()
                : collect();

            return response()->json([
                'status' => true,
                'message' => 'Categories and subcategories fetched successfully',
                'data' => $categories
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'status' => false,
                'message' => 'Something went wrong',
                'error' => $e->getMessage()
            ], 500);
        }
    }





    public function home(Request $request)
    {
        $country = Country::where('country_code', $request->country_code ?? 'IN')->first();

        if (!$country) {
            return response()->json([
                'status' => false,
                'message' => 'Invalid country'
            ], 400);
        }

        $sections = HomeSection::where('status', 1)
            ->orderBy('position')
            ->get();

        $result = [];

        foreach ($sections as $section) {

            $data = [];

            /* =====================
           ALL CATEGORY
           ===================== */
            if ($section->source_type === 'all_category') {

                // ICON STYLE → Categories
                if ($section->ui_type === 'icon_style') {
                    $data = Category::select('id', 'name', 'image')
                        ->get()
                        ->map(fn($c) => [
                            'id'    => $c->id,
                            'name'  => $c->name,
                            'image' => $c->image_full
                        ]);
                }

                // PRODUCT STYLE → All products
                if (in_array($section->ui_type, ['product_style', 'product_with_cart_style'])) {
                    $data = Products::where('status', 1)
                        ->whereHas('countries', fn($q) => $q->where('country_id', $country->id))
                        ->with('images')
                        ->take(10)
                        ->get()
                        ->map(fn($p) => [
                            'id'       => $p->id,
                            'name'     => $p->name,
                            'price'    => (float)$p->price,
                            'discount' => $p->discount_percentage,
                            'final_price' => $p->final_discount_price,
                            'image'    => $p->first_image_url
                        ]);
                }
            }

            /* =====================
           CATEGORY BASED
           ===================== */
            if ($section->source_type === 'category') {

                // PRODUCT STYLE
                if (in_array($section->ui_type, ['product_style', 'product_with_cart_style'])) {
                    $data = Products::where('category_id', $section->source_id)
                        ->where('status', 1)
                        ->whereHas('countries', fn($q) => $q->where('country_id', $country->id))
                        ->with('images')
                        ->take(10)
                        ->get()
                        ->map(fn($p) => [
                            'id'       => $p->id,
                            'name'     => $p->name,
                            'price'    => (float)$p->price,
                            'discount' => $p->discount_percentage,
                            'final_price' => $p->final_discount_price,
                            'image'    => $p->first_image_url
                        ]);
                }

                // ICON STYLE → Subcategories
                if ($section->ui_type === 'icon_style') {
                    $data = SubCategory::where('category_id', $section->source_id)
                        ->where('is_active', 1)
                        ->select('id', 'name', 'image')
                        ->get()
                        ->map(fn($s) => [
                            'id'    => $s->id,
                            'name'  => $s->name,
                            'image' => $s->image_url
                        ]);
                }
            }

            /* =====================
           SUBCATEGORY BASED
           ===================== */
            if ($section->source_type === 'subcategory') {

                $data = Products::where('sub_category_id', $section->source_id)
                    ->where('status', 1)
                    ->whereHas('countries', fn($q) => $q->where('country_id', $country->id))
                    ->with('images')
                    ->take(10)
                    ->get()
                    ->map(fn($p) => [
                        'id'       => $p->id,
                        'name'     => $p->name,
                        'price'    => (float)$p->price,
                        'discount' => $p->discount_percentage,
                        'final_price' => $p->final_discount_price,
                        'image'    => $p->first_image_url
                    ]);
            }

            /* =====================
           BANNER SECTION
           ===================== */


            if (in_array($section->source_type, ['banner', 'seasonal_banner'])) {

                $today = date("Y-m-d", strtotime(Carbon::today()));
                $seasonalFlag = 0;

                // 🔹 Check active seasonal banners with date range
                if ($section->source_type === 'seasonal_banner') {

                    $hasActiveSeasonal = Banner::where('status', 1)
                        ->where('seasonal_banner', 1)
                        ->whereDate('start_date', '<=', $today)
                        ->whereDate('end_date', '>=', $today)
                        ->exists();

                    $seasonalFlag = $hasActiveSeasonal ? 1 : 0;
                }

                $data = Banner::where('status', 1)
                    ->where('seasonal_banner', $seasonalFlag)

                    // 🔹 Apply date range ONLY for seasonal banners
                    ->when($seasonalFlag === 1, function ($q) use ($today) {
                        $q->whereDate('start_date', '<=', $today)
                            ->whereDate('end_date', '>=', $today);
                    })

                    ->where(function ($q) use ($country) {
                        $q->whereNull('category_id')
                            ->orWhereIn('category_id', function ($sub) use ($country) {
                                $sub->select('category_id')
                                    ->from('category_country')
                                    ->where('country_id', $country->id);
                            });
                    })
                    ->select('id', 'title', 'image', 'category_id', 'product_id')
                    ->take(10)
                    ->get()
                    ->map(fn($b) => [
                        'id' => $b->id,
                        'title' => $b->title,
                        'image' => $b->image_url,
                        'category_id' => $b->category_id,
                        'product_id' => $b->product_id,
                    ]);
            }


            $result[] = [
                'section_id' => $section->id,
                'title'      => $section->title,
                'ui_type'    => $section->ui_type,
                'source_type' => $section->source_type,
                'data'       => $data
            ];
        }

        return response()->json([
            'status'   => true,
            'country'  => $country->name,
            'sections' => $result
        ]);
    }
}
