<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\User;
use Illuminate\Support\Facades\Crypt;

class ForgotPasswordController extends Controller
{
    public function showForm()
    {
        return view('forgot_password');
    }

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

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

        if (!$user) {
            return redirect()->back()->with('error', 'Email tidak ditemukan.');
        }

        // Simpan email ke session sementara
        session(['reset_email' => $user->email]);

         return redirect()->route('password.reset.form')->with('email', $request->email);
    }

    public function showResetForm()
    {
        if (!session('reset_email')) {
            return redirect()->route('password.request')->with('error', 'Silakan masukkan email terlebih dahulu.');
        }

        return view('reset_password');
    }

    public function resetPassword(Request $request)
    {
        $request->validate([
            'password' => 'required|min:6|confirmed'
        ]);

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

        if (!$user) {
            return redirect()->route('password.request')->with('error', 'Terjadi kesalahan.');
        }

        $user->password = Crypt::encryptString($request->password);
        $user->save();

        session()->forget('reset_email');

        return redirect()->route('login')->with('success', 'Password berhasil diubah. Silakan login kembali.');
    }
}
