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

    public $company;

    public $current_company_rate = null;

    public $company_rates = [];

    #[Validate('required')] 
    public $amount = '';
    public $type = '';
    public $group = '';
    public $description = '';
    public $enabled = 1;

    public $is_edit = false;

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

    public function render()
    {
        $this->company_rates = $this->company->rates ?? [];
        return view('livewire.company_rate');
    }

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

    public function edit($id)
    {
        $this->resetFields();
        $this->is_edit = true;
        $this->current_company_rate = \App\Models\CompanyRate::findOrFail($id);
        $this->amount = $this->current_company_rate->amount;
        $this->type = $this->current_company_rate->type;
        $this->group = $this->current_company_rate->group;
        $this->description = $this->current_company_rate->description;
        $this->enabled = $this->current_company_rate->enabled == 1;
    }

    public function save()
    {
        $this->validate();
        try 
        {
            if ($this->current_company_rate == null)
            {
                \App\Models\CompanyActivity::create([
                    'company_id' => $this->company->id,
                    'amount' => $this->amount,
                    'type' => $this->type,
                    'group' => $this->group,
                    'description' => $this->description,
                    'enabled' => $this->enabled
                ]);
            }
            else
            {
                $this->current_company_rate->update([
                    'amount' => $this->amount,
                    'type' => $this->type,
                    'group' => $this->group,
                    '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_rate = null;

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

}
