<?php

namespace App\Http\Controllers;

use App\Models\Category;
use App\Models\Product;
use App\Models\User;
use App\Helpers\RoleHelper;
use Illuminate\Http\Request;

class PublicProductController extends Controller
{
    public function index(Request $request)
    {
        $categories = Category::withCount('products')->get();
        
        $query = Product::with('category')->where('is_active', true);
        
        if ($request->has('category') && $request->category != '') {
            $query->where('category_id', $request->category);
        }
        
        if ($request->has('search') && $request->search != '') {
            $query->where(function($q) use ($request) {
                $q->where('name', 'like', '%' . $request->search . '%')
                  ->orWhere('description', 'like', '%' . $request->search . '%');
            });
        }
        
        $products = $query->paginate(12);
        
        return view('shop.index', compact('categories', 'products'));
    }
    
    public function show($code)
    {
        // Vérifier d'abord si c'est un utilisateur (boutique personnalisée)
        $user = User::where('username', $code)
            ->orWhere('member_code', $code)
            ->where('is_active', true)
            ->first();
            
        if ($user && RoleHelper::canHaveShop($user->role)) {
            // Rediriger vers le contrôleur de boutique personnalisée
            return app(\App\Http\Controllers\Shop\UserShopController::class)->show($code);
        }
        
        // Sinon, traiter comme produit
        $product = Product::where('id', $code)->orWhere('slug', $code)->first();
        
        if (!$product) {
            abort(404, 'Produit ou boutique introuvable');
        }
        
        $relatedProducts = Product::where('category_id', $product->category_id)
            ->where('id', '!=', $product->id)
            ->where('stock', '>', 0)
            ->limit(4)
            ->get();
            
        return view('shop.show', compact('product', 'relatedProducts'));
    }
}
