<?php

namespace App\Livewire\Admin;

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)
    {

        $this->form->validate();

        try {
            $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']);

            $clientService->addClient($data);

            $this->dispatch('client-added');
            $this->dispatch('notify', message: 'Cliente adicionado com sucesso!');
        } catch (\Exception $e) {
            $this->dispatch('notify', message: 'Ocorreu um erro inesperado ao salvar.', type: 'error');
        }
    }

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