<?php


class mailbeez_configuration_wrapper
{

    static $gx_namespace = 'mailbeez';

    static function update($config_array)
    {
        return self::insert($config_array, true);
    }

    /**
     * @param string $key
     * @param string $value
     * @param array $meta
     */

    static function insertOrUpdate($key, $value, $meta = array())
    {
        $title = isset($meta['title']) ? $meta['title'] : 'MailBeez configuration setting';
        $description = isset($meta['description']) ? $meta['description'] : 'This is automatically updated. No need to edit.';

        $configData = self::read($key);

        if ($configData['result'] === true) {
            return self::update(
                array(
                    'configuration_key' => $key,
                    'configuration_value' => $value
                )
            );
        } else {
            return self::insert(array(
                'configuration_key' => $key,
                'configuration_value' => $value,
                'set_function' => ''
            ));
        }

    }


    static function insert($config_array, $do_update = false)
    {
        if (mh_cfg('MH_PLATFORM_GAMBIO_GX_CONFIGURATION')) {
            // Gambio GX4.2+ configuration service

            $key = $config_array['configuration_key'];


            /* GX4.5+ */
            /** @var Gambio\Core\Configuration\Services\ConfigurationService $service */
            /* GX4.2+ */
            /** @var Gambio\Core\Configuration\ConfigurationService $service */
            $service = self::getGxService();


            $current_config_array = self::read($key);
            if ($do_update) {
                // update
                unset($current_config_array['result']);
                $config_array = array_merge($current_config_array, $config_array);
                if (version_compare(MH_PLATFORM_GAMBIO_GX_VERSION, '4.5', '>=')) {
                    $service->save(self::qKey($key), self::encodeValue($config_array));
                } else {
                    $service->save(Gambio\Core\Configuration\Models\Write\Configuration::create(self::qKey($key), self::encodeValue($config_array)));
                }
            } else {
                // write / do not overwrite
                if ($current_config_array['result'] == false) {
                    if (version_compare(MH_PLATFORM_GAMBIO_GX_VERSION, '4.5', '>=')) {
                        $service->save(self::qKey($key), self::encodeValue($config_array));
                    } else {
                        $service->save(Gambio\Core\Configuration\Models\Write\Configuration::create(self::qKey($key), self::encodeValue($config_array)));
                    }
                }
            }

        } else {


            $title = addslashes(htmlspecialchars(isset($config_array['configuration_title']) ? $config_array['configuration_title'] : 'title_' . $config_array['configuration_key']));
            $description = addslashes(htmlspecialchars(isset($config_array['configuration_description']) ? $config_array['configuration_description'] : 'description_' . $config_array['configuration_key']));


            $check_query = mh_db_query("SELECT configuration_value FROM " . TABLE_CONFIGURATION . " WHERE configuration_key = '" . $config_array['configuration_key'] . "'");
            if (mh_db_num_rows($check_query) > 0 && !$do_update) {
                // config already exists, do not update
                return false;
            } elseif (mh_db_num_rows($check_query) > 0 && $do_update) {
                // config already exists, perform update

                $update = array();

                if (isset($config_array['configuration_value'])) {
                    $update[] = "configuration_value = '" . addslashes($config_array['configuration_value']) . "'";
                }
                if (isset($config_array['use_function'])) {
                    $update[] = "use_function = '" . addslashes($config_array['use_function']) . "'";
                }
                if (isset($config_array['set_function'])) {
                    $update[] = "set_function = '" . addslashes($config_array['set_function']) . "'";
                }

                if (count($update) > 0) {
                    $update_str = implode(', ', $update);
                    $result = mh_db_query("update " . TABLE_CONFIGURATION . " set " . $update_str . ", last_modified = now() where configuration_key = '" . $config_array['configuration_key'] . "'");
                    mh_reset_config_cache();
                }
                return $result;
            }

            if (!isset($config_array['set_function'])) {
                $config_array['set_function'] = '';
            }
            if (!isset($config_array['use_function'])) {
                $config_array['use_function'] = '';
            }

            // no config value yet, insert:
            // otherwise insert config
            switch (MH_PLATFORM) {
                case 'oscommerce':
                case 'creloaded':
                case 'digistore':
                case 'zencart':
                    return mh_db_query("INSERT INTO " . TABLE_CONFIGURATION . " (configuration_title, configuration_description, configuration_key, configuration_value, configuration_group_id, sort_order, set_function, use_function, date_added) VALUES ('" . $title . "', '" . $description . "', '" . $config_array['configuration_key'] . "', '" . addslashes($config_array['configuration_value']) . "', '6', '1', '" . addslashes($config_array['set_function']) . "', '" . addslashes($config_array['use_function']) . "', now())");
                    break;
                case 'mercari':
                    return mh_db_query("INSERT INTO " . TABLE_CONFIGURATION . " ( configuration_key, configuration_value, configuration_group_id, sort_order, set_function, use_function, date_added) VALUES ('" . $config_array['configuration_key'] . "', '" . addslashes($config_array['configuration_value']) . "',  '6', '1', '" . addslashes($config_array['set_function']) . "', '" . addslashes($config_array['use_function']) . "', now())");
                    break;
                case 'xtc':
                case 'gambio':
                    return xtc_db_query("INSERT INTO " . TABLE_CONFIGURATION . " ( configuration_key, configuration_value, configuration_group_id, sort_order, set_function, use_function, date_added) VALUES ('" . $config_array['configuration_key'] . "', '" . addslashes($config_array['configuration_value']) . "',  '6', '1', '" . addslashes($config_array['set_function']) . "', '" . addslashes($config_array['use_function']) . "', now())");
                    break;
                default:
                    echo 'platform not supported';
            }
        }
    }

    /**
     * @param string $config_key
     * @return array
     */

    static function read($config_key)
    {
        $result = false;
        $value = null;
        $title = null;
        $description = null;
        $use_function = null;
        $set_function = null;
        if (mh_cfg('MH_PLATFORM_GAMBIO_GX_CONFIGURATION')) {
            // Gambio GX4.2+ configuration service
//            $service = ;
            $configItem = self::getGxService()->find(self::qKey($config_key));
            if ($configItem) {
                $result = true;

                // handle is_cloud
                if ($config_key == 'is_cloud') {
                    $value = $configItem->value();
                    $title = '';
                    $description = '';
                    $use_function = '';
                    $set_function = '';
                } else {
                    $valueArray = self::decodeValue($configItem->value());
                    $value = $valueArray['configuration_value'];
                    $title = 'deprecated';
                    $description = 'deprecated';
                    $use_function = $valueArray['use_function'];
                    $set_function = $valueArray['set_function'];
                }
            }
        } else {
            $check_query = mh_db_query("SELECT configuration_value, use_function, set_function FROM " . TABLE_CONFIGURATION . " WHERE configuration_key = '" . $config_key . "'");
            if (mh_db_num_rows($check_query)) {
                $check = mh_db_fetch_array($check_query);
                $result = true;
                $value = $check['configuration_value'];
                $title = 'deprecated';
                $description = 'deprecated';
                $use_function = $check['use_function'];
                $set_function = $check['set_function'];
            }
        }
        return array(
            'result' => $result,
            'value' => $value,
            'use_function' => $use_function,
            'set_function' => $set_function
        );
    }

    /**
     * @param string|array $config_key_or_array
     * @return boolean
     */


    static function delete($config_key_or_array)
    {
        if (mh_cfg('MH_PLATFORM_GAMBIO_GX_CONFIGURATION')) {

            // Gambio GX4.2+ configuration service
            if (is_array($config_key_or_array)) {
                $qKeyArray = array();
                foreach ($config_key_or_array as $key) {
                    $qKeyArray[] = self::qKey($key);
                }
                return mh_db_query("DELETE FROM gx_configurations WHERE `key` in ('" . implode("', '", $qKeyArray) . "')");
            } else {
                return mh_db_query("DELETE FROM gx_configurations WHERE `key` = '" . self::qKey($config_key_or_array) . "'");
            }
        } else {
            if (is_array($config_key_or_array)) {
                return mh_db_query("DELETE FROM " . TABLE_CONFIGURATION . " WHERE configuration_key in ('" . implode("', '", $config_key_or_array) . "')");
            } else {
                return mh_db_query("DELETE FROM " . TABLE_CONFIGURATION . " WHERE configuration_key = '" . $config_key_or_array . "'");
            }
        }
    }


    /**
     * @param string $config_key_like
     * @param string $except_config_key
     * @return boolean
     */

    static function deleteLike($config_key_like, $except_config_key = null)
    {
        if (mh_cfg('MH_PLATFORM_GAMBIO_GX_CONFIGURATION')) {
            // Gambio GX4.2+ configuration service
            if (is_null($except_config_key)) {
                return mh_db_query("DELETE FROM gx_configurations WHERE `key` LIKE'" . self::qKey($config_key_like) . "'");
            } else {
                return mh_db_query("DELETE FROM gx_configurations WHERE `key` LIKE'" . self::qKey($config_key_like) . "%' and `key` != '" . self::qKey($except_config_key) . "'");
            }
        } else {
            if (is_null($except_config_key)) {
                return mh_db_query("DELETE FROM " . TABLE_CONFIGURATION . " WHERE configuration_key LIKE '" . $config_key_like . "%'");
            } else {
                return mh_db_query("DELETE FROM " . TABLE_CONFIGURATION . " WHERE configuration_key LIKE '" . $config_key_like . "%' and configuration_key != '" . $except_config_key . "'");
            }
        }
    }


    static function getGxService()
    {
        if (class_exists(LegacyDependencyContainer::class)) {
            $container = LegacyDependencyContainer::getInstance();

            if (version_compare(MH_PLATFORM_GAMBIO_GX_VERSION, '4.5', '>=')) {
                /* GX4.5+ */
                /** @var Gambio\Core\Configuration\Services\ConfigurationService $service */
                $service = $container->get(Gambio\Core\Configuration\Services\ConfigurationService::class);
            } else {

                /* GX4.2+ */
                /** @var Gambio\Core\Configuration\ConfigurationService $service */
                $service = $container->get(Gambio\Core\Configuration\ConfigurationService::class);
            }
            $service->find('namespace/config');
            return $service;
        }
        return false;
    }

    /*
     * return qualified Key with namespace
     *
     * @var $key
     *
     */

    static function qKey($key)
    {
        if ($key == 'is_cloud') {
            return 'gm_configuration/is_cloud';
        }

        return self::$gx_namespace . '/' . $key;
    }


    /**
     * encode configuration array to value json
     *
     * @param $value_array
     * @return false|mixed|string
     */

    static function encodeValue($value_array)
    {
        $value = [];

        $value['value'] = $value_array['configuration_value'];
        $value['set_function'] = isset($value_array['set_function']) ? $value_array['set_function'] : '';
        $value['use_function'] = isset($value_array['use_function']) ? $value_array['use_function'] : '';

        return json_encode($value);
    }

    /**
     * decode Value json
     *
     * @param $value_json
     * @return array
     */

    static function decodeValue($value_json)
    {
        $valueArrayRaw = json_decode($value_json, true);
        $valueArray = [];
        $valueArray['configuration_value'] = $valueArrayRaw['value'];
        $valueArray['set_function'] = isset($valueArrayRaw['set_function']) ? $valueArrayRaw['set_function'] : '';
        $valueArray['use_function'] = isset($valueArrayRaw['use_function']) ? $valueArrayRaw['use_function'] : '';

        return $valueArray;
    }

}