<?php

namespace Components\Support;

/**
 * Class ConfigStorageService
 *
 * Primitive config storage service layer to store/update/delete key value items
 * in TABLE_MAILBEEZ_MODULE_CONFIGURATION.
 *
 * @package Components\Support
 */
class ConfigStorageService
{
    /**
     * @return string
     */
    protected static function getTableName(): string
    {
        if (!defined('TABLE_MAILBEEZ_MODULE_CONFIGURATION')) {
            mh_define('TABLE_MAILBEEZ_MODULE_CONFIGURATION', DB_PREFIX . 'mailbeez_module_configuration');
        }
        return TABLE_MAILBEEZ_MODULE_CONFIGURATION;
    }

    /**
     * Store or update a value.
     *
     * @param string $key
     * @param mixed $value
     */
    public static function set(string $key, $value): void
    {
        $table = static::getTableName();
        mh_db_query("delete from " . $table . " where cfg_key = '" . mh_db_input($key) . "'");

        $sql_data_array = [
            'cfg_key' => $key,
            'cfg_value' => $value,
            'last_modified' => 'now()',
            'date_added' => 'now()'
        ];
        mh_db_perform($table, $sql_data_array);
    }

    /**
     * Read a value.
     *
     * @param string $key
     * @return mixed|false Returns the value or false if not found.
     */
    public static function get(string $key)
    {
        $table = static::getTableName();
        $cfg_query = mh_db_query("select cfg_value from " . $table . " where cfg_key = '" . mh_db_input($key) . "'");
        if (mh_db_num_rows($cfg_query) > 0) {
            $cfg = mh_db_fetch_array($cfg_query);
            return $cfg['cfg_value'];
        }
        return false;
    }

    /**
     * Delete a value.
     *
     * @param string $key
     */
    public static function delete(string $key): void
    {
        $table = static::getTableName();
        mh_db_query("delete from " . $table . " where cfg_key = '" . mh_db_input($key) . "'");
    }

    /**
     * Delete values matching a pattern (SQL LIKE).
     *
     * @param string $pattern
     */
    public static function deletePattern(string $pattern): void
    {
        $table = static::getTableName();
        mh_db_query("delete from " . $table . " where cfg_key like '" . mh_db_input($pattern) . "'");
    }
}
