<?php

namespace App\Http\Controllers\Client;

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

class RefuseController extends Controller
{
    /**
     * Show the refusal page.
     */
    public function show(Request $request, string $token): Response
    {
        $invitation = $request->attributes->get('declaration_invitation');
        $declaration = $invitation->declaration;

        $declaration->load(['client']);

        return Inertia::render('client/Refuse', [
            'declaration' => [
                'id' => $declaration->id,
                'title' => $declaration->title,
                'client_name' => $declaration->client->company_name,
            ],
            'token' => $token,
            'submitUrl' => route('client.refuse.store', ['token' => $token]),
        ]);
    }

    /**
     * Store the refusal.
     */
    public function store(Request $request, string $token): RedirectResponse
    {
        $invitation = $request->attributes->get('declaration_invitation');
        $declaration = $invitation->declaration;

        $request->validate([
            'reason' => ['nullable', 'string', 'max:65535'],
        ]);

        $declaration->update([
            'refused_at' => now(),
            'refusal_reason' => $request->input('reason'),
        ]);

        return back()->with('flash', ['type' => 'success', 'message' => 'Refus enregistré.']);
    }
}
