<?php
 
 /**
 * =============================================================================
 * @package         Blue Raven (Free Version)
 * @Plugin URI      https://enterrahost.com/plugins/blue-raven
 * 
 * @Author          EnterraHost
 * @Author URI      https://enterrahost.com
 * @License         GPL-2.0-or-later
 *  
 * @Copyright       (c) 2025 EnterraHost
 * @Contents        Plugin Tools > sitemap
 *
 * =============================================================================
 * 
 * || INDEX:
 * ||   - BLUE RAVEN ADMIN TOOL SITEMAP
 * || 
 * =============================================================================
 */

if ( ! defined( 'ABSPATH' ) ) exit; 

/*
============================================================
    BLUE RAVEN ADMIN TOOL SITEMAP
============================================================
*/

/**
 * Class Blue_Raven_Admin_Tools_SiteMap
 *
 * This class is responsible for rendering the sitemap page within the Blue Raven
 * Admin Tools section of the WordPress administration area. It handles the loading
 * of both the sitemap template and any associated JavaScript.
 */
class Blue_Raven_Admin_Tools_SiteMap {

    /**
     * Renders the sitemap page for the Blue Raven Admin Tools.
     */
    public function render() {
        self::load_tools_sitemap_template();
    }
    
    /**
     * Loads the sitemap template for the Blue Raven Admin Tools.
     *
     * This static method is intended to include the HTML structure and content
     * for the sitemap display.
     *
     * @access private 
     */
    private static function load_tools_sitemap_template() {
        
    ## =========== Fetch Valus from table =========== ##
    
        global $wpdb;

        ///-- Fetch general sitemap setting
        
        $sitemap = $wpdb->get_results( $wpdb->prepare(  "SELECT * FROM {$wpdb->prefix}BlueRavenValues WHERE setting LIKE %s",'%site-map%' ));

        ///-- Fetch IndexNow keys
        
        $siteMapKeys = $wpdb->get_results( $wpdb->prepare( "SELECT * FROM {$wpdb->prefix}BlueRavenValues WHERE setting LIKE %s",'%-site-map-key%'), ARRAY_A);
        $siteMapKeys_by_setting = [];
        if (!empty($siteMapKeys)) foreach ($siteMapKeys as $row) {  $siteMapKeys_by_setting[$row['setting']] = $row; }

    ## =========== HTML =========== ##  
    
        ?>
        <div class="flex-sb">
            <h3><?php esc_html_e('Site Map', 'blue-raven'); ?></h3>
            <h4>
                <?php esc_html_e('Need Help', 'blue-raven'); ?>
                <a href="<?php echo esc_url('https://portal.enterrahost.com/knowledgebase/4/'); ?>" target="_blank" rel="noopener noreferrer" style="margin-left: 8px;" title="<?php esc_attr_e('Learn more', 'blue-raven'); ?>"> <i class="fas fa-question-circle"></i></a>
            </h4>
        </div>

        <p class="enterra-highlight indent-one">
            <?php esc_html_e("A sitemap is an XML file that lists all the important pages of your website, helping search engines like Google understand your site structure and find new or updated content faster.", 'blue-raven'); ?>
            <br><br>
            <?php echo esc_html(isset($_SERVER['HTTP_HOST']) ? sanitize_text_field(wp_unslash($_SERVER['HTTP_HOST'])) : '') . '/br-sitemap.xml'; ?>
            <?php esc_html_e(" — Blue Raven will update your sitemap every 24 hours if this is enabled.", 'blue-raven'); ?>
        </p>

        <section>
            <div class="border-bottom-white flex-right" style="margin: 20px 0;">
                <h4 class="no-margin-padding spacing-right text-center"><?php esc_html_e('Switch On Site Map Updating', 'blue-raven'); ?></h4>
                <label class="switch">
                    <input type="checkbox" id="enable-site-map"
                        <?php if (!empty($sitemap) && isset($sitemap[0]->enabled) && $sitemap[0]->enabled) echo 'checked'; ?>>
                    <span class="slider"></span>
                </label>
            </div>
        </section>

        <section>
            <h4 class="spacing-right text-center"><?php esc_html_e('Instant Indexing with IndexNow', 'blue-raven'); ?></h4>
            <p class="indent-one">
                <?php esc_html_e("IndexNow is a protocol developed by Microsoft Bing that enables website owners to promptly inform search engines about content changes on their sites. Instead of waiting for search engine crawlers to discover new or updated pages, IndexNow allows immediate submission, facilitating faster indexing of changes.", 'blue-raven'); ?>
            </p>

            <div class="flex-right row-down-right" style="margin-top: 3rem;">
                <div class="flex-left spacing-right" style="margin: 20px 0;">
                    <label class="text-center" style="text-decoration: underline;">
                        <h4 class="no-margin-padding spacing-right-small text-center">
                            <a href="<?php echo esc_url('https://www.bing.com/webmasters'); ?>" target="_blank" rel="noopener noreferrer"><?php esc_html_e('Bing Key', 'blue-raven'); ?></a>
                        </h4>
                    </label>
                    <input type="text" name="bing-key" id="bing-key" placeholder="<?php esc_attr_e('KEY', 'blue-raven'); ?>" class="br-input" style="width:20rem;"
                        value="<?php echo !empty($siteMapKeys_by_setting['bing-site-map-key']['value']) ? esc_attr($siteMapKeys_by_setting['bing-site-map-key']['value']) : ''; ?>">
                </div>

                <div class="flex-right toggle-text-width" style="margin: 20px 0;">
                    <h4 class="no-margin-padding spacing-right text-center"><?php esc_html_e('Enable IndexNow for Bing', 'blue-raven'); ?></h4>
                    <label class="switch">
                        <input type="checkbox" id="enable-indexnow-site-map"
                            <?php if (!empty($siteMapKeys_by_setting['bing-site-map-key']) && isset($siteMapKeys_by_setting['bing-site-map-key']['enabled']) && $siteMapKeys_by_setting['bing-site-map-key']['enabled']) echo 'checked'; ?>>
                        <span class="slider"></span>
                    </label>
                </div>
            </div>

            <div style="height:1.2rem;">
                <?php
                $key = !empty($siteMapKeys_by_setting['bing-site-map-key']['value']) ? esc_attr($siteMapKeys_by_setting['bing-site-map-key']['value']) : '';

                if (!empty($key)) {
                    $safe_key = preg_replace('/[^a-zA-Z0-9]/', '', $key);

                    if (empty($safe_key)) {
                        echo '<span class="br-error">' . esc_html__('Invalid IndexNow key.', 'blue-raven') . '</span>';
                        return;
                    }

					$file_path = rtrim(sanitize_text_field(isset($_SERVER['DOCUMENT_ROOT']) ? wp_unslash($_SERVER['DOCUMENT_ROOT']) : ABSPATH), '/') . '/' . sanitize_file_name($safe_key) . '.txt';

                    if (!file_exists($file_path)) {
                        echo '<span class="br-error">';
                        echo esc_html__('⚠️ You are missing the required IndexNow .txt file in your site root.', 'blue-raven') . '<br>';
                        echo esc_html__('Please re-enable the feature. Do not delete the .txt file with this key: ', 'blue-raven');
                        echo '<strong>' . esc_html($safe_key) . '</strong>';
                        echo '</span>';
                        return;
                    }
                }
                ?>
                <p class="br-error" id="bing-verification-error-message" style="text-align:right;"></p>
            </div>
        </section>
        <?php
    }
}




