<?php

namespace App\Livewire\System;

use App\Livewire\Concerns\InteractsWithToasts;
use App\Models\User;
use App\Services\ActivityLogger;
use Illuminate\Support\Facades\Hash;
use Illuminate\Validation\Rules\Password as PasswordRule;
use Livewire\Attributes\Title;
use Livewire\Component;
use Livewire\WithFileUploads;

/**
 * A staff member's own account.
 */
#[Title('My profile')]
class Profile extends Component
{
    use InteractsWithToasts, WithFileUploads;

    public string $name = '';

    public string $email = '';

    public string $phone = '';

    public string $currentPassword = '';

    public string $password = '';

    public string $password_confirmation = '';

    public $avatar;

    public function mount(): void
    {
        $user = auth()->user();

        $this->name = $user->name;
        $this->email = $user->email;
        $this->phone = (string) $user->phone;
    }

    public function saveProfile(): void
    {
        /** @var User $user */
        $user = auth()->user();

        $this->validate([
            'name' => 'required|string|min:2|max:120',
            'email' => 'required|email|max:150|unique:users,email,'.$user->id,
            'phone' => 'nullable|string|max:30',
            'avatar' => 'nullable|image|max:'.config('thinkrax.uploads.image_max_kb'),
        ]);

        $data = [
            'name' => $this->name,
            'email' => strtolower(trim($this->email)),
            'phone' => $this->phone ?: null,
        ];

        if ($this->avatar) {
            $data['avatar_path'] = $this->avatar->store('avatars', config('filesystems.default'));
        }

        $user->fill($data)->save();

        $this->reset('avatar');

        $this->toastSuccess('Profile updated.');
    }

    public function changePassword(): void
    {
        /** @var User $user */
        $user = auth()->user();

        $this->validate([
            'currentPassword' => 'required',
            'password' => ['required', 'confirmed', PasswordRule::min(10)->letters()->numbers()],
        ]);

        /*
         * Re-authenticating protects against somebody walking up to an
         * unlocked machine — this panel can hand out subscriptions.
         */
        if (! Hash::check($this->currentPassword, $user->password)) {
            $this->addError('currentPassword', 'That is not your current password.');

            return;
        }

        $user->forceFill(['password' => $this->password])->save();

        $this->reset(['currentPassword', 'password', 'password_confirmation']);

        app(ActivityLogger::class)->log('staff.password_changed', "{$user->name} changed their password", $user);

        $this->toastSuccess('Password changed.');
    }

    public function render()
    {
        return view('livewire.system.profile');
    }
}
