<?php

namespace App\Http\Controllers;

use App\Models\Media;
use App\Models\Product;
use App\Models\Store;
use App\Models\User;
use Illuminate\Http\Request;

class ProductDisplayController extends Controller
{
    /**
     * Display a listing of the resource.
     */
    public function index(Request $request, $id)
    {
        if ($request->search) {
            $products = Product::query()
                ->with(['category'])
                ->where('store_id', $id)
                ->where('name', 'like', '%' . $request->search . '%')
                ->orWhere('price', 'like', $request->search)
                ->orWhereHas('category', function($query) use($request){
                    $query->where('name','like','%'.$request->search.'%');
                })
                ->latest()
                ->paginate(24)
                ->withQueryString();
        } else {
            $products = Product::query()
                ->with(['category'])
                ->where('store_id', $id)
                ->latest()
                ->paginate(12);
        }

        $store = Store::query()->where('id', $id)->first();

        return inertia('Product/Client/Index', [
            'store' => $store,
            'products' => $products
        ]);
    }

    /**
     * Display the specified resource.
     */
    public function show(Store $store, Product $product)
    {
        return inertia('Product/Client/Show', [
            'store' => $store,
            'product' => $product->load(['category'])
        ]);
    }

    /**
     * Show the about page.
     */
    public function contact($storeId)
    {
        $store = Store::query()->with('user')->where('id', $storeId)->first();
        $user = User::query()->where('id', $store->user_id)->first();
        return inertia('Product/Client/Contact', [
            'store' => $store,
            'user' => $user,
        ]);
    }
}
