<?php

namespace App\Livewire\Admin\Client;

use App\Livewire\Forms\ClientForm;
use App\Models\Client;
use App\Services\ClientService;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Crypt;
use Livewire\Attributes\On;
use Livewire\Component;
use Livewire\WithFileUploads;

use Exception;

class EditClient extends Component
{
    use WithFileUploads;

    public Client $client;
    public ClientForm $clientForm;

    #[On('update-client')]
    public function loadClient($id)
    {
        try {
            $this->client = Client::find($id);

            if ($this->client) {
                $this->clientForm->addClient($this->client);
            }
        } catch (Exception $e) {
            $this->dispatch('notify', message: 'Ocorreu um erro inesperado ao editar o cliente. ' + $e);
        }
    }
    public function edit(ClientService $clientService)
    {

        try {

            $this->authorize('editClient', Auth::user());
            $data = $this->clientForm->validate();

            if ($this->clientForm->profile_image_path) {
                $path = $this->clientForm->profile_image_path->store('client_logos', 'public');
                $data['profile_image_path'] = $path;
            } else {
                unset($data['profile_image_path']);
            }

            if (!empty($data['root_password'])) {
                $data['root_password'] = Crypt::encryptString($data['root_password']);
            } else {
                unset($data['root_password']);
            }

            if (!$clientService->updateClient($this->client, $data)) {
                throw new Exception('O serviço não confirmou a atualização.');
            }

            $this->dispatch('client-updated');
            $this->dispatch('notify', message: $this->clientForm->client_name . ' atualizado com sucesso!');
            $this->clientForm->reset();
        } catch (Exception $e) {
            $this->dispatch('notify', message: 'Falha na edição: ' . $e->getMessage(), type: 'error');
        }
    }
    public function render()
    {
        return view('livewire.admin.clients.edit-client');
    }
}
