<?php

/**
 * The admin-specific functionality of the plugin.
 *
 * @link       https://wwdh.de
 * @since      1.0.0
 *
 * @package    Wp_Oauth2_Client
 * @subpackage Wp_Oauth2_Client/admin
 */

use Twig\Environment;
use Twig\Error\LoaderError;
use Twig\Error\RuntimeError;
use Twig\Error\SyntaxError;
use WPOauth2\Client\OauthSettings;
use Firebase\JWT\JWK;
use Firebase\JWT\JWT;
use YahnisElsts\PluginUpdateChecker\v5\PucFactory;

/**
 * The admin-specific functionality of the plugin.
 *
 * Defines the plugin name, version, and two examples hooks for how to
 * enqueue the admin-specific stylesheet and JavaScript.
 *
 * @package    Wp_Oauth2_Client
 * @subpackage Wp_Oauth2_Client/admin
 * @author     Jens Wiecker <plugin@wwdh.de>
 */
class Wp_Oauth2_Client_Admin
{

    use OauthSettings;


    /**
     * Store plugin main class to allow admin access.
     *
     * @since    2.0.0
     * @access   private
     * @var Wp_Oauth2_Client $main The main class.
     */
    protected Wp_Oauth2_Client $main;

    /**
     * TWIG autoload for PHP-Template-Engine
     * the plugin.
     *
     * @since    1.0.0
     * @access   protected
     * @var      Environment $twig TWIG autoload for PHP-Template-Engine
     */
    protected Environment $twig;

    /**
     * The ID of this plugin.
     *
     * @since    1.0.0
     * @access   private
     * @var      string $basename The ID of this plugin.
     */
    private string $basename;

    /**
     * The version of this plugin.
     *
     * @since    1.0.0
     * @access   private
     * @var      string $version The current version of this plugin.
     */
    private string $version;
    protected array $settings;

    /**
     * Initialize the class and set its properties.
     *
     * @param string $plugin_name The name of this plugin.
     * @param string $version The version of this plugin.
     *
     * @since       1.0.0
     */
    public function __construct(string $plugin_name, string $version, Wp_Oauth2_Client $main, Environment $twig)
    {

        $this->basename = $plugin_name;
        $this->version = $version;
        $this->main = $main;
        $this->twig = $twig;
        $this->settings = $this->get_oauth_defaults();

    }

    public function register_wp_oauth2_client_admin_menu(): void
    {
        if ($this->main->check_wp_cron()) {
            add_menu_page(
                __('Lizenzen', 'wp-oauth2-client'),
                __('Lizenzen', 'wp-oauth2-client'),
                get_option('wp_oauth2_client_settings')['selected_user_role'],
                'wp-oauth2-client',
                '',
                $this->get_svg_icons('cloud_sync')
                , 2
            );

            $hook_suffix = add_submenu_page(
                'wp-oauth2-client',
                __('Produkte', 'wp-oauth2-client'),
                __('Produkte', 'wp-oauth2-client'),
                get_option('wp_oauth2_client_settings')['selected_user_role'],
                'wp-oauth2-client',
                array($this, 'wp_oauth2_client_login'));

            add_action('load-' . $hook_suffix, array($this, 'wp_oauth2_client_load_ajax_admin_options_script'));

            $hook_suffix = add_submenu_page(
                'wp-oauth2-client',
                __('Einstellungen', 'wp-oauth2-client'),
                __('Einstellungen', 'wp-oauth2-client'),
                get_option('wp_oauth2_client_settings')['selected_user_role'],
                'wp-oauth2',
                array($this, 'wp_oauth2_client_settings'));

        } else {
            $hook_suffix = add_menu_page(
                __('<span class="footer-red">Lizenzen Error</span>', 'wp-oauth2-client'),
                __('<span class="footer-red">Lizenzen Error<span class="text-danger">', 'wp-oauth2-client'),
                get_option('wp_oauth2_client_settings')['selected_user_role'],
                'wp-oauth2-client-cron-error',
                array($this, 'wp_oauth2_error_client_login'),
                $this->get_svg_icons('cloud_sync')
                , 2,
            );
        }
        add_action('load-' . $hook_suffix, array($this, 'wp_oauth2_client_load_ajax_admin_options_script'));
    }

    public function wp_oauth2_error_client_login(): void
    {
        $activesTheme = apply_filters($this->basename . '/current_theme_directory', '');
        $data = [
            'db' => WP_OAUTH2_CLIENT_DB_VERSION,
            'version' => $this->version,
            'theme' => $activesTheme,
        ];
        try {
            $template = $this->twig->render('@templates/wp-oauth2-wp-cron-error.html.twig', $data);
            echo $this->html_compress_template($template);
        } catch (LoaderError|SyntaxError|RuntimeError $e) {
            echo $e->getMessage();
        } catch (Throwable $e) {
            echo $e->getMessage();
        }
    }

    public function wp_oauth2_client_settings(): void
    {

        $activesTheme = apply_filters($this->basename . '/current_theme_directory', '');
        $error = '';
        $error_title = '';
        $error_msg = '';
        $isAuthentifiziert = '';
        $apiData = get_option($this->basename . '/oauth_api_data') ?? NULL;
        if ($apiData) {
            $isAuthentifiziert = $apiData['authentifizierung'];
        }
        $settings = get_option('wp_oauth2_client_settings');
        if ($isAuthentifiziert) {
            $getApiCal = apply_filters($this->basename . '/oauth2_get_client_data', '', true);

            if (isset($getApiCal['status']) && !$getApiCal['status']) {
                $error_title = $getApiCal['error_title'];
                $error_msg = $getApiCal['error_msg'];
            }

            if (isset($getApiCal['scope'])) {
                apply_filters($this->basename . '/set_client_scopes', $getApiCal['scope']);
            }

            $settings = get_option('wp_oauth2_client_settings');
        }

        $data = [
            's' => $settings,
            'select' => $this->get_oauth_defaults('select_user_role'),
            'db' => WP_OAUTH2_CLIENT_DB_VERSION,
            'version' => $this->version,
            'theme' => $activesTheme,
            'error' => $error,
            'error_title' => $error_title,
            'error_msg' => $error_msg,
            'isAuthentifiziert' => $isAuthentifiziert
        ];

        try {
            $template = $this->twig->render('@templates/wp-oauth2-client.html.twig', $data);
            echo $this->html_compress_template($template);
        } catch (LoaderError|SyntaxError|RuntimeError $e) {
            echo $e->getMessage();
        } catch (Throwable $e) {
            echo $e->getMessage();
        }
    }

    public function wp_oauth2_client_login(): void
    {
        //do_action('wp_oauth_client_sync');
        $settings = get_option('wp_oauth2_client_settings');
        $apiData = get_option($this->basename . '/oauth_api_data');
        $lizenz = [];
        $isAuthentifiziert = $apiData['authentifizierung'] ?? '';
        $apiCall = [];
        if ($isAuthentifiziert) {
            $apiCall = apply_filters($this->basename . '/oauth2_get_client_data', null);
        }

        $errorApi = [];
        $error = '';
        if (isset($apiCall['status']) && !$apiCall['status']) {
            $errorApi = $apiCall;
        }
        if (!$settings['client_scopes']) {
            $settings['client_scopes'] = 'BASIC PRODUKT';
        }
        if (
            !$settings['server_url'] ||
            !$settings['authorize_uri'] ||
            !$settings['token_uri'] ||
            !$settings['app_id'] ||
            !$settings['app_secret'] ||
            !$settings['callback_url']
        ) {
            $error = 'Ungültige Settings! OAuth2 Einstellungen überprüfen.';
        }

        $authorizeServer = $settings['server_url'] . '/' . $settings['authorize_uri'];
        $params = [
            'response_type' => 'code',
            'client_id' => $settings['app_id'],
            'redirect_uri' => $settings['callback_url'],
            'scope' => $settings['client_scopes'],
           // 'scope' => $settings['client_scopes'],
        ];
        $authUrl = $authorizeServer . '?' . http_build_query($params);
        if ($apiCall && isset($apiCall['lizenz_products'])) {
            update_option($this->basename . '/lizenz_products', $apiCall['lizenz_products']);
        }

        if ($apiCall && isset($apiCall['lizenz_data'])) {

            update_option($this->basename . '/lizenz_data', $apiCall['lizenz_data']);
            $userData = [
                'email' => $apiCall['email'],
                'logged_in_email' => $apiCall['logged_in_email'],
                'vorname' => $apiCall['vorname'],
                'nachname' => $apiCall['nachname'],
                'cronjob' => $apiCall['cronjob'],
                'scope' => $apiCall['scope']
            ];
            update_option($this->basename . '/user_license_data', $userData);

            $isInstall = false;
            foreach (get_option($this->basename . '/lizenz_data') as $tmp) {

                if ($tmp['aktiv']) {
                    $aktiv = 1;
                } else {
                    $aktiv = 0;
                }
                update_option($tmp['config']['basename'] . '_product_install_authorize', $aktiv);

                if ($tmp['config']['type'] == 'theme') {
                    if ($tmp['config']['basename'] == 'starter-theme-v2') {
                        if (str_replace(['v', '.'], '', $tmp['version']) < 206) {
                            continue;
                        }
                    }
                    $isInstall = apply_filters($this->basename . '/is_theme_install', $tmp['config']['basename']);
                    if ($isInstall) {
                        $currentTheme = apply_filters($this->basename . '/current_theme_directory', '');
                        if ($currentTheme != $tmp['config']['basename']) {
                            $tmp['config']['is_activated'] = false;
                        } else {
                            $tmp['config']['is_activated'] = true;
                        }
                    }
                    $filePath = get_theme_root() . '/' . $tmp['config']['basename'] . '/' . $tmp['config']['aktivierungs_file_path'];
                    if (is_file($filePath)) {
                        if ($aktiv) {
                            $tmp['is_file'] = 1;
                        } else {
                            $tmp['is_file'] = 0;
                            unlink($filePath);
                        }
                    } else {
                        if ($aktiv && $isInstall) {
                            $file = apply_filters($this->basename . '/product_download', '/api/' . $tmp['product_license'] . '/aktivierungs-file');
                            @file_put_contents($filePath, $file);
                        }
                        $tmp['is_file'] = 0;
                    }
                }

                if ($tmp['config']['type'] == 'plugin') {
                    $isInstall = apply_filters($this->basename . '/is_product_install', $tmp['config']['basename']);
                    if (is_plugin_active($tmp['config']['basename'] . '/' . $tmp['config']['basename'] . '.php')) {
                        $tmp['config']['is_activated'] = true;
                    }

                    $filePath = WP_PLUGIN_DIR . '/' . $tmp['config']['basename'] . '/' . $tmp['config']['aktivierungs_file_path'];
                    if (is_file($filePath)) {
                        if ($aktiv) {
                            $tmp['is_file'] = 1;
                        } else {
                            $tmp['is_file'] = 0;
                            unlink($filePath);
                        }
                    } else {
                        if ($aktiv && $isInstall) {
                            $file = apply_filters($this->basename . '/product_download', '/api/' . $tmp['product_license'] . '/aktivierungs-file');
                            @file_put_contents($filePath, $file);
                        }
                        $tmp['is_file'] = 0;
                    }
                }
                $download_uri = $settings['server_url'] . '/api/' . $tmp['product_license'] . '/token?redirect=' . urlencode(site_url());
                $tmp['is_install'] = $isInstall;
                $tmp['download_token'] = $download_uri;
                $lizenz[] = $tmp;
            }

            if (!$apiCall['cronjob']) {
                if ($settings['cron_sync_interval']) {
                    $settings['cron_sync_interval'] = '';
                    wp_clear_scheduled_hook('wp_oauth_client_sync');
                    update_option('wp_oauth2_client_settings', $settings);
                }
            }
            if ($settings['cron_sync_interval'] != $apiCall['cronjob']) {
                if ($apiCall['cronjob']) {
                    wp_clear_scheduled_hook('wp_oauth_client_sync');
                    @apply_filters($this->basename . '/fn_oath2_client_run_schedule_task', false);
                    $settings['cron_sync_interval'] = $apiCall['cronjob'];
                    update_option('wp_oauth2_client_settings', $settings);
                }
            }
        }

        //JOB NEWS
        $body = [
            'method' => 'GET',
            'timeout' => 45,
            'redirection' => 5,
            'httpversion' => '1.0',
            'sslverify' => true,
            'blocking' => true,
            'headers' => [
                'Content-Type' => '',
            ],
            'body' => []
        ];
        $srvUrl = $settings['server_url'] . '/api/api-news?page=1&active=1';
        $uri = sprintf('&newsFrom[before]=%s&newsTo[after]=%s&order[newsFrom]=desc', date('Y-m-d', current_time('timestamp')), date('Y-m-d', current_time('timestamp')));
        $url = $srvUrl . $uri;
        $response = wp_remote_get($url, $body);
        $news = [];
        if (!is_wp_error($response)) {
            $apiNews = json_decode($response['body'], true);
            foreach ($apiNews['hydra:member'] as $tmp) {
                $item = [
                    'content' => html_entity_decode($tmp['content']),
                    'id' => $tmp['id'],
                    'date' => $tmp['newsFrom'],
                    'title' => $tmp['title']
                ];
                $news[] = $item;
            }
        }


        $data = [
            's' => $settings,
            'db' => WP_OAUTH2_CLIENT_DB_VERSION,
            'version' => $this->version,
            'theme' => apply_filters($this->basename . '/current_theme_directory', ''),
            'error' => $error,
            'auth_url' => $url,
            'api' => $apiData,
            'api_call' => $apiCall,
            'isAuthentifiziert' => $isAuthentifiziert,
            'api_error' => $errorApi,
            'lizenz' => $lizenz,
            'news' => $news,
            'authUrl' => $authUrl
        ];

        try {
            $template = $this->twig->render('@templates/wp-oauth2-callback.html.twig', $data);
            echo $this->html_compress_template($template);
        } catch (LoaderError|SyntaxError|RuntimeError $e) {
            echo $e->getMessage();
        } catch (Throwable $e) {
            echo $e->getMessage();
        }
    }

    public function wp_oauth2_client_load_ajax_admin_options_script(): void
    {
        add_action('admin_enqueue_scripts', array($this, 'enqueue_scripts'));
        $title_nonce = wp_create_nonce('oath2_client_admin_handle');
        wp_register_script('oauth2-client-admin-ajax-script', '', [], '', true);
        wp_enqueue_script('oauth2-client-admin-ajax-script');
        wp_localize_script('oauth2-client-admin-ajax-script', 'oauth2Client', array(
            'ajax_url' => admin_url('admin-ajax.php'),
            'nonce' => $title_nonce,
        ));
    }

    /**
     * @throws Exception
     */
    public function admin_ajax_Oauth2Client(): void
    {
        check_ajax_referer('oath2_client_admin_handle');
        require 'ajax/WP_Oauth2_Client_Admin_Ajax.php';
        $adminAjaxHandle = WP_Oauth2_Client_Admin_Ajax::admin_ajax_instance($this->basename, $this->main, $this->twig);
        wp_send_json($adminAjaxHandle->admin_ajax_handle());
    }


    public function fn_product_lizenz_query(): void
    {
        global $wp;
        $wp->add_query_var('upload_code');
        $wp->add_query_var('code');
    }

    function fn_product_lizenz_callback_trigger(): void
    {

        global $apiCallback;
        if (get_query_var('upload_code')) {
            $upload_code = filter_input(INPUT_GET, 'upload_code', FILTER_UNSAFE_RAW);
            $slug = filter_input(INPUT_GET, 'slug', FILTER_UNSAFE_RAW);
            $type = filter_input(INPUT_GET, 'type', FILTER_VALIDATE_INT);
            //echo($upload_code).'<br>';
            //echo($slug).'<br>';
            //echo($type).'<br>';

            if ($upload_code && $type && $slug) {
                $apiCallback->oauth_api_download_product($upload_code, $type, $slug);
            }
            exit();
        }

        if (get_query_var('code')) {
            $code = filter_input(INPUT_GET, 'code', FILTER_UNSAFE_RAW);
            $error = filter_input(INPUT_GET, 'error', FILTER_UNSAFE_RAW);
            if ($code || $error) {
                $apiData = get_option($this->basename . '/oauth_api_data');
                $authentifizierung = $apiData['authentifizierung'] ?? false;
                if (!$authentifizierung) {
                    $apiCallback->oauth_api_callback();
                }
                exit();
            }
        }
    }

    /**
     * Register the Update-Checker for the Plugin.
     *
     * @since    1.0.0
     */
    public function set_wp_oauth2_client_update_checker(): void
    {
        $body = [
            'method' => 'GET',
            'timeout' => 45,
            'redirection' => 5,
            'httpversion' => '1.0',
            'sslverify' => true,
            'blocking' => true,
            'headers' => [],
            'body' => []
        ];
        $response = wp_remote_get(WP_OAUTH2_CLIENT_SERVER_URL . '/api/' . $this->basename . '/conf/update-options', $body);
        if (is_wp_error($response)) {
            echo $response->get_error_message();
            exit();
        }
        $response = json_decode($response['body'], true);
        update_option($this->basename . '/update_checker', $response);
        $options = get_option($this->basename . '/update_checker');
        if (WP_OAUTH2_CLIENT_UPDATE_AKTIV) {
            if ($options['is_git']) {
                $updateChecker = PucFactory::buildUpdateChecker(
                    $options['git_data']['git_url'],
                    WP_PLUGIN_DIR . DIRECTORY_SEPARATOR . $this->basename . DIRECTORY_SEPARATOR . $this->basename . '.php',
                    $this->basename
                );
                switch ($options['git_data']['update_type']) {
                    case '1':
                        $updateChecker->getVcsApi()->enableReleaseAssets();
                        break;
                    case '2':
                        $updateChecker->setBranch($options['git_data']['branch_name']);
                        break;
                }
            }
            if (!$options['is_git']) {
                PucFactory::buildUpdateChecker(
                    $options['update_url'],
                    WP_PLUGIN_DIR . DIRECTORY_SEPARATOR . $this->basename . DIRECTORY_SEPARATOR . $this->basename . '.php',
                    $this->basename
                );
            }
        }
    }

    /**
     * Register the JavaScript for the admin area.
     *
     * @since    1.0.0
     */
    public function enqueue_scripts()
    {

        /**
         * This function is provided for demonstration purposes only.
         *
         * An instance of this class should be passed to the run() function
         * defined in Wp_Oauth2_Client_Loader as all of the hooks are defined
         * in that particular class.
         *
         * The Wp_Oauth2_Client_Loader will then create the relationship
         * between the defined hooks and the functions defined in this
         * class.
         */
        wp_enqueue_script('jquery');
        wp_enqueue_style($this->basename . '-admin-bs', plugin_dir_url(__FILE__) . 'css/bs/bootstrap.min.css', array(), $this->version, false);
        wp_enqueue_style($this->basename . '-animate', plugin_dir_url(__FILE__) . 'css/tools/animate.min.css', array(), $this->version);
        wp_enqueue_style($this->basename . '-swal2', plugin_dir_url(__FILE__) . 'css/tools/sweetalert2.min.css', array(), $this->version, false);
        wp_enqueue_style($this->basename . '-clock', plugin_dir_url(__FILE__) . 'css/tools/flipclock.min.css', array(), $this->version, false);
        wp_enqueue_style($this->basename . '-bootstrap-icons-style', WP_OAUTH2_CLIENT_PLUGIN_URL . 'vendor/twbs/bootstrap-icons/font/bootstrap-icons.css', array(), $this->version);
        wp_enqueue_style($this->basename . '-admin-dashboard-style', plugin_dir_url(__FILE__) . 'css/admin-dashboard-style.css', array(), $this->version, false);

        wp_enqueue_script($this->basename . '-bs', plugin_dir_url(__FILE__) . 'js/bs/bootstrap.bundle.min.js', array(), $this->version, true);
        wp_enqueue_script($this->basename . '-swal2-script', plugin_dir_url(__FILE__) . 'js/tools/sweetalert2.all.min.js', array(), $this->version, true);
        wp_enqueue_script($this->basename . '-clock-script', plugin_dir_url(__FILE__) . 'js/tools/flipclock.min.js', array(), $this->version, true);
        wp_enqueue_script($this->basename, plugin_dir_url(__FILE__) . 'js/wp-oauth2-client-admin.js', array('jquery'), $this->version, false);

    }

    /**
     * @param $name
     *
     * @return string
     */
    private static function get_svg_icons($name): string
    {
        $icon = '';
        switch ($name) {
            case'fingerprint':
                $icon = '<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-fingerprint" viewBox="0 0 16 16">
  						 <path d="M8.06 6.5a.5.5 0 0 1 .5.5v.776a11.5 11.5 0 0 1-.552 3.519l-1.331 4.14a.5.5 0 0 1-.952-.305l1.33-4.141a10.5 10.5 0 0 0 .504-3.213V7a.5.5 0 0 1 .5-.5Z"/>
  						 <path d="M6.06 7a2 2 0 1 1 4 0 .5.5 0 1 1-1 0 1 1 0 1 0-2 0v.332c0 .409-.022.816-.066 1.221A.5.5 0 0 1 6 8.447c.04-.37.06-.742.06-1.115V7Zm3.509 1a.5.5 0 0 1 .487.513 11.5 11.5 0 0 1-.587 3.339l-1.266 3.8a.5.5 0 0 1-.949-.317l1.267-3.8a10.5 10.5 0 0 0 .535-3.048A.5.5 0 0 1 9.569 8Zm-3.356 2.115a.5.5 0 0 1 .33.626L5.24 14.939a.5.5 0 1 1-.955-.296l1.303-4.199a.5.5 0 0 1 .625-.329Z"/>
  						 <path d="M4.759 5.833A3.501 3.501 0 0 1 11.559 7a.5.5 0 0 1-1 0 2.5 2.5 0 0 0-4.857-.833.5.5 0 1 1-.943-.334Zm.3 1.67a.5.5 0 0 1 .449.546 10.72 10.72 0 0 1-.4 2.031l-1.222 4.072a.5.5 0 1 1-.958-.287L4.15 9.793a9.72 9.72 0 0 0 .363-1.842.5.5 0 0 1 .546-.449Zm6 .647a.5.5 0 0 1 .5.5c0 1.28-.213 2.552-.632 3.762l-1.09 3.145a.5.5 0 0 1-.944-.327l1.089-3.145c.382-1.105.578-2.266.578-3.435a.5.5 0 0 1 .5-.5Z"/>
  						 <path d="M3.902 4.222a4.996 4.996 0 0 1 5.202-2.113.5.5 0 0 1-.208.979 3.996 3.996 0 0 0-4.163 1.69.5.5 0 0 1-.831-.556Zm6.72-.955a.5.5 0 0 1 .705-.052A4.99 4.99 0 0 1 13.059 7v1.5a.5.5 0 1 1-1 0V7a3.99 3.99 0 0 0-1.386-3.028.5.5 0 0 1-.051-.705ZM3.68 5.842a.5.5 0 0 1 .422.568c-.029.192-.044.39-.044.59 0 .71-.1 1.417-.298 2.1l-1.14 3.923a.5.5 0 1 1-.96-.279L2.8 8.821A6.531 6.531 0 0 0 3.058 7c0-.25.019-.496.054-.736a.5.5 0 0 1 .568-.422Zm8.882 3.66a.5.5 0 0 1 .456.54c-.084 1-.298 1.986-.64 2.934l-.744 2.068a.5.5 0 0 1-.941-.338l.745-2.07a10.51 10.51 0 0 0 .584-2.678.5.5 0 0 1 .54-.456Z"/>
  						 <path d="M4.81 1.37A6.5 6.5 0 0 1 14.56 7a.5.5 0 1 1-1 0 5.5 5.5 0 0 0-8.25-4.765.5.5 0 0 1-.5-.865Zm-.89 1.257a.5.5 0 0 1 .04.706A5.478 5.478 0 0 0 2.56 7a.5.5 0 0 1-1 0c0-1.664.626-3.184 1.655-4.333a.5.5 0 0 1 .706-.04ZM1.915 8.02a.5.5 0 0 1 .346.616l-.779 2.767a.5.5 0 1 1-.962-.27l.778-2.767a.5.5 0 0 1 .617-.346Zm12.15.481a.5.5 0 0 1 .49.51c-.03 1.499-.161 3.025-.727 4.533l-.07.187a.5.5 0 0 1-.936-.351l.07-.187c.506-1.35.634-2.74.663-4.202a.5.5 0 0 1 .51-.49Z"/>
					     </svg>';
                break;
            case 'network':
                $icon = '<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-hdd-network" viewBox="0 0 16 16">
  						 <path d="M4.5 5a.5.5 0 1 0 0-1 .5.5 0 0 0 0 1zM3 4.5a.5.5 0 1 1-1 0 .5.5 0 0 1 1 0z"/>
  						 <path d="M0 4a2 2 0 0 1 2-2h12a2 2 0 0 1 2 2v1a2 2 0 0 1-2 2H8.5v3a1.5 1.5 0 0 1 1.5 1.5h5.5a.5.5 0 0 1 0 1H10A1.5 1.5 0 0 1 8.5 14h-1A1.5 1.5 0 0 1 6 12.5H.5a.5.5 0 0 1 0-1H6A1.5 1.5 0 0 1 7.5 10V7H2a2 2 0 0 1-2-2V4zm1 0v1a1 1 0 0 0 1 1h12a1 1 0 0 0 1-1V4a1 1 0 0 0-1-1H2a1 1 0 0 0-1 1zm6 7.5v1a.5.5 0 0 0 .5.5h1a.5.5 0 0 0 .5-.5v-1a.5.5 0 0 0-.5-.5h-1a.5.5 0 0 0-.5.5z"/>
					     </svg>';
                break;
            case'cloud_sync':
                $icon = '<svg xmlns="http://www.w3.org/2000/svg" x="0px" y="0px"
	                     viewBox="0 0 24 24" style="enable-background:new 0 0 24 24;" xml:space="preserve">
                         <path d="M21,15.6C21,15.6,20.9,15.6,21,15.6c-0.4-2-2.1-3.6-4.2-3.6c-1.7,0-3.1,1-3.8,2.4c-1.9,0.1-3.4,1.7-3.4,3.6
	                     c0,2,1.6,3.6,3.6,3.6l7.8,0c1.7,0,3-1.3,3-3S22.6,15.6,21,15.6z M7.2,2.7v2.5c-2.8,1-4.8,3.6-4.8,6.8c0,2.1,0.9,4,2.4,5.3v-2.9h2.4
	                     v7.2H0v-2.4h3.3C1.3,17.4,0,14.9,0,12C0,7.5,3.1,3.8,7.2,2.7z M19.2,4.8h-3.3c1.7,1.5,2.9,3.6,3.2,6h-2.4c-0.3-1.6-1.1-3.1-2.3-4.1
	                     v2.9H12V2.4h7.2V4.8z"/>
                         </svg>';

                break;

            default:
        }

        return 'data:image/svg+xml;base64,' . base64_encode($icon);

    }

    protected function html_compress_template(string $string): string
    {
        if (!$string) {
            return $string;
        }

        return preg_replace(['/<!--(.*)-->/Uis', "/[[:blank:]]+/"], ['', ' '], str_replace([
            "\n",
            "\r",
            "\t"
        ], '', $string));
    }

    public function url_check($url)
    {
        $hdrs = @get_headers($url);
        return is_array($hdrs) ? preg_match('/^HTTP\\/\\d+\\.\\d+\\s+2\\d\\d\\s+.*$/', $hdrs[0]) : false;
    }
}
