<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\EmailVerificationRequest;
use Illuminate\Http\RedirectResponse;
use Illuminate\Support\Facades\Auth;
use App\Models\User;
 use Illuminate\Http\Request;
use Illuminate\Auth\Events\Verified;

class EmailVerificationController extends Controller
{

public function verify(Request $request, $id, $hash)
{
    $user = User::findOrFail($id);

    // Prevent cross-account verification
    if (Auth::check() && Auth::id() !== $user->id) {
        Auth::logout(); // logout current user (User B)
    }

    // Re-check after logout
    if (Auth::check() && Auth::id() !== $user->id) {
        abort(403, 'You are not authorized to verify this email.');
    }

    // Validate hash
    if (! hash_equals((string) $hash, sha1($user->getEmailForVerification()))) {
        abort(403, 'Invalid verification link.');
    }

    // Verify email if not already verified
    if (! $user->hasVerifiedEmail()) {
        $user->markEmailAsVerified();
        event(new Verified($user));
    }

    // Log the correct user in (User A)
    Auth::login($user);

    return redirect('/email/verified-success')->with('toast', [
        'type' => 'success',
        'message' => 'Email verified successfully!',
    ]);
}



}
