<?php

namespace App\Http\Controllers;

use App\Models\QrCode;
use Illuminate\Http\Request;
use Illuminate\Support\Str;

class QrCodeController extends Controller
{
    public function index()
    {
        $qrCodes = QrCode::with('evento', 'jugador', 'aficionado')->get();
        return response()->json($qrCodes);
    }

    public function show($id)
    {
        $qrCode = QrCode::with('evento', 'jugador', 'aficionado')->findOrFail($id);
        return response()->json($qrCode);
    }

    public function store(Request $request)
    {
        $data = $request->validate([
            'id_evento' => 'required|string|max:36',
            'id_jugador' => 'nullable|string|max:6',
            'tipo_qr' => 'required|in:invitado,publico',
            'escaneos_restantes' => 'nullable|integer|min:1',
            'id_aficionado' => 'nullable|integer',
        ]);
        $data['id_qr'] = Str::uuid()->toString();
        $qrCode = QrCode::create($data);
        return response()->json($qrCode, 201);
    }

    public function update(Request $request, $id)
    {
        $qrCode = QrCode::findOrFail($id);
        $data = $request->validate([
            'id_evento' => 'sometimes|string|max:36',
            'id_jugador' => 'nullable|string|max:6',
            'tipo_qr' => 'sometimes|in:invitado,publico',
            'escaneos_restantes' => 'nullable|integer|min:1',
            'id_aficionado' => 'nullable|integer',
        ]);
        $qrCode->update($data);
        return response()->json($qrCode);
    }

    public function destroy($id)
    {
        $qrCode = QrCode::findOrFail($id);
        $qrCode->delete();
        return response()->json(null, 204);
    }
}
