<?php

namespace App\Http\Livewire\Profile;

use Illuminate\Support\Facades\Auth;
use Laravel\Fortify\Contracts\UpdatesUserPasswords;
use Livewire\Component;

class UpdatePasswordForm extends Component
{
    /**
     * The component's state.
     *
     * @var array
     */
    public $state = [
        'current_password' => '',
        'password' => '',
        'password_confirmation' => '',
    ];

    /**
     * Mount the component.
     *
     * @return void
     */
    public function mount()
    {
        $profile = getActiveProfile();

        if (!$profile) {
            abort(403, 'No active profile');
        }

        // CRITICAL SECURITY: Validate user has ownership/access to this profile
        // This prevents unauthorized password changes via session manipulation
        \App\Helpers\ProfileAuthorizationHelper::authorize($profile);
    }

    /**
     * Update the user's password.
     *
     * @param  \Laravel\Fortify\Contracts\UpdatesUserPasswords  $updater
     * @return void
     */
    public function updatePassword(UpdatesUserPasswords $updater)
    {
        $profile = getActiveProfile();

        if (!$profile) {
            abort(403, 'No active profile');
        }

        // CRITICAL SECURITY: Validate authorization before password update
        \App\Helpers\ProfileAuthorizationHelper::authorize($profile);

        $this->resetErrorBag();

        $updater->update(Auth::user(), $this->state);

        if (request()->hasSession()) {
            request()->session()->put([
                'password_hash_'.Auth::getDefaultDriver() => Auth::user()->getAuthPassword(),
            ]);
        }

        $this->state = [
            'current_password' => '',
            'password' => '',
            'password_confirmation' => '',
        ];

        $this->dispatch('saved');
    }

    /**
     * Get the current user of the application.
     *
     * @return mixed
     */
    public function getUserProperty()
    {
        return Auth::user();
    }

    /**
     * Render the component.
     *
     * @return \Illuminate\View\View
     */
    public function render()
    {
        $profile = getActiveProfile();

        if (!$profile) {
            abort(403, 'No active profile');
        }

        // CRITICAL SECURITY: Re-validate authorization on every render
        \App\Helpers\ProfileAuthorizationHelper::authorize($profile);

        return view('profile.update-password-form');
    }
}
