<?php

namespace App\Http\Controllers\Public;

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

class CategoryController extends Controller
{
    public function index(Request $request)
    {
        $query = Category::whereNull('parent_id')->where('is_active', true)->with('children')->withCount('products');

        if ($request->has('letter') && $request->letter != 'All') {
            $query->where('name', 'like', $request->letter . '%');
        }

        $categories = $query->orderBy('name', 'asc')->get();
        $currentLetter = $request->letter ?? 'All';

        return view('public.categories.index', compact('categories', 'currentLetter'));
    }

    public function show(Request $request, $slug)
    {
        $category = Category::where('slug', $slug)->where('is_active', true)->withCount('products')->firstOrFail();
        
        // Get all category IDs (self + children)
        $categoryIds = $category->children()->pluck('id')->push($category->id);

        // Build query with filters
        $query = \App\Models\Product::whereIn('category_id', $categoryIds)->with('seller', 'category');

        // Price filter
        if ($request->filled('min_price')) {
            $query->where('price', '>=', $request->min_price);
        }
        if ($request->filled('max_price')) {
            $query->where('price', '<=', $request->max_price);
        }
        
        // MOQ filter
        if ($request->filled('min_moq')) {
            $query->where('moq', '>=', $request->min_moq);
        }
        if ($request->filled('max_moq')) {
            $query->where('moq', '<=', $request->max_moq);
        }
        
        // Location filter (city, state, or country)
        if ($request->filled('location')) {
            $location = $request->location;
            $query->whereHas('seller', function($q) use ($location) {
                $q->where('city', 'like', "%{$location}%")
                  ->orWhere('state', 'like', "%{$location}%")
                  ->orWhere('country', 'like', "%{$location}%");
            });
        }
        
        // Verified seller filter
        if ($request->verified) {
            $query->whereHas('seller', function($q) {
                $q->where('is_verified', true);
            });
        }
        
        $products = $query->paginate(12)->appends($request->query());
        
        $promotedProducts = \App\Models\Product::whereHas('seller.subscription.plan', function($q) {
            $q->where('is_featured', true);
        })->inRandomOrder()->take(5)->get();

        $trendingProducts = \App\Models\Product::withCount('analytics')
            ->orderBy('analytics_count', 'desc')
            ->take(5)
            ->get();
        
        return view('public.categories.show', compact('category', 'products', 'promotedProducts', 'trendingProducts'));
    }
}
