<?php

namespace App\Http\Controllers\Player;

use App\Http\Controllers\Controller;
use App\Models\WhitelistApplication;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Inertia\Inertia;
use Inertia\Response;

/**
 * Successor to the legacy "White List application" form that shipped in
 * `view/profile/settings.php` but was never functional (it called an
 * undefined `checkIsRequest()` helper and posted to a non-existent
 * `action=create_request` handler).
 */
class WhitelistApplicationController extends Controller
{
    public function create(Request $request): Response
    {
        return Inertia::render('Player/WhitelistApply', [
            'existingApplication' => WhitelistApplication::query()
                ->where('user_id', $request->user()->id)
                ->latest()
                ->first(),
        ]);
    }

    public function store(Request $request): RedirectResponse
    {
        $data = $request->validate([
            'answers' => ['required', 'array'],
            'answers.*' => ['required', 'string', 'max:1000'],
        ]);

        $existing = WhitelistApplication::query()
            ->where('user_id', $request->user()->id)
            ->where('status', 'pending')
            ->exists();

        if ($existing) {
            return back()->with('error', 'You already have a pending application.');
        }

        WhitelistApplication::create([
            'user_id' => $request->user()->id,
            'answers' => $data['answers'],
        ]);

        return redirect()->route('dashboard')->with('success', 'Your whitelist application has been submitted.');
    }
}
