<?php

namespace App\Livewire;

use App\Models\Park;
use App\Models\ParkArea;
use Livewire\Component;
use Illuminate\Validation\Rule;

class ParkAreaFormComponent extends Component
{
    public Park $park;
    public ?ParkArea $area = null;
    
    // Form fields
    public string $name = '';
    public ?string $description = '';
    public ?string $opening_date = '';
    public ?string $closing_date = '';

    public function mount(Park $park, ?ParkArea $area = null): void
    {
        $this->park = $park;
        $this->area = $area;
        
        if ($area) {
            $this->name = $area->name;
            $this->description = $area->description ?? '';
            $this->opening_date = $area->opening_date?->format('Y-m-d') ?? '';
            $this->closing_date = $area->closing_date?->format('Y-m-d') ?? '';
        }
    }

    public function rules(): array
    {
        $unique = $this->area
            ? Rule::unique('park_areas', 'name')
                ->where('park_id', $this->park->id)
                ->ignore($this->area->id)
            : Rule::unique('park_areas', 'name')
                ->where('park_id', $this->park->id);

        return [
            'name' => ['required', 'string', 'min:2', 'max:255', $unique],
            'description' => ['nullable', 'string'],
            'opening_date' => ['nullable', 'date'],
            'closing_date' => ['nullable', 'date', 'after:opening_date'],
        ];
    }

    public function save(): void
    {
        $data = $this->validate();
        $data['park_id'] = $this->park->id;

        if ($this->area) {
            $this->area->update($data);
            $message = 'Area updated successfully!';
        } else {
            $this->area = ParkArea::create($data);
            $message = 'Area created successfully!';
        }

        session()->flash('message', $message);
        
        $this->redirectRoute('parks.areas.show', [
            'park' => $this->park,
            'area' => $this->area,
        ]);
    }

    public function render()
    {
        return view('livewire.park-area-form-component', [
            'isEditing' => (bool)$this->area,
        ]);
    }
}