<?php

namespace onespace\tools\activeApi\models\zoho;

use Yii;

/**
 * This is the model class for table "zoho_settings".
 */
class ZohoSettings extends \onespace\tools\activeApi\models\zoho\base\ZohoSettings {
    public static function findByGroup(string $groupName): array {
        return self::findAll(['setting_group' => $groupName]);
    }

    public static function findAllOAuthScope(): array {
        return self::findByGroup('oAuthScope');
    }

    public static function findAllTokens(): array {
        return self::findByGroup('oAuth');
    }

    public static function enableAuthenticated(): bool {
        $model = self::findAuthenticated();
        $model->setting_value = "1";
        return $model->save();
    }

    public static function disableAuthenticated(): bool {
        $model = self::findAuthenticated();
        $model->setting_value = "0";
        return $model->save();
    }

    public static function findAuthenticated(): ZohoSettings {
        return self::findOne([
            'setting_group' => 'scopeAuthenticated',
            'setting_key' => 'authenticated',
        ]);
    }

    public static function newScope(string $settingName): bool {
        $model = new ZohoSettings();
        $model->setting_group = 'oAuthScope';
        $model->setting_key = $settingName;
        $model->setting_value = "1";
        $success = $model->save();

        return $success & self::disableAuthenticated();
    }

    public static function newOrUpdateValue(string $group, string $key, mixed $value): bool {
        $model = ZohoSettings::findOne(['setting_group' => $group, 'setting_key' => $key]);
        if ($model === null) {
            $model = new ZohoSettings(['setting_group' => $group, 'setting_key' => $key]);
        }
        $model->setting_value = (string)$value;
        $success = $model->save();
        if (!$success) {
            Yii::warning(['setting_group' => $group, 'setting_key' => $key], __METHOD__);
            Yii::error($model->getErrors(), __METHOD__);
        }
        return $success;
    }
}
