<?php
// If user not in admin area, abort.
defined('DRAGONIZER_ADMIN_INIT') || die();

require_once 'dragonizer-shared-functions.php';

function display_caching($obj)
{
    $callback = is_multisite() ? 'is_plugin_active_for_network' : 'is_plugin_active';
    $plugins = array_filter($obj->bad_plugins['optimizer'], $callback);

    if (count($plugins) > 0) {
        dragonizer_display_plugin_warning($obj, $plugins);
    } else {
        dragonizer_display_cache_settings($obj);
    }
}

function dragonizer_display_cache_triggers_info()
{
?>
    <style>
        .dragonizer-cache-info {
            margin: 30px 0;
        }

        .dragonizer-cache-header {
            background: #fff;
            border-radius: 6px;
            box-shadow: rgba(0, 0, 0, .05) 0 1px 2px 0 !important;
            border: 1px solid #eee;
            padding: 20px;
            display: flex;
            align-items: center;
            justify-content: space-between;
            cursor: pointer;
            transition: all 0.2s ease;
        }

        .dragonizer-cache-header:hover {
            box-shadow: rgba(0, 0, 0, .1) 0 1px 3px 0 !important;
        }

        .dragonizer-cache-title {
            font-size: 16px;
            font-weight: 500;
            color: #333;
            display: flex;
            align-items: center;
            gap: 8px;
        }

        .dragonizer-cache-content {
            max-height: 0;
            overflow: hidden;
            transition: max-height 0.5s ease;
        }

        .dragonizer-cache-content.expanded {
            max-height: 2000px;
        }

        .dragonizer-cache-inner {
            background: #fff;
            border-radius: 6px;
            box-shadow: rgba(0, 0, 0, .05) 0 1px 2px 0 !important;
            border: 1px solid #eee;
            padding: 24px;
            margin-top: 10px;
        }

        .dragonizer-cache-section {
            margin-bottom: 32px;
        }

        .dragonizer-cache-section:last-child {
            margin-bottom: 0;
        }

        .dragonizer-cache-section h3 {
            font-size: 15px;
            font-weight: 500;
            color: #333;
            margin: 0 0 16px;
            padding-bottom: 8px;
            border-bottom: 1px solid #e0e0e0;
            display: flex;
            align-items: center;
            gap: 8px;
        }

        .dragonizer-cache-section h3 .dashicons {
            color: #0073aa;
            font-size: 16px;
            width: 16px;
            height: 16px;
        }

        .dragonizer-trigger-list {
            margin: 0;
            padding: 0;
            list-style: none;
        }

        .dragonizer-trigger-list li {
            position: relative;
            padding-inline-start: 20px;
            margin-bottom: 12px;
            color: #555;
            line-height: 1.6;
        }

        .dragonizer-trigger-list li:last-child {
            margin-bottom: 0;
        }

        .dragonizer-trigger-list li:before {
            content: '';
            position: absolute;
            inset-inline-start: 0;
            top: 10px;
            width: 4px;
            height: 4px;
            background: #0073aa;
            border-radius: 50%;
        }

        .dragonizer-cache-expand {
            display: flex;
            align-items: center;
            gap: 6px;
            color: #0073aa;
            font-size: 14px;
            font-weight: 500;
        }

        .dragonizer-cache-expand .dashicons {
            transition: transform 0.3s ease;
            font-size: 16px;
            width: 16px;
            height: 16px;
        }

        .dragonizer-cache-expand.expanded .dashicons {
            transform: rotate(180deg);
        }

        /* RTL Support */
        [dir="rtl"] .dragonizer-trigger-list li {
            padding-right: 20px;
            padding-left: 0;
        }

        [dir="rtl"] .dragonizer-trigger-list li:before {
            right: 0;
            left: auto;
        }

        [dir="rtl"] .dragonizer-cache-expand.expanded .dashicons {
            transform: rotate(-180deg);
        }
    </style>

    <div class="dragonizer-cache-info">
        <div class="dragonizer-cache-header" onclick="toggleCacheInfo(this)">
            <div class="dragonizer-cache-title">
                <span class="dashicons dashicons-info-outline"></span>
                <?php esc_html_e('When is cache automatically managed by Dragonizer?', 'dragonizer'); ?>
            </div>
            <div class="dragonizer-cache-expand">
                <span class="expand-text"><?php esc_html_e('Show details', 'dragonizer'); ?></span>
                <span class="dashicons dashicons-arrow-down-alt2"></span>
            </div>
        </div>

        <div class="dragonizer-cache-content">
            <div class="dragonizer-cache-inner">
                <!-- Complete Cache Clear Events -->
                <div class="dragonizer-cache-section">
                    <h3>
                        <span class="dashicons dashicons-backup"></span>
                        <?php esc_html_e('Complete Cache Clear', 'dragonizer'); ?>
                    </h3>
                    <ul class="dragonizer-trigger-list">
                        <li><?php esc_html_e('WordPress core system updates', 'dragonizer'); ?></li>
                        <li><?php esc_html_e('Plugin activation or deactivation events', 'dragonizer'); ?></li>
                        <li><?php esc_html_e('Theme switching or customization changes', 'dragonizer'); ?></li>
                        <li><?php esc_html_e('Global setting changes (permalink structure, tag base, category base)', 'dragonizer'); ?></li>
                        <li><?php esc_html_e('Navigation menu updates (creation, modification, deletion)', 'dragonizer'); ?></li>
                        <li><?php esc_html_e('Widget area modifications and updates', 'dragonizer'); ?></li>
                        <li><?php esc_html_e('Language and translation setting changes', 'dragonizer'); ?></li>
                        <li><?php esc_html_e('Term and taxonomy modifications (creation, editing, deletion)', 'dragonizer'); ?></li>
                        <li><?php esc_html_e('Link system modifications (creation, editing, deletion)', 'dragonizer'); ?></li>
                        <li><?php esc_html_e('WordPress security key changes (AUTH_KEY and NONCE_KEY)', 'dragonizer'); ?></li>
                        <li><?php esc_html_e('Critical nonce changes in WordPress forms and AJAX requests', 'dragonizer'); ?></li>
                    </ul>
                </div>

                <!-- Homepage-Specific Cache Clear -->
                <div class="dragonizer-cache-section">
                    <h3>
                        <span class="dashicons dashicons-admin-home"></span>
                        <?php esc_html_e('Homepage Cache Clear', 'dragonizer'); ?>
                    </h3>
                    <ul class="dragonizer-trigger-list">
                        <li><?php esc_html_e('New post publications and updates', 'dragonizer'); ?></li>
                        <li><?php esc_html_e('Changes to featured WooCommerce products', 'dragonizer'); ?></li>
                        <li><?php esc_html_e('Homepage widget and layout modifications', 'dragonizer'); ?></li>
                        <li><?php esc_html_e('Main menu structure changes affecting the homepage', 'dragonizer'); ?></li>
                        <li><?php esc_html_e('Post status transitions (publishing, unpublishing, scheduling)', 'dragonizer'); ?></li>
                    </ul>
                </div>

                <!-- Page-Specific Cache Clear -->
                <div class="dragonizer-cache-section">
                    <h3>
                        <span class="dashicons dashicons-admin-page"></span>
                        <?php esc_html_e('Page-Specific Cache Clear', 'dragonizer'); ?>
                    </h3>
                    <ul class="dragonizer-trigger-list">
                        <li><?php esc_html_e('Individual post or page updates and modifications', 'dragonizer'); ?></li>
                        <li><?php esc_html_e('Comment status changes and updates on specific posts', 'dragonizer'); ?></li>
                        <li><?php esc_html_e('Page builder content updates (Elementor, Beaver Builder, WPBakery, Divi, Oxygen, Thrive)', 'dragonizer'); ?></li>
                        <li><?php esc_html_e('Media attachment updates and modifications', 'dragonizer'); ?></li>
                        <li><?php esc_html_e('Custom post type content changes', 'dragonizer'); ?></li>
                        <li><?php esc_html_e('Archive pages when related content is modified', 'dragonizer'); ?></li>
                    </ul>
                </div>

                <?php if (class_exists('WooCommerce')): ?>
                    <!-- WooCommerce-Specific Cache Management -->
                    <div class="dragonizer-cache-section">
                        <h3>
                            <span class="dashicons dashicons-cart"></span>
                            <?php esc_html_e('WooCommerce Cache Management', 'dragonizer'); ?>
                        </h3>
                        <ul class="dragonizer-trigger-list">
                            <li><?php esc_html_e('Product updates including variations and stock changes', 'dragonizer'); ?></li>
                            <li><?php esc_html_e('Order processing and status changes', 'dragonizer'); ?></li>
                            <li><?php esc_html_e('Product review submissions and modifications', 'dragonizer'); ?></li>
                            <li><?php esc_html_e('Product category and tag page updates', 'dragonizer'); ?></li>
                            <li><?php esc_html_e('Scheduled sales start and end events', 'dragonizer'); ?></li>
                            <li><?php esc_html_e('Shop page and product archive modifications', 'dragonizer'); ?></li>
                            <li><?php esc_html_e('Cart, checkout, and account page updates', 'dragonizer'); ?></li>
                            <li><?php esc_html_e('Product search and filter page changes', 'dragonizer'); ?></li>
                            <li><?php esc_html_e('Order completion and thank you page updates', 'dragonizer'); ?></li>
                        </ul>
                    </div>
                <?php endif; ?>

                <!-- Cache Clear Notifications -->
                <div class="dragonizer-cache-section">
                    <h3>
                        <span class="dashicons dashicons-bell"></span>
                        <?php esc_html_e('Cache Clear Notifications', 'dragonizer'); ?>
                    </h3>
                    <ul class="dragonizer-trigger-list">
                        <li><?php esc_html_e('Major system updates requiring cache refresh', 'dragonizer'); ?></li>
                        <li><?php esc_html_e('Plugin activation and deactivation notices', 'dragonizer'); ?></li>
                        <li><?php esc_html_e('Database update notifications', 'dragonizer'); ?></li>
                    </ul>
                </div>
            </div>
        </div>
    </div>

    <script>
        function toggleCacheInfo(element) {
            const content = element.nextElementSibling;
            const expandBtn = element.querySelector('.dragonizer-cache-expand');
            const expandText = expandBtn.querySelector('.expand-text');

            content.classList.toggle('expanded');
            expandBtn.classList.toggle('expanded');

            expandText.textContent = content.classList.contains('expanded') ?
                '<?php esc_html_e('Hide details', 'dragonizer'); ?>' :
                '<?php esc_html_e('Show details', 'dragonizer'); ?>';
        }
    </script>
<?php
}

function dragonizer_display_plugin_warning($obj, $plugins)
{
    $obj->modules_status['caching'] = '0';
    $obj->save_settings(['modules_status' => $obj->modules_status]);
?>
    <p style="font-size: larger;"><i style="margin:5px;color:orange" class="dashicons dashicons-admin-plugins"></i><?php _e('To use this section and avoid any possible disruption, you must first <strong>disable</strong> the following plugins.', 'dragonizer'); ?></p>
    <table style="margin:0 auto; border-spacing: 5px;text-align: left;">
        <tbody>
            <?php
            foreach ($plugins as $plugin) {
                $plugin_data = get_plugin_data(WP_PLUGIN_DIR . DIRECTORY_SEPARATOR . $plugin);
            ?>
                <tr>
                    <td><strong><span style="text-decoration: line-through;text-decoration-color: red;"><?= esc_attr($plugin_data['Name']) ?></span></strong></td>
                    <td><a href="<?= esc_url_raw(wp_nonce_url(admin_url('admin-post.php?action=deactivate_plugin&plugin=' . rawurlencode($plugin)), 'deactivate_plugin')) ?>" style="line-height: 22px!important;" class="button button-secondaty deactive-bad-plugins"><?= esc_html__('Deactivate', 'dragonizer') ?><span class="dashicons dashicons-trash"></span></a></td>
                </tr>
            <?php
            }
            ?>
        </tbody>
    </table>

    <script>
        (function($) {
            $(function() {
                $('div.toggle-btn').remove();
                $('p.submit').remove();
                $('div.pro-disabled').removeClass('pro-disabled');
                $('a.deactive-bad-plugins').on('click', function() {
                    $('.dragonizer_tab_group #loader-wrapper').removeClass('loaded');
                });
            });
        })(jQuery);
    </script>
<?php
}

function dragonizer_display_cron_timed_status($obj)
{
    $current_time = time();
    $next_scheduled = wp_next_scheduled('dragonizer_clear_expired_cache');
    $last_run = get_option('dragonizer_last_run_clear_expired_cache');
    $expected_interval = $obj->settings['caching']['cache_expiry_interval']; // in seconds 
    $expected_interval = isset($obj->settings['caching']['cache_expiry_interval']) ?
        intval($obj->settings['caching']['cache_expiry_interval']) : 36000;

    echo '<div class="dragon-hidden dragonizer-status">';
    echo '<h2 class="dragonizer-title">' . esc_html__('Cache Auto Clearing Status', 'dragonizer') . '</h2>';
    echo '<div class="dragonizer-grid">';

    dragonizer_display_status_card(
        esc_html__('Cache Auto Clearing', 'dragonizer'),
        $current_time,
        $next_scheduled,
        $last_run,
        $expected_interval,
        true
    );

    echo '</div></div>';
}

function dragonizer_display_cron_dynamic_status($obj)
{
    $current_time = time();
    $next_scheduled = wp_next_scheduled('dragonizer_update_dynamic_content');
    $last_run = get_option('dragonizer_last_run_update_dynamic_content', 0);
    $expected_interval = isset($obj->settings['caching']['dynamic_cache_refresh']) ?
        intval($obj->settings['caching']['dynamic_cache_refresh']) : 10800;

    echo '<div class="dragonizer-status dragon-hidden" id="dynamic-cron-status">';
    echo '<h2 class="dragonizer-title">' . esc_html__('Dynamic Cache Status', 'dragonizer') . '</h2>';
    echo '<div class="dragonizer-grid">';

    dragonizer_display_status_card(
        esc_html__('Dynamic Content Update', 'dragonizer'),
        $current_time,
        $next_scheduled,
        $last_run,
        $expected_interval,
        true
    );

    echo '</div></div>';
}

function dragonizer_display_cache_settings($obj)
{
?>
    <input type="hidden" name="dragonizer_settings[caching]" value="">

    <p class="dragon-hidden"><?php esc_html_e('This section generates static html files from your dynamic site. After a html file is generated your webserver will serve that file instead of processing the comparatively heavier and more expensive WordPress PHP scripts.', 'dragonizer'); ?></p>

    <?php

    $last_changed = $obj->settings['data']['changed'];
    $now = time();

    $cron_status = 'skip';

    if ($now - $last_changed > 15) {
        // Check cron status
        $cron_status = dragonizer_check_cron_status();
    }

    // Get cache mode
    // $cache_mode = isset($obj->settings['caching']['cache_mode']) ? $obj->settings['caching']['cache_mode'] : 'dynamic';
    $cache_mode = 'timed';

    // Display caching status if there are no issues
    if ($cron_status !== 'error' && $cron_status !== 'skip') {
        if (
            $obj->settings['modules_status']['caching'] &&
            !empty($obj->settings['caching']['cache_status']) &&
            ($obj->settings['caching']['cache_status'] !== 'Disable')
        ) {
            // Display appropriate cron status based on cache mode
            if ($cache_mode === 'dynamic') {
                dragonizer_display_cron_dynamic_status($obj);
            } else {
                dragonizer_display_cron_timed_status($obj);
            }
        }
    }
    ?>

    <input type="hidden" name="dragonizer_settings[caching]" value="">

    <h3 class="dragon-hidden"><?php esc_html_e('Cache Control Settings', 'dragonizer'); ?> <span class="dragonizer_security_badge dragonizer_warning_badge"><?php esc_html_e('Usually safe', 'dragonizer'); ?></span></h3>
    <p class="dragon-hidden"><?php esc_html_e('Carefully review the description and customize the page cache settings to best suit your website\'s specific requirements.', 'dragonizer'); ?></p>

    <?php
    // Display common cache options
    dragonizer_display_cache_options($obj);

    // Display both settings sections - visibility controlled by JavaScript
    echo '<div id="dynamic-cache-settings" class="dragon-hidden">';
    dragonizer_display_dynamic_cache_settings($obj);
    echo '</div>';

    echo '<div id="timeout-cache-settings" class="dragon-hidden">';
    dragonizer_display_cache_timeout_settings($obj);
    echo '</div>';

    // Display exclude settings
    dragonizer_display_exclude_settings($obj);

    // Add the new cache triggers info section
    dragonizer_display_cache_triggers_info();

    ?>
    <script type="text/javascript">
        jQuery(document).ready(function($) {
            // Function to show/hide settings based on cache mode
            function toggleCacheSettings(mode) {
                if (mode === 'dynamic') {
                    $('#dynamic-cache-settings').show();
                    $('#timeout-cache-settings').hide();
                } else {
                    $('#dynamic-cache-settings').hide();
                    $('#timeout-cache-settings').show();
                }
            }

            // Get the cache mode select element - using more specific selector
            var cacheModeSelect = $('select[name="dragonizer_settings[caching][cache_mode]"]');

            // Run on initial page load
            toggleCacheSettings(cacheModeSelect.val());

            // Handle change events
            cacheModeSelect.on('change', function() { // this is
                toggleCacheSettings($(this).val());
            });

            // Existing parameter handling
            $('#no_cache_query_params_fld').change(function() {
                change_para_status(this.checked);
            });

            change_para_status($('#no_cache_query_params_fld').prop("checked"));

            function change_para_status(para_checked) {
                para_checked ? ($('#rejected_parameters_tr').hide() && $('#accepted_parameters_tr').show()) :
                    ($('#rejected_parameters_tr').show() && $('#accepted_parameters_tr').hide());
            }

            $('#dragonizer_cache_timeout_checkall_fld').hide();
        });
    </script>
<?php
}

function dragonizer_display_dynamic_cache_settings($obj)
{
    if (!isset($obj->caching_dynamic) || empty($obj->caching_dynamic)) {
        return;
    }

    echo '<h3 class="dragon-hidden">' . esc_html__('Dynamic Cache Settings', 'dragonizer') . '</h3>';

    echo '<table class="dragon-hidden wp-list-table widefat fixed striped posts dragonizer_options-table dragonizer_tweaks-table">
        <thead>
            <tr>
                <th class="column-title manage-column column-primary">
                    <strong>' . esc_html__('Options', 'dragonizer') . '</strong>
                </th>
                <th><string>' . esc_html__('Explanation', 'dragonizer') . '</string></th>
            </tr>
        </thead>
        <tbody>';

    foreach ($obj->caching_dynamic as $dragonizer_option_slug => $dragonizer_option) {
        if ($dragonizer_option['type'] === 'select') {
            echo '<tr>
                <td class="column-title column-primary">
                    <strong>' . esc_html__($dragonizer_option['title'], 'dragonizer') . '</strong>
                    <button type="button" class="toggle-row">
                        <span class="screen-reader-text">' . esc_html__('Show more details', 'dragonizer') . '</span>
                    </button>
                </td>
                <td class="explanation-column" data-colname="' . esc_attr__('Explanation', 'dragonizer') . '">
                    <select name="dragonizer_settings[caching][' . esc_attr($dragonizer_option_slug) . ']">';

            foreach ($dragonizer_option['values'] as $value) {
                $selected = isset($obj->settings['caching'][$dragonizer_option_slug]) &&
                    $obj->settings['caching'][$dragonizer_option_slug] == $value[0];
                echo '<option value="' . esc_attr($value[0]) . '" ' . selected($selected, true, false) . '>'
                    . esc_html($value[1]) . '</option>';
            }

            echo '</select><br> ' . wp_kses_post($dragonizer_option['description']) . '
                </td>
            </tr>';
        }
    }

    echo '</tbody></table>';
}

function dragonizer_display_cache_options($obj)
{
    $dragonizer_allowed_description_tags = array(
        'br'   => array(),
        'span' => array(
            'style' => array(),
            'class' => array(),
        ),
    );
?>
    <table class="dragon-hidden wp-list-table widefat fixed striped posts dragonizer_options-table dragonizer_cleanup-table">
        <thead>
            <tr>
                <td class="manage-column column-cb check-column"><input style="margin-top:4px!important" type="checkbox" name="check_all" <?php @checked(true, $obj->all_options_checked($obj->caching, 'caching', ['cache_expiry_interval', 'cache_lifetime']), true); ?>></td>
                <th class="column-title manage-column column-primary"><strong><?php esc_html_e('Options', 'dragonizer'); ?></strong></th>
                <th><strong><?php esc_html_e('Explanation', 'dragonizer'); ?></strong></th>
            </tr>
        </thead>
        <tbody>
            <?php foreach ($obj->caching as $dragonizer_option_slug => $dragonizer_option) {
                if (empty($dragonizer_option['type'])) {
            ?>
                    <tr>
                        <th scope="row" class="check-column">
                            <input type="checkbox" name="dragonizer_settings[caching][<?= $dragonizer_option_slug ?>]" id="<?php echo esc_attr($dragonizer_option_slug . '_fld'); ?>" <?php @checked(true, array_key_exists($dragonizer_option_slug, (is_array($obj->settings['caching'] ?? null) ? $obj->settings['caching'] : [])), true); ?>>
                        </th>
                        <td class="column-title column-primary"><strong><?php echo __($dragonizer_option['title'], 'dragonizer'); ?></strong>
                            <button type="button" class="toggle-row"><span class="screen-reader-text"><?php __('Show more details', 'dragonizer'); ?></span></button>
                        </td>
                        <td class="explanation-column" data-colname="<?php echo esc_attr(_e('Explanation', 'dragonizer')); ?>"><?php echo wp_kses(__($dragonizer_option['description'], 'dragonizer'), $dragonizer_allowed_description_tags); ?></td>
                    </tr>
                <?php
                } elseif ($dragonizer_option['type'] === 'select') {
                ?>
                    <tr>
                        <th scope="row" class="check-column"></th>
                        <td class="column-title column-primary">
                            <strong><?php echo __($dragonizer_option['title'], 'dragonizer'); ?></strong>
                            <button type="button" class="toggle-row">
                                <span class="screen-reader-text"><?php __('Show more details', 'dragonizer'); ?></span>
                            </button>
                        </td>
                        <td class="explanation-column" data-colname="<?php echo esc_attr(_e('Explanation', 'dragonizer')); ?>">
                            <select name="dragonizer_settings[caching][<?= $dragonizer_option_slug  ?>]">
                                <?php
                                foreach ($dragonizer_option['values'] as $value) {
                                    $currentKey   = $value[0];
                                    $currentValue = $value[1];
                                    $defaultValue = $dragonizer_option['default'][0];

                                    if (isset($obj->settings['caching'][$dragonizer_option_slug])) {
                                        if (isset($obj->settings['caching'][$dragonizer_option_slug]['value'])) {
                                            $selected = @selected($obj->settings['caching'][$dragonizer_option_slug]['value'] ?? false, $currentKey);
                                        } else {
                                            $selected = @selected($obj->settings['caching'][$dragonizer_option_slug] ?? false, $currentKey);
                                        }
                                    } else {
                                        $selected = ($defaultValue == $currentKey) ? selected($defaultValue, $currentKey) : '';
                                    }
                                ?>
                                    <option value='<?= $currentKey ?>' <?= $selected ?>><?= $currentValue ?></option>
                                <?php
                                }
                                ?>
                            </select> <br><span><?= $dragonizer_option['description'] ?></span>
                        </td>
                    </tr>
            <?php
                }
            }
            ?>
        </tbody>
    </table>
<?php
}

function dragonizer_display_cache_timeout_settings($obj)
{
    $dragonizer_allowed_description_tags = array(
        'br'   => array(),
        'bdo' => array(
            'style' => array(),
        ),
        'span' => array(
            'style' => array(),
        ),
    );
?>
    <h3 class="dragon-hidden"><?php esc_html_e('Cache Timeout Settings', 'dragonizer'); ?></h3>
    <p class="dragon-hidden"><?php esc_html_e('Automatically clears cached content after a specified time, ensuring your site remains fast and up-to-date.', 'dragonizer'); ?></p>

    <table class="dragon-hidden wp-list-table widefat fixed striped posts dragonizer_options-table dragonizer_cleanup-table">
        <thead>
            <tr>
                <td class="manage-column column-cb check-column "><input style="margin-top:4px!important" type="checkbox" name="check_all" id="dragonizer_cache_timeout_checkall_fld" <?php @checked(true, $obj->all_options_checked($obj->caching, 'caching', ['cache_expiry_interval', 'cache_lifetime']), true); ?>></td>
                <th class="column-title manage-column column-primary"><strong><?php esc_html_e('Options', 'dragonizer'); ?></strong></th>
                <th><strong><?php esc_html_e('Explanation', 'dragonizer'); ?></strong></th>
            </tr>
        </thead>
        <tbody>
            <?php foreach ($obj->caching_lifetime as $dragonizer_option_slug => $dragonizer_option) {
                if (empty($dragonizer_option['type'])) {
            ?>
                    <tr>
                        <th scope="row" class="check-column">
                            <input type="checkbox" name="dragonizer_settings[caching][<?= $dragonizer_option_slug ?>]" id="<?php echo esc_attr($dragonizer_option_slug . '_fld'); ?>" <?php @checked(true, array_key_exists($dragonizer_option_slug, (is_array($obj->settings['caching'] ?? null) ? $obj->settings['caching'] : [])), true); ?>>
                        </th>
                        <td class="column-title column-primary"><strong><?php echo __($dragonizer_option['title'], 'dragonizer'); ?></strong>
                            <button type="button" class="toggle-row"><span class="screen-reader-text"><?php __('Show more details', 'dragonizer'); ?></span></button>
                        </td>
                        <td class="explanation-column" data-colname="<?php echo esc_attr(_e('Explanation', 'dragonizer')); ?>"><?php echo wp_kses(__($dragonizer_option['description'], 'dragonizer'), $dragonizer_allowed_description_tags); ?></td>
                    </tr>
                <?php
                } elseif ($dragonizer_option['type'] === 'select') {
                ?>
                    <tr>
                        <th scope="row" class="check-column"></th>
                        <td class="column-title column-primary">
                            <strong><?php echo __($dragonizer_option['title'], 'dragonizer'); ?></strong>
                            <button type="button" class="toggle-row">
                                <span class="screen-reader-text"><?php __('Show more details', 'dragonizer'); ?></span>
                            </button>
                        </td>
                        <td class="explanation-column" data-colname="<?php echo esc_attr(_e('Explanation', 'dragonizer')); ?>">
                            <select name="dragonizer_settings[caching][<?= $dragonizer_option_slug  ?>]">
                                <?php
                                foreach ($dragonizer_option['values'] as $value) {
                                    $currentKey   = $value[0];
                                    $currentValue = $value[1];
                                    $defaultValue = $dragonizer_option['default'][0];

                                    if (isset($obj->settings['caching'][$dragonizer_option_slug])) {
                                        if (isset($obj->settings['caching'][$dragonizer_option_slug]['value'])) {
                                            $selected = @selected($obj->settings['caching'][$dragonizer_option_slug]['value'] ?? false, $currentKey);
                                        } else {
                                            $selected = @selected($obj->settings['caching'][$dragonizer_option_slug] ?? false, $currentKey);
                                        }
                                    } else {
                                        $selected = ($defaultValue == $currentKey) ? selected($defaultValue, $currentKey) : '';
                                    }
                                ?>
                                    <option value='<?= $currentKey ?>' <?= $selected ?>><?= $currentValue ?></option>
                                <?php
                                }
                                ?>
                            </select> <br><span><?= $dragonizer_option['description'] ?></span>
                        </td>
                    </tr>
            <?php
                }
            }
            ?>
        </tbody>
    </table>
<?php
}

function dragonizer_display_exclude_settings($obj)
{
    $dragonizer_allowed_description_tags = array(
        'br'   => array(),
        'bdo' => array(
            'style' => array(),
        ),
        'span' => array(
            'style' => array(),
        ),
    );
?>
    <h3 class="dragon-hidden"><?php esc_html_e('Exclude Settings', 'dragonizer'); ?> <span class="dragonizer_security_badge dragonizer_warning_badge"><?php esc_html_e('Advanced users', 'dragonizer'); ?></span></h3>
    <p class="dragon-hidden"><?php esc_html_e('By default, Dragonizer caches as many pages as possible. If you have some pages that should not be cached for whatever reason, you should use the following settings.', 'dragonizer'); ?></p>

    <table class="dragon-hidden wp-list-table widefat fixed striped posts dragonizer_options-table dragonizer_optimize-table">
        <thead>
            <tr>
                <td class="manage-column column-cb check-column"></td>
                <th class="column-title manage-column column-primary"><strong><?php esc_html_e('Options', 'dragonizer'); ?></strong></th>
                <th><strong><?php esc_html_e('Explanation', 'dragonizer'); ?></strong></th>
            </tr>
        </thead>
        <tbody>
            <?php
            $count_color = 1;
            foreach ($obj->caching_other as $dragonizer_option_slug => $dragonizer_option) {
                $display = '';
                if ($dragonizer_option_slug == 'accepted_parameters' || $dragonizer_option_slug == 'rejected_parameters') {
                    $display = 'display:none;';
                    $count_color = 1;
                } else {
                    $count_color++;
                }
                $background = $count_color % 2 == 0 ? 'background-color: #faf6f7!important;' : 'background-color:white!important';
            ?>
                <tr id="<?php echo esc_attr($dragonizer_option_slug . '_tr'); ?>" style="<?php echo $display . $background; ?>">
                    <th scope="row" class="check-column">
                        <?php if (isset($dragonizer_option['type']) && $dragonizer_option['type'] != 'selector') { ?>
                            <input type="checkbox" name="dragonizer_settings[caching][<?= $dragonizer_option_slug ?>]" id="<?php echo esc_attr($dragonizer_option_slug . '_fld'); ?>" <?php @checked(true, array_key_exists($dragonizer_option_slug, (is_array($obj->settings['caching'] ?? null) ? $obj->settings['caching'] : [])), true); ?>>
                        <?php } ?>
                    </th>
                    <td class="column-title column-primary"><strong><?php echo __($dragonizer_option['title'], 'dragonizer'); ?></strong>
                        <button type="button" class="toggle-row"><span class="screen-reader-text"><?php __('Show more details', 'dragonizer'); ?></span></button>
                    </td>
                    <td class="explanation-column" data-colname="<?php echo esc_attr(_e('Choose', 'dragonizer')); ?>">
                        <?php if (isset($dragonizer_option['type']) && $dragonizer_option['type'] == 'selector') {
                            $data = is_array($obj->get('caching', $dragonizer_option_slug)) ? implode(',', $obj->get('caching', $dragonizer_option_slug)) : '';
                        ?>
                            <div>
                                <textarea style="display: none;" id="<?= $dragonizer_option_slug ?>" rows="5" data-type="string" data-exclusion-type="selectors" data-texts='{"add":"<?php _e("add", "dragonizer"); ?>","save":"<?php _e("save", "dragonizer"); ?>"}' data-setting="exclusion"><?= $data ?></textarea>
                            </div>
                            <p style="margin:10px"> <?php echo wp_kses(__($dragonizer_option['description'], 'dragonizer'), $dragonizer_allowed_description_tags); ?> </p>
                        <?php
                        } else {
                            echo wp_kses(__($dragonizer_option['description'], 'dragonizer'), $dragonizer_allowed_description_tags);
                        } ?>
                    </td>
                </tr>
            <?php } ?>
        </tbody>
    </table>


    <style>
        .exclusion-wrap,
        .exclusion-wrap .exclusions-content {
            width: 100%;
            -webkit-box-sizing: border-box;
            box-sizing: border-box
        }

        .exclusion-wrap .dark_blue_link {
            margin-right: 10px !important;
            margin-left: auto !important;
            box-shadow: unset !important;
            line-height: 21px !important;
        }

        .exclusion-wrap .exclusions-content {
            position: relative;
            padding: 5px;
            margin-bottom: 10px;
            min-height: 120px;
            border: 1px solid #aaa;
            border: 1px solid #3c434a;
            border-radius: 8px;
            -webkit-transition: all .15s ease-in;
            -o-transition: all .15s ease-in;
            transition: all .15s ease-in;
            background-color: white
        }

        .exclusion-wrap .exclusions-content:not(.plus) {
            z-index: 1
        }

        .exclusion-wrap .exclusions-content:hover {
            border: 1px solid #3c434a
        }

        .exclusion-wrap .exclusions-content:hover .plus:after,
        .exclusion-wrap .exclusions-content:hover .plus:before {
            visibility: visible;
            opacity: 1
        }

        .exclusion-wrap .exclusions-content .plus:after,
        .exclusion-wrap .exclusions-content .plus:before {
            content: '';
            position: absolute;
            visibility: hidden;
            opacity: 0;
            top: calc(50% - 1px);
            left: calc(50% - 10px);
            width: 20px;
            height: 2px;
            background: #005908;
            -webkit-transition: opacity .15s ease-in;
            -o-transition: opacity .15s ease-in;
            transition: opacity .15s ease-in;
            z-index: 0
        }

        .exclusion-wrap .exclusions-content .plus:after {
            top: calc(50% - 10px);
            left: calc(50% - 1px);
            width: 2px;
            height: 20px
        }

        .exclusion-wrap .exclusions-content>div[data-index] {
            position: relative;
            float: left;
            margin: 2px;
            padding: 5px 30px 5px 10px;
            background: #0a4b78;
            color: #fff;
            border-radius: 8px;
            direction: ltr
        }

        .exclusion-wrap .exclusions-content span[data-action=delete] {
            cursor: pointer;
            position: absolute;
            top: calc(50% - 10px);
            right: 5px;
            height: 20px;
            width: 20px;
            border-radius: 50%;
            -moz-border-radius: 50%;
            -webkit-border-radius: 50%;
            background: #9d0110
        }

        .exclusion-wrap .exclusions-content span[data-action=delete]:after,
        .exclusion-wrap .exclusions-content span[data-action=delete]:before {
            content: '';
            position: absolute;
            display: block;
            width: 60%;
            height: 2px;
            top: calc(50% - 1px);
            right: 20%;
            background: #fff;
            -webkit-transition: all .2s ease-in-out;
            -o-transition: all .2s ease-in-out;
            transition: all .2s ease-in-out
        }

        .exclusion-wrap .exclusions-content span[data-action=delete]:before {
            -webkit-transform: rotate(45deg);
            -ms-transform: rotate(45deg);
            transform: rotate(45deg)
        }

        .exclusion-wrap .exclusions-content span[data-action=delete]:after,
        .exclusion-wrap .exclusions-content span[data-action=delete]:hover:before {
            -webkit-transform: rotate(-45deg);
            -ms-transform: rotate(-45deg);
            transform: rotate(-45deg)
        }

        .exclusion-wrap .exclusions-content span[data-action=delete]:hover:after {
            -webkit-transform: rotate(45deg);
            -ms-transform: rotate(45deg);
            transform: rotate(45deg)
        }

        .exclusion-wrap textarea {
            display: none
        }

        .exclusion-wrap .buttons-wrap select {
            min-width: 90px;
            vertical-align: unset
        }

        .exclusion-wrap .buttons-wrap button {
            min-width: 100px;
            margin-right: 0
        }

        .exclusion-wrap[data-type=urls] .buttons-wrap input {
            width: calc(100% - 214px)
        }

        .exclusion-wrap .buttons-wrap input {
            width: calc(100% - 111px);
            border: unset !important;
            box-shadow: unset !important;
            line-height: 20px !important;
        }

        .exclusion-wrap .buttons-wrap .error-message {
            margin-bottom: 10px
        }

        @media screen and (max-width:782px) {

            .deactivation-popup[data-type=wrapper] .options-wrap label,
            .exclusion-wrap .buttons-wrap select {
                margin-bottom: 10px
            }

            .exclusion-wrap .buttons-wrap input {
                width: 100%;
                display: inline-block;
                margin-right: 0;
                margin-bottom: 10px
            }

            .exclusion-wrap[data-type=urls] .buttons-wrap input {
                width: calc(100% - 10px)
            }
        }

        .exclusion-wrap input.error[type=text],
        .exclusion-wrap input.error[type=text]:focus,
        .exclusion-wrap textarea.error,
        .exclusion-wrap textarea.error:focus {
            border: 1px solid #dc143c;
            -webkit-box-shadow: 0 0 2px 1px rgb(220 20 60 / 15%), inset 0 0 2px 1px rgb(220 20 60 / 15%);
            box-shadow: 0 0 2px 1px rgb(220 20 60 / 15%), inset 0 0 2px 1px rgb(220 20 60 / 15%)
        }
    </style>

    <script>
        "use strict";

        function _typeof(t) {
            return (_typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function(t) {
                return typeof t
            } : function(t) {
                return t && "function" == typeof Symbol && t.constructor === Symbol && t !== Symbol.prototype ? "symbol" : typeof t
            })(t)
        }! function(U) {
            U(document).ready(function() {
                var a = {
                    validateSelector: function(t) {
                        try {
                            return document.querySelector(t), !0
                        } catch (t) {
                            return !1
                        }
                    },
                    prepare: function() {
                        U('[ data-setting="exclusion"]').each(function() {
                            var t = U(this),
                                a = U(this).attr("id"),
                                e = t.data("texts"),
                                n = t.val();
                            "object" != _typeof(e) && (e = {
                                add: "Add",
                                save: "Save"
                            });
                            for (var i = "string" == typeof(i = t.data("separator")) && "" !== i ? i : ",", r = "string" == typeof(r = t.data("exclusion-type")) && "" !== r ? r : "selectors", s = "string" == typeof n && "" !== n ? n.split("string" == typeof i && "" !== i ? i : ",") : [], o = "", d = 0, l = s[d]; d < s.length; l = s[++d]) o = o + '<div data-index="' + d + '" data-action="edit"><span class="selector">' + l + '</span><input type="hidden" name="dragonizer_settings[caching][' + a + '][]" value="' + l + '"></input><span data-action="delete"></span></div>';
                            var p = U('<div class="exclusion-wrap" data-type="' + r + '"><div data-id="' + a + '" class="exclusions-content clearfix" data-action="add"><div class="plus"></div>' + o + '</div><div class="buttons-wrap hidden"><div class="error-message hidden"></div>' + ("urls" === r ? '<select><option value="path">Path</option><option value="regex">RegEx</option><option value="http">HTTP</option><option value="https">HTTPS</option><option value="domain">Domain</option></select> : ' : "") + '<input type="text"><button style="line-height:21px!important" type="button" class="dark_blue_link button" data-action="confirm" data-texts=' + JSON.stringify(e) + ">" + e.add + "</button></div></div>");
                            t.before(p), p.append(t)
                        })
                    },
                    actionsHandler: function(t) {
                        t.preventDefault(), t.stopPropagation();
                        var a = U(this),
                            e = ((S = a.parents("td")).find("p.warning"), a.parents(".exclusion-wrap")),
                            n = e.find("textarea"),
                            i = e.find(".buttons-wrap"),
                            r = i.find(".error-message"),
                            s = i.find("input"),
                            o = i.find("select"),
                            d = i.find("button"),
                            l = e.find(".exclusions-content"),
                            p = l.attr("data-id"),
                            c = l.find(".selector"),
                            u = l.find("div[data-index]"),
                            f = s.val(),
                            v = d.attr("data-texts"),
                            y = a.attr("data-action"),
                            g = a.attr("data-state"),
                            x = n.data("exclusion-type"),
                            f = "string" == typeof f && "" !== f ? f.trim() : "",
                            g = "confirm" === (y = "string" == typeof y && "" !== y ? y : void 0) && "string" == typeof g && "" !== g ? g : "add",
                            x = "string" == typeof x && "" !== x ? x : "selectors";
                        try {
                            v = JSON.parse(v)
                        } catch (t) {
                            v = {
                                add: "Add",
                                save: "Save"
                            }
                        }
                        switch (y) {
                            case "add":
                                d.text(v.add).attr("data-state", "add").removeAttr("data-editing"), s.removeClass("error").val(""), i.slideDown("fast"), r.text("").slideUp("fast"), s.focus();
                                break;
                            case "edit":
                                var h = a.find(".selector");
                                s.removeClass("error").val(h.text()), d.text(v.save).attr("data-state", "save").attr("data-editing", a.attr("data-index")), i.slideDown("fast"), r.text("").slideUp("fast"), s.focus();
                                break;
                            case "delete":
                                a.parents("div[data-index]").fadeOut("fast", function() {
                                    U(this).remove()
                                }), d.removeAttr("data-editing").removeAttr("data-state"), i.slideUp("fast"), s.removeClass("error").val(""), r.text("").slideUp("fast");
                                break;
                            case "confirm":
                                for (var m = o.val(), b = !1, k = "urls" === x ? m + ":" + f : f, w = (w = "urls" === x ? [k] : k.split(",")).map(function(t) {
                                        return "string" == typeof t ? t.trim() : t
                                    }), h = U(c[S = 0]); S < c.length; h = U(c[++S])) {
                                    var S = h.text();
                                    if ((w = w.filter(function(t) {
                                            return "save" === g && h.parent().attr("data-index") === a.attr("data-editing") && S === t || S !== t
                                        })).length <= 0) {
                                        b = !0, s.addClass("error"), r.text("").slideUp("fast");
                                        break
                                    }
                                }
                                if (b) break;
                                var _, A = function(t, a) {
                                    var e = U('<div data-index="' + (_ + a) + '" data-action="edit" class="hidden"><span class="selector">' + t + '</span><input type="hidden" name="dragonizer_settings[caching][' + p + '][]" value="' + t + '"></input><span data-action="delete"></span></div>');
                                    l.append(e), e.fadeIn("fast")
                                };
                                "add" === g && "" !== f && 0 < w.length ? (_ = 0 < u.length ? parseInt(u.last().attr("data-index"), 10) + 1 : 0, w.map(A)) : "save" === g && "" !== f && 0 < w.length && (_ = a.attr("data-editing"), l.find('div[data-index="' + _ + '"] .selector').text(w.shift()), l.find('div[data-index="' + _ + '"] input').val(l.find('div[data-index="' + _ + '"] .selector').text()), 0 < w.length && (_ = 0 < u.length ? parseInt(u.last().attr("data-index"), 10) + 1 : 0, w.map(A))), d.removeAttr("data-editing").removeAttr("data-state"), s.removeClass("error").val(""), r.text("").slideUp("fast")
                        }
                    }
                };
                U(function() {
                    var t = U(this);
                    a.prepare(), t.on("click", ".exclusion-wrap [data-action]", a.actionsHandler), U(".buttons-wrap>input").keyup(function(t) {
                        13 === t.keyCode && U(this).closest(".buttons-wrap").children(".dark_blue_link").click()
                    }), U(document).on("keydown", ".buttons-wrap>input", ":input:not(textarea)", function(t) {
                        return "Enter" != t.key
                    }), U(".exclusion-wrap input").on("change focus blur input keypress", function() {}), U(".buttons-wrap").on("focusout", function() {
                        U(this).slideUp("fast")
                    }), U(".minus").click(function() {
                        var t = U(this).parent().find("input"),
                            a = (a = parseInt(t.val()) - 1) < 0 ? 0 : a;
                        return t.val(a), t.change(), !1
                    }), U(".plus").click(function() {
                        var t = U(this).parent().find("input"),
                            a = 15 < (a = parseInt(t.val()) + 1) ? 15 : a;
                        return t.val(a), t.change(), !1
                    })
                })
            })
        }(jQuery);

        (function($) {
            // Function to check for .button-primary and hide .dragonizer-cache-status if not found
            function checkButtonAndHideStatus() {
                if ($('.button-primary').length === 0) {
                    $('.dragonizer-cache-status').hide();
                }
            }

            // Document ready handler
            $(document).ready(function() {
                // Initial check
                checkButtonAndHideStatus();

                // Optional: Set up a MutationObserver to watch for DOM changes
                if (window.MutationObserver) {
                    var observer = new MutationObserver(checkButtonAndHideStatus);
                    observer.observe(document.body, {
                        childList: true,
                        subtree: true
                    });
                }
            });

            // Public method to recheck (useful for AJAX-loaded content)
            $.fn.recheckDragonizerStatus = function() {
                checkButtonAndHideStatus();
                return this;
            };

        })(jQuery);
    </script>

<?php
}
?>