<?php

namespace App\Http\Controllers;

use App\Models\PosPayment;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

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

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

        $posPayment = PosPayment::create($validated);

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

    public function show($id)
    {
        $posPayment = PosPayment::findOrFail($id);

        return response()->json($posPayment->load('posSales'));
    }

    public function update(Request $request, $id)
    {
        $posPayment = PosPayment::findOrFail($id);

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

        $posPayment->update($validated);

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

    public function destroy($id)
    {
        $posPayment = PosPayment::findOrFail($id);

        $posPayment->delete();

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