<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Http\RedirectResponse;
use Illuminate\Support\Facades\Auth;
use Illuminate\View\View;

class VerifyOtpController extends Controller
{
    /**
     * Show OTP verification form untuk login
     * Accessible untuk guest users (setelah login dengan password)
     */
    public function show(): \Illuminate\View\View|\Illuminate\Http\RedirectResponse
{
    // Kalau udah login, langsung ke dashboard
    if (Auth::check()) {
        return redirect()->route('dashboard');
    }

    $email = session('pending_login_email');
    
    // Kalau session kosong, balik ke login TANPA flash apapun
    if (!$email) {
        return redirect()->route('login');
    }

    return view('auth.verify-otp-login', ['email' => $email]);
}

    /**
     * Verify OTP code untuk login
     */
    public function verify(Request $request): RedirectResponse
    {
        $request->validate([
            'otp_code' => ['required', 'string', 'digits:6'],
        ], [
            'otp_code.required' => 'Kode OTP harus diisi',
            'otp_code.digits' => 'Kode OTP harus 6 digit',
        ]);

        // Get pending email dari session
        $email = session('pending_login_email');
        
        if (!$email) {
            return redirect(route('login'))->withErrors(['message' => 'Session expired. Silakan login kembali.']);
        }

        // Get user by email
        $user = User::where('email', $email)->first();

        if (!$user) {
            session()->forget('pending_login_email');
            return redirect(route('login'))->withErrors(['message' => 'User not found.']);
        }

        // Verify OTP
        if ($user->verifyOtpCode($request->otp_code)) {
            // OTP benar - regenerate session dan login user
            $remember = session('remember', false);
            session()->forget(['pending_login_email', 'remember']);

            // ✅ Opsi B: Auto-mark email sebagai verified
            // OTP via email = bukti user punya akses ke email tsb
            if (!$user->hasVerifiedEmail()) {
                $user->markEmailAsVerified();
            }

            $request->session()->regenerate();
            Auth::login($user, $remember);

            return redirect()->intended(route('dashboard'))->with('success', 'Login berhasil! Selamat datang.');
        }

        // OTP salah
        $otp = $user->getCurrentTwoFactorCode();
        
        if ($otp && $otp->isLocked()) {
            session()->forget('pending_login_email');
            return redirect(route('login'))->withErrors([
                'message' => 'Terlalu banyak percobaan salah. Silakan login kembali.'
            ]);
        }

        $attempts_left = $otp ? (3 - $otp->attempts) : 0;
        
        return back()->withErrors([
            'otp_code' => "Kode OTP salah. Sisa percobaan: {$attempts_left}"
        ])->withInput();
    }

    /**
     * Resend OTP code untuk login
     */
    public function resend(Request $request): RedirectResponse
    {
        $email = session('pending_login_email');
        
        if (!$email) {
            return redirect(route('login'));
        }

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

        if (!$user) {
            session()->forget('pending_login_email');
            return redirect(route('login'));
        }

        // Generate dan kirim OTP baru
        $user->generateAndSendOtpCode();

        return back()->with('success', 'OTP code baru sudah dikirim ke email Anda.');
    }
}