<?php

namespace App\Livewire\Pages\Profile;

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

class Security extends Component
{
    public string $currentPassword = '';

    public string $newPassword = '';

    public string $newPasswordConfirmation = '';

    public function changePassword(): void
    {
        $this->validate([
            'currentPassword' => 'required',
            'newPassword' => 'required|min:8|confirmed',
        ]);

        if (! Hash::check($this->currentPassword, auth()->user()->password)) {
            $this->addError('currentPassword', 'Current password is incorrect.');

            return;
        }

        auth()->user()->update(['password' => Hash::make($this->newPassword)]);
        $this->reset(['currentPassword', 'newPassword', 'newPasswordConfirmation']);
        session()->flash('status', 'Password changed successfully.');
    }

    public function render(): View
    {
        return view('livewire.pages.profile.security')
            ->layout('layouts.nimuli-app', ['title' => 'Security']);
    }
}
