<?php
namespace App\Http\Controllers\API\Customer;

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

class CustomerProductController extends Controller
{
    public function index(Request $request): JsonResponse
    {
        $products = Product::with(['vendor:id,store_name,slug', 'category:id,name'])
            ->where('status', 'published')
            ->when($request->search, fn($q) => $q->where('name', 'like', "%{$request->search}%")->orWhere('description', 'like', "%{$request->search}%"))
            ->when($request->category_id, fn($q) => $q->where('category_id', $request->category_id))
            ->when($request->vendor_id, fn($q) => $q->where('vendor_id', $request->vendor_id))
            ->when($request->min_price, fn($q) => $q->where('price', '>=', $request->min_price))
            ->when($request->max_price, fn($q) => $q->where('price', '<=', $request->max_price))
            ->when($request->sort === 'price_asc', fn($q) => $q->orderBy('price'))
            ->when($request->sort === 'price_desc', fn($q) => $q->orderByDesc('price'))
            ->when($request->sort === 'rating', fn($q) => $q->orderByDesc('average_rating'))
            ->when($request->sort === 'popular', fn($q) => $q->orderByDesc('sales_count'))
            ->when(!$request->sort, fn($q) => $q->latest())
            ->paginate(20);
        return response()->json($products);
    }

    public function show(string $slug): JsonResponse
    {
        $product = Product::with(['vendor:id,store_name,slug,logo', 'category:id,name', 'reviews' => fn($q) => $q->with('user:id,name,avatar')->where('status', 'approved')->latest()->limit(10)])
            ->where('slug', $slug)->where('status', 'published')->firstOrFail();
        $product->increment('view_count');
        return response()->json(['product' => $product]);
    }

    public function categories(): JsonResponse
    {
        $categories = Category::where('is_active', true)->withCount(['products' => fn($q) => $q->where('status', 'published')])->get();
        return response()->json(['categories' => $categories]);
    }

    public function stores(): JsonResponse
    {
        $stores = Vendor::where('status', 'approved')
            ->with('user:id,name')
            ->withCount(['products' => fn($q) => $q->where('status', 'published')])
            ->paginate(20);
        return response()->json($stores);
    }

    public function store(string $slug): JsonResponse
    {
        $vendor = Vendor::with('user:id,name')->where('slug', $slug)->where('status', 'approved')->firstOrFail();
        $products = Product::with('category:id,name')->where('vendor_id', $vendor->id)->where('status', 'published')->paginate(20);
        return response()->json(['vendor' => $vendor, 'products' => $products]);
    }
}
