<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use App\Http\Requests\Auth\LoginRequest;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\View\View;

class AuthenticatedSessionController extends Controller
{
    /**
     * Display the login view.
     */
    public function create(): View
    {
        // Check if user is coming from installation
        $fromInstall = request()->get('from_install', false);
        
        return view('auth.login', compact('fromInstall'));
    }

    /**
     * Handle an incoming authentication request.
     */
    public function store(LoginRequest $request): RedirectResponse
    {
        $request->authenticate();

        $request->session()->regenerate();

        $user = Auth::user();
        
        // Check if user's email is verified
        if (!$user->hasVerifiedEmail()) {
            // Check if it's a test email address
            $email = $user->email;
            $isTestEmail = str_contains($email, '@example.com') || 
                          str_contains($email, '@test.com') || 
                          str_contains($email, '@localhost') ||
                          str_contains($email, '@demo.com');
            
            if ($isTestEmail) {
                // Redirect to test email warning page
                return redirect()->route('test-email-warning');
            }
            
            // For real email addresses, send verification email
            if (!$request->session()->has('verification_email_sent')) {
                try {
                    $user->sendEmailVerificationNotification();
                    $request->session()->put('verification_email_sent', true);
                } catch (\Exception $e) {
                    // Log the error but don't prevent login
                    // Email sending failed - user can still access system
                }
            }
            
            return redirect()->route('verification.notice')
                ->with('success', 'Please verify your email address before accessing your account.');
        }

        $redirectRoute = $user->hasRole('admin') ? route('admin.dashboard', absolute: false) : route('dashboard', absolute: false);

        return redirect()->intended($redirectRoute);
    }

    /**
     * Destroy an authenticated session.
     */
    public function destroy(Request $request): RedirectResponse
    {
        Auth::guard('web')->logout();

        $request->session()->invalidate();

        $request->session()->regenerateToken();

        return redirect('/');
    }
}