<?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 CompanyActivity extends Component
{

    public $company;

    public $current_company_activity = null;

    public $company_activities = [];

    #[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_activities = $this->company->activities ?? [];
        return view('livewire.company_activity');
    }

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

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

    public function save()
    {
        $this->validate();
        try 
        {
            if ($this->current_company_activity == null)
            {
                \App\Models\CompanyActivity::create([
                    'company_id' => $this->company->id,
                    'name' => $this->name,
                    'description' => $this->description,
                    'enabled' => $this->enabled
                ]);
            }
            else
            {
                $this->current_company_activity->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;
        } catch (\Exception $ex) {
            session()->flash('error','Errore (' . $ex->getMessage() . ')');
        }
    }

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

}
