<?php

namespace App\Livewire;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\DB;
use Livewire\Attributes\Validate;
use Livewire\Component;
use Livewire\Attributes\Layout;

class CompanyService extends Component
{

    public $company;

    public $current_company_service = null;

    public $company_services = [];

    #[Validate('required')] 
    public $name = '';
    public $description = '';
    public $enabled = 1;

    public $is_edit = false;

    public function resetFields(){
        $this->name = '';
        $this->description = '';
        $this->enabled = 1;
    }

    public function render()
    {
        $this->company_services = $this->company->services ?? [];
        return view('livewire.company_service');
    }

    public function add()
    {
        $this->resetFields();
        $this->is_edit = true;
        $this->current_company_service = null;
    }

    public function edit($id)
    {
        $this->resetFields();
        $this->is_edit = true;
        $this->current_company_service = \App\Models\CompanyService::findOrFail($id);
        $this->name = $this->current_company_service->name;
        $this->description = $this->current_company_service->description;
        $this->enabled = $this->current_company_service->enabled == 1;
    }

    public function save()
    {
        $this->validate();
        try 
        {
            if ($this->current_company_service == null)
            {
                \App\Models\CompanyService::create([
                    'company_id' => $this->company->id,
                    'name' => $this->name,
                    'description' => $this->description,
                    'enabled' => $this->enabled
                ]);
            }
            else
            {
                $this->current_company_service->update([
                    'name' => $this->name,
                    'description' => $this->description,
                    'enabled' => $this->enabled ? 1 : 0,
                ]);
            }
            session()->flash('success','Dati salvati con successo');
            $this->resetFields();
            $this->is_edit = false;

            $this->dispatch("update");
        } catch (\Exception $ex) {
            session()->flash('error','Errore (' . $ex->getMessage() . ')');
        }
    }

    public function cancel()
    {
        $this->resetFields();
        $this->is_edit = false;
        $this->current_company_service = null;

        $this->dispatch("update");
    }

}
