<?php

namespace App\Http\Livewire\Profile;

use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use Livewire\Component;

class UpdateNonUserPasswordForm extends Component
{
    public $state = [
        'current_password' => '',
        'password' => '',
        'password_confirmation' => '',
    ];

    public function updatePassword()
    {
        $profileName = strtolower(getActiveProfileType());
        $this->validate([
            'state.current_password' => ['required', 'string'],
            'state.password' => timebank_config('rules.profile_' . $profileName . '.password'),
        ]);

        $activeProfile = getActiveprofile();

        // CRITICAL SECURITY: Validate user has ownership/access to this profile
        \App\Helpers\ProfileAuthorizationHelper::authorize($activeProfile);

        // Check if the current password matches
        if (!Hash::check($this->state['current_password'], $activeProfile->password)) {
            $this->addError('state.current_password', __('The provided password does not match your current password.'));
            return;
        }

        // Update the password
        $activeProfile->forceFill([
            'password' => Hash::make($this->state['password']),
        ])->save();

        activity()
            ->useLog(class_basename(getActiveProfileType()))
            ->performedOn($activeProfile)
            ->causedBy(Auth::guard('web')->user())
            ->event('password_changed')
            ->log('Password changed for ' . $activeProfile->name);

        // Dispatch a success message
        $this->dispatch('saved');
    }

    public function render()
    {
        return view('livewire.profile.update-non-user-password-form');
    }
}
