<?php

namespace App\Http\Controllers;

use App\Models\Tenant\User;
use Illuminate\Http\Request;

class InvitationController extends Controller
{
    public function show(string $token)
    {
        $user = User::findByInvitationToken($token);
        if (! $user || ! $user->isPendingInvitation()) {
            return view('invitations.invalid');
        }
        // Invitations expire after 7 days
        if ($user->invited_at && $user->invited_at->lt(now()->subDays(7))) {
            return view('invitations.expired');
        }

        return view('invitations.accept', [
            'token' => $token,
            'name' => $user->name,
            'email' => $user->email,
            'company' => $user->company?->display_name ?? $user->company?->name ?? 'AutoCRM',
        ]);
    }

    public function accept(string $token, Request $request)
    {
        $request->validate([
            'password' => 'required|min:8|confirmed',
        ]);

        $user = User::findByInvitationToken($token);
        if (! $user || ! $user->isPendingInvitation()) {
            return view('invitations.invalid');
        }
        if ($user->invited_at && $user->invited_at->lt(now()->subDays(7))) {
            return view('invitations.expired');
        }

        $user->acceptInvitation($request->input('password'));

        // Redirect to tenant login on the appropriate subdomain
        $loginUrl = $user->company?->url('/app/login') ?? '/app/login';
        return redirect($loginUrl)->with('status', 'Invitația a fost acceptată. Loghează-te cu noua parolă.');
    }
}
