<?php
namespace App\Livewire\Task;

use Livewire\Component;
use App\Models\Task;

class Form extends Component
{
    public $model;
	public string $name;
	public string $description = "";

    public $action = 'store';

    protected function rules()
    {
        return [
			'name' => 'required',
			'description' => 'required',
        ];
    }

    public function mount ($model = null){
        if (!empty($model)) {
            $task = Task::find($model);

            $this->model = $model;

            $this->name = $task->name;
			$this->description = $task->description;

            $this->action = 'update';
        }
    }

    public function store()
    {
        $validatedData = $this->validate();
        Task::create($validatedData);
        $this->dispatch('closeModal');
    }

    public function update()
    {
        $validatedData = $this->validate();
        $task = Task::find($this->model);
        if (!empty($task)) {
            $task->update($validatedData);
        }
        $this->dispatch('closeModal');
    }

    public function render()
    {
        return view('livewire.task.form');
    }
}