<?php

namespace App\Livewire\Admin;

use App\Models\RentalType;
use Illuminate\Support\Str;
use Livewire\Component;

class RentalTypes extends Component
{
    public $name = '';
    public $description = '';
    public $editingId = null;

    public function save()
    {
        $this->validate([
            'name' => 'required|string|max:255',
            'description' => 'nullable|string',
        ]);

        if ($this->editingId) {
            $rentalType = RentalType::find($this->editingId);
            $rentalType->update([
                'name' => $this->name,
                'slug' => Str::slug($this->name),
                'description' => $this->description,
            ]);
            session()->flash('message', 'Rental type updated successfully!');
        } else {
            RentalType::create([
                'name' => $this->name,
                'slug' => Str::slug($this->name),
                'description' => $this->description,
            ]);
            session()->flash('message', 'Rental type created successfully!');
        }

        $this->reset(['name', 'description', 'editingId']);
    }

    public function edit($id)
    {
        $rentalType = RentalType::findOrFail($id);
        $this->editingId = $id;
        $this->name = $rentalType->name;
        $this->description = $rentalType->description;
    }

    public function delete($id)
    {
        RentalType::findOrFail($id)->delete();
        session()->flash('message', 'Rental type deleted successfully!');
    }

    public function cancel()
    {
        $this->reset(['name', 'description', 'editingId']);
    }

    public function render()
    {
        $rentalTypes = RentalType::withCount('listings')->get();

        return view('livewire.admin.rental-types', compact('rentalTypes'))
            ->layout('layouts.app');
    }
}
