<?php

// Exit if accessed directly.
if (!defined('ABSPATH')) exit;

/**
 * HELPER COMMENT START
 * 
 * This class is used to bring your plugin to life. 
 * All the other registered classed bring features which are
 * controlled and managed by this class.
 * 
 * Within the add_hooks() function, you can register all of 
 * your WordPress related actions and filters as followed:
 * 
 * add_action( 'my_action_hook_to_call', array( $this, 'the_action_hook_callback', 10, 1 ) );
 * or
 * add_filter( 'my_filter_hook_to_call', array( $this, 'the_filter_hook_callback', 10, 1 ) );
 * or
 * add_shortcode( 'my_shortcode_tag', array( $this, 'the_shortcode_callback', 10 ) );
 * 
 * Once added, you can create the callback function, within this class, as followed: 
 * 
 * public function the_action_hook_callback( $some_variable ){}
 * or
 * public function the_filter_hook_callback( $some_variable ){}
 * or
 * public function the_shortcode_callback( $attributes = array(), $content = '' ){}
 * 
 * 
 * HELPER COMMENT END
 */

/**
 * Class Rdg_Blocks_Run
 *
 * Thats where we bring the plugin to life
 *
 * @package		RDGBLOCKS
 * @subpackage	Classes/Rdg_Blocks_Run
 * @author		RDGCorp
 * @since		1.0.0
 */
class Rdg_Blocks_Run {
    /**
     * Our Rdg_Blocks_Run constructor 
     * to run the plugin logic.
     *
     * @since 1.0.0
     */

    function __construct() {
        $this->add_hooks();
    }

    /**
     * ######################
     * ###
     * #### WORDPRESS HOOKS
     * ###
     * ######################
     */

    /**
     * Registers all WordPress and plugin related hooks
     *
     * @access	private
     * @since	1.0.0
     * @return	void
     */

    private function add_hooks() {
        add_action('admin_enqueue_scripts', array( $this, 'enqueue_backend_scripts_and_styles'), 20);
        add_action('acf/init', array( $this, 'add_custom_acf_options_page'), 20);
        register_activation_hook(RDGBLOCKS_PLUGIN_FILE, array( $this, 'activation_hook_callback'));
        add_action('acf/input/admin_enqueue_scripts', array( $this, 'custom_acf_admin_enqueue_scripts'));

        add_action('admin_menu', [$this, 'rdg_add_admin_page']);

    }

    public function rdg_add_admin_page() {
        add_menu_page(
            'Blocks Cache',
            'RDG Blocks Cache',
            'manage_options',
            'rdg-cached-blocks',
            [$this, 'rdg_display_cached_blocks'],
            'dashicons-database',
            82
        );
        
        // Add diagnostic submenu
        add_submenu_page(
            'rdg-cached-blocks',
            'System Diagnostic',
            'Diagnostic',
            'manage_options',
            'rdg-blocks-diagnostic',
            [$this, 'rdg_display_diagnostic']
        );
    }

    public function rdg_display_cached_blocks() {
        $cache = new Rdg_Blocks_Cache();
        $connect = $cache->getRedisConnect();

        if (!$connect) {
            echo '<div class="wrap">';
            echo '<h1>Redis connection error</h1>';
            echo '<div class="notice notice-warning"><p><strong>Redis:</strong> Redis connection failed.</p></div>';
            echo '</div>';
            return;
        }

        $per_pages_valid = [20, 30, 50];
        $filter_type = isset($_GET['filter_type']) ? sanitize_text_field($_GET['filter_type']) : null;
        $filter_type_id = isset($_GET['filter_type_id']) ? sanitize_text_field($_GET['filter_type_id']) : null;
        $filter_block_type = isset($_GET['filter_block_type']) ? sanitize_text_field($_GET['filter_block_type']) : null;
        $filter_block_status = isset($_GET['filter_block_status']) ? sanitize_text_field($_GET['filter_block_status']) : null;
        $per_page = isset($_GET['filter_per_page']) ? sanitize_text_field($_GET['filter_per_page']) : 20;
        $per_page = in_array($per_page, $per_pages_valid) ? $per_page : 20;
        $current_page = isset($_GET['paged']) ? sanitize_text_field($_GET['paged']) : 1;

        $data_filter_type = [];
        $data_filter_type_ids = [];
        $data_filter_block_types = [];
        $data_filter_block_status = ['active', 'retrying', 'paused'];
        $blocks = $cache->getCacheList();

        $filtered_blocks = [];
        foreach ($blocks as $block) {
            // Parse cache key format: block_name:post_type:post_id:block_id:redis_db[:date_suffix]
            // Supports both 5 parts (standard) and 6 parts (with optional date suffix)
            $parts = explode(':', $block);
            $block_name = $parts[0] ?? '';
            $block_type = $parts[1] ?? '';
            $block_type_id = $parts[2] ?? '';
            $block_id = $parts[3] ?? '';
            $redis_db = $parts[4] ?? '';
            // Optional 6th part is date_suffix, ignore it for parsing purposes

            if (!in_array($block_type, $data_filter_type)) {
                $data_filter_type[] = $block_type;
            }

            if (!in_array($block_type_id, $data_filter_type_ids)) {
                $data_filter_type_ids[] = $block_type_id;
            }

            if (!in_array($block_name, $data_filter_block_types)) {
                $data_filter_block_types[] = $block_name;
            }

            if (!empty($filter_type) && $block_type !== $filter_type) continue;
            if (!empty($filter_type_id) && $block_type_id !== $filter_type_id) continue;
            if (!empty($filter_block_type) && $block_name !== $filter_block_type) continue;

            if (!empty($filter_block_status)) {
                $failed_name = $cache->getCacheFailedName($block);
                $failed_block = $cache->getCacheBlock($failed_name);

                if (
                    ($filter_block_status === 'active' && !empty($failed_block)) ||
                    ($filter_block_status === 'retrying' && (empty($failed_block) || $failed_block === RDG_BLOCK_CACHE_FAILED_RETRY)) ||
                    ($filter_block_status === 'paused' && $failed_block !== RDG_BLOCK_CACHE_FAILED_RETRY)
                ) {
                    continue;
                }
            }

            $data_block_json = $cache->getCacheBlock($block);
            if (empty($data_block_json)) {
                // CRITICAL FIX: Don't auto-delete empty cache in admin panel
                // Keep it visible so admins can see blocks that need regeneration
                // Let the regenerate_cache cron handle deletion after multiple failed attempts
                error_log(sprintf(
                    'RDG Blocks / Admin Panel: Empty cache detected for %s - Keeping in list (visible to admin for manual regeneration)',
                    $block
                ));
                
                // Still add to filtered list but mark it visually in admin panel
                // The regenerate_cache cron will handle cleanup if needed
                continue;
            }

            $filtered_blocks[] = $block;
        }

        $total_items = count($filtered_blocks);
        $total_pages = ceil($total_items / $per_page);
        $offset = ($current_page - 1) * $per_page;
        $blocks_paginated = array_slice(array_values($filtered_blocks), $offset, $per_page);

        echo '<div class="wrap">';
        echo '<h1>Cached Blocks in Redis</h1>';
        echo '<table class="widefat fixed filters_cache">';
        echo '<thead><tr><th>';

        echo '<select class="filter_cache" id="filter_type">';
        echo '<option value="">All Post Types</option>';
        echo '</select>';

        echo '<select class="filter_cache" id="filter_type_id">';
        echo '<option value="">All Post IDs</option>';
        echo '</select>';

        echo '<select class="filter_cache" id="filter_block_type">';
        echo '<option value="">All RDG Blocks</option>';
        echo '</select>';

        echo '<select class="filter_cache" id="filter_block_status">';
        echo '<option value="">All Status</option>';
        echo '</select>';

        echo '<select class="filter_cache" id="filter_per_page">';
            $selected = 20;
            foreach ($per_pages_valid as $option) {
                $selected = ($per_page == $option) ? 'selected' : '';
                echo "<option value='{$option}' {$selected}>{$option}</option>";
            }
        echo '</select>';

        echo '<a name="redis-cache-delete-all" href="#" class="button">Delete All</a>';
        echo '<a name="redis-cache-delete-selected" href="#" class="button">Delete Selected</a>';
        echo '<a name="redis-cache-filter-clear" href="#" class="button">Reset Filter</a>';

        echo '</th></tr></thead><tbody>';
        echo '</tbody></table>';
        echo '</div>';

        echo '<div class="wrap">';
        echo '<table class="widefat fixed filters_cache_data">';
        echo '<thead><tr>';
        echo '<th class="item">#</th>';
        echo '<th class="time">Time</th>';
        echo '<th class="name">Name</th>';
        echo '<th class="request">Request</th>';
        echo '<th class="data">Data</th>';
        echo '<th class="actionsb">Actions</th>';
        echo '</tr></thead>';
        echo '<tbody>';

        $i = 1;
        foreach ($blocks_paginated as $block) {
            $data_block_json = $cache->getCacheBlock($block);
            $time = $cache->getCacheBlockTime($block);
            $data_block = json_decode($data_block_json, true);
            
            echo '<tr class="item_'.$block.'">';
            echo '<td>' . $offset + $i . '</td>';
            echo '<td>' . $time . '</td>';
            echo '<td>' . esc_html($block) . '</td>';
            echo '<td><pre style="height: 8rem;overflow: scroll;resize: vertical;">' . print_r($data_block['api_attributes'], true) . '</pre></td>';
            echo '<td class="api_response_item_'.$block.'"><pre style="height: 8rem;overflow: scroll;resize: vertical;">' . print_r($data_block['api_response'], true) . '</pre></td>';
            echo '<td class="actions">';
            echo '<a name="redis-cache-delete" data-cache="'.$block.'" href="#" class="button">Delete</a>';
            echo '<a name="redis-cache-update" data-cache="'.$block.'" href="#" class="button">Generate</a>';
            echo '</td>';
            echo '</tr>';

            $i++;
        }

        ?>
        <script>
            let jsonData = <?php echo json_encode([
                'data_filter_type' => $data_filter_type,
                'data_filter_type_ids' => $data_filter_type_ids,
                'data_filter_block_types' => $data_filter_block_types,
                'data_filter_block_status' => $data_filter_block_status,
                'selected' => [
                    'filter_type' => $filter_type,
                    'filter_type_id' => $filter_type_id,
                    'filter_block_type' => $filter_block_type,
                    'filter_block_status' => $filter_block_status,
                ],
            ]); ?>;
        </script>
        <?php

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

        echo '<div class="wrap pagination_cache_data"><nav class="cache-pagination">';
            for ($i = 1; $i <= $total_pages; $i++) {
                $url = add_query_arg([
                    'paged' => $i,
                    'filter_type' => $filter_type,
                    'filter_type_id' => $filter_type_id,
                    'filter_block_type' => $filter_block_type,
                    'filter_block_status' => $filter_block_status,
                    'filter_per_page' => $per_page,
                ], admin_url('admin.php?page=rdg-cached-blocks'));

                $active = ($i == $current_page) ? 'active' : '';
                if ($active) $url = '#';

                echo "<a href='{$url}' class='{$active}'>{$i}</a>";
            }
        echo '</nav></div>';

    }

    /**
     * System diagnostic page
     * Displays information about cron jobs, Redis, cache and system status
     */
    public function rdg_display_diagnostic() {
        $cache = new Rdg_Blocks_Cache();
        $redis_connected = $cache->getRedisConnect();
        
        // Get cron jobs information
        $cron_array = [];
        if (function_exists('_get_cron_array')) {
            $cron_array = _get_cron_array();
        } else {
            // Fallback: get directly from option
            $cron_option = get_option('cron');
            if (is_array($cron_option)) {
                $cron_array = $cron_option;
            }
        }
        
        $rdg_crons = [];
        $all_crons = [];
        
        if ($cron_array && is_array($cron_array)) {
            foreach ($cron_array as $timestamp => $cron) {
                if (!is_array($cron)) continue;
                
                foreach ($cron as $hook => $dings) {
                    if (!is_array($dings)) continue;
                    
                    foreach ($dings as $sig => $data) {
                        if (!is_array($data)) continue;
                        
                        $all_crons[] = [
                            'hook' => $hook,
                            'next_run' => $timestamp,
                            'interval' => isset($data['schedule']) ? $data['schedule'] : 'single',
                            'args' => isset($data['args']) ? $data['args'] : []
                        ];
                        
                        // Filter RDG Blocks crons
                        if (strpos($hook, 'rdg_blocks') !== false) {
                            $rdg_crons[] = [
                                'hook' => $hook,
                                'next_run' => $timestamp,
                                'next_run_formatted' => date('Y-m-d H:i:s', $timestamp),
                                'interval' => isset($data['schedule']) ? $data['schedule'] : 'single',
                                'args' => isset($data['args']) ? $data['args'] : [],
                                'is_past' => $timestamp < time()
                            ];
                        }
                    }
                }
            }
        }
        
        // Get Redis information
        $redis_info = [];
        if ($redis_connected) {
            try {
                $cache_list = $cache->getCacheList();
                $redis_info = [
                    'connected' => true,
                    'host' => defined('WP_REDIS_HOST') ? WP_REDIS_HOST : 'N/A',
                    'port' => defined('WP_REDIS_PORT') ? WP_REDIS_PORT : 'N/A',
                    'total_blocks' => count($cache_list),
                    'blocks' => []
                ];
                
                // Get details of some blocks
                $sample_blocks = array_slice($cache_list, 0, 10);
                foreach ($sample_blocks as $block_name) {
                    $block_data = $cache->getCacheBlock($block_name);
                    $ttl = $cache->getCacheBlockTimeSeg($block_name);
                    $failed_name = $cache->getCacheFailedName($block_name);
                    $failed_count = $cache->getCacheBlock($failed_name);
                    
                    $redis_info['blocks'][] = [
                        'name' => $block_name,
                        'ttl' => $ttl,
                        'ttl_formatted' => $cache->getCacheBlockTime($block_name),
                        'has_data' => !empty($block_data),
                        'failed_count' => $failed_count ? intval($failed_count) : 0,
                        'status' => $failed_count >= RDG_BLOCK_CACHE_FAILED_RETRY ? 'paused' : ($failed_count > 0 ? 'retrying' : 'active')
                    ];
                }
            } catch (\Exception $e) {
                $redis_info['error'] = $e->getMessage();
            }
        } else {
            $redis_info = [
                'connected' => false,
                'error' => 'Could not connect to Redis'
            ];
        }
        
        // Get configuration options
        $cache_status = get_option('rdg_blocks_cache_status', 1);
        $cache_cron_time = get_option('rdg_blocks_cache_cron_time', 'five_minute');
        $cache_last_run = get_option('rdg_blocks_cache_last_run', 'Never');
        $cron_time = get_option('rdg_blocks_cron_time', 'hourly');
        $cron_time_shortpixel = get_option('rdg_blocks_cron_time_shortpixel', 'hourly');
        
        // Check if WP_CRON is disabled
        $wp_cron_disabled = defined('DISABLE_WP_CRON') && DISABLE_WP_CRON;
        
        // Check next scheduled executions
        $next_cache_cron = wp_next_scheduled('rdg_blocks_cache_cron_event');
        $next_main_cron = wp_next_scheduled('rdg_blocks_cron_event');
        $next_shortpixel_cron = wp_next_scheduled('rdg_blocks_cron_event_shortpixel');
        
        ?>
        <div class="wrap">
            <h1>System Diagnostic - RDG Blocks</h1>
            
            <?php if (isset($_GET['regenerate']) && $_GET['regenerate'] === 'success'): ?>
                <div class="notice notice-success is-dismissible">
                    <p><strong>Success:</strong> The cache regeneration process has been completed. Check the logs for details.</p>
                </div>
            <?php endif; ?>
            
            <?php if (isset($_GET['regenerate']) && $_GET['regenerate'] === 'error'): ?>
                <div class="notice notice-error is-dismissible">
                    <p><strong>Error:</strong> An error occurred while regenerating the cache. <?php echo isset($_GET['message']) ? esc_html(urldecode($_GET['message'])) : ''; ?></p>
                </div>
            <?php endif; ?>
            
            <?php if (isset($_GET['cron_scheduled']) && $_GET['cron_scheduled'] === 'success'): ?>
                <div class="notice notice-success is-dismissible">
                    <p><strong>Success:</strong> The cache regeneration cron has been scheduled correctly.</p>
                </div>
            <?php endif; ?>
            
            <?php if (isset($_GET['regenerate_cache']) && $_GET['regenerate_cache'] === 'success'): ?>
                <div class="notice notice-success is-dismissible">
                    <p><strong>Success:</strong> The regenerate_cache process has been completed. Check the logs for details.</p>
                </div>
            <?php endif; ?>
            
            <?php if (isset($_GET['regenerate_cache']) && $_GET['regenerate_cache'] === 'error'): ?>
                <div class="notice notice-error is-dismissible">
                    <p><strong>Error:</strong> An error occurred while executing regenerate_cache. <?php echo isset($_GET['message']) ? esc_html(urldecode($_GET['message'])) : ''; ?></p>
                </div>
            <?php endif; ?>
            
            <div style="margin: 20px 0;">
                <form method="post" action="" style="display: inline-block;">
                    <?php wp_nonce_field('rdg_regenerate_all', 'rdg_regenerate_nonce'); ?>
                    <input type="hidden" name="action" value="regenerate_all">
                    <button type="submit" 
                            class="button button-primary button-large"
                            onclick="return confirm('Are you sure you want to regenerate all cache? This may take several minutes.');">
                        🔄 Regenerate All Cache (inGodWeTrust)
                    </button>
                </form>
                <form method="post" action="" style="display: inline-block; margin-left: 10px;">
                    <?php wp_nonce_field('rdg_regenerate_cache', 'rdg_regenerate_cache_nonce'); ?>
                    <input type="hidden" name="action" value="regenerate_cache">
                    <button type="submit" 
                            class="button button-secondary button-large"
                            onclick="return confirm('Execute regenerate_cache now? This will fill empty blocks with API data.');">
                        🔄 Execute Regenerate Cache (Fill Data)
                    </button>
                </form>
                <a href="<?php echo admin_url('admin.php?page=rdg-cached-blocks'); ?>" class="button">
                    View Block Cache
                </a>
            </div>
            
            <!-- WP_CRON Status -->
            <div class="card" style="margin: 20px 0;">
                <h2>WP_CRON Status</h2>
                <table class="widefat">
                    <tbody>
                        <tr>
                            <td><strong>WP_CRON Enabled:</strong></td>
                            <td>
                                <?php if ($wp_cron_disabled): ?>
                                    <span style="color: red;">❌ DISABLED</span>
                                    <p><em>If WP_CRON is disabled, you need to configure a system cron that runs: <code>wp cron event run --due-now</code></em></p>
                                <?php else: ?>
                                    <span style="color: green;">✅ ENABLED</span>
                                <?php endif; ?>
                            </td>
                        </tr>
                        <tr>
                            <td><strong>Cache Status:</strong></td>
                            <td>
                                <?php if ($cache_status == 1): ?>
                                    <span style="color: green;">✅ ACTIVE</span>
                                <?php else: ?>
                                    <span style="color: red;">❌ DISABLED</span>
                                    <p><em>Cache is disabled. Blocks will not be automatically regenerated.</em></p>
                                <?php endif; ?>
                            </td>
                        </tr>
                    </tbody>
                </table>
            </div>
            
            <!-- RDG Blocks Cron Jobs -->
            <div class="card" style="margin: 20px 0;">
                <h2>RDG Blocks Cron Jobs</h2>
                <?php if (empty($rdg_crons)): ?>
                    <div class="notice notice-warning">
                        <p><strong>⚠️ Warning:</strong> No scheduled RDG Blocks cron jobs found.</p>
                    </div>
                <?php else: ?>
                    <table class="widefat">
                        <thead>
                            <tr>
                                <th>Hook</th>
                                <th>Next Execution</th>
                                <th>Interval</th>
                                <th>Status</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($rdg_crons as $cron): ?>
                                <tr>
                                    <td><code><?php echo esc_html($cron['hook']); ?></code></td>
                                    <td>
                                        <?php echo esc_html($cron['next_run_formatted']); ?>
                                        <?php if ($cron['is_past']): ?>
                                            <span style="color: red;">(Overdue)</span>
                                        <?php endif; ?>
                                    </td>
                                    <td><?php echo esc_html($cron['interval']); ?></td>
                                    <td>
                                        <?php if ($cron['is_past']): ?>
                                            <span style="color: orange;">⚠️ Pending</span>
                                        <?php else: ?>
                                            <span style="color: green;">✅ Scheduled</span>
                                        <?php endif; ?>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                    
                    <h3>Specific Next Executions</h3>
                    <table class="widefat">
                        <tbody>
                            <tr>
                                <td><strong>Cache Regeneration:</strong></td>
                                <td>
                                    <?php if ($next_cache_cron): ?>
                                        <?php echo date('Y-m-d H:i:s', $next_cache_cron); ?>
                                        (<?php echo human_time_diff($next_cache_cron, time()); ?>)
                                    <?php else: ?>
                                        <span style="color: red;">❌ Not scheduled</span>
                                        <form method="post" action="" style="display: inline-block; margin-left: 10px;">
                                            <?php wp_nonce_field('rdg_schedule_cache_cron', 'rdg_schedule_cron_nonce'); ?>
                                            <input type="hidden" name="action" value="schedule_cache_cron">
                                            <button type="submit" class="button button-small">Schedule Cron</button>
                                        </form>
                                    <?php endif; ?>
                                </td>
                            </tr>
                            <tr>
                                <td><strong>Main Cron:</strong></td>
                                <td>
                                    <?php if ($next_main_cron): ?>
                                        <?php echo date('Y-m-d H:i:s', $next_main_cron); ?>
                                        (<?php echo human_time_diff($next_main_cron, time()); ?>)
                                    <?php else: ?>
                                        <span style="color: red;">❌ Not scheduled</span>
                                    <?php endif; ?>
                                </td>
                            </tr>
                            <tr>
                                <td><strong>ShortPixel Cron:</strong></td>
                                <td>
                                    <?php if ($next_shortpixel_cron): ?>
                                        <?php echo date('Y-m-d H:i:s', $next_shortpixel_cron); ?>
                                        (<?php echo human_time_diff($next_shortpixel_cron, time()); ?>)
                                    <?php else: ?>
                                        <span style="color: red;">❌ Not scheduled</span>
                                    <?php endif; ?>
                                </td>
                            </tr>
                        </tbody>
                    </table>
                <?php endif; ?>
            </div>
            
            <!-- Cron Configuration -->
            <div class="card" style="margin: 20px 0;">
                <h2>Cron Configuration</h2>
                <table class="widefat">
                    <tbody>
                        <tr>
                            <td><strong>Cache Regeneration Interval:</strong></td>
                            <td><?php echo esc_html($cache_cron_time); ?></td>
                        </tr>
                        <tr>
                            <td><strong>Last Cache Execution:</strong></td>
                            <td><?php echo esc_html($cache_last_run); ?></td>
                        </tr>
                        <tr>
                            <td><strong>Main Cron Interval:</strong></td>
                            <td><?php echo esc_html($cron_time); ?></td>
                        </tr>
                        <tr>
                            <td><strong>ShortPixel Cron Interval:</strong></td>
                            <td><?php echo esc_html($cron_time_shortpixel); ?></td>
                        </tr>
                    </tbody>
                </table>
            </div>
            
            <!-- Redis Status -->
            <div class="card" style="margin: 20px 0;">
                <h2>Redis Status</h2>
                <?php if ($redis_info['connected']): ?>
                    <table class="widefat">
                        <tbody>
                            <tr>
                                <td><strong>Connection:</strong></td>
                                <td><span style="color: green;">✅ Connected</span></td>
                            </tr>
                            <tr>
                                <td><strong>Host:</strong></td>
                                <td><?php echo esc_html($redis_info['host']); ?></td>
                            </tr>
                            <tr>
                                <td><strong>Port:</strong></td>
                                <td><?php echo esc_html($redis_info['port']); ?></td>
                            </tr>
                            <tr>
                                <td><strong>Total Blocks in Cache:</strong></td>
                                <td><?php echo esc_html($redis_info['total_blocks']); ?></td>
                            </tr>
                        </tbody>
                    </table>
                    
                    <?php if (!empty($redis_info['blocks'])): ?>
                        <h3>Block Sample (first 10)</h3>
                        <table class="widefat">
                            <thead>
                                <tr>
                                    <th>Block Name</th>
                                    <th>Remaining TTL</th>
                                    <th>Has Data</th>
                                    <th>Failed Attempts</th>
                                    <th>Status</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php foreach ($redis_info['blocks'] as $block): ?>
                                    <tr>
                                        <td><code><?php echo esc_html($block['name']); ?></code></td>
                                        <td>
                                            <?php echo esc_html($block['ttl_formatted']); ?>
                                            (<?php echo esc_html($block['ttl']); ?> sec)
                                        </td>
                                        <td>
                                            <?php if ($block['has_data']): ?>
                                                <span style="color: green;">✅</span>
                                            <?php else: ?>
                                                <span style="color: red;">❌</span>
                                            <?php endif; ?>
                                        </td>
                                        <td><?php echo esc_html($block['failed_count']); ?></td>
                                        <td>
                                            <?php 
                                            $status_colors = [
                                                'active' => 'green',
                                                'retrying' => 'orange',
                                                'paused' => 'red'
                                            ];
                                            $status_labels = [
                                                'active' => '✅ Active',
                                                'retrying' => '⚠️ Retrying',
                                                'paused' => '⏸️ Paused'
                                            ];
                                            ?>
                                            <span style="color: <?php echo $status_colors[$block['status']]; ?>;">
                                                <?php echo $status_labels[$block['status']]; ?>
                                            </span>
                                        </td>
                                    </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    <?php endif; ?>
                <?php else: ?>
                    <div class="notice notice-error">
                        <p><strong>❌ Error:</strong> <?php echo esc_html($redis_info['error']); ?></p>
                    </div>
                <?php endif; ?>
            </div>
            
            <!-- All Cron Jobs (last 20) -->
            <div class="card" style="margin: 20px 0;">
                <h2>All Cron Jobs (last 20)</h2>
                <?php if (empty($all_crons)): ?>
                    <p>No scheduled cron jobs found.</p>
                <?php else: ?>
                    <table class="widefat">
                        <thead>
                            <tr>
                                <th>Hook</th>
                                <th>Next Execution</th>
                                <th>Interval</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php 
                            $sorted_crons = $all_crons;
                            usort($sorted_crons, function($a, $b) {
                                return $a['next_run'] - $b['next_run'];
                            });
                            $sorted_crons = array_slice($sorted_crons, 0, 20);
                            foreach ($sorted_crons as $cron): ?>
                                <tr>
                                    <td><code><?php echo esc_html($cron['hook']); ?></code></td>
                                    <td><?php echo date('Y-m-d H:i:s', $cron['next_run']); ?></td>
                                    <td><?php echo esc_html($cron['interval']); ?></td>
                                </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                <?php endif; ?>
            </div>
        </div>
        <?php
        
        // Handle schedule cron action
        if (isset($_POST['action']) && $_POST['action'] === 'schedule_cache_cron' && current_user_can('manage_options')) {
            check_admin_referer('rdg_schedule_cache_cron', 'rdg_schedule_cron_nonce');
            
            $cache_cron_time = get_option('rdg_blocks_cache_cron_time', 'five_minute');
            
            // Clear existing cron if any
            wp_clear_scheduled_hook('rdg_blocks_cache_cron_event');
            
            // Schedule new cron
            wp_schedule_event(time(), $cache_cron_time, 'rdg_blocks_cache_cron_event');
            
            error_log('RDG Blocks / Diagnostic: Cache cron scheduled successfully with interval: ' . $cache_cron_time);
            
            wp_redirect(admin_url('admin.php?page=rdg-blocks-diagnostic&cron_scheduled=success'));
            exit;
        }
        
        // Handle regenerate_cache action
        if (isset($_POST['action']) && $_POST['action'] === 'regenerate_cache' && current_user_can('manage_options')) {
            check_admin_referer('rdg_regenerate_cache', 'rdg_regenerate_cache_nonce');
            
            error_log('RDG Blocks / Diagnostic: Starting regenerate_cache...');
            
            global $rdgb;
            $rdgb = (!empty($rdgb)) ? $rdgb : Rdg_Blocks::instance();
            
            $cli = new RDG_Blocks_CLI();
            
            // Increase execution time
            ini_set('max_execution_time', 300);
            set_time_limit(300);
            
            // Execute directly
            try {
                error_log('RDG Blocks / Diagnostic: Executing regenerate_cache()...');
                $cli->regenerate_cache(true); // Force = true to execute even if status is disabled
                error_log('RDG Blocks / Diagnostic: regenerate_cache() completed successfully');
                
                wp_redirect(admin_url('admin.php?page=rdg-blocks-diagnostic&regenerate_cache=success'));
            } catch (\Exception $e) {
                error_log('RDG Blocks / Diagnostic: Error executing regenerate_cache: ' . $e->getMessage());
                wp_redirect(admin_url('admin.php?page=rdg-blocks-diagnostic&regenerate_cache=error&message=' . urlencode($e->getMessage())));
            }
            exit;
        }
        
        // Handle regeneration action
        if (isset($_POST['action']) && $_POST['action'] === 'regenerate_all' && current_user_can('manage_options')) {
            check_admin_referer('rdg_regenerate_all', 'rdg_regenerate_nonce');
            
            error_log('RDG Blocks / Diagnostic: Starting inGodWeTrust regeneration...');
            
            // Execute inGodWeTrust programmatically
            global $rdgb;
            $rdgb = (!empty($rdgb)) ? $rdgb : Rdg_Blocks::instance();
            
            $cli = new RDG_Blocks_CLI();
            
            // Increase execution time
            ini_set('max_execution_time', 300);
            set_time_limit(300);
            
            // Execute directly instead of using cron
            try {
                error_log('RDG Blocks / Diagnostic: Executing inGodWeTrust()...');
                $cli->inGodWeTrust();
                error_log('RDG Blocks / Diagnostic: inGodWeTrust() completed successfully');
                
                wp_redirect(admin_url('admin.php?page=rdg-blocks-diagnostic&regenerate=success'));
            } catch (\Exception $e) {
                error_log('RDG Blocks / Diagnostic: Error executing inGodWeTrust: ' . $e->getMessage());
                wp_redirect(admin_url('admin.php?page=rdg-blocks-diagnostic&regenerate=error&message=' . urlencode($e->getMessage())));
            }
            exit;
        }
    }

    public function custom_acf_admin_enqueue_scripts() {
        wp_enqueue_script( 'custom-acf-input-js', RDGBLOCKS_PLUGIN_URL.'core/includes/assets/js/ajax_response.js', false, '1.0.0' );
    }

    /**
     * ######################
     * ###
     * #### WORDPRESS HOOK CALLBACKS
     * ###
     * ######################
     */

    /**
     * Enqueue the backend related scripts and styles for this plugin.
     * All of the added scripts andstyles will be available on every page within the backend.
     *
     * @access	public
     * @since	1.0.0
     *
     * @return	void
     */

    public function enqueue_backend_scripts_and_styles($hook) {
        wp_enqueue_style('rdgblocks-backend-styles', RDGBLOCKS_PLUGIN_URL.'core/includes/assets/css/backend-styles.css', [], RDGBLOCKS_VERSION, 'all');
        wp_enqueue_script('rdgblocks-backend-scripts', RDGBLOCKS_PLUGIN_URL.'core/includes/assets/js/backend-scripts.js', [], RDGBLOCKS_VERSION, false);
        wp_localize_script('rdgblocks-backend-scripts', 'rdgblocks', [
            'plugin_name' => __(RDGBLOCKS_NAME, RDGBLOCKS_NAME_SLUG),
        ]);
        wp_localize_script('rdgblocks-backend-scripts', 'rdg_block_var', [
            'ajaxurl' => admin_url('admin-ajax.php'),
        ]);

        if ($hook == 'toplevel_page_rdg-cached-blocks') {
            wp_enqueue_script('rdgblocks-cache-scripts', RDGBLOCKS_PLUGIN_URL.'core/includes/assets/js/rdg-blocks-cache.js', [], RDGBLOCKS_VERSION, false);
        }
    }

    /**
     * Add the Advanced Custom fields
     * options pages
     *
     * @access	public
     * @since	1.0.0
     * @link	https://www.advancedcustomfields.com/resources/acf_add_options_page/
     *
     * @return	void
     */

    public function add_custom_acf_options_page() {
        // Check function exists.
        if(function_exists('acf_add_options_page')) {
            // Register options page.
            acf_add_options_page([
                'page_title' => __('RDG Blocks'),
                'menu_title' => __('RDG Blocks'),
                'menu_slug' => RDGBLOCKS_NAME_SLUG,
                'capability' => 'edit_posts',
                'redirect' => true
            ]);

            global $rdgb;
            if (!empty($rdgb)) {
                $menus = $rdgb->helpers->getMenus();

                $menus[] = [
                    'page_title'  => __('Cache Maintenance'),
                    'menu_title'  => 'Cache Maintenance',
                    'parent_slug' => RDGBLOCKS_NAME_SLUG,
                ];

                $menus[] = [
                    'page_title'  => __('Categories Maintenance'),
                    'menu_title'  => 'Categories Maintenance',
                    'parent_slug' => RDGBLOCKS_NAME_SLUG,
                ];

                $menus[] = [
                    'page_title'  => __('Images Maintenance'),
                    'menu_title'  => 'Images Maintenance',
                    'parent_slug' => RDGBLOCKS_NAME_SLUG,
                ];

                $menus[] = [
                    'page_title'  => 'Resources',
                    'menu_title'  => 'Resources',
                    'parent_slug' => RDGBLOCKS_NAME_SLUG,
                ];

                $menus[] = [
                    'page_title'  => __('Settings'),
                    'menu_title'  => 'Settings',
                    'parent_slug' => RDGBLOCKS_NAME_SLUG,
                ];

                $menus[] = [
                    'page_title'  => 'Sports Categories',
                    'menu_title'  => 'Sports Categories',
                    'parent_slug' => RDGBLOCKS_NAME_SLUG,
                ];

                // $menus[] = [
                //     'page_title'  => 'Redis Cache',
                //     'menu_title'  => 'Redis Cache',
                //     'parent_slug' => RDGBLOCKS_NAME_SLUG,
                // ];

                function compareMenuTitle($a, $b) {
                    return strcmp($a['menu_title'], $b['menu_title']);
                }

                $order_menu = array_values($menus);
                usort($order_menu, 'compareMenuTitle');

                foreach ($order_menu as $key => $menu) {
                    acf_add_options_page(array(
                        'page_title'  => $menu['page_title'],
                        'menu_title'  => $menu['menu_title'],
                        'parent_slug' => RDGBLOCKS_NAME_SLUG,
                    ));
                }
            }
        }
    }

    

    /**
     * ####################
     * ### Activation/Deactivation hooks
     * ####################
     */
        
    /*
    * This function is called on activation of the plugin
    *
    * @access	public
    * @since	1.0.0
    *
    * @return	void
    */

    public function activation_hook_callback() {
        if (!function_exists('is_plugin_active')) {
            require_once ABSPATH . 'wp-admin/includes/plugin.php';
        }
        
        if (!is_plugin_active('advanced-custom-fields-pro/acf.php') && !is_plugin_active('advanced-custom-fields/acf.php')) {
            deactivate_plugins(plugin_basename(__FILE__));
            wp_die(
                'RDGBLOCKS requires Advanced Custom Fields Pro to be active.<br /> <b>Please activate ACF before activating this plugin.</  b>',
                'Activation Error',
                array('back_link' => true)
            );
        }
    }
}

add_action('wp_ajax_nopriv_rdg_blocks_delete_cache_all','deleteAllRdgBlocksCache');
add_action('wp_ajax_rdg_blocks_delete_cache_all','deleteAllRdgBlocksCache');

function deleteAllRdgBlocksCache() {
    $cache = new Rdg_Blocks_Cache();
    $connect = $cache->getRedisConnect();

    if (!$connect) {
        error_log(sprintf('%s / deleteAllRdgBlocksCache: Redis connection failed.', RDGBLOCKS_NAME));
        echo 'RDG Blocks: Could not delete cache.';
        wp_die();
    }

    $deleted = $cache->delAllCache();
    if ($deleted) {
        error_log(sprintf('%s / deleteAllRdgBlocksCache: Delete all cache.', RDGBLOCKS_NAME));
        echo 'success';
        wp_die();
    }

    error_log(sprintf('%s / deleteAllRdgBlocksCache: Could not delete all cache.', RDGBLOCKS_NAME));
    echo 'RDG Blocks: Could not delete all cache.';
    wp_die();
}

add_action('wp_ajax_nopriv_rdg_blocks_delete_cache_selected','deleteSelectedRdgBlocksCache');
add_action('wp_ajax_rdg_blocks_delete_cache_selected','deleteSelectedRdgBlocksCache');

function deleteSelectedRdgBlocksCache() {
    $selected = $_POST['selected'];
    if (empty($selected)) wp_die();

    $selected_array = explode(',', $selected);
    if (!is_array($selected_array) || count($selected_array) == 0) {
        error_log(sprintf('%s / deleteSelectedRdgBlocksCache: Selected is not an array.', RDGBLOCKS_NAME));
        wp_die();
    }

    $cache = new Rdg_Blocks_Cache();
    $connect = $cache->getRedisConnect();

    if (!$connect) {
        error_log(sprintf('%s / deleteSelectedRdgBlocksCache: Redis connection failed.', RDGBLOCKS_NAME));
        wp_die();
    }

    $cache_deleted = [];
    
    foreach ($selected_array as $block) {
        if (empty($block)) continue;

        $block_name = $block;
        if (substr($block, 0, 5) == 'item_') {
            $block_name = substr($block, 5);
        }

        $deleted = $cache->delCacheBlock($block_name);
        if ($deleted) {
            $cache_deleted[] = $block_name;
        }
    }

    error_log(print_r([
        'message' => sprintf('%s / deleteSelectedRdgBlocksCache: Delete Selected cache.', RDGBLOCKS_NAME),
        'cache_deleted' => $cache_deleted,
    ], true));
    wp_die();
}

add_action('wp_ajax_nopriv_rdg_blocks_delete_cache','deleteRdgBlocksCache');
add_action('wp_ajax_rdg_blocks_delete_cache','deleteRdgBlocksCache');

function deleteRdgBlocksCache() {
    $cache_name = $_POST['cache'];
    if (empty($cache_name)) wp_die();

    $cache = new Rdg_Blocks_Cache();
    $connect = $cache->getRedisConnect();

    if (!$connect) {
        error_log(sprintf('%s / deleteRdgBlocksCache: Redis connection failed.', RDGBLOCKS_NAME));
        echo 'RDG Blocks: Could not delete cache.';
        wp_die();
    }

    $deleted = $cache->delCacheBlock($cache_name);

    if (!$deleted) {
        error_log(sprintf('%s / deleteRdgBlocksCache: Failed to delete cache for %s', RDGBLOCKS_NAME, $cache_name));
        wp_die();
    }

    echo 'success';
    error_log(sprintf('%s / deleteRdgBlocksCache: Delete cache %s', RDGBLOCKS_NAME, $cache_name));

    wp_die();
}

add_action('wp_ajax_nopriv_rdg_blocks_update_cache','updateRdgBlocksCache');
add_action('wp_ajax_rdg_blocks_update_cache','updateRdgBlocksCache');

function updateRdgBlocksCache() {
    $cache_name = $_POST['cache'];
    if (empty($cache_name)) wp_die();

    $cache = new Rdg_Blocks_Cache();
    $connect = $cache->getRedisConnect();

    if (!$connect) {
        error_log(sprintf('%s / updateRdgBlocksCache: Redis connection failed.', RDGBLOCKS_NAME));
        echo 'RDG Blocks: Could not update cache.';
        wp_die();
    }

    global $rdgb;
    $block = $cache->getCacheBlock($cache_name);
    $attributes = json_decode($block, true);
    $block_name = explode(':', $cache_name)[0];
    $block = $rdgb->settings->getBlock(str_replace('_', '-', $block_name));

    if (is_array($attributes)) {
        $api_attributes = $attributes['api_attributes'];

        $response = $rdgb->helpers->getApiRequest(
            $api_attributes['request'],
            $api_attributes['method'],
            $api_attributes['headers']
        );

        if ($response['http_code'] != 200) {
            $rdgb->helpers->getApiError($response['http_code'], [
                'block' => $block_name,
                'http_code' => $response['http_code'],
                'api_attributes' => $api_attributes
            ]);

            echo 'RDG Blocks: Could not update cache.';

            wp_die();
        }

        $response_json = $rdgb->helpers->isJson($response['data']);
        if ($response_json == null) {
            $rdgb->helpers->getApiError('json_response', [
                'block' => $block_name,
                'code' => 'json_response',
                'api_attributes' => $api_attributes
            ]);

            echo 'RDG Blocks: Could not update cache.';

            wp_die();
        }

        if ($block->isPreSaved()) {
            $attributes['cache_name'] = $cache_name;
            $attributes['block'] = $block;
            $response_json = $block->getPreSavedData($response_json, $attributes);
        }
        
        $updated = $cache->updateCacheBlock($cache_name, $attributes, $response_json);
        if ($updated) {
            // Parse cache key format: block_name:post_type:post_id:block_id:redis_db[:date_suffix]
            // Supports both 5 parts (standard) and 6 parts (with optional date suffix)
            $tems = explode(':', $cache_name);
            $rdgb->helpers->getApiError('update_cache', [
                'page_type' => $tems[1] ?? '',
                'post_id' => $tems[2] ?? '',
                'block_name' => $cache_name,
            ]);

            print_r($response_json);
        } else{
            echo 'RDG Blocks: Could not update cache.';
        }
    }   

    wp_die();
}

