<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use App\Http\Requests\Auth\LoginRequest;
use App\Models\User;
use App\Services\CaptchaService;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use Illuminate\View\View;
use Laravel\Socialite\Facades\Socialite;

class AuthenticatedSessionController extends Controller
{
    /**
     * Display the login view.
     * Generate CAPTCHA and pass checksum to view
     */
    public function create(): View
    {
        $captchaChecksum = CaptchaService::generateCaptcha();
        return view('auth.login', ['captchaChecksum' => $captchaChecksum]);
    }

    /**
     * Handle an incoming authentication request.
     * Validate CAPTCHA first, then validate credentials
     * After password verified, generate OTP and redirect to OTP verification page
     */
    public function store(LoginRequest $request): RedirectResponse
    {
        // Validate CAPTCHA before anything else
        $captchaChecksum = $request->input('captcha_checksum');
        $captchaInput = $request->input('captcha');

        if (!$captchaChecksum || !$captchaInput) {
            return back()->withErrors(['captcha' => 'Silakan isi CAPTCHA.']);
        }

        if (!CaptchaService::validateCaptcha($captchaInput, $captchaChecksum)) {
            $remaining = CaptchaService::getRemainingAttempts();
            if ($remaining <= 0) {
                CaptchaService::forget();
                return back()->withErrors(['captcha' => 'Terlalu banyak upaya CAPTCHA yang gagal. Silakan refresh dan coba lagi.']);
            }
            return back()->withErrors(['captcha' => 'CAPTCHA salah. Coba lagi.']);
        }

        // Validasi email & password TANPA login (2FA flow)
        $request->validateCredentials();

        // Cari user berdasarkan email
        $user = User::where('email', $request->email)->first();

        if (!$user) {
            return back()->withErrors(['email' => 'Akun tidak ditemukan.']);
        }

        // Cek pengaturan 2FA user
        if ($user->two_factor_enabled) {
            // Generate OTP dan kirim via email
            $user->generateAndSendOtpCode();

            // Store email di session untuk verify OTP nanti
            session(['pending_login_email' => $user->email]);
            session(['remember' => $request->boolean('remember')]);

            // Redirect ke verify OTP page
            return redirect()->route('verify.otp.show')
                ->with('status', 'Kode verifikasi OTP telah dikirim ke email Gmail Anda. Silakan periksa kotak masuk atau folder spam.');
        }

        // Jika 2FA nonaktif, langsung login
        Auth::login($user, $request->boolean('remember'));
        $request->session()->regenerate();
        
        return redirect()->intended(route('dashboard'))->with('success', 'Login berhasil! Selamat datang.');
    }

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

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

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

        return redirect('/');
    }

    public function redirectToGoogle()
    {
        return Socialite::driver('google')->redirect();
    }

    public function handleGoogleCallback()
    {
        try {
            $googleUser = Socialite::driver('google')->user();
        } catch (\Exception $e) {
            return redirect()->route('login')
                ->withErrors(['email' => 'Login Google gagal. Coba lagi.']);
        }

        $user = User::where('email', $googleUser->email)->first();

        // Kalau email tidak terdaftar di sistem
        if (!$user) {
            return redirect()->route('login')
                ->withErrors(['email' => 'Akun dengan email ini tidak terdaftar di sistem.']);
        }

        // Update google_id kalau belum ada
        if (!$user->google_id) {
            $user->update(['google_id' => $googleUser->id]);
        }

        // Cek pengaturan 2FA user
        if ($user->two_factor_enabled) {
            // Generate OTP dan kirim via email
            $user->generateAndSendOtpCode();

            session(['pending_login_email' => $user->email]);
            session(['remember' => false]);

            return redirect()->route('verify.otp.show')
                ->with('status', 'Kode OTP telah dikirim ke email Anda. Silakan cek kotak masuk.');
        }

        // Jika 2FA nonaktif, langsung login
        Auth::login($user, false);
        session()->regenerate();
        
        return redirect()->intended(route('dashboard'))->with('success', 'Login berhasil! Selamat datang.');
    }
}
