<?php

namespace App\Livewire\Settings;

use App\Models\VehicleType;
use Livewire\Component;
use Livewire\WithPagination;

class VehicleTypeIndex extends Component
{
    use WithPagination;

    public bool $isEditing = false;

    public ?int $vehicleTypeId = null;

    public string $name = '';

    protected function rules()
    {
        return [
            'name' => 'required|string|max:255|unique:vehicle_types,name,'.$this->vehicleTypeId,
        ];
    }

    public function create()
    {
        $this->isEditing = false;
        $this->reset(['name', 'vehicleTypeId']);
        $this->dispatch('open-modal');
    }

    public function edit(VehicleType $vehicleType)
    {
        $this->isEditing = true;
        $this->vehicleTypeId = $vehicleType->id;
        $this->name = $vehicleType->name;
        $this->dispatch('open-modal');
    }

    public function save()
    {
        $this->validate();

        if ($this->isEditing) {
            $vehicleType = VehicleType::findOrFail($this->vehicleTypeId);
            $vehicleType->update(['name' => $this->name]);
            session()->flash('flash.banner', 'Vehicle type updated successfully!');
        } else {
            VehicleType::create(['name' => $this->name]);
            session()->flash('flash.banner', 'Vehicle type created successfully!');
        }

        $this->dispatch('close-modal');
    }

    public function delete(VehicleType $vehicleType)
    {
        // Optional: Check if the type is in use before deleting
        // if ($vehicleType->vehicles()->count() > 0) {
        //     session()->flash('flash.banner', 'This vehicle type is in use and cannot be deleted.');
        //     session()->flash('flash.bannerStyle', 'danger');
        //     return;
        // }

        $vehicleType->delete();
        session()->flash('flash.banner', 'Vehicle type deleted successfully.');
    }

    public function render()
    {
        $vehicleTypes = VehicleType::latest()->paginate(10);

        return view('livewire.settings.vehicle-type-index', [
            'vehicleTypes' => $vehicleTypes,
        ]);
    }
}
