<?php

namespace App\Livewire;

use Livewire\Component;
use App\Models\SubCounty;
use App\Models\SubCounty as SubCountyModel;
use Livewire\Attributes\On;

class Subcounties extends Component
{
	protected $listeners=['openAddModal','editSubCounty'];
	
	// add the properties for input fields
	public $SubCountyID;
    public $SubCountyName;
	
	protected $rules = [
        'SubCountyName' => 'required',
    ];
	
	protected $messages = [
        'SubCountyName.required' => 'SubCounty name is required'
    ];
	
    public function render()
    {
        return view('livewire.subcounties');
    }
	
	// add new subcounty
    public function saveSubCounty()
    {
        // validate the data
        $this->validate();
		
		if(SubCountyModel::where('SubCountyName', $this->SubCountyName)->exists()){
			//toast
			$this->dispatch('alert', [
				'type' => 'error',
				'message' => "SubCounty already exists!",
			]);
			return;
		}

		$subcounty=SubCountyModel::create([
            'SubCountyName' => $this->SubCountyName
        ]);
		
		$this->resetFields();
		
		//event
        $this->dispatch('closeModal', 'addModal');
		$this->dispatch('refreshDatatable');
		
		//toast
        $this->dispatch('alert', [
            'type' => 'success',
            'message' => "SubCounty Added Successfully!",
        ]);
    }
	
	//edit subcounty
	#[Renderless]
    public function editSubCounty($id)
    {
		$subcounty = SubCountyModel::find($id);
		
		if($subcounty){
			$this->SubCountyID = $subcounty->SubCountyID;
			$this->SubCountyName=$subcounty->SubCountyName;
			$this->resetValidation();
			$this->dispatch('openModal', 'editModal');
		}
		else{
            return redirect()->back();
        }
		$this->skipRender();
    }
	
	public function updateSubCounty()
    {
        $this->validate();

		$subcounty = SubCountyModel::find($this->SubCountyID);
		$subcounty->SubCountyName=$this->SubCountyName;
		$subcounty->save();
		
        $this->resetFields();
		
		//event
        $this->dispatch('closeModal', 'editModal');
		$this->dispatch('refreshDatatable');
		
		//toast
        $this->dispatch('alert', [
            'type' => 'success',
            'message' => "SubCounty Updated Successfully!",
        ]);
    }
	
	public function resetFields()
    {
        $this->resetValidation();
        $this->SubCountyName = '';
      
    }
	
	public function openAddModal()
    {
        $this->resetValidation();
        $this->SubCountyName = '';
		$this->dispatch('openModal', 'addModal');
    }
	
	#[On('subcounty-deleted')]
    public function deleteSubCounty($id)
    {
		$deletesubcounty=SubCountyModel::find($id)->delete();
		$this->dispatch('refreshDatatable');
		
		//toast
		$this->dispatch('alert', [
			'type' => 'success',
			'message' => "SubCounty deleted Successfully!!",
		]);

    }
	
}
