<?php

namespace App\Livewire\Settings;

use Livewire\Component;
use App\Models\Zona;

class ZoneIndex extends Component
{
    public string $nuovaZona = '';
    public ?int $editingId = null;
    public string $editingNome = '';

    public function addZona()
    {
        $this->validate(['nuovaZona' => 'required|string|max:100|unique:zone,nome']);
        Zona::create(['nome' => $this->nuovaZona, 'attivo' => true]);
        $this->nuovaZona = '';
        session()->flash('success', 'Zona aggiunta.');
    }

    public function startEdit(int $id)
    {
        $zona = Zona::findOrFail($id);
        $this->editingId = $id;
        $this->editingNome = $zona->nome;
    }

    public function saveEdit()
    {
        $this->validate(['editingNome' => "required|string|max:100|unique:zone,nome,{$this->editingId}"]);
        $zona = Zona::findOrFail($this->editingId);
        $zona->update(['nome' => $this->editingNome]);
        $this->editingId = null;
        $this->editingNome = '';
        session()->flash('success', 'Zona aggiornata.');
    }

    public function cancelEdit()
    {
        $this->editingId = null;
        $this->editingNome = '';
    }

    public function toggleActive(int $id)
    {
        $zona = Zona::findOrFail($id);
        $zona->update(['attivo' => !$zona->attivo]);
    }

    public function deleteZona(int $id)
    {
        $zona = Zona::findOrFail($id);
        if ($zona->territori()->exists()) {
            session()->flash('error', "Impossibile eliminare: la zona '{$zona->nome}' ha territori associati.");
            return;
        }
        $zona->delete();
        session()->flash('success', "Zona '{$zona->nome}' eliminata.");
    }

    public function render()
    {
        return view('livewire.settings.zone-index', [
            'zone' => Zona::orderBy('nome')->get(),
        ]);
    }
}
