<?php

namespace App\Http\Controllers\Client;

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

class ConfirmController extends Controller
{
    /**
     * Show the confirmation 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/Confirm', [
            'declaration' => [
                'id' => $declaration->id,
                'title' => $declaration->title,
                'client_name' => $declaration->client->company_name,
            ],
            'token' => $token,
            'submitUrl' => route('client.confirm.store', ['token' => $token]),
        ]);
    }

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

        $request->validate([
            'signature' => ['required', 'string', 'max:255'],
        ]);

        $declaration->update([
            'validated_at' => now(),
            'confirmed_by_type' => ActorType::Client,
            'confirmed_by_id' => $declaration->client_id,
            'confirmation_signature' => $request->input('signature'),
            'status' => \App\Enums\DeclarationStatus::EnCours,
        ]);

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