<?php
namespace App\Livewire\Settings;

use App\Models\Configuration;
use Livewire\Component;

class ConfigurationPanel extends Component
{
    public string $activeGroup = 'general';
    public array $values = [];

    public function mount(): void {
        $this->loadValues();
    }

    public function loadValues(): void {
        $configs = Configuration::forGroup($this->activeGroup)->get();
        $this->values = $configs->pluck('value', 'key')->toArray();
    }

    public function updatedActiveGroup(): void {
        $this->loadValues();
    }

    public function save(): void {
        abort_unless(auth()->user()->hasRole(['superadmin', 'admin']), 403);
        foreach ($this->values as $key => $value) {
            Configuration::set($key, $value);
        }
        Configuration::clearCache();
        $this->dispatch('notify', type: 'success', message: 'Configuración guardada.');
    }

    public function render() {
        $configs = Configuration::forGroup($this->activeGroup)->get();
        return view('livewire.settings.configuration-panel', compact('configs'));
    }
}
