<?php

namespace App\Services;

use App\Models\Setting;

class GeneralSettingsService
{

    public function getSettings()
    {
        $settings = Setting::get();

        $arrayOfSettings = $settings->map(function ($key) {
            return  [$key->settings_key => $key->settings_value];
        });

        return array_merge(...$arrayOfSettings);
    }

    public function update($settings)
    {
        foreach ($this->prepareToUpdate($settings) as $setting => $value) {
            Setting::updateOrCreate(
                [
                    'settings_key' => $setting
                ],
                [
                    'settings_value' => $value
                ]
            );
        }
    }

    private function prepareToUpdate($data)
    {
        return [
            'user_registeration_is_enabled' => isset($data["allow_register"]) ? 1 : 0,
            'fromName' => $data["from_name"],
            'fromEmail' => $data["from_email"],
            'timezone' => $data["timezone"],
            'mail_signature' => $data["mail_signature"],
        ];
    }
}
