<?php

namespace App\Components\Account;

use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Str;
use Livewire\Component;
use Livewire\WithFileUploads;

class AccountProfile extends Component {
    use WithFileUploads;

    public string $name_first = '';
    public string $name_last = '';
    public string $email = '';

    public $avatar;

    public $croppedAvatar;

    public function mount(): void {
        $u = Auth::user();
        $this->name_first = $u->name_first;
        $this->name_last = $u->name_last;
        $this->email = $u->email_address;
    }

    public function updatedAvatar(): void {
        $this->validate([
            'avatar' => 'nullable|image|max:4096',
        ]);

        $this->dispatch('avatar-selected', url: $this->avatar?->temporaryUrl());
    }

    public function save(): void {
        $this->validate([
            'name_first' => 'required|string|max:100',
            'name_last' => 'required|string|max:100',
            'email' => 'required|email|unique:users,email_address,' . Auth::id(),
            'croppedAvatar' => 'nullable|image|max:4096',
        ]);

        $u = Auth::user();

        if ($this->croppedAvatar) {
            $filename = Str::uuid() . '.jpg';
            $path = $this->croppedAvatar->storeAs('avatars', $filename, 'public');
            $u->profile_photo_path = $path;
        }

        $u->name_first = $this->name_first;
        $u->name_last = $this->name_last;
        $u->email_address = $this->email;
        $u->save();

        session()->flash('success', 'Profile updated');
    }

    public function render() {
        return view('components.account.account-profile');
    }
}
