<?php

// app/Http/Controllers/OtpController.php

namespace App\Http\Controllers;

use App\Helpers\OtpHelper;
use App\Mail\OtpMail;
use App\Models\Otp;
use App\Providers\RouteServiceProvider;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Mail;

class OtpController extends Controller
{

    public function showVerifyForm()
    {
        return view('auth.otp-verify');
    }


    public function verifyOtp(Request $request)
    {
        // 1. Validate input
        $request->validate([
            'otp' => 'required|string',
        ]);

        // 2. Ensure OTP session exists
        if (!session()->has('otp_email') || !session()->has('otp_password')) {
            return redirect()->route('login')
                ->withErrors(['otp' => 'Your session has expired. Please login again.']);
        }

        // 3. Find OTP record (with optional expiry)
        $otpRecord = Otp::where('email', session('otp_email'))
            ->where('otp', $request->otp)
            ->first();

        if (!$otpRecord) {
            return back()->withErrors([
                'otp' => 'Invalid or expired OTP.',
            ]);
        }

        // 4. Attempt authentication
        $credentials = [
            'email'    => session('otp_email'),
            'password' => session('otp_password'),
        ];

        if (!Auth::attempt($credentials)) {
            return back()->withErrors([
                'otp' => 'Authentication failed.',
            ]);
        }

        // 5. ✅ OTP VERIFIED — update timestamp
        auth()->user()->update([
            'last_otp_verified_at' => now(),
        ]);

        // 6. Cleanup OTP + session
        $otpRecord->delete();

        session()->forget([
            'otp_sent',
            'otp_email',
            'otp_password',
        ]);

        // 7. Regenerate session (prevent fixation)
        $request->session()->regenerate();

        // 8. Redirect to dashboard
        return redirect()->intended(RouteServiceProvider::HOME);
    }
}
