<?php
namespace ModulesGarden\OpenXchangeAddon\App\UI\Admin\Settings\Providers;

use ModulesGarden\OpenXchangeAddon\Core\UI\Interfaces\AdminArea;
use ModulesGarden\OpenXchangeAddon\Core\Models\ModuleSettings\Model;
use ModulesGarden\OpenXchangeAddon\Core\UI\Widget\Forms\DataProviders\BaseDataProvider;
use ModulesGarden\OpenXchangeAddon\App\UI\Admin\Settings\Constants;

class SettingsDataProvider extends BaseDataProvider implements AdminArea
{
    protected $id = 'settingsDataProvider';
    protected $name = 'settingsDataProvider';

    public function read()
    {
        $data = Model::pluck('value', 'setting');
        $colorSettings = [
            'mainColor', 'topbarBackground', 'topbarHover', 'linkHover', 'linkColor', 'listSelectedFocus',
            'listSelected', 'listHover'
        ];
        foreach($colorSettings as $setting)
        {
            $this->data[$setting] = $data[$setting];
            $this->data[$setting.'Picker'] = $data[$setting.'Picker'];
        }

        $textSettings = [
            'logoUrlLight', 'logoUrlDark', 'logoWidth', 'logoHeight'
        ];
        foreach($textSettings as $setting)
        {
            $this->data[$setting] = $data[$setting];
        }

        $configSettings = [
            'portalURL', 'portalName', 'timezone', 'languagedef', 'language', 'autofill'
        ];
        foreach($configSettings as $setting)
        {
            if ($setting == 'language')
            {
                $this->data[$setting] = unserialize($data[$setting]);
            }
            else
            {
                $this->data[$setting] = $data[$setting];
            }
        }

        $timozonesData = [];
        
        foreach (Constants::TIMEZONES as $value)
        {
            $timozonesData += $value;
        }

        $this->availableValues['timezone'] = $timozonesData;
        
        foreach(Constants::LANGUAGES as $name => $language)
        {
            $this->availableValues['language'][$language] = $name;
            $this->availableValues['languagedef'][$language] = $name;
        }
    }

    public function update()
    {
        foreach($this->formData as $setting => $value)
        {
            if (is_array($value))
            {
                Model::updateOrCreate(['setting' => $setting], ['value' => serialize($value)]);
            }
            else
            {
                Model::updateOrCreate(['setting' => $setting], ['value' => $value]);
            }
        }
    }
}
