<?php

namespace App\Http\Controllers\Web;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Str;

class ForgotPasswordController extends Controller
{
    public function showForm()
    {
        return view('auth.forgot-password');
    }

    public function sendResetLink(Request $request)
    {
        $request->validate([
            'email' => ['required', 'email'],
        ]);

        // Check if the user exists
        $user = \App\Models\User::where('email', $request->email)->first();

        if (!$user) {
            return back()->withErrors([
                'email' => 'Email address not found in our records.',
            ])->onlyInput('email');
        }

        // Generate OTP
        $otp = random_int(100000, 999999);

        // Store OTP in password_reset_tokens table
        DB::table('password_reset_tokens')->updateOrInsert(
            ['email' => $request->email],
            [
                'token' => $otp,
                'created_at' => now(),
            ]
        );

        // For now, flash the OTP as a status message (replace with actual email sending later)
        // TODO: Implement actual email sending
        // Mail::to($request->email)->send(new \App\Mail\PasswordResetOtp($otp));

        return redirect()->route('password.verify-otp', ['email' => $request->email])
            ->with('status', 'OTP has been generated. Please check your email.');
    }

    public function showVerifyOtp(Request $request)
    {
        return view('auth.verify-otp', ['email' => $request->query('email')]);
    }

    public function verifyOtp(Request $request)
    {
        $request->validate([
            'email' => ['required', 'email'],
            'otp' => ['required', 'string'],
        ]);

        $record = DB::table('password_reset_tokens')
            ->where('email', $request->email)
            ->where('token', $request->otp)
            ->first();

        if (!$record) {
            return back()->withErrors(['otp' => 'Invalid OTP code.'])->onlyInput('email');
        }

        // Check if OTP is expired (15 minutes)
        if (now()->diffInMinutes($record->created_at) > 15) {
            return back()->withErrors(['otp' => 'OTP has expired. Please request a new one.']);
        }

        return redirect()->route('password.reset', [
            'email' => $request->email,
            'token' => $request->otp,
        ]);
    }

    public function showResetForm(Request $request)
    {
        return view('auth.reset-password', [
            'email' => $request->query('email'),
            'token' => $request->query('token'),
        ]);
    }

    public function resetPassword(Request $request)
    {
        $request->validate([
            'email' => ['required', 'email'],
            'token' => ['required', 'string'],
            'password' => ['required', 'confirmed', 'min:8'],
        ]);

        // Verify the token
        $record = DB::table('password_reset_tokens')
            ->where('email', $request->email)
            ->where('token', $request->token)
            ->first();

        if (!$record) {
            return back()->withErrors(['email' => 'Invalid reset token.']);
        }

        // Update the password
        $user = \App\Models\User::where('email', $request->email)->first();
        $user->update([
            'password' => bcrypt($request->password),
        ]);

        // Delete the token
        DB::table('password_reset_tokens')->where('email', $request->email)->delete();

        return redirect()->route('login')->with('status', 'Password has been reset successfully. Please sign in.');
    }
}
