<?php

namespace App\Services\Settings;

use App\Models\Configuration;
use App\Models\Setting;
use Illuminate\Support\Facades\DB;

class SettingsService
{
    public function get(): array
    {
        $settings = Setting::singleton();

        return [
            'site_name' => $settings->name,
            'timezone' => $settings->timezone,
            'administrator_email' => Configuration::getConfig('administrator_email') ?? '',
        ];
    }

    public function update(array $payload, int $userId): array
    {
        return DB::transaction(function () use ($payload, $userId) {
            $settings = Setting::singleton();

            $updates = [];
            if (array_key_exists('site_name', $payload)) {
                $updates['name'] = $payload['site_name'];
            }
            if (array_key_exists('timezone', $payload)) {
                $updates['timezone'] = $payload['timezone'];
            }

            if (!empty($updates)) {
                $updates['updated_by'] = $userId;
                $settings->fill($updates);
                $settings->save();
            }

            if (array_key_exists('administrator_email', $payload)) {
                Configuration::setConfigValueByKey('administrator_email', (string) $payload['administrator_email']);
            }

            return $this->get();
        });
    }
}
