<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Validation\ValidationException;
use App\Models\User;
use Illuminate\Console\View\Components\Alert;
use Illuminate\Support\Facades\Redis;
use Illuminate\Support\Facades\Hash;
use Uuid;

class ResetPasswordController extends Controller
{
    // public function __construct()
    // {
    //     $this->middleware('guest')->except('logout');
    // }
    
    public function index()
    {
        
        return view('reset-password');
    }

        public function cek(Request $request)
    {
        // Validasi input email
        $request->validate([
            'email' => 'required|email|exists:users,email',
        ], [
            'email.required' => 'Email harus diisi.',
            'email.email' => 'Format email tidak valid.',
            'email.exists' => 'Email tidak terdaftar.', // Menghindari pengecekan manual di database
        ]);

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

        // Simpan data ke session
        session()->put([
            'reset_email' => $user->email,
            'reset_name' => $user->name
        ]);

        return redirect()->route('reset-password')->with('success', 'Email ditemukan, silakan reset password.');
    }

    public function reset(Request $request)
    {
        // Pastikan email tersedia di session
        if (!session()->has('reset_email')) {
            return redirect()->route('reset-password')->with('error', 'Silakan cek email terlebih dahulu.');
        }

        $email = session('reset_email');

        // Validasi password baru
        $request->validate([
            'password' => 'required|string|min:8|confirmed',
        ], [
            'password.required' => 'Password harus diisi.',
            'password.min' => 'Password harus minimal 8 karakter.',
            'password.confirmed' => 'Konfirmasi password tidak cocok.',
        ]);

        // Update password user
        User::where('email', $email)->update([
            'password' => Hash::make($request->password),
        ]);

        // Hapus session setelah reset password berhasil
        session()->forget(['reset_email', 'reset_name']);

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