<?php

namespace App\Http\Controllers;

use App\Models\Invitation;
use App\Models\User;
use Illuminate\Auth\Events\Registered;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use Illuminate\Validation\Rules;

class InvitationController extends Controller
{
    public function showAcceptForm($token)
    {
        $invitation = Invitation::where('token', $token)->firstOrFail();

        if ($invitation->is_used) {
            return redirect('/login')->with('error', 'This invitation link has already been used.');
        }

        if ($invitation->expires_at < now()) {
            return redirect('/')->with('error', 'This invitation link has expired.');
        }

        return view('auth.accept-invite', compact('invitation'));
    }

    public function accept(Request $request, $token)
    {
        $invitation = Invitation::where('token', $token)->firstOrFail();

        if ($invitation->is_used || $invitation->expires_at < now()) {
            return redirect('/')->with('error', 'This invitation link is invalid or expired.');
        }

        $request->validate([
            'name' => 'required|string|max:255',
            'password' => ['required', 'confirmed', Rules\Password::defaults()],
        ]);

        $user = User::create([
            'name' => $request->name,
            'email' => $invitation->email,
            'password' => Hash::make($request->password),
            'user_type' => 'company_user',
            'company_id' => $invitation->company_id,
            'is_active' => true,
            'email_verified_at' => now(), // pre-verified because of email invite
        ]);

        $user->assignRole('planner');

        $invitation->is_used = true;
        $invitation->save();

        Auth::login($user);

        return redirect('/company/dashboard')->with('success', 'Welcome to the team!');
    }
}
