<?php

namespace App\Http\Controllers;

use Illuminate\Auth\Events\PasswordReset;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Password;
use Illuminate\Support\Str;
use Illuminate\Validation\Rules\Password as PasswordRule;

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

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

        $user = \App\Models\User::where('email', $request->email)->first();

        if (! $user) {
            return back()->with('status', 'Jika email terdaftar, kode OTP telah dikirim. Silakan cek inbox (atau folder spam).');
        }

        $otp = random_int(100000, 999999);
        $user->email_verification_code = $otp;
        $user->save();

        try {
            \Mail::mailer('smtp')->to($user->email)->send((new \App\Mail\EmailVerificationCode($otp, 'password_reset'))
                ->from('e31221353@student.polije.ac.id', 'Absensi PT. Triatra'));
        } catch (\Exception $e) {
            \Log::error('Gagal mengirim email OTP reset password: ' . $e->getMessage());
        }

        return redirect()->route('password.otp.verify.form', ['email' => $user->email])
            ->with('status', 'Kode OTP dikirim ke email Anda. Masukkan kode untuk melanjutkan reset password.');
    }

    public function otpVerifyForm(Request $request)
    {
        $email = $request->query('email');

        return view('auth.verify-otp', [
            'email' => $email,
            'formAction' => route('password.otp.verify'),
            'title' => 'Verifikasi OTP Lupa Password',
            'info' => 'Masukkan kode OTP yang dikirim ke email untuk melakukan reset password.',
        ]);
    }

    public function otpVerify(Request $request)
    {
        $request->validate([
            'email' => ['required', 'email'],
            'otp' => ['required', 'digits:6'],
        ]);

        $user = \App\Models\User::where('email', $request->email)
            ->where('email_verification_code', $request->otp)
            ->first();

        if (! $user) {
            return back()->withErrors(['otp' => 'Kode OTP salah atau tidak valid.'])->withInput();
        }

        $user->email_verification_code = null;
        $user->save();

        $request->session()->put('password_reset_email', $user->email);

        return redirect()->route('password.reset')->with('status', 'OTP berhasil diverifikasi. Silakan masukkan password baru.');
    }

    public function resetForm(Request $request)
    {
        $email = $request->session()->get('password_reset_email');

        if (! $email) {
            return redirect()->route('password.request')->withErrors(['email' => 'Proses reset password tidak valid. Silakan mulai dari awal.']);
        }

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

    public function resetFormWithToken(string $token)
    {
        return view('auth.reset-password', ['token' => $token]);
    }

    public function update(Request $request)
    {
        $passwordResetEmail = $request->session()->get('password_reset_email');

        if ($passwordResetEmail) {
            $request->validate([
                'email' => ['required', 'email'],
                'password' => ['required', 'confirmed', PasswordRule::min(8)],
            ]);

            if ($request->email !== $passwordResetEmail) {
                return back()->withErrors(['email' => 'Email tidak sesuai dengan session verifikasi.']);
            }

            $user = \App\Models\User::where('email', $passwordResetEmail)->first();

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

            $user->password = $request->password;
            $user->remember_token = Str::random(60);
            $user->save();

            $request->session()->forget('password_reset_email');

            return redirect()->route('login')->with('status', 'Password berhasil direset. Silakan login dengan password baru.');
        }

        $request->validate([
            'token' => ['required'],
            'email' => ['required', 'email'],
            'password' => ['required', 'confirmed', PasswordRule::min(8)],
        ]);

        $status = Password::reset(
            $request->only('email', 'password', 'password_confirmation', 'token'),
            function ($user) use ($request) {
                $user->forceFill([
                    'password' => $request->password, // auto hashed by cast
                    'remember_token' => Str::random(60),
                ])->save();

                event(new PasswordReset($user));
            }
        );

        if ($status === Password::PASSWORD_RESET) {
            // Optionally auto-login after reset
            if (Auth::attempt($request->only('email', 'password'))) {
                $request->session()->regenerate();
                return redirect()->route('dashboard');
            }
            return redirect()->route('login')->with('status', __($status));
        }

        return back()->withErrors(['email' => __($status)]);
    }
}
