<?php
// app/Http/Controllers/Auth/LoginController.php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
use App\Models\User;
use App\Models\PasswordReset;
use App\Mail\PasswordResetOtpMail;
use App\Helpers\EmailConfig;

class LoginController extends Controller
{
    public function showLoginForm()
    {
        return view('auth.login');
    }

    public function login(Request $request)
    {
        $credentials = $request->validate([
            'email' => 'required|email',
            'password' => 'required',
        ]);

        if (Auth::attempt($credentials, $request->filled('remember'))) {
            $request->session()->regenerate();
            return redirect()->intended('/home');
        }

        return back()->withErrors([
            'email' => 'The provided credentials do not match our records.',
        ])->onlyInput('email');
    }

    public function logout(Request $request)
    {
        Auth::logout();
        $request->session()->invalidate();
        $request->session()->regenerateToken();
        return redirect('/');
    }

    public function showForgotPasswordForm()
    {
        return view('auth.forgot-password');
    }

    public function sendResetLinkEmail(Request $request)
    {
        $request->validate([
            'email' => 'required|email|exists:users,email'
        ]);

        $user = User::where('email', $request->email)->first();
        
        if (!$user) {
            return back()->withErrors(['email' => 'Email address not found.']);
        }

        // Generate OTP
        $otp = str_pad(random_int(100000, 999999), 6, '0', STR_PAD_LEFT);
        
        // Create or update password reset record
        PasswordReset::updateOrCreate(
            ['email' => $user->email],
            [
                'token' => $otp,
                'created_at' => now()
            ]
        );

        // Generate reset URL
        $resetUrl = route('password.reset', ['token' => $otp]);

        try {
            // Configure email settings
            EmailConfig::configureMail();
            
            // Send OTP email
            Mail::to($user->email)->send(new PasswordResetOtpMail($user, $otp, $resetUrl));
            
            return back()->with('status', 'Password reset OTP sent to your email address. Please check your inbox and spam folder.');
        } catch (\Exception $e) {
            return back()->withErrors(['email' => 'Failed to send OTP. Please try again later.']);
        }
    }

    public function showResetForm(Request $request, $token)
    {
        $passwordReset = PasswordReset::where('token', $token)
            ->where('created_at', '>', now()->subMinutes(15))
            ->first();

        if (!$passwordReset) {
            return redirect()->route('password.request')
                ->withErrors(['token' => 'Invalid or expired OTP. Please request a new one.']);
        }

        return view('auth.reset-password', ['token' => $token]);
    }

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

        $passwordReset = PasswordReset::where('token', $request->token)
            ->where('email', $request->email)
            ->where('created_at', '>', now()->subMinutes(15))
            ->first();

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

        $user = User::where('email', $request->email)->first();
        
        if (!$user) {
            return back()->withErrors(['email' => 'User not found.']);
        }

        // Update password
        $user->password = Hash::make($request->password);
        $user->save();

        // Delete the password reset record
        $passwordReset->delete();

        return redirect()->route('login')
            ->with('status', 'Password reset successfully. You can now login with your new password.');
    }
}