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

require_once 'dragonizer-shared-functions.php';

function display_preloading($obj)
{
    // Display preloading options table
    dragonizer_display_preloading_options($obj);
}

function dragonizer_check_sitemap_availability()
{
    if (defined('DR_YOASTـSEO')) {
?>
        <p class="dragon-hidden">
            <img style="vertical-align:middle" src="<?= _dr(DRAGONIZER_ASE_URL, 'images', 'other', 'yoast.svg') ?>" />
            <?= __('It seems that you are using the <b style="color:#92205C">Yoast SEO</b> plugin, Dragonizer will use the sitemap created by this plugin for preloading.', 'dragonizer') ?>
        </p>
    <?php
    } elseif (defined('DR_RANK_MATH')) {
    ?>
        <p class="dragon-hidden" style="margin-bottom:30px">
            <img style="vertical-align:middle" src="<?= _dr(DRAGONIZER_ASE_URL, 'images', 'other', 'rankmath.svg') ?>" />
            <?= __('It seems that you are using the <b style="color:#57619F">Rank Math SEO</b> plugin, Dragonizer will use the sitemap created by this plugin for preloading.', 'dragonizer') ?>
        </p>
    <?php
    } else {
        // Other SEO plugins or sitemap generators
    }
    return true;
}

function dragonizer_display_preloading_status($obj)
{
    $current_time = time();
    $next_scheduled_sitemap = wp_next_scheduled('dragonizer_sitemap_check');
    $last_run_sitemap = get_option('dragonizer_last_run_sitemap_check');
    $expected_interval_sitemap = $obj->settings['preloading']['sitemap_check']['value']; // in seconds
    $next_scheduled_preload = wp_next_scheduled('dragonizer_preload');
    $last_run_preload = get_option('dragonizer_last_run_preload');
    $expected_interval_preload = $obj->settings['preloading']['interval']['value'] * 60; // Convert minutes to seconds

    echo '<div class="dragon-hidden dragonizer-status">';
    echo '<h2 class="dragonizer-title">' . esc_html__('Preloading and Sitemap Check Status', 'dragonizer') . '</h2>';
    echo '<div class="dragonizer-grid">';

    // Sitemap Check Status
    dragonizer_display_status_card(esc_html__('Sitemap Checking', 'dragonizer'), $current_time, $next_scheduled_sitemap, $last_run_sitemap, $expected_interval_sitemap);

    // Preloading Status
    dragonizer_display_status_card(esc_html__('Preloading', 'dragonizer'), $current_time, $next_scheduled_preload, $last_run_preload, $expected_interval_preload);

    echo '</div>'; // .dragonizer-grid
    echo '</div>'; // .dragonizer-status
}

function dragonizer_is_valid_sitemap($url)
{
    if (!is_string($url)) return false;

    // Fast HEAD request first to check status and content type
    $head = wp_remote_head($url, [
        'timeout' => 5,
        'redirection' => 2,
        'httpversion' => '1.1',
        'headers' => ['Accept' => 'application/xml,text/xml'],
    ]);

    if (is_wp_error($head) || wp_remote_retrieve_response_code($head) !== 200) {
        return false;
    }

    // Get just the first 1KB of content to check XML structure
    $response = wp_remote_get($url, [
        'timeout' => 5,
        'redirection' => 2,
        'httpversion' => '1.1',
        'headers' => [
            'Range' => 'bytes=0-1024',
            'Accept' => 'application/xml,text/xml'
        ]
    ]);

    if (is_wp_error($response)) {
        return false;
    }

    $content = wp_remote_retrieve_body($response);

    // Quick pattern match for XML sitemap structure
    return preg_match('/<\?xml.*?>/i', $content)
        && preg_match('/<(urlset|sitemapindex)[^>]*xmlns=.*?>/i', $content);
}

function dragonizer_display_preloading_options($obj)
{
    ?>

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

    <p class="dragon-hidden"><?php esc_html_e('Cache preloading automatically creates and stores cached versions of site pages in advance, significantly enhancing load times for first-time visitors and alleviating server strain.', 'dragonizer'); ?></p>

    <?php

    $dragonizer_allowed_description_tags = array(
        'br'   => array(),
        'span' => array(
            'style' => array(),
            'class' => array(),
        ),
    );

    $cron_status = 'skip';
    $search_engines_discouraged = $empty_sitemap = false;
    $is_valid_sitemap = $cheking_sitemap = true;

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

    if ($now - $last_changed > 15) {

        // Check if search engines are discouraged from indexing the site
        $search_engines_discouraged = get_option('blog_public') == '0';

        $sitemap = get_option('dragonizer_sitemap', null) ?: '';
        $is_valid_sitemap = dragonizer_is_valid_sitemap($sitemap);

        $empty_sitemap = get_option('dragonizer_sitemap_empty', false);
        $cheking_sitemap = get_option('dragonizer_sitemap_cheking', false);

        // Check cron status
        $cron_status = dragonizer_check_cron_status();
    }

    if ($cheking_sitemap || !$obj->settings['modules_status']['preloading']) {
        //do nothing
    } elseif ($search_engines_discouraged) {
        dragonizer_display_error(
            'warning',
            __('Currently, preloading is disabled because your sitemap is not available.', 'dragonizer'),
            __('Search Engines Discouraged', 'dragonizer'),
            __('Action: Enable search engine indexing in WordPress Settings > Reading.', 'dragonizer')
        );
    } elseif (!$is_valid_sitemap) {
        dragonizer_display_error(
            'warning',
            __('Currently, preloading is disabled because your sitemap is invalid or inaccessible.', 'dragonizer'),
            __('Invalid Sitemap Detected', 'dragonizer'),
            __('Action: 1. Check your sitemap configuration and content. 2. After fixing, disable and re-enable the preloading section to refresh the sitemap status.', 'dragonizer')
        );
    } elseif ($empty_sitemap) {
        dragonizer_display_error(
            'warning',
            __('Currently, preloading is disabled because your sitemap exists but contains no URLs.', 'dragonizer'),
            __('Empty Sitemap Detected', 'dragonizer'),
            __('Action: 1. Check your sitemap configuration and content. 2. After fixing, disable and re-enable the preloading section to refresh the sitemap status.', 'dragonizer')
        );
    } else {

        // Display preloading status if there are no issues
        if ($cron_status !== 'error'  && $cron_status !== 'skip') {
            if ($cron_status !== 'warning') {
                // Check sitemap availability
                dragonizer_check_sitemap_availability();
            }

            // Display preloading status if the module is active
            if ($obj->settings['modules_status']['preloading']) {
                dragonizer_display_preloading_status($obj);
            }
        }
    }

    ?>

    <h3 class="dragon-hidden"><?php esc_html_e('Cache Preloading', '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 cache preloading settings and select options that align with your hosting/server capabilities to ensure optimal performance and avoid potential issues.', '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" <?php @checked(true, $obj->all_options_checked($obj->preloading, 'preloading', ['count', 'interval']), 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->preloading as $dragonizer_option_slug => $dragonizer_option) {
                if (empty($dragonizer_option['type'])) {
            ?>
                    <tr>
                        <th scope="row" class="check-column">
                            <input type="checkbox" name="dragonizer_settings[preloading][<?= $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['preloading'] ?? null) ? $obj->settings['preloading'] : [])), 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[preloading][<?= $dragonizer_option_slug  ?>][value]">
                                <?php
                                foreach ($dragonizer_option['values'] as $value) {
                                    $currentKey   = $value[0];
                                    $currentValue = $value[1];
                                    $defaultValue = $dragonizer_option['default'][0];

                                    if (isset($obj->settings['preloading'][$dragonizer_option_slug]['value'])) {
                                        $selected = @selected($obj->settings['preloading'][$dragonizer_option_slug]['value'] ?? 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
    dragonizer_display_preloading_stats($obj);
}


function dragonizer_display_preloading_stats($obj)
{
    global $wpdb;
    $table_name = $wpdb->prefix . "dragonizer_preload_cache";
    $total_pages = 0;
    $preloaded_pages = 0;

    if ($wpdb->get_var("SHOW TABLES LIKE '{$table_name}'") == $table_name) {
        $total_pages = (int)$wpdb->get_var("SELECT COUNT(id) FROM {$table_name}") ?: 0;
        $preloaded_pages = (int)$wpdb->get_var("SELECT COUNT(id) FROM {$table_name} WHERE UNIX_TIMESTAMP(`preloaded_at`) != '0'");
    }

    $search_engines_discouraged = get_option('blog_public') == '0';

    if (!$search_engines_discouraged) {
    ?>
        <div class="dashCards">
            <div class="dragon-hidden dashCard">
                <div class="title-icon" id="refresh-icon-1"><i class="dashicons dashicons-update"></i></div>
                <div class="title"><?= __('Total number of pages', 'dragonizer') ?></div>
                <div class="body">
                    <div class="icon"> <i style="color:darkred" class="dashicons dashicons-schedule"></i> </div>
                    <div class="value"><?= $total_pages ?></div>
                </div>
            </div>

            <div class="dragon-hidden dashCard">
                <div class="title-icon" id="refresh-icon-2"><i class="dashicons dashicons-update"></i></div>
                <div class="title"><?= __('Preloaded pages', 'dragonizer') ?></div>
                <div class="body">
                    <div class="icon"> <i style="color:goldenrod" class="dashicons dashicons-star-filled"></i></div>
                    <div class="value"><?= $preloaded_pages ?></div>
                </div>
            </div>
        </div>

        <script>
            jQuery(document).ready(function($) {
                $('.dragonizer_tab_group').on('click', '.dashCard .title-icon', function() {
                    var $icon = $(this).find('.dashicons');
                    $icon.addClass('rotate');

                    var ajaxAction = '';
                    var iconId = $(this).attr('id');

                    switch (iconId) {
                        case 'refresh-icon-1':
                            ajaxAction = 'update_sitemap_links';
                            break;
                        case 'refresh-icon-2':
                            ajaxAction = 'count_preloaded_links';
                            break;
                    }

                    var $valueDiv = $(this).closest('.dashCard').find('.value');

                    $.ajax({
                        url: '<?= admin_url('admin-ajax.php') ?>',
                        type: 'POST',
                        data: {
                            action: ajaxAction,
                        },
                        success: function(response) {
                            $valueDiv.html(response);
                            $icon.removeClass('rotate');
                        },
                        error: function(error) {
                            console.error(error);
                            $icon.removeClass('rotate');
                        }
                    });
                });

                function checkButtonAndHideStatus() {
                    if ($('.button-primary').length === 0) {
                        $('.dragonizer-preload-status').hide();
                    }
                }

                checkButtonAndHideStatus();

                if (window.MutationObserver) {
                    var observer = new MutationObserver(checkButtonAndHideStatus);
                    observer.observe(document.body, {
                        childList: true,
                        subtree: true
                    });
                }
            });

            jQuery.fn.recheckDragonizerStatus = function() {
                checkButtonAndHideStatus();
                return this;
            };
        </script>

        <style>
            .dashCards {
                padding: 1em;
                display: flex;
                flex-direction: row;
                flex-flow: row wrap;
                align-items: center;
                justify-content: center;
                margin-bottom: 200px;
            }

            .dashCards .dashCard {
                background: #FFF;
                min-width: 20%;
                max-width: 20%;
                border-radius: 0.5em;
                padding: 1em;
                box-shadow: 0 0.12em 0.45em #CCC;
                margin: 1em;
                display: flex;
                flex-direction: column;
                position: relative;
            }

            @media screen and (max-width:768px) {
                .dashCards .dashCard {
                    min-width: 95%;
                    max-width: 95%;
                }
            }

            .dashCards .dashCard .title {
                color: #333;
                padding: 0 0 0.5em 0;
                margin: 0 0 1em 0;
                border-bottom: 1px solid #f0f0f0;
                font-weight: 700;
                font-size: larger;
            }

            .dashCards .dashCard .body {
                display: flex;
                font-size: 4em;
                justify-content: space-between;
            }

            .dashCards .dashCard .body .icon {
                color: #c0c0c0;
            }

            .dashCards .dashCard .body .icon .dashicons {
                width: 45px;
                height: 45px;
                font-size: 42px;
            }

            .dashCards .dashCard .body .value {
                line-height: 1.4em;
                color: #666;
                font-size: x-large;
            }

            .dashCards .dashCard .title-icon {
                position: absolute;
                top: -10px;
                right: -10px;
                background-color: #FFF;
                padding: 5px;
                border-radius: 50%;
                box-shadow: 0px 0px 5px #CCC;
            }

            .rtl .dashCards .dashCard .title-icon {
                right: auto;
                left: -10px;
            }

            @keyframes spin {
                0% {
                    transform: rotate(0deg);
                }

                100% {
                    transform: rotate(360deg);
                }
            }

            .dashicons.rotate {
                animation: spin 1s linear infinite;
            }
        </style>
<?php
    }
}
