<?php

// If this file is called directly, abort.
defined('WPINC') || die();

if (!isset($_SERVER['DOCUMENT_ROOT']))  $_SERVER['DOCUMENT_ROOT'] = "";
if (!isset($_SERVER['HTTP_HOST']))      $_SERVER['HTTP_HOST'] = "";
if (!isset($_SERVER['REQUEST_METHOD'])) $_SERVER['REQUEST_METHOD'] = "";

function _dr(): string
{
    return wp_normalize_path(implode('/', func_get_args()));
}

function dr_clean_url($url): string
{
    return filter_var($url, FILTER_SANITIZE_URL);
}

function dr_locale()
{
    // Determine the current locale
    $locale = determine_locale();

    // Allow developers to modify the locale
    $locale = apply_filters('plugin_locale', $locale, 'dragonizer');

    // Get the plugin's base path
    $plugin_base = dirname(plugin_basename(DRAGONIZER_FILE));

    // First try to load from WP_LANG_DIR/plugins/
    $mofile_global = WP_LANG_DIR . '/plugins/dragonizer-' . $locale . '.mo';
    if (file_exists($mofile_global)) {
        load_textdomain('dragonizer', $mofile_global);
    }

    // Then try to load from plugin's languages directory
    $mofile_local = dirname(DRAGONIZER_FILE) . '/languages/dragonizer-' . $locale . '.mo';
    if (file_exists($mofile_local)) {
        load_textdomain('dragonizer', $mofile_local);
    }

    // As a fallback, try loading from the default location
    load_plugin_textdomain('dragonizer', false, $plugin_base . '/languages');
}

function dr_check(): bool
{
    $error_conditions = [];

    // Check if the current plugin slug matches 'dragonizer/dragonizer.php'
    if (DRAGONIZER_BASE !== 'dragonizer/dragonizer.php') {
        $error_conditions['wrong_slug'] = true;
    }

    // Check PHP version
    if (version_compare(PHP_VERSION, '7.4.0', '<')) {
        $error_conditions['php_version'] = true;
    }

    // Check WordPress version
    if (version_compare(get_bloginfo('version'), '5.3.0', '<')) {
        $error_conditions['wp_version'] = true;
    }

    // Check for mb_detect_encoding function
    if (!function_exists('mb_detect_encoding')) {
        $error_conditions['mb_detect_encoding'] = true;
    }

    // Define a function to safely test eval()
    $test_eval = function () {
        try {
            $result = eval('return 7 + 6;');
            return $result === 13;
        } catch (\Throwable $e) {
            // Handle any exceptions that may occur
            return false;
        }
    };

    // Execute the testEval function and check for errors
    if (!$test_eval()) {
        $error_conditions['eval_not_working'] = true;
    }

    if (empty($error_conditions)) {
        return true;
    }

    // Add admin notices hook to display errors based on the stored conditions
    add_action('admin_notices', function () use ($error_conditions) {  // Use reference to ensure we capture updates to the array
        if (!empty($error_conditions)) {

            $html = '<div class="notice notice-error" id="drag_dragonizer_about">';
            $html .= '<div style="display: flex; align-items: center;"><img style="margin-top:1em;margin-left:1em;margin-right:1em;width:74px" src="' . _dr(DRAGONIZER_URL, '/assets/images/logo/main.png') . '?ver=' . DRAGONIZER_VER . '" alt=""><div> <h2 style="font-weight: bold; font-size: 2em; ">' . __('Dragonizer', 'dragonizer') . '</h2> <p style="margin-top:-1em; display: flex; align-items: center;">' . __('Your assistant to make WordPress more powerful', 'dragonizer') . '</p> </div> </div> <br>';
            if (!empty($error_conditions['wrong_slug'])) {
                $html .= '<p>' . __('This plugin is not installed correctly. Please make sure the plugin slug is "dragonizer/dragonizer.php".', 'dragonizer') . '</p>';
            }
            if (!empty($error_conditions['php_version'])) {
                $html .= '<p>' . sprintf(__('This plugin requires PHP 7.4.0 or higher, but your PHP version is %s.', 'dragonizer'), PHP_VERSION) . '</p>';
            }
            if (!empty($error_conditions['wp_version'])) {
                $html .= '<p>' . sprintf(__('This plugin requires WordPress 5.3.0 or higher, but your WordPress version is %s.', 'dragonizer'), get_bloginfo('version')) . '</p>';
            }
            if (!empty($error_conditions['mb_detect_encoding'])) {
                $html .= '<p>' . __('The mb_detect_encoding function is unavailable. The mbstring PHP extension may not be configured correctly. Please check its installation and settings, or contact your hosting provider for assistance.', 'dragonizer') . '</p>';
            }
            if (!empty($error_conditions['rtl_careunit_version'])) {
                $html .= '<p>' . __('Please update the RTL-CareUnit plugin to at least version %s for compatibility.', 'dragonizer') . '</p>';
            }
            if (!empty($error_conditions['eval_not_working'])) {
                $html .= '<p>' . __('The eval() function is disabled or not available in this environment, which is required for dragonizer plugin.', 'dragonizer') . '</p>';
            }
            $html .= '<br><br></div>';
            echo $html;
        }
    });

    return false;
}

function dr_array_equal($array1, $array2): bool
{
    return is_array($array1)
        && is_array($array2)
        && count($array1) == count($array2)
        && array_multisort($array1)
        && array_multisort($array2)
        && serialize($array1) === serialize($array2);
}

function dr_to_https($url): string
{
    if (dr_is_url($url) && dr_is_ssl()) {
        $url = str_replace('http://', 'https://', $url);
    }

    return $url;
}

function dr_boolean($value)
{
    if (is_string($value)) {
        switch (strtolower($value)) {
            case '+':
            case '1':
            case 'y':
            case 'on':
            case 'yes':
            case 'true':
            case 'enabled':
                return true;

            case '-':
            case '0':
            case 'n':
            case 'no':
            case 'off':
            case 'false':
            case 'disabled':
                return false;
        }
    }

    return $value;
}

function dr_relative_to_url(string $path): string
{
    // If it's already an absolute URL, return it
    if (preg_match('#^https?://#', $path)) {
        return $path;
    }

    // Get upload directory info
    $upload_dir = wp_upload_dir();
    $base_dir = wp_normalize_path($upload_dir['basedir']);
    $base_url = $upload_dir['baseurl'];

    // Convert path to normalized form
    $path = wp_normalize_path($path);

    // If this is a full server path
    if (strpos($path, ABSPATH) === 0 || strpos($path, $base_dir) === 0) {
        // If it's in uploads directory
        if (strpos($path, $base_dir) === 0) {
            $relative_path = str_replace($base_dir, '', $path);
            return rtrim($base_url, '/') . '/' . ltrim($relative_path, '/');
        }

        // If it's in WordPress root directory
        $relative_path = str_replace(ABSPATH, '', $path);
        return rtrim(site_url(), '/') . '/' . ltrim($relative_path, '/');
    }

    // If it starts with a forward slash and includes the subdirectory
    if (strpos($path, '/') === 0) {
        $site_path = parse_url(site_url(), PHP_URL_PATH);
        if ($site_path && strpos($path, $site_path) === 0) {
            // Remove duplicate subdirectory
            $path = substr($path, strlen($site_path));
        }
        return rtrim(site_url(), '/') . '/' . ltrim($path, '/');
    }

    // If it's already a relative path with wp-content
    if (strpos($path, 'wp-content/') !== false) {
        $relative_path = substr($path, strpos($path, 'wp-content/'));
        return rtrim(site_url(), '/') . '/' . $relative_path;
    }

    // Default fallback: append to site URL
    return rtrim(site_url(), '/') . '/' . ltrim($path, '/');
}

function dr_url_to_relative(string $url, bool $removeSubdirectory = false): string
{
    // Ensure the URL is cleaned up.
    $cleanedUrl = dr_clean_url($url);

    // Get the domain of the site to use for comparison.
    $siteUrl = get_site_url();
    $siteDomain = parse_url($siteUrl, PHP_URL_HOST);

    // Remove the domain from the URL, leaving the path, including the subdirectory if present.
    $relativePath = preg_replace('#^https?://' . preg_quote($siteDomain, '#') . '#i', '', $cleanedUrl);

    if ($removeSubdirectory) {
        // Determine the path to the WordPress installation directory.
        $wpInstallDir = parse_url($siteUrl, PHP_URL_PATH);

        // Make sure to remove the installation directory from the relative path if needed.
        if (!empty($wpInstallDir)) {
            $relativePath = preg_replace('#^' . preg_quote($wpInstallDir, '#') . '#', '', $relativePath);
        }
    }

    // Ensure the path starts with a '/'.
    if ($relativePath === '' || $relativePath[0] !== '/') {
        $relativePath = '/' . $relativePath;
    }

    return $relativePath;
}

function dr_get_domain_only($host): string
{
    $host = strtolower(trim($host));
    $host = ltrim(str_replace("http://", "", str_replace("https://", "", $host)), "www.");
    $count = substr_count($host, '.');

    if ($count === 2) {
        if (strlen(explode('.', $host)[1]) > 3) $host = explode('.', $host, 2)[1];
    } elseif ($count > 2) {
        $host = dr_get_domain_only(explode('.', $host, 2)[1]);
    }

    $host = explode('/', $host);

    return $host[0];
}

function dr_current_url(): string
{
    return _dr((dr_is_ssl() ? 'https://' : 'http://') . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']);
}

function dr_simple_url(string $url): string
{
    return str_replace(['http://', 'https://', 'www.'], '', rtrim($url, '/#'));
}

function dr_is_ssl(): bool
{
    switch (true) {
        case (isset($_SERVER['HTTPS']) && dr_boolean($_SERVER['HTTPS'])):
        case (isset($_SERVER['SERVER_PORT']) && (int)$_SERVER['SERVER_PORT'] == 443):
        case (isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https'):
            return true;
        default:
            return false;
    }
}

function dr_is_url(string $url, bool $scheme = true): bool
{
    if ($scheme) {
        return preg_match('~^(https?:)?//~', $url);
    } else {
        // Add a scheme if it's missing
        if (!preg_match('/^https?:\/\//', $url)) {
            $url = 'http://' . ltrim($url, '/');
        }
        // Use FILTER_VALIDATE_URL for validation
        return filter_var($url, FILTER_VALIDATE_URL) !== false;
    }
}

function dr_remove_cdata(string $str): string
{
    return (false !== strpos($str, '<![CDATA['))
        ? str_replace(array('/* <![CDATA[ */', '/* ]]> */', '/*<![CDATA[*/', '/*]]>*/', '<![CDATA[', ']]>'), '', $str)
        : $str;
}

function dr_redirect($redirect_url = false, $return = false)
{
    if (!empty($redirect_url)) {
        if ($return || headers_sent()) {
            $script = '<script type="text/javascript" data-no-optimize="1" data-no-defer="1">document.location = "' . esc_attr(stripslashes($redirect_url)) . '"</script>';
            if ($return) return $script;
            echo $script;
        } else {
            wp_redirect($redirect_url, "301");
            exit();
        }
    }

    return false;
}

function dr_to_shamsi($gy = null, $gm = null, $gd = null): string
{
    $time = false;

    if (count(func_get_args()) === 0) {

        if (get_locale() !== 'fa_IR') return date("Y/m/d H:i:s");

        $dt = new DateTime("now", new DateTimeZone('Asia/Tehran'));

        $gy = $dt->format("Y");
        $gm = $dt->format("m");
        $gd = $dt->format("d");

        $gh = $dt->format("H");
        $gi = $dt->format("i");
        $gs = $dt->format("s");

        $time = true;
    } elseif (count(func_get_args()) === 1) {
        if (get_locale() !== 'fa_IR') return date("Y/m/d H:i:s", $gy);

        $dt = new DateTime('@' . $gy, new DateTimeZone('Asia/Tehran'));

        $gy = $dt->format("Y");
        $gm = $dt->format("m");
        $gd = $dt->format("d");

        $gh = $dt->format("H");
        $gi = $dt->format("i");
        $gs = $dt->format("s");

        $time = true;
    } else {
        $gh = $gi = $gs = '';
    }

    $g_d_m = array(0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334);
    $gy2 = ($gm > 2) ? ($gy + 1) : $gy;
    $days = 355666 + (365 * $gy) + ((int)(($gy2 + 3) / 4)) - ((int)(($gy2 + 99) / 100)) + ((int)(($gy2 + 399) / 400)) + $gd + $g_d_m[$gm - 1];
    $jy = -1595 + (33 * ((int)($days / 12053)));
    $days %= 12053;
    $jy += 4 * ((int)($days / 1461));
    $days %= 1461;

    if ($days > 365) {
        $jy += (int)(($days - 1) / 365);
        $days = ($days - 1) % 365;
    }

    if ($days < 186) {
        $jm = 1 + (int)($days / 31);
        $jd = 1 + ($days % 31);
    } else {
        $jm = 7 + (int)(($days - 186) / 30);
        $jd = 1 + (($days - 186) % 30);
    }

    $date = sprintf('%d/%02d/%02d', $jy, $jm, $jd);
    return $time ? $date . sprintf(' %02d:%02d:%02d', $gh, $gi, $gs) : $date;
}

function dr_is_localhost($whitelist = ['127.0.0.1', '::1']): bool
{
    return in_array($_SERVER['REMOTE_ADDR'], $whitelist);
}

function dr_substr($string, $needle, $nth = 0, $start = 0): string
{
    $i = $pos = 0;
    do {
        $pos = stripos($string, $needle, $pos + 1);
    } while ($i++ < ($nth - 1));

    return substr($string, $start, $pos);
}

function dr_strposa($haystack, $needles = [], $offset = 0)
{
    $chr = [];
    foreach ($needles as $needle) {
        $res = ($offset === -1) ? dr_starts_with($haystack, $needle) : stripos($haystack, $needle, $offset);
        if ($res !== false) $chr[$needle] = $res;
    }

    if (empty($chr)) return false;

    return min($chr);
}

function dr_in_array(string $search, array $array, bool $ends_with = false): bool
{
    foreach ($array as $value) {
        if ($ends_with) {
            if (dr_ends_with($search, $value) !== false) return true;
        } else {
            if (stripos($search, $value) !== false) return true;
        }
    }

    return false;
}

function dr_in_array2(string $search, array $array, bool $ends_with = false): bool
{
    foreach ($array as $value) {
        if ($ends_with) {
            // Check if the search string ends with the current array value
            if (substr_compare($search, $value, -strlen($value)) === 0) return true;
        } else {
            // Case-insensitive substring search
            if (stripos($search, $value) !== false) return true;
        }
    }
    return false;
}

function dr_substr_replace($string, $replacement, $start, $length = null)
{
    return mb_substr($string, 0, $start) . $replacement . mb_substr($string, $start + ($length ?: mb_strlen($string)));
}

function dr_replace_first($search, $replace, $subject): string
{
    $pos = mb_stripos($subject, $search);
    return $pos === false ? $subject : dr_substr_replace($subject, $replace, $pos, mb_strlen($search));
}

function dr_replace_last($search, $replace, $subject): string
{
    $pos = mb_strrpos($subject, $search);
    return $pos !== false ? dr_substr_replace($subject, $replace, $pos, mb_strlen($search)) : $subject;
}

function dr_ends_with($haystack, $needle): bool
{
    $length = strlen($needle);

    return substr($haystack, -$length) === $needle || !$length;
}

function dr_starts_with($haystack, $needle): bool
{
    $length = strlen($needle);

    return substr($haystack, 0, $length) === $needle;
}

function dr_is_woocommerce(): bool
{
    return in_array('woocommerce/woocommerce.php', apply_filters('active_plugins', get_option('active_plugins')));
}

function dr_is_login($login_slug = '')
{
    try {
        $shahkar_login_url_option = get_option('shahkar_indexpage_url');
        $shahkar_login_url_path   = $shahkar_login_url_option ? '/' . trim($shahkar_login_url_option, '/') . '/' : '';
        $wp_login_url             = wp_login_url('', true);
    } catch (\Throwable $th) {
        $wp_login_url           = 'NOTVALIDURIX';
        $shahkar_login_url_path = '';
    }

    $current_request_uri       = rtrim(strtolower(parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH) ?: 'NOTVALIDURIX'), '/');
    $parsed_wp_login_path      = rtrim(strtolower(parse_url($wp_login_url, PHP_URL_PATH)), '/');
    $parsed_shahkar_login_path = $shahkar_login_url_path ? rtrim(strtolower($shahkar_login_url_path), '/') : 'NOTVALIDURIX';

    switch (true) {
        case (did_action('login_header')):
        case (function_exists('login_header')):
        case (!empty($_SERVER['PHP_SELF']) && $_SERVER['PHP_SELF'] === '/wp-login.php'):
        case (dr_strposa($current_request_uri, ['loggedout=true', '/login/', '/login']) !== false):
        case (!empty($_REQUEST['action']) && $_REQUEST['action'] === 'register'):
        case (isset($GLOBALS['pagenow']) && $GLOBALS['pagenow'] === 'wp-login.php'):
        case ($login_slug !== '' && dr_ends_with(rtrim(add_query_arg(null, null), '/'), $login_slug) !== false):
        case ($current_request_uri === $parsed_wp_login_path):
        case ($shahkar_login_url_path && stripos($current_request_uri, $parsed_shahkar_login_path) !== false):
            return true;

        default:
            return false;
    }
}

function dr_insert_after(string $html, string $new_content, string $tag_name = 'body', $first = true): string
{
    return preg_replace($first ? "#(<{$tag_name}[^>]*>)#is" : "#(<{$tag_name}[^>]*>)(?!.*<{$tag_name}[^>]*>)#is", '$1' . $new_content, $html, 1);
}

function dr_array_merge(): array
{
    $args = func_get_args();

    if (func_num_args() == 0) return [];
    if (func_num_args() == 1) return $args[0];

    $result = array_flip(array_flip($args[0]));
    foreach (array_slice($args, 1) as $arg) {
        if (!empty($arg)) {
            $result =
                array_flip(
                    array_flip(
                        array_merge($result, $arg)
                    )
                );
        }
    }

    return array_values($result);
}

function dr_parse_args(array $args, array $default): array
{
    $args = array_merge($default, $args);

    return array_intersect_key($args, $default);
}

function dr_remove_parameter(string $url, string $param): string
{
    $urlQuery = parse_url($url, PHP_URL_QUERY);
    parse_str($urlQuery, $urlQueryArr);
    unset($urlQueryArr[$param]);

    return rtrim(str_replace($urlQuery, http_build_query($urlQueryArr), $url), '?');
}

function dr_base_url(string $url): string
{
    $result = parse_url($url);

    return $result['scheme'] . "://" . $result['host'];
}

function dr_chmod($targetPath, $permissions = 0644)
{
    if (file_exists($targetPath)) {
        return @chmod($targetPath, $permissions);
    }

    return false;
}

function dr_die_array($input, string $title = '', bool $die = true): void
{
    echo "<h4>$title</h4>";
    echo '<pre>';
    is_array($input) ? var_export($input) : var_dump($input);
    echo '</pre><br>';
    $die and die;
}

function dr_object($array)
{
    if (is_array($array)) {
        return (object) array_map(__FUNCTION__, $array);
    }
    return $array;
}

function dr_array_merge_recursive($array1, $array2): array
{
    if ($array2 === null) {
        return $array1;
    }

    foreach ($array2 as $key => $value) {
        if (is_array($value) && isset($array1[$key]) && is_array($array1[$key])) {
            $array1[$key] = dr_array_merge_recursive($array1[$key], $value);
        } elseif (!is_numeric($key) || !in_array($value, $array1)) {
            $array1[$key] = $value;
        }
    }

    return $array1;
}

function dr_replace_keys_hyphens(&$array, $parentKey = null)
{
    $newArray = array();
    foreach ($array as $key => $value) {
        if ($parentKey === 'values') {
            $newKey = $key;
        } else {
            $newKey = str_replace('-', '_', $key);
        }

        if (is_array($value)) {
            $value = dr_replace_keys_hyphens($value, $key);
        }

        $newArray[$newKey] = $value;
    }
    return $newArray;
}

function dr_fix_settings($default, $options)
{
    return dr_object(dr_array_merge_recursive($default, dr_boolean_recursive(dr_replace_keys_hyphens($options))));
}

function dr_boolean_recursive($array)
{
    foreach ($array as &$value) {
        if (is_array($value)) {
            $value = dr_boolean_recursive($value);
        } else {
            $value = dr_boolean($value);
        }
    }
    return $array;
}

function dr_make_relative_path(string $absolute_path): string
{
    // Check if WordPress functions are available
    if (!function_exists('get_home_path')) {
        return $absolute_path; // Return original path if not in WordPress environment
    }

    // Get the WordPress installation's root path
    $wp_root_path = get_home_path();

    // Make the path relative if it starts with the WordPress root path
    if (substr($absolute_path, 0, strlen($wp_root_path)) == $wp_root_path) {
        return '/' . ltrim(substr($absolute_path, strlen($wp_root_path)), '/');
    }

    // Return the original path if it's not within the WordPress root directory
    return $absolute_path;
}

function dr_current_host()
{
    $site_url = site_url();

    $parsed_url = parse_url($site_url);
    $host = $parsed_url['host'];

    // Split the host into its subdomain and main domain components
    $host_parts = explode('.', $host);

    // Check if there is a subdomain present (assuming at least a domain and a TLD)
    if (count($host_parts) > 2) {
        // Extract subdomain (everything except the last two parts)
        $subdomain = implode('-', array_slice($host_parts, 0, -2));
        // Extract main domain (last two parts)
        $main_domain = implode('-', array_slice($host_parts, -2));
        // Return the string with subdomain first, followed by main domain
        return $subdomain . '-' . $main_domain;
    } else {
        // No subdomain, just replace dots with dashes in the host
        return str_replace('.', '-', $host);
    }
}

function dr_clean_dragonizer_transients($excludes = ['saving_settings', 'cache_clear_needed'])
{
    global $wpdb;

    // Query to get all transients starting with 'dragonizer_'
    $transients = $wpdb->get_col("
        SELECT option_name 
        FROM $wpdb->options 
        WHERE option_name LIKE '_transient_dragonizer_%' 
        OR option_name LIKE '_transient_timeout_dragonizer_%'
    ");

    // Loop through the transients
    foreach ($transients as $transient) {
        $transient_name = str_replace(['_transient_timeout_', '_transient_'], '', $transient);

        // Check if the transient name contains any of the excluded strings
        $exclude = false;
        foreach ($excludes as $exclude_term) {
            if (strpos($transient_name, $exclude_term) !== false) {
                $exclude = true;
                break;
            }
        }

        // If not excluded, delete the transient
        if (!$exclude) {
            delete_transient($transient_name);
        }
    }
}

function dr_handle_transient($name, $mode = 'get', $value = null, $expiration = 0)
{
    // Remove prefix if it's already there to avoid double prefixing
    $prefix = 'dragonizer_';
    $name = (strpos($name, $prefix) === 0) ? $name : $prefix . $name;

    switch ($mode) {
        case 'set':
            if ($expiration > 0) {
                // Only set expiration if it's greater than 0
                return set_transient($name, $value, $expiration);
            } else {
                // For zero expiration, store without timeout
                return set_transient($name, $value);
            }

        case 'get':
            $transient_value = get_transient($name);

            // Only check expiration for non-false values and when there might be an expiration
            if ($transient_value !== false) {
                $timeout_option = "_transient_timeout_" . str_replace($prefix, '', $name);
                $expiration_time = get_option($timeout_option);

                // Only consider it expired if there is an expiration time and it's passed
                if ($expiration_time && $expiration_time < time()) {
                    delete_transient($name);
                    return false;
                }
            }
            return $transient_value;

        case 'delete':
            return delete_transient($name);

        default:
            return false;
    }
}

function dr_get_log_filename()
{
    $formatted_host = dr_current_host();

    return $formatted_host . '-debug-' . hash('adler32', $formatted_host) . '.log';
}

function dr_trim_log_file($file_path, $max_size = 5)
{
    // Convert the size to bytes
    $max_size_in_bytes = $max_size * 1048576; // 1 MB = 1,048,576 bytes

    if (file_exists($file_path) && filesize($file_path) > $max_size_in_bytes) {
        // Read the current content of the file
        $content = file($file_path);

        // Determine the number of lines to remove
        // For example, remove the first 20% of lines
        $lines_to_remove = ceil(count($content) * 0.2);
        $trimmed_content = array_slice($content, $lines_to_remove);

        // Write the trimmed content back to the file
        DRFS::write($file_path, $trimmed_content);
    }
}

function dr_word_appears_twice_strpos($word, $string)
{
    // Check if the word is a string and not empty
    if (!is_string($word) || $word === '') {
        return false;
    }

    // Check if the string is valid
    if (!is_string($string)) {
        return false;
    }

    $firstOccurrence = strpos($string, $word);
    if ($firstOccurrence !== false) {
        $secondOccurrence = strpos($string, $word, $firstOccurrence + strlen($word));
        return $secondOccurrence !== false;
    }
    return false;
}

function dr_get_data($url)
{
    $urls = array(
        str_replace('https://', 'http://', $url),
        str_replace('http://', 'https://', $url)
    );

    foreach ($urls as $try_url) {
        $response = wp_remote_get($try_url, array('timeout' => 30));

        if (!is_wp_error($response) && wp_remote_retrieve_response_code($response) === 200) {
            return wp_remote_retrieve_body($response);
        }
    }

    return false;
}













// Function to get update data with local fallback
function dr_get_update_data($url)
{
    global $localUpdateFile;

    $response = wp_remote_get($url, array('timeout' => 10));

    if (!is_wp_error($response) && wp_remote_retrieve_response_code($response) === 200) {
        return wp_remote_retrieve_body($response);
    } else {
        error_log("Failed to fetch remote update data. Using local fallback.");
        if (file_exists($localUpdateFile)) {
            return file_get_contents($localUpdateFile);
        } else {
            error_log("Local fallback file not found at: $localUpdateFile");
            return false;
        }
    }
}

function dr_ensure_scheme(string $url): string
{
    return preg_replace("/(http(s)?:\/\/|\/\/)(.*)/i", "http$2://$3", $url);
}

function dr_url_to_dir(string $url): ?string
{
    // Check for empty input or just a dot
    if (empty($url) || $url === '.') {
        return null;
    }

    $upload_dirs = wp_upload_dir();
    $site_url = get_site_url();
    $home_url = get_home_url();

    // Handle cases where site_url and home_url might be different
    $site_path = parse_url($site_url, PHP_URL_PATH) ?: '';
    $home_path = parse_url($home_url, PHP_URL_PATH) ?: '';
    $upload_path = parse_url($upload_dirs['baseurl'], PHP_URL_PATH) ?: '';

    // Extract just the path portion without decoding
    $parsed = parse_url($url);
    if (!$parsed || empty($parsed['path'])) {
        return null;
    }

    // Split the path to separate the filename
    $path_parts = explode('/', $parsed['path']);
    $filename = end($path_parts);

    // Only decode the directory path, not the filename
    $dir_path = implode('/', array_slice($path_parts, 0, -1));

    // Handle multisite subdirectory installations
    if (is_multisite() && !is_subdomain_install()) {
        $blog_details = get_blog_details();
        if ($blog_details && !empty($blog_details->path)) {
            $blog_path = rtrim($blog_details->path, '/');
            $dir_path = preg_replace('#^' . preg_quote($blog_path, '#') . '#', '', $dir_path);
        }
    }

    // Determine the base path considering subdirectory installations
    if (strpos($url, $upload_dirs['baseurl']) !== false) {
        // Handle upload directory path
        $dir_path = str_replace($upload_path, '', $dir_path);
        $base_dir = $upload_dirs['basedir'];
    } elseif (strpos($url, $site_url) !== false) {
        // Handle site URL path
        $dir_path = str_replace($site_path, '', $dir_path);
        $base_dir = ABSPATH;
    } elseif (strpos($url, $home_url) !== false) {
        // Handle home URL path
        $dir_path = str_replace($home_path, '', $dir_path);
        $base_dir = ABSPATH;
    } elseif (preg_match('#/wp-content/uploads/#', $dir_path)) {
        // Handle direct upload URLs that might not match site URL
        $upload_position = strpos($dir_path, '/wp-content/uploads/');
        $dir_path = substr($dir_path, $upload_position);
        $base_dir = WP_CONTENT_DIR;
    } else {
        // Default to ABSPATH
        $base_dir = ABSPATH;
    }

    // Clean up the paths
    $base_dir = rtrim($base_dir, '/');
    $dir_path = trim($dir_path, '/');

    // Handle special cases where WP_CONTENT_DIR might be outside ABSPATH
    if (strpos($dir_path, 'wp-content/uploads') === 0) {
        $dir_path = substr($dir_path, strlen('wp-content/uploads'));
        $base_dir = $upload_dirs['basedir'];
    }

    // Construct the final path preserving the original filename
    $file_path = $base_dir . '/' . $dir_path . '/' . $filename;

    // Clean up double slashes and normalize
    $file_path = preg_replace('#/+#', '/', $file_path);

    // Security check: Prevent directory traversal
    $real_path = realpath(dirname($file_path));
    if ($real_path === false) {
        return null;
    }

    // Verify the path is within allowed WordPress directories
    $allowed_paths = [
        realpath(ABSPATH),
        realpath(WP_CONTENT_DIR),
        realpath($upload_dirs['basedir'])
    ];

    $is_allowed = false;
    foreach ($allowed_paths as $allowed_path) {
        if ($allowed_path && strpos($real_path, $allowed_path) === 0) {
            $is_allowed = true;
            break;
        }
    }

    if (!$is_allowed) {
        return null;
    }

    // Check if file exists
    if (file_exists($file_path)) {
        return $file_path;
    }

    return null;
}

function dr_minified_path(string $file_path): string
{
    $file_path = dr_clean_url($file_path);
    $file_path = str_replace(array('https://' . $_SERVER['HTTP_HOST'] . '/', 'http://' . $_SERVER['HTTP_HOST'] . '/', '//' . $_SERVER['HTTP_HOST'] . '/'), array('/', '/', '/'), $file_path);
    $file_path = dr_fix_subfolder($file_path);

    return $file_path;
}

function dr_fix_subfolder(string $file_path): string
{
    // Retrieve the site URL and document root
    $site_url = get_site_url(); // WordPress function to get the site URL
    $site_path = parse_url($site_url, PHP_URL_PATH); // Extract the path component from the site URL
    $document_root = wp_normalize_path($_SERVER['DOCUMENT_ROOT']);

    // Ensure that the file path starts with the document root
    if (strpos($file_path, $document_root) === 0) {
        // Strip the document root from the file path to get the relative path
        $relative_path = substr($file_path, strlen($document_root));

        // Check if the site is installed in a subdirectory and the relative path does not already reflect this
        if ($site_path && strpos($relative_path, $site_path) !== 0) {
            // Adjust the path to include the site path
            $file_path = rtrim($document_root, '/') . $site_path . $relative_path;
        }
    }

    return wp_normalize_path($file_path);
}

/**
 * Log a message for the Dragonizer system
 *
 * Configuration: Define DRAGONIZER_DEBUG constant before using this function.
 * Possible values for DRAGONIZER_DEBUG:
 * - boolean true: Enable all sections with default level (info)
 * - string (log level): Enable all sections with specified level
 * - string (section name): Enable only specified section with default level (info)
 * - array [level, sections]: Enable specified sections with specified level
 *
 * Log Levels:
 * - debug: Logs all messages
 * - info: Logs info, warning, and error messages
 * - warning: Logs warning and error messages
 * - error: Logs only error messages
 *
 * @param string $section The section of the code generating the log
 * @param string $message The message to be logged
 * @param string $level The log level (debug, info, warning, error)
 * @return bool True if the message was logged, false otherwise
 */
function dragonizer_log($section, $message, $level = 'info')
{
    if (!defined('DRAGONIZER_DEBUG')) {
        return false;
    }

    $default_level = 'info';
    $default_sections = ['preloading', 'login_customizer', 'critical_css', 'settings', 'updater', 'cache', 'cron'];
    $log_levels = ['debug' => 0, 'info' => 1, 'warning' => 2, 'error' => 3];

    // Parse DRAGONIZER_DEBUG configuration
    if (is_bool(DRAGONIZER_DEBUG)) {
        $debug_level = DRAGONIZER_DEBUG ? $default_level : null;
        $active_sections = $default_sections;
    } elseif (is_string(DRAGONIZER_DEBUG)) {
        if (isset($log_levels[DRAGONIZER_DEBUG])) {
            $debug_level = DRAGONIZER_DEBUG;
            $active_sections = $default_sections;
        } elseif (in_array(DRAGONIZER_DEBUG, $default_sections)) {
            $debug_level = $default_level;
            $active_sections = [DRAGONIZER_DEBUG];
        } else {
            return false;
        }
    } elseif (is_array(DRAGONIZER_DEBUG) && count(DRAGONIZER_DEBUG) === 2) {
        $debug_level = DRAGONIZER_DEBUG[0];
        $active_sections = array_intersect(DRAGONIZER_DEBUG[1], $default_sections);
        if (!isset($log_levels[$debug_level]) || empty($active_sections)) {
            return false;
        }
    } else {
        return false;
    }

    // Check if logging is enabled and the section is active
    if ($debug_level === null || !in_array($section, $active_sections)) {
        return false;
    }

    // Check if the logging level is valid and appropriate
    // if (!isset($log_levels[$level]) || $log_levels[$level] < $log_levels[$debug_level]) {
    //     return false;
    // }

    // Ensure the log directory exists and is writable
    $log_dir = WP_CONTENT_DIR . '/logs';
    if (!is_dir($log_dir) && !mkdir($log_dir, 0755, true)) {
        error_log("Failed to create log directory: $log_dir");
        return false;
    }

    // Log the message
    $log_file = $log_dir . '/dragonizer.log';
    $log_entry = sprintf(
        "[%s] [%s-%s]: %s%s",
        date('Y-m-d H:i:s'),
        $section,
        $level,
        $message,
        PHP_EOL
    );

    $directory = dirname($log_file);
    if (!file_exists($directory)) {
        if (!wp_mkdir_p($directory)) {
            return false;
        }
    }

    if (file_put_contents($log_file, $log_entry, FILE_APPEND | LOCK_EX) === false) {
        error_log("Failed to write to log file: $log_file");
        return false;
    }

    return true;
}

// Example usage:
// define('DRAGONIZER_DEBUG', 'debug'); // or any other valid configuration
// dragonizer_log('caching', 'Detailed debug information.', 'debug');
// dragonizer_log('optimizing', 'General information.', 'info');
// dragonizer_log('tweaks', 'Warning about performance.', 'warning');
// dragonizer_log('security', 'Critical error detected.', 'error');