<?php

namespace App\Livewire;

use Livewire\Component;
use Livewire\Attributes\Validate;

class Resource extends Component
{

    #[Validate('required')] 
    public $first_name = '';
    public $last_name = '';
    public $birth_day = null;
    public $birth_place_id = null;
    public $fiscal_code = '';
    public $phone = '';
    public $email = '';
    public $address = '';
    public $zip = '';
    public $city_id = null;
    public $country_id = null;
    public $domicile = '';
    public $enabled = true;

    public $current_resource = null;

    public $is_edit = false;

    public function render()
    {

        // Get Resource
        $this->current_resource = \App\Models\Resource::first();

        if ($this->current_resource != null)
        {

            $this->first_name = $this->current_resource->first_name;
            $this->last_name = $this->current_resource->last_name;
            $this->birth_day = $this->current_resource->birth_day;
            $this->birth_place_id = $this->current_resource->birth_place_id;
            $this->fiscal_code = $this->current_resource->fiscal_code;
            $this->phone = $this->current_resource->phone;
            $this->email = $this->current_resource->email;
            $this->address = $this->current_resource->address;
            $this->zip = $this->current_resource->zip;
            $this->city_id = $this->current_resource->city_id;
            $this->country_id = $this->current_resource->country_id;
            $this->domicile = $this->current_resource->domicile;
            $this->enabled = $this->current_resource->enabled;

        }

        return view('livewire.resource');
    }

    public function update()
    {

        $this->validate();

        try {
            $this->current_resource->update([
                'first_name' => $this->first_name,
                'last_name' => $this->last_name,
                'birth_day' => $this->birth_day,
                'birth_place_id' => $this->birth_place_id,
                'fiscal_code' => $this->fiscal_code,
                'phone' => $this->phone,
                'email' => $this->email,
                'address' => $this->address,
                'zip' => $this->zip,
                'city_id' => $this->city_id,
                'country_id' => $this->country_id,
                'domicile' => $this->domicile,
                'enabled' => $this->enabled,
            ]);
            session()->flash('success','Dato aggiornato');
            //$this->resetFields();
            $this->is_edit = false;
        } catch (\Exception $ex) {
            session()->flash('error','Errore (' . $ex->getMessage() . ')');
        }

    }

}
