<?php

namespace App\Livewire\Settings;

use App\Domain\Shared\Models\SystemSetting;
use App\Domain\Shared\Services\SettingsService;
use Livewire\Attributes\Layout;
use Livewire\Attributes\Title;
use Livewire\Component;

#[Layout('layouts.app')]
#[Title('إعدادات النظام')]
class SystemSettingsForm extends Component
{
    public string $activeGroup = 'general';
    public array $settings = [];
    public array $settingsMeta = [];

    public function mount(): void
    {
        $this->authorize('settings.manage');
        $this->loadSettings();
    }

    public function loadSettings(): void
    {
        $academyId = app('current_academy')?->id;
        if (!$academyId) {
            return;
        }

        $records = SystemSetting::withoutGlobalScope('academy')
            ->where('academy_id', $academyId)
            ->where('group', $this->activeGroup)
            ->get();

        $this->settings = $records->mapWithKeys(fn ($s) => [$s->key => $s->value])->toArray();
        $this->settingsMeta = $records->mapWithKeys(fn ($s) => [
            $s->key => [
                'type' => $s->type,
                'description_ar' => $s->description_ar,
            ],
        ])->toArray();
    }

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

    public function save(SettingsService $service): void
    {
        foreach ($this->settings as $key => $value) {
            $type = $this->settingsMeta[$key]['type'] ?? 'string';
            $service->set($key, $value, $this->activeGroup, $type);
        }
        session()->flash('success', __('تم حفظ الإعدادات بنجاح'));
    }

    public function render()
    {
        $groups = [
            'general' => 'عام',
            'financial' => 'مالي',
            'attendance' => 'حضور',
            'pricing' => 'تسعير',
            'notifications' => 'إشعارات',
            'enrollment' => 'تسجيلات',
        ];

        return view('livewire.settings.system-settings-form', [
            'groups' => $groups,
        ]);
    }
}
