<?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,
                'label_ar' => $s->label_ar,
                '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', __('تم حفظ الإعدادات بنجاح'));
    }

    /**
     * Settings that should only be visible when their parent boolean is enabled.
     * Format: 'child_key' => 'parent_boolean_key'
     */
    public static array $dependsOn = [
        'absence_penalty_amount' => 'trainer_absence_penalty_enabled',
        'late_penalty_amount' => 'trainer_late_penalty_enabled',
        'cancelled_session_pay_percent' => 'cancelled_session_pay_enabled',
        'social_insurance_percent' => 'social_insurance_enabled',
    ];

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

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