<?php

namespace App\Http\Controllers;

use App\Models\PosProduct;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Validation\Rule;

class PosProductController extends Controller
{
    public function index()
    {
        $userId = request()->query('user_id');
        if (!$userId) {
            return response()->json(['message' => 'User ID required'], 400);
        }
        return response()->json(PosProduct::where('user_id', $userId)->get());
    }

    public function store(Request $request)
    {
        $validated = $request->validate([
            'name' => 'required|string|max:255',
            'type' => 'required|string|max:255',
            'sku' => 'nullable|string|max:255',
            'user_id' => 'required|integer',
        ]);

        $posProduct = PosProduct::create($validated);

        return response()->json($posProduct, 201);
    }

    public function show($id)
    {
        $posProduct = PosProduct::findOrFail($id);

        return response()->json($posProduct);
    }

    public function update(Request $request, $id)
    {
        $posProduct = PosProduct::findOrFail($id);

        $validated = $request->validate([
            'name' => 'sometimes|required|string|max:255',
            'type' => 'sometimes|required|string|max:255',
            'sku' => 'nullable|string|max:255',
        ]);

        $posProduct->update($validated);

        return response()->json($posProduct);
    }

    public function destroy($id)
    {
        $posProduct = PosProduct::findOrFail($id);

        $posProduct->delete();

        return response()->json(null, 204);
    }
}
