<?php

namespace MediaTrim\Utils;

/**
 * Class Helper
 *
 * Collection of utility helpers shared across the plugin.
 *
 * @package MediaTrim\Utils
 */
class Helper
{

    /**
     * Generate a unique ID
     *
     * @return string
     */
    public static function generate_unique_id()
    {
        return 'mtrim-' . uniqid();
    }

    /**
     * Get plugin settings
     *
     * @param string $key     The setting key.
     * @param mixed  $default The default value if the setting doesn't exist.
     * @return mixed
     */
    public static function get_plugin_setting($key, $default = null)
    {
        $settings = get_option('mtrim_settings', []);
        return isset($settings[$key]) ? $settings[$key] : $default;
    }

    /**
     * Update plugin settings
     *
     * @param string $key   The setting key.
     * @param mixed  $value The value to save.
     * @return bool
     */
    public static function update_plugin_setting($key, $value)
    {
        $settings = get_option('mtrim_settings', []);
        $settings[$key] = $value;
        return update_option('mtrim_settings', $settings);
    }

    /**
     * Check if a plugin is active
     *
     * @param string $plugin_path The path to the plugin file.
     * @return bool
     */
    public static function is_plugin_active($plugin_path)
    {
        return in_array($plugin_path, (array) get_option('active_plugins', []), true) || self::is_plugin_active_for_network($plugin_path);
    }

    /**
     * Check if a plugin is active for the entire network
     *
     * @param string $plugin_path The path to the plugin file.
     * @return bool
     */
    public static function is_plugin_active_for_network($plugin_path)
    {
        if (!is_multisite()) {
            return false;
        }

        $plugins = get_site_option('active_sitewide_plugins');
        if (isset($plugins[$plugin_path])) {
            return true;
        }

        return false;
    }

    /**
     * Sanitize HTML classes
     *
     * @param string|array $classes The classes to sanitize.
     * @return string
     */
    public static function sanitize_html_classes($classes)
    {
        if (!is_array($classes)) {
            $classes = explode(' ', $classes);
        }

        $classes = array_map('sanitize_html_class', $classes);
        return implode(' ', $classes);
    }

    /**
     * Get installed WordPress Plugin List
     *
     * @return array
     */
    public static function get_plugins()
    {
        if (!function_exists('get_plugins')) {
            require_once MTRIM_PLUGIN_PATH . 'wp-admin/includes/plugin.php';
        }
        return get_plugins();
    }
}
