<?php

// If this file is called directly, abort.
defined('ABSPATH') || die('No direct access!');

class Dragonizer_Login_Customizer
{
    private static $options;

    public function process(array $options = [])
    {
        // dragonizer_log('login_customizer', 'Starting process method', 'debug');

        if (empty($options) || !empty(self::$options)) {
            // dragonizer_log('login_customizer', 'Process method exited early: empty options or options already set', 'info');
            return;
        }

        $default = [
            'template'              => 'default',
            'logo'                  => '',
            'background'            => '',
            'color'                 => '',
            'blur_background_image' => false,
            'disable_lang_selector' => false,
            'disable_register_link' => false,
            'disable_back_to_site'  => false,
            'disable_privacy_link'  => false,
            'login_font'            => 'default'
        ];

        self::$options = dr_fix_settings($default, $options);
        // dragonizer_log('login_customizer', 'Options set: ' . json_encode(self::$options), 'debug');

        if ($this->settings()->disable_lang_selector) {
            add_filter('login_display_language_dropdown', '__return_false');
            // dragonizer_log('login_customizer', 'Language selector disabled', 'info');
        }

        if ($this->settings()->template === 'default') {
            // dragonizer_log('login_customizer', 'Using default template', 'info');
            if (
                $this->settings()->logo !== '' ||
                $this->settings()->disable_register_link !== false ||
                $this->settings()->disable_back_to_site !== false ||
                $this->settings()->disable_privacy_link !== false
            ) {
                // dragonizer_log('login_customizer', 'Generating login CSS for default template with customizations', 'debug');
                $this->generate_login_css($this->settings()->login_font);
            }
        } else {
            // dragonizer_log('login_customizer', 'Using custom template: ' . $this->settings()->template, 'info');
            $this->generate_login_template($this->settings()->login_font);
        }

        if ($this->settings()->login_font === 'default') {
            // dragonizer_log('login_customizer', 'Using default login font, process method completed', 'info');
            return;
        }

        // dragonizer_log('login_customizer', 'Applying custom login font: ' . $this->settings()->login_font, 'info');

        $css_contents = DRFS::read(_dr(DRAGONIZER_ASE_DIR, 'css', "dragonizer-font-global-rtl.min.css"));

        if ($css_contents) {
            // dragonizer_log('login_customizer', 'Custom font CSS loaded successfully', 'debug');
            $css_contents = str_replace(['DRAGONIZER_ASE_URL', 'DRAGONIZER_FONT_NAME', 'DRAGONIZER_TITLE_FONT_NAME', 'body.rtl '], [DRAGONIZER_ASE_URL, $this->settings()->login_font, $this->settings()->login_font, ''], $css_contents);
            $slug    = 'login-font';
            add_action(
                'login_enqueue_scripts',
                function () use ($css_contents,  $slug) {
                    (new Dragonizer_Login_Customizer())->add_inline_css($css_contents, $slug);
                },
                PHP_INT_MAX
            );
            // dragonizer_log('login_customizer', 'Custom font CSS enqueued', 'debug');
        } else {
            // dragonizer_log('login_customizer', 'Failed to load custom font CSS', 'warning');
        }

        // dragonizer_log('login_customizer', 'Process method completed', 'info');
    }

    private function settings(): object
    {
        if (is_object(self::$options)) {
            return self::$options;
        } else {
            return (object)[];
        }
    }

    public function add_inline_script(string $content, string $slug, bool $infooter = false)
    {
        wp_register_script(DRAGONIZER_NAME . "-$slug", false, [], DRAGONIZER_VER, $infooter);
        wp_enqueue_script(DRAGONIZER_NAME . "-$slug");
        wp_add_inline_script(DRAGONIZER_NAME . "-$slug", $content);
    }

    public function add_inline_css(string $content, string $slug)
    {
        wp_register_style(DRAGONIZER_NAME . "-$slug", false);
        wp_enqueue_style(DRAGONIZER_NAME . "-$slug");
        wp_add_inline_style(DRAGONIZER_NAME . "-$slug", $content);
    }

    private function generate_login_template($login_font = false)
    {
        // dragonizer_log('login_customizer', 'Starting generate_login_template method', 'debug');

        $css_file = DRFS::read(_dr(DRAGONIZER_PAR_DIR, 'login-page-templates', 'styles', $this->settings()->template . '.css'));

        if (!$css_file) {
            // dragonizer_log('login_customizer', 'CSS file not found for template: ' . $this->settings()->template, 'error');
            return;
        }

        // dragonizer_log('login_customizer', 'CSS file loaded successfully', 'debug');

        // Default logo path
        $default_logo = _dr(DRAGONIZER_URL, '/assets/images/logo/main.png') . '?ver=' . DRAGONIZER_VER;

        // Handle logo
        $logo_result = $this->handle_image_url($this->settings()->logo, $default_logo, 'logo');
        $custom_logo = $logo_result['url'];
        $dimensions = $logo_result['dimensions'];

        // Process logo dimensions
        $logoSize = '';
        if (is_array($dimensions)) {
            if ($dimensions['width'] == $dimensions['height']) {
                $logoSize = "width: 100px; height: 100px;";
            } elseif ($dimensions['width'] > $dimensions['height']) {
                $ratio = $dimensions['width'] / $dimensions['height'];
                $logoSize = ($ratio > 2) ? "width: 200px; height: " . round(200 / $ratio) . "px;" : "width: " . round($ratio * 100) . "px; height: 100px;";
            } else {
                $ratio = $dimensions['height'] / $dimensions['width'];
                $logoSize = ($ratio > 2) ? "width: " . round(200 / $ratio) . "px; height: 200px;" : "width: 100px; height: " . round($ratio * 100) . "px;";
            }
            // dragonizer_log('login_customizer', 'Logo size set to: ' . $logoSize, 'debug');
        }

        // Default background based on the template setting
        $default_background = DRAGONIZER_URL . 'app/partials/login-page-templates/backgrounds/' . str_replace('template', 'background', $this->settings()->template) . '.webp';

        // Handle background
        $bg_result = $this->handle_image_url($this->settings()->background, $default_background, 'background');
        $custom_background = $bg_result['url'];

        if (empty($this->settings()->color) || $this->settings()->color === '#ffffff') {
            // dragonizer_log('login_customizer', 'Using default color scheme for template: ' . $this->settings()->template, 'info');
            switch ($this->settings()->template) {
                case 'template-01':
                    $colorOne = '#9d0110';
                    break;
                case 'template-02':
                    $colorOne = '#a07500';
                    $colorTwo = '#D39C10';
                    break;
                case 'template-03':
                    $colorOne = '#F89269';
                    $colorTwo = '#FF692E';
                    break;
                case 'template-04':
                    $colorOne = '#2e3f4e';
                    $colorTwo = '#222222';
                    break;
                case 'template-05':
                    $colorOne = '#00594b';
                    $colorTwo = '#014038';
                    break;
                default:
                    $colorOne = '#d00';
                    $colorTwo = '#a00';
                    break;
            }
        } else {
            // dragonizer_log('login_customizer', 'Using custom color: ' . $this->settings()->color, 'info');
            $colorOne  = $this->settings()->color;
            $lightDark = $this->get_brightness_color($colorOne) > 30 ? -0.3 : 0.1;
            $colorTwo  = $this->adjust_brightness($colorOne, $lightDark);
        }

        $back_to_site  = $this->settings()->disable_back_to_site  !== false ? 'display: none !important;' : '';
        $register_link = $this->settings()->disable_register_link !== false ? 'display: none !important;' : '';
        $privacy_link  = $this->settings()->disable_privacy_link  !== false ? 'display: none !important;' : '';

        $blur_image    = $this->settings()->blur_background_image !== false ? 'backdrop-filter: blur(5px);' : '';

        // dragonizer_log('login_customizer', 'Applying customizations to CSS', 'debug');

        $css_file = str_replace('__PowerdBy__', $this->get_dragonizer_powered(), $css_file);
        $css_file = str_replace('__logoSize__', $logoSize, $css_file);
        $css_file = str_replace('__Custom_Logo_Location__', $custom_logo, $css_file);
        $css_file = str_replace('__Background_Image_Blur__', $blur_image, $css_file);
        $css_file = str_replace('__Custom_Background_Location__', $custom_background, $css_file);
        $css_file = str_replace('__register_link__', $register_link, $css_file);
        $css_file = str_replace('__back_to_site__', $back_to_site, $css_file);
        $css_file = str_replace('__privacy_link__', $privacy_link, $css_file);

        $css_file = str_replace('__ColorOne__', $colorOne, $css_file);
        $css_file = str_replace('__ColorTik__', str_replace('#', '', $colorOne), $css_file);

        if ($this->settings()->template !== 'template-01') {
            $css_file = str_replace('__ColorTwo__', $colorTwo, $css_file);
        }

        $content = $css_file;
        $slug = 'customize-login';

        // dragonizer_log('login_customizer', 'Adding CSS to login_enqueue_scripts action', 'debug');
        add_action(
            'login_enqueue_scripts',
            function () use ($content,  $slug) {
                (new Dragonizer_Login_Customizer())->add_inline_css($content, $slug);
            },
            PHP_INT_MAX
        );

        $clean_font = $login_font === 'default' ? '' : '-1==n.innerHTML.indexOf("@font-face")&&';

        $content = '(function(){document.querySelectorAll("style").forEach((function(n){-1==(n.id||"").indexOf("dragonizer")&&(' . $clean_font . '-1==n.innerHTML.indexOf(".login h1 a")&&-1==n.innerHTML.indexOf(".login #wp-submit")||n.remove())}));})();';
        $slug    = 'clean-unwanted-styles';

        // dragonizer_log('login_customizer', 'Adding script to clean unwanted styles', 'debug');
        add_action(
            'login_enqueue_scripts',
            function () use ($content,  $slug) {
                (new Dragonizer_Login_Customizer())->add_inline_script($content, $slug, true);
            },
            PHP_INT_MAX
        );

        // dragonizer_log('login_customizer', 'generate_login_template method completed', 'info');
    }


    private function is_external_url($url)
    {
        if (!filter_var($url, FILTER_VALIDATE_URL)) {
            return false;
        }

        $parsed_url = parse_url($url);
        $host = isset($parsed_url['host']) ? $parsed_url['host'] : '';

        // Get main site domain
        $site_host = parse_url(site_url(), PHP_URL_HOST);

        // Strip www. from both hosts for comparison
        $host = preg_replace('/^www\./i', '', $host);
        $site_host = preg_replace('/^www\./i', '', $site_host);

        // If the host is different from the site host, it's external
        $is_external = ($host !== $site_host);

        // dragonizer_log('login_customizer', "URL host check: {$url} - Host: {$host}, Site Host: {$site_host}, Is External: " . ($is_external ? 'true' : 'false'), 'debug');

        return $is_external;
    }

    private function handle_image_url($url, $default_url, $type = 'logo')
    {
        if (empty($url)) {
            // dragonizer_log('login_customizer', "Using default {$type}", 'info');
            return [
                'url' => $default_url,
                'dimensions' => false
            ];
        }

        // dragonizer_log('login_customizer', "Processing {$type} url: " . $url, 'info');

        // Check if URL is external (CDN)
        if ($this->is_external_url($url)) {
            // dragonizer_log('login_customizer', "Processing external CDN {$type}", 'debug');

            // For external URLs, try to get dimensions but always use the URL
            $dimensions = $this->get_remote_image_dimensions($url);

            if (!$dimensions) {
                // dragonizer_log('login_customizer', "Could not get dimensions for external {$type}, using defaults", 'debug');
                $dimensions = ['width' => 100, 'height' => 100];
            }

            return [
                'url' => $url,
                'dimensions' => $dimensions
            ];
        } else {
            // For local URLs
            // dragonizer_log('login_customizer', "Processing local {$type}", 'debug');

            // Try to get local path
            $local_path = dr_url_to_dir($url);

            if ($local_path && file_exists($local_path)) {
                // dragonizer_log('login_customizer', "Found local {$type} at: " . $local_path, 'debug');
                $dimensions = $this->get_dimensions_from_url($url);

                if (!$dimensions) {
                    $dimensions = ['width' => 100, 'height' => 100];
                }

                return [
                    'url' => $url,
                    'dimensions' => $dimensions
                ];
            } else {
                // If local path not found, treat as external
                // dragonizer_log('login_customizer', "Local path not found for {$type}, treating as external", 'debug');

                $dimensions = $this->get_remote_image_dimensions($url);
                if (!$dimensions) {
                    $dimensions = ['width' => 100, 'height' => 100];
                }

                return [
                    'url' => $url,
                    'dimensions' => $dimensions
                ];
            }
        }
    }

    private function get_remote_image_dimensions($url)
    {
        if (empty($url)) {
            return false;
        }

        // First try wp_get_http_headers which handles WordPress specifics
        $headers = wp_get_http_headers($url);
        if (!$headers || isset($headers['status']) && $headers['status'] != 200) {
            // Fallback to direct get_headers
            $headers = get_headers($url, 1);
            if (!$headers || strpos($headers[0], '200') === false) {
                return false;
            }
        }

        // Try WordPress HTTP API first
        $response = wp_safe_remote_get($url, [
            'timeout' => 5,
            'sslverify' => false
        ]);

        if (!is_wp_error($response) && wp_remote_retrieve_response_code($response) === 200) {
            $data = wp_remote_retrieve_body($response);
        } else {
            // Fallback to cURL
            $ch = curl_init($url);
            curl_setopt_array($ch, [
                CURLOPT_RETURNTRANSFER => true,
                CURLOPT_TIMEOUT => 5,
                CURLOPT_SSL_VERIFYPEER => false,
                CURLOPT_SSL_VERIFYHOST => false,
            ]);
            $data = curl_exec($ch);
            curl_close($ch);
        }

        if (!$data) {
            return false;
        }

        // Try to create image from string
        $image = @imagecreatefromstring($data);
        if (!$image) {
            return false;
        }

        $dimensions = [
            'width' => imagesx($image),
            'height' => imagesy($image)
        ];

        imagedestroy($image);
        return $dimensions;
    }

    private function get_dragonizer_powered(): string
    {
        $default_powered = "Powered by Dragonizer";
        $template = defined('DRAGONIZER_POWERED') ? DRAGONIZER_POWERED : $default_powered;

        // Validate and format template if custom
        if (defined('DRAGONIZER_POWERED')) {
            if (!is_string($template)) {
                error_log('Dragonizer: DRAGONIZER_POWERED must be a string');
                $template = $default_powered;
            } else {
                $template = strip_tags(trim($template));

                // Validate allowed characters
                if (!preg_match('/^[a-zA-Z0-9\s\.\-_:;\|\{\}@#%!&*()\[\]]+$/', $template)) {
                    error_log('Dragonizer: DRAGONIZER_POWERED contains invalid characters');
                    $template = $default_powered;
                }
            }
        }

        // Prepare replacement values
        $version = defined('DRAGONIZER_VER') ? DRAGONIZER_VER : '';

        // Replace template variables
        $replacements = [
            '{version}' => htmlspecialchars($version)
        ];
        $template = strtr($template, $replacements);

        // Clean up formatting
        return preg_replace('/\s+/', ' ', $template);
    }

    private function adjust_brightness($hexCode, $adjustPercent)
    {
        $hexCode = ltrim($hexCode, '#');

        if (strlen($hexCode) == 3) {
            $hexCode = $hexCode[0] . $hexCode[0] . $hexCode[1] . $hexCode[1] . $hexCode[2] . $hexCode[2];
        }

        $hexCode = array_map('hexdec', str_split($hexCode, 2));

        foreach ($hexCode as &$color) {
            $adjustableLimit = $adjustPercent < 0 ? $color : 255 - $color;
            $adjustAmount = ceil($adjustableLimit * $adjustPercent);

            $color = str_pad(dechex($color + $adjustAmount), 2, '0', STR_PAD_LEFT);
        }

        return '#' . implode($hexCode);
    }

    private function get_brightness_color($hex)
    {
        $hex = str_replace('#', '', $hex);

        $c_r = hexdec(substr($hex, 0, 2));
        $c_g = hexdec(substr($hex, 2, 2));
        $c_b = hexdec(substr($hex, 4, 2));

        return (($c_r * 299) + ($c_g * 587) + ($c_b * 114)) / 1000;
    }

    private function get_dimensions_from_url($url)
    {
        // Extract dimensions from file name if available
        if (preg_match('/(?:.+)-([0-9]+)x([0-9]+)\.(jpg|jpeg|png|gif|svg|webp)$/i', $url, $matches)) {
            return ['width' => (int)$matches[1], 'height' => (int)$matches[2]];
        }

        // Convert URL to local path
        $local_path = dr_url_to_dir($url);

        if ($local_path && file_exists($local_path)) {
            // For local files
            $image_size = @getimagesize($local_path);
            if ($image_size) {
                return ['width' => $image_size[0], 'height' => $image_size[1]];
            }
        } else {
            // For remote files
            $context = stream_context_create([
                'http' => [
                    'method' => 'HEAD',
                    'timeout' => 5
                ]
            ]);
            $headers = @get_headers($url, 1, $context);

            if ($headers && strpos($headers[0], '200') !== false) {
                if (isset($headers['Content-Length'])) {
                    $file_size = $headers['Content-Length'];
                    $max_size = 1024 * 1024; // 1MB

                    if ($file_size <= $max_size) {
                        $image_data = @file_get_contents($url, false, stream_context_create(['http' => ['timeout' => 5]]));
                        if ($image_data) {
                            $image_size = @getimagesizefromstring($image_data);
                            if ($image_size) {
                                return ['width' => $image_size[0], 'height' => $image_size[1]];
                            }
                        }
                    } else {
                        // For large files, try to get dimensions from exif data
                        $exif = @exif_read_data($url);
                        if ($exif && isset($exif['COMPUTED']['Width'], $exif['COMPUTED']['Height'])) {
                            return ['width' => $exif['COMPUTED']['Width'], 'height' => $exif['COMPUTED']['Height']];
                        }
                    }
                }
            }
        }

        // If we couldn't determine the size, log a warning
        // dragonizer_log('login_customizer', "Failed to get image dimensions for URL: $url", 'warning');
        return false;
    }

    private function generate_login_css($login_font)
    {
        $css = new Dragonizer_CSS_Generator();

        if ($this->settings()->logo !== '') {
            $css->add_rule('.login h1 a', [
                'background-image' => "url('{$this->settings()->logo}')",
                'filter' => 'drop-shadow(5px 5px 40px white)',
            ]);
        }

        if ($this->settings()->disable_privacy_link !== false) {
            $css->add_rule('.login .privacy-policy-page-link', ['display' => "none !important",]);
        }

        if ($this->settings()->disable_register_link !== false) {
            $css->add_rule('.login #nav', ['display' => "none !important",]);
        }

        if ($this->settings()->disable_back_to_site !== false) {
            $css->add_rule('.login #backtoblog', ['display' => "none !important",]);
        }

        $css->close_blocks(); // close all blocks

        $content = $this->strip_css_white_spaces($css->get_output());
        $slug    = 'customize-login';

        add_action(
            'login_enqueue_scripts',
            function () use ($content,  $slug) {
                (new Dragonizer_Login_Customizer())->add_inline_css($content, $slug);
            },
            PHP_INT_MAX
        );

        $clean_font = $login_font === 'default' ? '' : '-1==n.innerHTML.indexOf("@font-face")&&';

        $content = 'document.querySelectorAll("style").forEach((function(e){-1==(e.id||"").indexOf("dragonizer")&&(' . $clean_font . '-1==e.innerHTML.indexOf(".login h1 a")&&-1==e.innerHTML.indexOf(".login #wp-submit")||e.remove())})),document.getElementById("custom-login-css").remove();';
        $slug    = 'clean-unwanted-styles';

        add_action(
            'login_enqueue_scripts',
            function () use ($content,  $slug) {
                (new Dragonizer_Login_Customizer())->add_inline_script($content, $slug, true);
            },
            PHP_INT_MAX
        );
    }

    private function strip_css_white_spaces($content)
    {
        $content = preg_replace('~^\s*~m', '', $content);
        $content = preg_replace('~\s*$~m', '', $content);
        $content = preg_replace('~\s+~', ' ', $content);
        $content = preg_replace('~\s*([\*$\~^|]?+=|[{};,>\~]|!important\b)\s*~', '$1', $content);
        $content = preg_replace('~([\[(:>\+])\s+~', '$1', $content);
        $content = preg_replace('~\s+([\]\)>\+])~', '$1', $content);
        $content = preg_replace('~\s+(:)(?![^\}]*\{)~', '$1', $content);
        $pseudos = array('nth-child', 'nth-last-child', 'nth-last-of-type', 'nth-of-type');
        $content = preg_replace('~:(' . implode('|', $pseudos) . ')\(\s*([+-]?)\s*(.+?)\s*([+-]?)\s*(.*?)\s*\)~', ':$1($2$3$4$5)', $content);
        $content = str_replace(';}', '}', $content);
        return trim($content);
    }
}

class Dragonizer_Login_Hidden
{
    private $wp_login_php;
    private $settings;

    public function process(array $args = [])
    {
        $default = [
            'login_page'     => 'securelogin',
            'redirect_admin' => '404'
        ];

        $this->settings = (object) dr_parse_args($args, $default);

        global $wp_version;
        if (version_compare($wp_version, '4.0-RC1-src', '<')) {
            add_action('admin_notices', array($this, 'admin_notices_incompatible'));
            add_action('network_admin_notices', array($this, 'admin_notices_incompatible'));
            return;
        }

        if (is_multisite() && !function_exists('is_plugin_active_for_network') || !function_exists('is_plugin_active')) {
            include_once(ABSPATH . '/wp-admin/includes/plugin.php');
        }


        add_action('plugins_loaded', array($this, 'plugins_loaded'), 9999);
        add_action('wp_loaded', array($this, 'wp_loaded'));
        add_action('setup_theme', array($this, 'setup_theme'), 1);

        add_filter('site_url', array($this, 'site_url'), 10, 4);
        add_filter('network_site_url', array($this, 'network_site_url'), 10, 3);
        add_filter('wp_redirect', array($this, 'wp_redirect'), 10, 2);
        add_filter('site_option_welcome_email', array($this, 'welcome_email'));

        remove_action('template_redirect', 'wp_redirect_admin_locations', 1000);

        add_action('template_redirect', array($this, 'redirect_export_data'));
        add_filter('login_url', array($this, 'login_url'), 10, 3);

        add_filter('site_status_tests', array($this, 'site_status_tests'));

        add_action('wp_logout', function () {
            $home_url  = apply_filters("dragonizer_redirect_url", home_url('/'));
            wp_redirect($home_url);
            exit();
        });
    }

    public function admin_notices_incompatible()
    {
        echo '<div class="error notice is-dismissible"><p>' . __('Please upgrade to the latest version of WordPress to activate', 'dragonizer') . ' <strong>' . __('Dragonizer Hide Login', 'dragonizer') . '</strong>.</p></div>';
    }

    private function new_login_slug()
    {
        return $this->settings->login_page;
    }

    private function new_redirect_slug()
    {
        return $this->settings->redirect_admin;
    }

    public function site_status_tests($tests)
    {
        unset($tests['async']['loopback_requests']);
        return $tests;
    }

    private function use_trailing_slashes()
    {
        return ('/' === substr(get_option('permalink_structure'), -1, 1));
    }

    private function user_trailingslashit($string)
    {
        return $this->use_trailing_slashes() ? trailingslashit($string) : untrailingslashit($string);
    }

    private function wp_template_loader()
    {
        global $pagenow;

        $pagenow = 'index.php';

        if (!defined('WP_USE_THEMES')) {
            define('WP_USE_THEMES', true);
        }

        wp();

        include_once(ABSPATH . WPINC . '/template-loader.php');

        die;
    }

    public function new_login_url($scheme = null)
    {
        $url = apply_filters('dragonizer_hide_login_home_url', home_url('/', $scheme));

        if (get_option('permalink_structure')) {
            return $this->user_trailingslashit($url . $this->new_login_slug());
        } else {
            return $url . '?' . $this->new_login_slug();
        }
    }

    public function new_redirect_url($scheme = null)
    {
        if (get_option('permalink_structure')) {
            return $this->user_trailingslashit(home_url('/', $scheme) . $this->new_redirect_slug());
        } else {
            return home_url('/', $scheme) . '?' . $this->new_redirect_slug();
        }
    }

    public function redirect_export_data()
    {
        if (!empty($_GET) && isset($_GET['action']) && 'confirmaction' === $_GET['action'] && isset($_GET['request_id']) && isset($_GET['confirm_key'])) {
            $request_id = (int) $_GET['request_id'];
            $key        = sanitize_text_field(wp_unslash($_GET['confirm_key']));
            $result     = wp_validate_user_request_key($request_id, $key);
            if (!is_wp_error($result)) {
                wp_redirect(add_query_arg(
                    array(
                        'action'      => 'confirmaction',
                        'request_id'  => $_GET['request_id'],
                        'confirm_key' => $_GET['confirm_key']
                    ),
                    $this->new_login_url()
                ));
                exit();
            }
        }
    }

    public function plugins_loaded()
    {

        global $pagenow;

        if (
            !is_multisite()
            && (strpos(rawurldecode($_SERVER['REQUEST_URI']), 'wp-signup') !== false
                || strpos(rawurldecode($_SERVER['REQUEST_URI']), 'wp-activate') !== false) && apply_filters('dragonizer_hide_login_signup_enable', false) === false
        ) {

            wp_die(__('This feature is not enabled.', 'dragonizer'));
        }

        $request = parse_url(rawurldecode($_SERVER['REQUEST_URI']));

        if ((strpos(rawurldecode($_SERVER['REQUEST_URI']), 'wp-login.php') !== false
                || (isset($request['path']) && untrailingslashit($request['path']) === site_url('wp-login', 'relative')))
            && !is_admin()
        ) {

            $this->wp_login_php = true;

            $_SERVER['REQUEST_URI'] = $this->user_trailingslashit('/' . str_repeat('-/', 10));

            $pagenow = 'index.php';
        } elseif ((isset($request['path']) && untrailingslashit($request['path']) === home_url($this->new_login_slug(), 'relative'))
            || (!get_option('permalink_structure')
                && isset($_GET[$this->new_login_slug()])
                && empty($_GET[$this->new_login_slug()]))
        ) {

            $_SERVER['SCRIPT_NAME'] = $this->new_login_slug();

            $pagenow = 'wp-login.php';
        } elseif ((strpos(rawurldecode($_SERVER['REQUEST_URI']), 'wp-register.php') !== false
                || (isset($request['path']) && untrailingslashit($request['path']) === site_url('wp-register', 'relative')))
            && !is_admin()
        ) {

            $this->wp_login_php = true;

            $_SERVER['REQUEST_URI'] = $this->user_trailingslashit('/' . str_repeat('-/', 10));

            $pagenow = 'index.php';
        }
    }


    public function setup_theme()
    {
        global $pagenow;

        if (!is_user_logged_in() && 'customize.php' === $pagenow) {
            wp_die(__('This has been disabled', 'dragonizer'), 403);
        }
    }

    public function wp_loaded()
    {
        global $pagenow;

        $request = parse_url(rawurldecode($_SERVER['REQUEST_URI']));

        do_action('dragonizer_hide_login_before_redirect', $request);

        if (!(isset($_GET['action']) && $_GET['action'] === 'postpass' && isset($_POST['post_password']))) {

            if (is_admin() && !is_user_logged_in() && !defined('WP_CLI') && !defined('DOING_AJAX') && !defined('DOING_CRON') && $pagenow !== 'admin-post.php' && $request['path'] !== '/wp-admin/options.php') {
                wp_safe_redirect($this->new_redirect_url());
                die();
            }

            if (!is_user_logged_in() && isset($_GET['wc-ajax']) && $pagenow === 'profile.php') {
                wp_safe_redirect($this->new_redirect_url());
                die();
            }

            if (!is_user_logged_in() && isset($request['path']) && $request['path'] === '/wp-admin/options.php') {
                header('Location: ' . $this->new_redirect_url());
                die;
            }

            if ($pagenow === 'wp-login.php' && isset($request['path']) && $request['path'] !== $this->user_trailingslashit($request['path']) && get_option('permalink_structure')) {
                wp_safe_redirect($this->user_trailingslashit($this->new_login_url())
                    . (!empty($_SERVER['QUERY_STRING']) ? '?' . $_SERVER['QUERY_STRING'] : ''));

                die;
            } elseif ($this->wp_login_php) {

                if (($referer = wp_get_referer())
                    && strpos($referer, 'wp-activate.php') !== false
                    && ($referer = parse_url($referer))
                    && !empty($referer['query'])
                ) {

                    parse_str($referer['query'], $referer);

                    @require_once WPINC . '/ms-functions.php';

                    if (
                        !empty($referer['key'])
                        && ($result = wpmu_activate_signup($referer['key']))
                        && is_wp_error($result)
                        && ($result->get_error_code() === 'already_active'
                            || $result->get_error_code() === 'blog_taken')
                    ) {

                        wp_safe_redirect($this->new_login_url()
                            . (!empty($_SERVER['QUERY_STRING']) ? '?' . $_SERVER['QUERY_STRING'] : ''));

                        die;
                    }
                }

                $this->wp_template_loader();
            } elseif ($pagenow === 'wp-login.php') {
                global $error, $interim_login, $action, $user_login;

                $redirect_to = admin_url();

                $requested_redirect_to = '';
                if (isset($_REQUEST['redirect_to'])) {
                    $requested_redirect_to = $_REQUEST['redirect_to'];
                }

                if (is_user_logged_in()) {
                    $user = wp_get_current_user();
                    if (!isset($_REQUEST['action'])) {
                        $logged_in_redirect = apply_filters('whl_logged_in_redirect', $redirect_to, $requested_redirect_to, $user);
                        wp_safe_redirect($logged_in_redirect);
                        die();
                    }
                }

                @require_once ABSPATH . 'wp-login.php';

                die;
            }
        }
    }

    public function site_url($url, $path, $scheme, $blog_id)
    {
        return $this->filter_wp_login_php($url, $scheme);
    }

    public function network_site_url($url, $path, $scheme)
    {
        return $this->filter_wp_login_php($url, $scheme);
    }

    public function wp_redirect($location, $status)
    {
        if (strpos($location, 'https://wordpress.com/wp-login.php') !== false) {
            return $location;
        }

        return $this->filter_wp_login_php($location);
    }

    public function filter_wp_login_php($url, $scheme = null)
    {
        if (strpos($url, 'wp-login.php?action=postpass') !== false) {
            return $url;
        }

        if (strpos($url, 'wp-login.php') !== false && strpos(wp_get_referer(), 'wp-login.php') === false) {

            if (is_ssl()) {
                $scheme = 'https';
            }

            $args = explode('?', $url);

            if (isset($args[1])) {

                parse_str($args[1], $args);

                if (isset($args['login'])) {
                    $args['login'] = rawurlencode($args['login']);
                }

                $url = add_query_arg($args, $this->new_login_url($scheme));
            } else {

                $url = $this->new_login_url($scheme);
            }
        }

        return $url;
    }

    public function welcome_email($value)
    {
        return $value = str_replace('wp-login.php', trailingslashit($this->new_login_slug()), $value);
    }

    public function forbidden_slugs()
    {
        $wp = new \WP;

        return array_merge($wp->public_query_vars, $wp->private_query_vars);
    }

    public function login_url($login_url, $redirect, $force_reauth)
    {
        if ($force_reauth === false) {
            return $login_url;
        }

        if (empty($redirect)) {
            return $login_url;
        }

        $redirect = explode('?', $redirect);

        if ($redirect[0] === admin_url('options.php')) {
            $login_url = admin_url();
        }

        return $login_url;
    }
}

class Dragonizer_CSS_Generator
{
    protected $raw = '';
    protected $block_level = 0;
    protected $linebreak = "\n";
    protected $settings = null;
    protected $default_options = [
        'indentation'  => '  ',
    ];

    public function __construct($options = [])
    {
        $this->settings = array_merge($this->default_options, $options);
    }

    public function get_output($compress = false)
    {
        $this->close_blocks();
        if (!$compress)
            return $this->raw;
        return $this->minify($this->raw);
    }

    public function minify(string $value)
    {
        $value = str_replace("@keyframes ", "@keyframes_", $value);
        $value = str_replace("@media screen and", "@media_screen_and", $value);
        $value = preg_replace("~/([0-9]*px(?!;))~", "$1 ", $value);
        $value = str_replace(["\n", "  "], "", $value);
        $value = str_replace(" {", "{", $value);
        $value = str_replace(" }", "}", $value);
        $value = str_replace(": ", ":", $value);
        $value = str_replace("@media_screen_and", "@media screen and", $value);
        return str_replace("@keyframes_", "@keyframes ", $value);
    }

    public function add_raw($string)
    {
        $this->raw .= $string;
    }

    public function add_rule($selectors, $declarations_array)
    {
        $declarations = [];
        $selector_indentation = str_repeat($this->settings['indentation'], $this->block_level);
        $declaration_indentation = str_repeat($this->settings['indentation'], $this->block_level + 1);

        if (!is_array($selectors)) {
            $selectors = [$selectors];
        }

        foreach ($selectors as $key => $value) {
            $selectors[$key] = $selector_indentation . trim($value);
        }

        foreach ($declarations_array as $key => $value) {
            $declarations[] = $declaration_indentation . trim($key) . ': ' . trim($value) . ';' . $this->linebreak;
        }

        $this->raw .= implode(',' . $this->linebreak, $selectors) . ' {';
        $this->raw .= $this->linebreak . implode('', $declarations);
        $this->raw .= $selector_indentation . '}' . $this->linebreak;
    }

    public function open_block($type, $props = '')
    {
        $block_indentation = str_repeat($this->settings['indentation'], $this->block_level);
        $this->raw .= $block_indentation . '@' . $type . ' ' . trim($props) . ' {' . $this->linebreak;
        $this->block_level++;
    }

    public function close_block()
    {
        if ($this->block_level > 0) {
            $this->block_level--;
            $block_indentation = str_repeat($this->settings['indentation'], $this->block_level);
            $this->raw .= $block_indentation . '}' . $this->linebreak;
        }
    }

    public function close_blocks()
    {
        while ($this->block_level > 0) {
            $this->close_block();
        }
    }
}
