<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use Illuminate\Auth\Access\AuthorizationException;
use Illuminate\Auth\Events\Verified;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\View\View;

class VerificationController extends Controller
{
    /*
    |--------------------------------------------------------------------------
    | Email Verification Controller
    |--------------------------------------------------------------------------
    |
    | This controller is responsible for handling email verification for any
    | user that recently registered with the application. Emails may also
    | be re-sent if the user didn't receive the original email message.
    |
    */

    /**
     * Where to redirect users after verification.
     *
     * @var string
     */
    protected string $redirectTo = 'user/administration';

    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('auth')->except('verify');
        $this->middleware('signed')->only('verify');
        $this->middleware('throttle:6,1')->only('verify', 'resend');
    }

    /**
     * Show the email verification notice.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\RedirectResponse|\Illuminate\View\View
     */
    public function show(Request $request): View|RedirectResponse
    {
        // If user is not authenticated, redirect to login
        if (!$request->user()) {
            return redirect('user/login');
        }

        // If already verified, show success page instead of verification notice
        if ($request->user()->hasVerifiedEmail()) {
            return view('user/registration/registration-success');
        }

        // Show verification notice (waiting for email verification)
        return view('user/registration/verification-notice');
    }


    /**
     * Mark the user's email address as verified.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\JsonResponse|\Illuminate\Http\RedirectResponse
     *
     * @throws \Illuminate\Auth\Access\AuthorizationException
     */
    public function verify(Request $request)
    {
        try {
            // Get user by ID from route parameter
            $user = \App\Models\Account::findOrFail($request->route('id'));

            // Retrieve user's locale from cache and set it
            try {
                $cachedLocale = \Illuminate\Support\Facades\Cache::get('user_locale_' . $user->id);
                if ($cachedLocale) {
                    $supportedLocales = ['en', 'de', 'fr', 'es', 'it', 'pl', 'ru', 'tr', 'pt', 'nl', 'cz', 'dk', 'gr', 'hu', 'ro'];
                    if (in_array($cachedLocale, $supportedLocales)) {
                        app()->setLocale($cachedLocale);
                        if ($request->hasSession()) {
                            $request->session()->put('language', $cachedLocale);
                        }
                    }
                }
            } catch (\Exception $e) {
                // If locale retrieval fails, continue without it
                \Log::warning('Failed to retrieve locale from cache', ['error' => $e->getMessage()]);
            }

            // Verify the hash matches the user's email
            if (! hash_equals((string) $request->route('hash'), sha1($user->getEmailForVerification()))) {
                throw new AuthorizationException;
            }

            // If already verified, redirect
            if ($user->hasVerifiedEmail()) {
                // Log the user in if not already authenticated
                try {
                    if (!auth()->check()) {
                        auth()->login($user);
                    }
                } catch (\Exception $e) {
                    \Log::warning('Failed to log in user during verification', ['error' => $e->getMessage()]);
                }

                return $request->wantsJson()
                    ? new JsonResponse([], 204)
                    : redirect($this->getRedirectPath());
            }

            // Mark as verified
            if ($user->markEmailAsVerified()) {
                event(new Verified($user));
            }

            // Log the user in if not already authenticated
            try {
                if (!auth()->check()) {
                    auth()->login($user);
                }
            } catch (\Exception $e) {
                \Log::warning('Failed to log in user after verification', ['error' => $e->getMessage()]);
            }

            if ($response = $this->verified($request)) {
                return $response;
            }

            return $request->wantsJson()
                ? new JsonResponse([], 204)
                : redirect($this->getRedirectPath())->with('verified', true);
        } catch (\Exception $e) {
            \Log::error('Verification error', [
                'error' => $e->getMessage(),
                'trace' => $e->getTraceAsString()
            ]);

            // Redirect to login with error message
            return redirect('user/login')->with('error', 'An error occurred during verification. Please try logging in.');
        }
    }

    /**
     * Get the redirect path after verification.
     *
     * @return string
     */
    protected function getRedirectPath(): string
    {
        if (method_exists($this, 'redirectPath')) {
            return $this->redirectPath();
        }

        return property_exists($this, 'redirectTo') ? $this->redirectTo : 'user/administration';
    }

    /**
     * The user has been verified.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return mixed
     */
    protected function verified(Request $request): mixed
    {
        return view('user/registration/registration-success');
    }

    /**
     * Resend the email verification notification.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\JsonResponse|\Illuminate\Http\RedirectResponse
     */
    public function resend(Request $request)
    {
        // If user is not authenticated, redirect to login
        if (!$request->user()) {
            return redirect('user/login');
        }

        if ($request->user()->hasVerifiedEmail()) {
            return $request->wantsJson()
                ? new JsonResponse([], 204)
                : redirect($this->redirectPath());
        }

        $request->user()->sendEmailVerificationNotification();

        return $request->wantsJson()
            ? new JsonResponse([], 202)
            : back()->with('resent', true);
    }

    /**
     * Check if the user's email has been verified (AJAX endpoint).
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function check(Request $request): JsonResponse
    {
        // If user is not authenticated, return not verified
        if (!$request->user()) {
            return new JsonResponse(['verified' => false], 200);
        }

        // Return verification status
        return new JsonResponse([
            'verified' => $request->user()->hasVerifiedEmail()
        ], 200);
    }
}
