<?php

namespace Workdo\MobileServiceManagement\Entities;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Factories\HasFactory;

class MobileServiceThemeSetting extends Model
{
    use HasFactory;

    protected $fillable = [
        'name',
        'value',
        'workspace',
        'created_by'
    ];

    private static $allSettings = null;

    public static function getAllSettings($created_by = null, $workspace = null)
    {
        if (self::$allSettings === null) {
            $workspace         = $workspace ?: getActiveWorkSpace();
            $created_by        = $created_by ?: creatorId();
            $settings          = self::where('workspace', $workspace)->where('created_by', $created_by)->get();
            self::$allSettings = $settings->pluck('value', 'name')->toArray();
        }
        return self::$allSettings;
    }

    public static function getSettingsBySlug($slug)
    {
        $workspace = \App\Models\WorkSpace::where('slug', $slug)->first();
        if (!$workspace) {
            return [];
        }

        $settings = self::where('workspace', $workspace->id)->where('created_by', $workspace->created_by)->get();
        return $settings->pluck('value', 'name')->toArray();
    }

    public static function getSetting($name, $default = null, $created_by = null, $workspace = null)
    {
        $allSettings = self::getAllSettings($created_by, $workspace);
        return $allSettings[$name] ?? $default;
    }

    public static function setSetting($name, $value, $created_by = null, $workspace = null)
    {
        $workspace  = $workspace ?: getActiveWorkSpace();
        $created_by = $created_by ?: creatorId();

        $result = self::updateOrCreate(
            [
                'name'       => $name,
                'workspace'  => $workspace,
                'created_by' => creatorId()
            ],
            [
                'value' => $value,
            ]
        );

        self::$allSettings = null;

        return $result;
    }

    public static function setMultipleSettings(array $settings, $created_by = null, $workspace = null)
    {
        $workspace  = $workspace ?: getActiveWorkSpace();
        $created_by = $created_by ?: creatorId();

        foreach ($settings as $key => $value) {
            self::updateOrCreate(
                [
                    'name'       => $key,
                    'workspace'  => $workspace,
                    'created_by' => $created_by,
                ],
                [
                    'value' => $value,
                ]
            );
        }

        self::$allSettings = null;

        return true;
    }
}
