<?php

namespace App\Http\Controllers;

use App\Events\ProfileSwitchEvent;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash; // Add Hash facade
use Illuminate\Support\Facades\Password;
use Illuminate\Support\Str; // Add Str facade

class ResetNonUserPasswordController extends Controller
{
    /**
     * Display the form to request a password reset link.
     */
    public function showLinkRequestForm($profileType)
    {
        return view('auth.forgot-non-user-password', ['profileType' => $profileType]);
    }

    /**
     * Handle sending the password reset link.
     */
    public function sendResetLinkEmail(Request $request, $profileType)
    {
        $request->validate(['email' => 'required|email']);

        $broker = $this->getPasswordBroker($profileType);

        // This will now use the model defined in the provider for $broker (e.g., Admin model)
        $status = Password::broker($broker)->sendResetLink(
            $request->only('email')
        );

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

    /**
     * Display the password reset view for the given token.
     *
     * If no token is present, display the link request form.
     */
    public function showResetForm(Request $request, $profileType, $token = null)
    {
        if (is_null($token)) {
            return $this->showLinkRequestForm($profileType);
        }

        $email = $request->query('email');

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

    /**
     * Reset the given profile's password.
     */
    public function reset(Request $request, $profileType)
    {
        // Dynamically get the password validation rules from the config
        $passwordRules = timebank_config('rules.profile_' . strtolower($profileType) . '.password', ['required', 'string', 'min:8', 'confirmed']);

        $request->validate([
            'token' => 'required',
            'email' => 'required|email',
            'password' => $passwordRules,
        ]);

        $broker = $this->getPasswordBroker($profileType);

        // Attempt to reset the password. This will also use the model defined in the provider.
        $status = Password::broker($broker)->reset(
            $request->only('email', 'password', 'password_confirmation', 'token'),
            function ($profile, $password) {
                // $profile will be an instance of Admin, Bank, etc.
                $profile->forceFill([
                    'password' => Hash::make($password),
                ])->save();

                //Log the user in to this elevated profile if that's desired after reset
                if ($profile) {
                    $profileClassName = get_class($profile);

                    session([
                        'activeProfileType'  => $profileClassName,
                        'activeProfileId'    => $profile->id,
                        'activeProfileName'  => $profile->name,
                        'activeProfilePhoto' => $profile->profile_photo_path,
                        'last_activity' => now(),
                        'profile-switched-notification' => true,
                    ]);
                    event(new ProfileSwitchEvent($profile)); 
                }
            }
        );

        return $status === Password::PASSWORD_RESET
                    ? redirect()->route('main')->with('status', __($status)) // Or a specific login for that profile type
                    : back()->withInput($request->only('email'))
                            ->withErrors(['email' => __($status)]);
    }

    /**
     * Get the password broker for the given profile type.
     */
    private function getPasswordBroker($profileType)
    {
        // Ensure this maps to the keys in config/auth.php 'passwords'
        $brokers = [
            'admin' => 'admins',
            'bank' => 'banks',
            // 'organization' => 'organizations', // etc.
        ];
        // Fallback to 'users' broker if profileType doesn't match,
        // or handle as an error if only specific profile types are allowed here.
        return $brokers[strtolower($profileType)] ?? 'users';
    }
}
