<?php

namespace App\Http\Controllers\User;

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

class ProductController extends Controller
{
    public function index()
    {
        // Fetch only logged-in user's products
        $products = Product::where('user_id', session('user_id'))->get();

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

    public function create()
    {
        $products = Product::where('user_id', session('user_id'))->get();
        return view('user.products.create', compact('products'));
    }

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

public function store(Request $request)
{
    $request->validate([
        'product_name' => 'required|string|max:255',
     
        'price' => 'required|numeric|min:0',
    ]);

    $userId = session('user_id'); // or auth()->id()

    $product = Product::create([
        'product_name' => $request->product_name,
   
        'price' => $request->price,
        'user_id' => $userId,
    ]);

    if ($request->ajax()) {
        return response()->json([
            'status' => 'success',
            'product' => $product
        ]);
    }

    return redirect()->route('user.products.index')->with('success', 'Product added.');
}

public function update(Request $request, $id)
{
    $request->validate([
        'product_name' => 'required|string|max:255',
    
        'price' => 'required|numeric|min:0',
    ]);

    $product = Product::findOrFail($id);

    $product->update([
        'product_name' => $request->product_name,
     
        'price' => $request->price,
    ]);

    if ($request->ajax()) {
        return response()->json([
            'status' => 'success',
            'product' => $product
        ]);
    }

    return redirect()->route('user.products.index')->with('success', 'Product updated.');
}

}
