<?php

namespace App\Http\Controllers;

use App\Models\Product;
use Illuminate\Http\Request;

class CatalogoController extends Controller
{
    /**
     * Muestra el catálogo público de productos.
     */
    public function index(Request $request)
    {
        // 1. Atrapamos lo que el usuario escribió o seleccionó
        $query = $request->input('search');
        $type = $request->input('type');

        // --- CONSULTA PARA LA GRILLA (PAGINADA) ---
        $productsQuery = Product::query();

        $productsQuery->when($query, function ($q) use ($query) {
            return $q->where('name', 'like', "%{$query}%");
        });

        if ($type) {
            $productsQuery->where('type', $type);
        } else {
            $productsQuery->where('type', '!=', 'service');
        }

        //mostrar si tiene stock mayor a 0
        $productsQuery->where('stock_quantity', '>', 0);

        // Resultados paginados
        $products = $productsQuery->orderBy('name', 'asc')->paginate(12)->withQueryString(); 

        $allProducts = Product::where('type', '!=', 'service')
            ->where('stock_quantity', '>', 0)
            ->orderBy('name', 'asc')
            ->get();

        // Devuelve la vista
        return view('catalogo.index', compact('products', 'allProducts'));
    }

    public function show(Product $product) 
    {
        return view('catalogo.show', compact('product'));
    }
}