<?php

namespace App\Services;

use App\Models\SystemSetting;
use Illuminate\Support\Collection;

class SettingsService
{
    public function allGrouped(): Collection
    {
        return SystemSetting::query()
            ->orderBy('group')
            ->orderBy('id')
            ->get()
            ->groupBy('group');
    }

    public function emergencyLockEnabled(): bool
    {
        return (bool) optional(SystemSetting::query()->where('key', 'emergency_lock_mode')->first())->typedValue();
    }

    public function get(string $key, mixed $default = null): mixed
    {
        $setting = SystemSetting::query()->where('key', $key)->first();

        return $setting ? $setting->typedValue() : $default;
    }

    public function update(array $payload): void
    {
        $settings = SystemSetting::query()->get()->keyBy('id');

        foreach ($payload as $id => $value) {
            $setting = $settings->get((int) $id);

            if (! $setting) {
                continue;
            }

            $setting->update([
                'value' => match ($setting->type) {
                    'boolean' => $value ? '1' : '0',
                    default => (string) $value,
                },
            ]);
        }
    }
}
