<?php

/*
|--------------------------------------------------------------------------
| OwnStore - Build your own online store
| Author: TakfeDev (takfedev@gmail.com)
| All Rights Reserved
|--------------------------------------------------------------------------
*/

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Category;
use App\Models\Product;
use App\Models\Banner;
use Inertia\Inertia;

class HomeController extends Controller
{
    public function index(Request $request)
    {
        // 1. Fetch Categories
        $categories = Category::with(['subcategories' => function($q) {
            $q->where('is_active', true)->orderBy('name');
        }])
        ->whereNull('parent_id')
        ->where('is_active', true)
        ->orderBy('name')
        ->get(); 

        // 2. Fetch Super Deals (UPDATED to include Global Flash Sale logic & eager loading)
        $superDeals = Product::with(['images', 'seller:id,company_name,name,flash_sale_percentage'])
            ->where(function($q) {
                $q->where('discount_percentage', '>', 0)
                  ->orWhereHas('seller', function($sq) {
                      $sq->where('flash_sale_percentage', '>', 0);
                  });
            })
            ->orderBy('discount_percentage', 'desc')
            ->take(10)
            ->get();

        // 3. Fetch Regular Products (Paginated) - Added seller flash_sale_percentage
        $products = Product::with(['images', 'seller:id,company_name,name,flash_sale_percentage'])
            ->latest() 
            ->paginate(12); 

        // Return JSON if it's an AJAX "Load More" request
        if ($request->wantsJson()) {
            return response()->json($products);
        }

        // 4. Fetch Banners
        $banners = Banner::where('is_active', true)->orderBy('sort_order')->take(10)->get();

        // 5. Render React Page
        return Inertia::render('Home', [
            'dbCategories' => $categories,
            'superDeals' => $superDeals,
            'dbProducts' => $products, 
            'banners' => $banners 
        ]);
    }
}