<?php

namespace App\Http\Controllers\User;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\Product;
use Illuminate\View\View;

class ProductController extends Controller
{

    public function index(Request $request): View
    {
        $query = Product::query();

        if ($request->filled('search')) {
            $search = $request->search;
            $query->where(function ($q) use ($search) {
                $q->where('product_name', 'like', "%$search%")
                  ->orWhere('code', 'like', "%$search%")
                  ->orWhere('brand', 'like', "%$search%");
            });
        }

        if ($request->sort === 'price_asc') {
            $query->orderBy('selling_price', 'asc');
        } elseif ($request->sort === 'price_desc') {
            $query->orderBy('selling_price', 'desc');
        } else {
            $query->latest();
        }

        if ($request->filled('brand')) {
            $query->where('brand', $request->brand);
        }

        $brands = Product::select('brand')->distinct()->pluck('brand');

        $products = $query->paginate(10)->withQueryString();

        return view('pages.user.products.index', compact('products', 'brands'));
    }

}