<?php

namespace App\Livewire\Admin\Client;

use App\Models\Client;
use App\Services\ClientService;
use App\Livewire\Forms\ClientForm; // 1. Importa seu Form Object
use Illuminate\Support\Facades\Auth;
use Livewire\Component;
use Livewire\WithFileUploads;
use Illuminate\Support\Facades\Crypt;


class AddClient extends Component
{
    use WithFileUploads;
    public ClientForm $form;
    public function save(ClientService $clientService)
    {


        try {
            $this->authorize('addClient', Auth::user());
            $this->form->validate();

            $data = $this->form->all();
            $data['name'] = $data['client_name'];

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

            $data['root_password'] = Crypt::encryptString($data['root_password']);

            $client = $clientService->addClient($data);

            $this->dispatch('client-added');
            $this->dispatch('notify', message: $client->name . ' adicionado com sucesso!');
            $this->form->reset();

        } catch (\Exception $e) {
            $this->dispatch('notify', message: 'Ocorreu um erro inesperado ao salvar. ' . $e->getMessage(), type: 'error');
        }
    }


    public function render()
    {
        return view('livewire.admin.clients.add-client');
    }
}
