<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Password;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Auth;

class ForgotPasswordController extends Controller
{
    // Tampilkan Form Lupa Password
    public function showLinkRequestForm()
    {
        return view('auth.forgot-password');
    }

    // Kirim Link Reset ke Email
    public function sendResetLinkEmail(Request $request)
    {
        $request->validate(['email' => 'required|email', 'role' => 'required|in:petani,pembeli']);

        $broker = $request->role == 'petani' ? 'petanis' : 'pembelis';

        $status = Password::broker($broker)->sendResetLink(
            $request->only('email')
        );

        return $status == Password::RESET_LINK_SENT
            ? back()->with(['status' => __($status)])
            : back()->withErrors(['email' => __($status)]);
    }

    // Tampilkan Form Reset Password (Link dari Email)
    public function showResetForm(Request $request, $token = null)
    {
        return view('auth.reset-password')->with(
            ['token' => $token, 'email' => $request->email, 'role' => $request->role]
        );
    }

    // Proses Simpan Password Baru
    public function reset(Request $request)
    {
        $request->validate([
            'token' => 'required',
            'email' => 'required|email',
            'password' => 'required|min:6|confirmed',
        ]);

        $broker = 'pembelis'; 
        if (\App\Models\Petani::where('email', $request->email)->exists()) {
            $broker = 'petanis';
        }

        $status = Password::broker($broker)->reset(
            $request->only('email', 'password', 'password_confirmation', 'token'),
            function ($user, $password) {
                $user->forceFill([
                    'password' => Hash::make($password)
                ])->save();
            }
        );

        return $status == Password::PASSWORD_RESET
            ? redirect()->route('login')->with('success', 'Password berhasil direset! Silakan login.')
            : back()->withErrors(['email' => __($status)]);
    }
}