<?php

namespace App\Livewire\Admin\Features\Modals;

use App\Models\Feature;
use App\Models\FeatureGroup;
use Illuminate\Support\Str;
use LivewireUI\Modal\ModalComponent;

class Form extends ModalComponent
{
    public $featureId;

    public $label = '';
    public $key = '';
    public $icon = 'heroicon-o-check';

    public $iconGroups = [
        'Allgemein' => [
            'heroicon-o-check',
            'heroicon-o-x-mark',
            'heroicon-o-star',
            'heroicon-o-bolt',
        ],
        'User' => [
            'heroicon-o-user',
            'heroicon-o-users',
        ],
        'Zeit' => [
            'heroicon-o-calendar',
            'heroicon-o-clock',
        ],
        'System' => [
            'heroicon-o-cog',
            'heroicon-o-wrench',
        ],
    ];

    public $group_id = null;
    public $active = true;

    public $groups = [];

    public function mount($id = null)
    {
        $this->groups = FeatureGroup::orderBy('sort')->get();

        if ($id) {
            $feature = Feature::findOrFail($id);

            $this->featureId = $feature->id;
            $this->label = $feature->label;
            $this->key = $feature->key;
            $this->icon = $feature->icon;
            $this->group_id = $feature->group_id;
            $this->active = $feature->active;
        }
    }

    public function updatedLabel($value)
    {
        if (!$this->featureId) {
            $this->key = Str::slug($value);
        }
    }

    public function save()
    {
        $this->validate([
            'label' => 'required|string|max:255',
            'key' => 'required|string|max:255',
            'group_id' => 'nullable|exists:feature_groups,id',
        ]);

        $feature = Feature::updateOrCreate(
            ['id' => $this->featureId],
            [
                'label' => $this->label,
                'key' => $this->key,
                'icon' => $this->icon,
                'feature_group_id' => $this->group_id,
                'active' => $this->active,
            ]
        );

        // 👉 wichtig für Plan Modal reload
        $this->dispatch('featureCreated', featureId: $feature->id);
        $this->dispatch('closeModal');
    }

    public function render()
    {
        return view('livewire.admin.features.modals.form');
    }
}
