<?php

/**
 * The file that defines the core plugin class
 *
 * A class definition that includes attributes and functions used across both the
 * public-facing side of the site and the admin area.
 *
 * @link       http://example.com
 * @since      1.0.0
 *
 * @package    agile_tix
 * @subpackage agile_tix/includes
 */

/**
 * The core plugin class.
 *
 * This is used to define internationalization, admin-specific hooks, and
 * public-facing site hooks.
 *
 * Also maintains the unique identifier of this plugin as well as the current
 * version of the plugin.
 *
 * @since      1.0.0
 * @package    agile_tix
 * @subpackage agile_tix/includes
 * @author     AgileTix
 */
class agile_tix
{

    /**
     * The loader that's responsible for maintaining and registering all hooks that power
     * the plugin.
     *
     * @since    1.0.0
     * @access   protected
     * @var      agile_tix_Loader    $loader    Maintains and registers all hooks for the plugin.
     */
    protected $loader;

    /**
     * The unique identifier of this plugin.
     *
     * @since    1.0.0
     * @access   protected
     * @var      string    $agile_tix    The string used to uniquely identify this plugin.
     */
    protected $agile_tix;

    /**
     * The current version of the plugin.
     *
     * @since    1.0.0
     * @access   protected
     * @var      string    $version    The current version of the plugin.
     */
    protected $version;

    /**
     * Define the core functionality of the plugin.
     *
     * Set the plugin name and the plugin version that can be used throughout the plugin.
     * Load the dependencies, define the locale, and set the hooks for the admin area and
     * the public-facing side of the site.
     *
     * @since    1.0.0
     */
    public function __construct()
    {
        if (defined('agile_tix_VERSION')) {
            $this->version = agile_tix_VERSION;
        } else {
            $this->version = '1.0.0';
        }
        $this->agile_tix = 'agile-ticketing';

        $this->load_dependencies();
        $this->set_locale();
        $this->define_admin_hooks();
        $this->define_public_hooks();
    }

    /**
     * Load the required dependencies for this plugin.
     *
     * Include the following files that make up the plugin:
     *
     * - agile_tix_Loader. Orchestrates the hooks of the plugin.
     * - agile_tix_i18n. Defines internationalization functionality.
     * - agile_tix_Admin. Defines all hooks for the admin area.
     * - agile_tix_Public. Defines all hooks for the public side of the site.
     *
     * Create an instance of the loader which will be used to register the hooks
     * with WordPress.
     *
     * @since    1.0.0
     * @access   private
     */
    private function load_dependencies()
    {

        /**
         * The class responsible for orchestrating the actions and filters of the
         * core plugin.
         */
        require_once plugin_dir_path(dirname(__FILE__)) . 'includes/agile-ticketing-loader.php';

        /**
         * The class responsible for defining internationalization functionality
         * of the plugin.
         */
        require_once plugin_dir_path(dirname(__FILE__)) . 'includes/agile-ticketing-i18n.php';

        /**
         * The class responsible for defining all actions that occur in the admin area.
         */
        require_once plugin_dir_path(dirname(__FILE__)) . 'admin/agile-ticketing-admin.php';

        /**
         * The class responsible for defining all actions that occur in the public-facing
         * side of the site.
         */
        require_once plugin_dir_path(dirname(__FILE__)) . 'public/agile-ticketing-public.php';

        require_once plugin_dir_path(dirname(__FILE__)) . 'includes/agile-ticketing-options.php';
        require_once plugin_dir_path(dirname(__FILE__)) . 'includes/agile-ticketing-post.php';
        //require_once plugin_dir_path(dirname(__FILE__)) . 'includes/agile-ticketing-template-registration.php';
        require_once plugin_dir_path(dirname(__FILE__)) . 'includes/agile-ticketing-data-fetcher.php';
        require_once plugin_dir_path(dirname(__FILE__)) . 'includes/agile-ticketing-post-creator.php';
        require_once plugin_dir_path(dirname(__FILE__)) . 'includes/agile-ticketing-rest-route.php';
        require_once plugin_dir_path(dirname(__FILE__)) . 'includes/agile-ticketing-shortcodes.php';
        require_once plugin_dir_path(dirname(__FILE__)) . 'includes/agile-ticketing-event-champ-integrate.php';
        require_once plugin_dir_path(dirname(__FILE__)) . 'includes/agile-ticketing-executionTime.php';
        require_once plugin_dir_path(dirname(__FILE__)) . 'includes/agile-ticketing-amy-moive-integrate.php';
        require_once plugin_dir_path(dirname(__FILE__)) . 'includes/agile-ticketing-custom-support.php';
        require_once plugin_dir_path(dirname(__FILE__)) . 'includes/agile-ticketing-location-services.php';
        require_once plugin_dir_path(dirname(__FILE__)) . 'public/ats-integrate/widget-activate.php';

        $this->loader = new agile_tix_Loader();
    }

    /**
     * Define the locale for this plugin for internationalization.
     *
     * Uses the agile_tix_i18n class in order to set the domain and to register the hook
     * with WordPress.
     *
     * @since    1.0.0
     * @access   private
     */
    private function set_locale()
    {

        $plugin_i18n = new agile_tix_i18n();

        $this->loader->add_action('plugins_loaded', $plugin_i18n, 'load_plugin_textdomain');

    }

    /**
     * Register all of the hooks related to the admin area functionality
     * of the plugin.
     *
     * @since    1.0.0
     * @access   private
     */
    private function define_admin_hooks()
    {

        $plugin_admin = new agile_tix_Admin($this->get_agile_tix(), $this->get_version());
        $this->loader->add_action('admin_enqueue_scripts', $plugin_admin, 'enqueue_styles');
        $this->loader->add_action('admin_enqueue_scripts', $plugin_admin, 'enqueue_scripts');

        $plugin_options = new agile_tix_Options($this->get_agile_tix(), $this->get_version());
        $this->loader->add_action('admin_init', $plugin_options, 'agile_register_settings_tabs');
        $this->loader->add_action('admin_menu', $plugin_options, 'agile_options_page');
        //$this->loader->add_action('admin_footer', $plugin_options,'agile_custom_theme_map_set_required');
        $this->loader->add_action('update_option_agile_field_style_editor', $plugin_options, 'agile_save_custom_style_to_file');
        //$this->loader->add_action('wp_ajax_agile_get_meta_fields', $plugin_options, 'agile_get_meta_fields_ajax');//think this got scrapped in the custom rework
        
        // Add AJAX hooks for real-time utility metrics
        $this->loader->add_action('wp_ajax_agile_get_utility_metrics', 'agile_tix_Options', 'ajax_get_utility_metrics');

        $this->loader->add_filter('plugin_action_links_agile-ticketing-plugin/Agile_Ticketing.php' , $plugin_options, 'agile_plugin_settings_link');
        //$this->loader->add_action('admin_post_ats_reset_content_default', $plugin_options , 'agile_reset_content_to_default');
        //$this->loader->add_action('update_option_agile_field_password',$plugin_options, 'agile_verify_credentials_after_save');
        $this->loader->add_action('admin_init', $plugin_options, 'agile_verify_credentials_after_save');
        $this->loader->add_action('admin_notices', $plugin_options, 'agile_display_settings_errors');

        $this->loader->add_action('wp_ajax_agile_refresh_ats_data',$plugin_options, 'agile_refresh_ats_data');
        $this->loader->add_action('wp_ajax_agile_activate_webhook', $plugin_options, 'agile_activate_webhook');
        $this->loader->add_action('wp_ajax_agile_get_tax_by_post_type', $plugin_options, 'agile_get_tax_by_postType');
        $this->loader->add_action('wp_ajax_agile_refresh_utility',$plugin_options, 'agile_refresh_utility');
        $this->loader->add_action('wp_ajax_agile_get_style_preset', $plugin_options, 'agile_get_style_preset');
        $this->loader->add_action('wp_ajax_agile_save_custom_style_preset', $plugin_options, 'agile_save_custom_style_preset');
        

        $plugin_post = new agile_tix_post_type($this->get_agile_tix(), $this->get_version());
        $this->loader->add_action('init', $plugin_post, 'register_agile_custom_post_type');
        $this->loader->add_action('pre_get_posts', $plugin_post, 'agile_post_adjust_queries');
        $this->loader->add_action('pre_get_posts', $plugin_post, 'ats_add_custom_post_type_to_rss_feed');
        $this->loader->add_action('pre_get_posts', $plugin_post, 'ats_coming_soon_feed_query');

        $rest_endpoint = new agile_tix_Rest_Route();
        $this->loader->add_action('rest_api_init', $rest_endpoint, 'agile_register_rest_options');
        $this->loader->add_action('rest_api_init', $rest_endpoint, 'prefix_register_routes');
        $this->loader->add_filter('robots_txt', $rest_endpoint, 'agile_modify_robots');
        //$this->loader->add_action('init', $rest_endpoint, 'create_agile_API_agent_user');
        //$this->loader->add_filter('rest_authentication_errors', $rest_endpoint, 'agile_whitelist_api_by_header', 10, 1);
        //$this->loader->add_filter('rest_pre_dispatch', $rest_endpoint, 'agile_prevalidate_ping_signature', 10, 2);

        //$agile_tix_template_register = new agile_tix_template_registration($this->get_agile_tix(), $this->get_version());
        //$this->loader->add_action('init', $agile_tix_template_register, 'register_agile_template');

        $post_creator = new agile_tix_post_creator($this->get_agile_tix(), $this->get_version());
        //$this->loader->add_action('agile_process_events_batch', $post_creator, 'agile_handle_events_batch', 10, 1);
        //$this->loader->add_action('agile_finalize_processing', $post_creator, 'agile_finalize_processing');

        //$this->loader->add_action('admin_head', new agile_tix_Widget_Active(), 'agile_echo_head');

        $activator = new agile_tix_Widget_Active();
        $this->loader->add_action('admin_head',$activator , 'agile_echo_head');
        /*$this->loader->add_action('admin_head', function() {
            echo '<!-- DEBUG: admin_head hook fired -->';
        });*/
        //$this->loader->add_action('wp_head', new agile_tix_Widget_Active(), 'agile_echo_head');
        
         // Ensure Action Scheduler queue runner is properly initialized
        $this->loader->add_action('action_scheduler_init', $this, 'verify_action_scheduler_setup', 20);
        
        // Add diagnostic checks (admin only)
        $this->loader->add_action('admin_init', $this, 'diagnose_action_scheduler', 20);
        
    }

    
    /**
     * Register all of the hooks related to the public-facing functionality
     * of the plugin.
     *
     * @since    1.0.0
     * @access   private
     */
    private function define_public_hooks()
    {
        $plugin_public = new agile_tix_Public($this->get_agile_tix(), $this->get_version());

        $this->loader->add_action('wp_enqueue_scripts', $plugin_public, 'enqueue_styles');
        $this->loader->add_action('wp_enqueue_scripts', $plugin_public, 'enqueue_scripts');
        $this->loader->add_action('wp_head', new agile_tix_Widget_Active(), 'agile_echo_head');

        $plugin_options = new agile_tix_Options($this->get_agile_tix(), $this->get_version());
        $this->loader->add_action('wp_enqueue_scripts', $plugin_options, 'agile_enqueue_user_styles');
        $this->loader->add_filter('post_thumbnail_html',$plugin_options, 'agile_hide_featured_image_conditionally', 10, 3);

        $post_creator = new agile_tix_post_creator($this->get_agile_tix(), $this->get_version());
        $this->loader->add_action('agile_process_events_batch', $post_creator, 'agile_handle_events_batch', 10, 3 );
        $this->loader->add_action('agile_finalize_processing', $post_creator, 'agile_finalize_processing');
        $this->loader->add_filter( 'action_scheduler_queue_runner_concurrent_batches', $post_creator, 'agile_increase_concurrent_batches' );
        $this->loader->add_filter( 'action_scheduler_queue_runner_batch_size', $post_creator, 'agile_increase_batch_size');


        $plugin_shortcodes = new agile_tix_ShortCodes();
        $this->loader->add_action('init', $plugin_shortcodes, 'ats_registerShortCodes');
    }

    /**
     * Run the loader to execute all of the hooks with WordPress.
     *
     * @since    1.0.0
     */
    public function run()
    {
        $this->loader->run();
    }

    /**
     * The name of the plugin used to uniquely identify it within the context of
     * WordPress and to define internationalization functionality.
     *
     * @since     1.0.0
     * @return    string    The name of the plugin.
     */
    public function get_agile_tix()
    {
        return $this->agile_tix;
    }

    /**
     * The reference to the class that orchestrates the hooks with the plugin.
     *
     * @since     1.0.0
     * @return    agile_tix_Loader    Orchestrates the hooks of the plugin.
     */
    public function get_loader()
    {
        return $this->loader;
    }

    /**
     * Retrieve the version number of the plugin.
     *
     * @since     1.0.0
     * @return    string    The version number of the plugin.
     */
    public function get_version()
    {
        return $this->version;
    }

    /** 
     * General utility logging function to write to our own log file instead of the bulk /wp-content/debug.log accessed with WP_DEBUG_LOG
     * Called with agile_tix::agile_tix_log_event("This is a test call to create the file");
     * VERY IMPORTANT NOTE! this drops the log file in the larger WP_CONTENT folder instead of in the plugin's folder
     * This is good for for maintaining the log between plugin instances, but bad practise for a real plugin
     * Change the logfile path to plugin_dir_path(__FILE__) . agile_tix-log.txt before release
     * @param mixed $message 
     */
    static function agile_tix_log_event($message)
    {
        
        $log_file = WP_CONTENT_DIR . '/agile_tix-log.txt'; //Use this for debug
        //$log_file =  plugin_dir_path(__FILE__) . 'agile_tix-log.txt'; //Use this for prod release

        // Ensure the file exists or create it
        if (!file_exists($log_file)) {
            
            file_put_contents($log_file, "Log file created on " . date('Y-m-d H:i:s') . "\n");
        }
        
        $message = '[' . date('Y-m-d H:i:s') . '] ' . $message . "\n";
        file_put_contents($log_file, $message, FILE_APPEND);
    }

    /**
     * Verify Action Scheduler is properly set up after initialization
     * 
     * @since 1.1.0
     */
    public function verify_action_scheduler_setup() {
        if (!class_exists('ActionScheduler')) {
            agile_tix::agile_tix_log_event('ERROR: Action Scheduler class not found after initialization');
            return;
        }

        // Verify queue runner is initialized
        $runner = ActionScheduler::runner();
        if (!$runner) {
            agile_tix::agile_tix_log_event('ERROR: Action Scheduler runner not available');
            return;
        }

        // Ensure queue runner is initialized
        if (method_exists($runner, 'init')) {
            // Check if init has been called by checking if the cron schedule filter is registered
            if (!has_filter('cron_schedules', array($runner, 'add_wp_cron_schedule'))) {
                agile_tix::agile_tix_log_event('WARNING: Action Scheduler queue runner not initialized - initializing now');
                $runner->init();
            }
        }

        // Verify the cron event is scheduled (even if WP Cron is disabled, scheduling should work)
        $cron_context = array('WP Cron');
        $next_run = wp_next_scheduled('action_scheduler_run_queue', $cron_context);
        
        if (!$next_run) {
            // Try to schedule it manually
            agile_tix::agile_tix_log_event('WARNING: action_scheduler_run_queue cron event not scheduled - attempting to schedule manually');
            
            // Ensure the 'every_minute' schedule exists
            if (!has_filter('cron_schedules', array($runner, 'add_wp_cron_schedule'))) {
                add_filter('cron_schedules', array($runner, 'add_wp_cron_schedule'));
            }
            
            // Schedule the event
            $schedule = apply_filters('action_scheduler_run_schedule', 'every_minute');
            $scheduled = wp_schedule_event(time(), $schedule, 'action_scheduler_run_queue', $cron_context);
            
            if ($scheduled === false) {
                agile_tix::agile_tix_log_event('ERROR: Failed to schedule action_scheduler_run_queue cron event');
            } else {
                agile_tix::agile_tix_log_event('SUCCESS: Manually scheduled action_scheduler_run_queue cron event');
            }
        } else {
            //agile_tix::agile_tix_log_event('INFO: action_scheduler_run_queue cron event is scheduled (next run: ' . date('Y-m-d H:i:s', $next_run) . ')');
        }

        // Verify the queue runner hook is registered
        if (!has_action('action_scheduler_run_queue', array($runner, 'run'))) {
            agile_tix::agile_tix_log_event('WARNING: Action Scheduler queue runner hook not registered - registering now');
            add_action('action_scheduler_run_queue', array($runner, 'run'));
        }

        // Verify async request mechanism is set up (important when WP Cron is disabled)
        if (method_exists($runner, 'hook_dispatch_async_request')) {
            // Check if shutdown hook is registered for async requests
            if (!has_action('shutdown', array($runner, 'maybe_dispatch_async_request'))) {
                agile_tix::agile_tix_log_event('WARNING: Async request mechanism not hooked - hooking now');
                $runner->hook_dispatch_async_request();
            }
        }
        
        // If WP Cron is disabled and we have pending actions, try to process them immediately
        if (defined('DISABLE_WP_CRON') && DISABLE_WP_CRON) {
            $store = ActionScheduler::store();
            if ($store && method_exists($store, 'has_pending_actions_due')) {
                if ($store->has_pending_actions_due()) {
                    agile_tix::agile_tix_log_event('INFO: WP Cron disabled but actions are due - attempting to process via queue runner');
                    try {
                        $processed = $runner->run('WP Cron Disabled - Auto Process');
                        agile_tix::agile_tix_log_event(sprintf('INFO: Processed %d actions automatically', $processed));
                    } catch (Exception $e) {
                        agile_tix::agile_tix_log_event('ERROR: Failed to auto-process actions - ' . $e->getMessage());
                    }
                }
            }
        }
    }

    /**
     * Diagnostic checks for Action Scheduler issues
     * Only runs in admin area
     * 
     * @since 1.1.0
     */
    public function diagnose_action_scheduler() {
        // Only run for administrators
        if (!current_user_can('manage_options')) {
            return;
        }

        // Only run once per admin page load
        static $diagnosed = false;
        if ($diagnosed) {
            return;
        }
        $diagnosed = true;

        $issues = array();
        $warnings = array();

        // Check if Action Scheduler is available
        if (!function_exists('as_schedule_single_action') && !class_exists('ActionScheduler')) {
            $issues[] = 'Action Scheduler is not loaded. Check if it\'s being blocked or if there\'s a conflict.';
            //agile_tix::agile_tix_log_event('DIAGNOSIS: Action Scheduler not loaded');
        } else {
            // Check if WP Cron is disabled
            if (defined('DISABLE_WP_CRON') && DISABLE_WP_CRON) {
                $warnings[] = 'WP Cron is disabled. Actions will not run automatically unless you have a real cron job configured.';
                //agile_tix::agile_tix_log_event('DIAGNOSIS: WP Cron is disabled');
            }

            // Check if queue runner cron event is scheduled (check with context parameter like Action Scheduler does)
            $cron_context = array('WP Cron');
            $next_run = wp_next_scheduled('action_scheduler_run_queue', $cron_context);
            if (!$next_run) {
                $issues[] = 'Action Scheduler queue runner cron event is not scheduled. Actions may not execute automatically.';
                //agile_tix::agile_tix_log_event('DIAGNOSIS: action_scheduler_run_queue cron event not scheduled');
            } else {
                $time_until_next = $next_run - time();
                if ($time_until_next > 300) { // More than 5 minutes
                    $warnings[] = sprintf('Next Action Scheduler run is scheduled in %d minutes. This seems unusually long.', round($time_until_next / 60));
                }
            }

            // Check if queue runner hook is registered
            if (class_exists('ActionScheduler')) {
                $runner = ActionScheduler::runner();
                if ($runner && !has_action('action_scheduler_run_queue', array($runner, 'run'))) {
                    $issues[] = 'Action Scheduler queue runner hook is not registered. Queue runner may not be initialized.';
                    //agile_tix::agile_tix_log_event('DIAGNOSIS: Queue runner hook not registered');
                }
                
                // Check if async request mechanism is available (important when WP Cron is disabled)
                if ($runner && method_exists($runner, 'hook_dispatch_async_request')) {
                    if (!has_action('shutdown', array($runner, 'maybe_dispatch_async_request'))) {
                        $warnings[] = 'Action Scheduler async request mechanism is not hooked. This is needed when WP Cron is disabled.';
                        //agile_tix::agile_tix_log_event('DIAGNOSIS: Async request mechanism not hooked');
                    } else {
                        //agile_tix::agile_tix_log_event('DIAGNOSIS: Async request mechanism is properly hooked');
                    }
                }
            }

            // Check for actions in ALL statuses to see what's really there
            if (function_exists('as_get_scheduled_actions')) {
                $statuses = array('pending', 'in-progress', 'complete', 'failed', 'canceled');
                $all_actions_by_status = array();
                
                foreach ($statuses as $status) {
                    $actions = as_get_scheduled_actions(array(
                        'status' => $status,
                        'per_page' => -1,
                        'group' => 'agile_events_processing'
                    ));
                    $all_actions_by_status[$status] = $actions;
                    //agile_tix::agile_tix_log_event(sprintf('DIAGNOSIS: Found %d actions with status "%s" in agile_events_processing group', count($actions), $status));
                }
                
                $pending_actions = $all_actions_by_status['pending'];
                $pending_count = count($pending_actions);
                
                if ($pending_count > 0) {
                    $warnings[] = sprintf('There are %d pending actions in the agile_events_processing group. They should execute automatically if WP Cron is working.', $pending_count);
                    
                    // Get detailed info about pending actions
                    foreach ($pending_actions as $action) {
                        $action_id = method_exists($action, 'get_id') ? $action->get_id() : 'N/A';
                        $hook = method_exists($action, 'get_hook') ? $action->get_hook() : 'N/A';
                        $scheduled_date = null;
                        $scheduled_timestamp = 0;
                        
                        if (method_exists($action, 'get_schedule')) {
                            $schedule = $action->get_schedule();
                            if ($schedule && method_exists($schedule, 'get_date')) {
                                $scheduled_date = $schedule->get_date();
                                $scheduled_timestamp = $scheduled_date ? $scheduled_date->getTimestamp() : 0;
                            }
                        }
                        
                        $now = current_time('timestamp', true);
                        $is_overdue = $scheduled_timestamp > 0 && $scheduled_timestamp < $now;
                        $args = method_exists($action, 'get_args') ? json_encode($action->get_args()) : 'N/A';
                        /*
                        agile_tix::agile_tix_log_event(sprintf(
                            'DIAGNOSIS: Pending action ID %s - Hook: %s, Scheduled: %s (%s), Overdue: %s, Args: %s',
                            $action_id,
                            $hook,
                            $scheduled_date ? $scheduled_date->format('Y-m-d H:i:s') : 'N/A',
                            $scheduled_timestamp ? date('Y-m-d H:i:s', $scheduled_timestamp) : 'N/A',
                            $is_overdue ? 'YES' : 'NO',
                            $args
                        ));
                        */
                        if ($is_overdue && $action_id !== 'N/A') {
                            $warnings[] = sprintf('Action ID %s (hook: %s) is overdue and should have executed already.', $action_id, $hook);
                        }
                    }
                    
                    // Check if queue runner can process actions
                    if (class_exists('ActionScheduler')) {
                        $runner = ActionScheduler::runner();
                        $store = ActionScheduler::store();
                        if ($runner && $store && method_exists($store, 'has_pending_actions_due')) {
                            $has_due = $store->has_pending_actions_due();
                            //agile_tix::agile_tix_log_event('DIAGNOSIS: Store reports has_pending_actions_due = ' . ($has_due ? 'true' : 'false'));
                            
                            if (!$has_due && $pending_count > 0) {
                                $warnings[] = 'Queue runner reports no actions due, but pending actions exist. This may indicate a scheduling issue.';
                                
                                // Try to manually trigger the queue runner
                                //agile_tix::agile_tix_log_event('DIAGNOSIS: Attempting to manually trigger queue runner');
                                try {
                                    $processed = $runner->run('Manual Diagnostic');
                                    //agile_tix::agile_tix_log_event(sprintf('DIAGNOSIS: Queue runner processed %d actions', $processed));
                                } catch (Exception $e) {
                                    //agile_tix::agile_tix_log_event('DIAGNOSIS ERROR: Failed to run queue runner - ' . $e->getMessage());
                                }
                            }
                        }
                    }
                } else {
                    // No pending actions found, but user says there should be one
                    //agile_tix::agile_tix_log_event('DIAGNOSIS: No pending actions found in agile_events_processing group, but user reported seeing one. Checking all statuses...');
                    
                    $total_found = 0;
                    foreach ($all_actions_by_status as $status => $actions) {
                        if (count($actions) > 0) {
                            $total_found += count($actions);
                            foreach ($actions as $action) {
                                $action_id = method_exists($action, 'get_id') ? $action->get_id() : 'N/A';
                                $hook = method_exists($action, 'get_hook') ? $action->get_hook() : 'N/A';
                                $scheduled_date = null;
                                
                                if (method_exists($action, 'get_schedule')) {
                                    $schedule = $action->get_schedule();
                                    if ($schedule && method_exists($schedule, 'get_date')) {
                                        $scheduled_date = $schedule->get_date();
                                    }
                                }
                                /*
                                agile_tix::agile_tix_log_event(sprintf(
                                    'DIAGNOSIS: Found action ID %s with status "%s" - Hook: %s, Scheduled: %s',
                                    $action_id,
                                    $status,
                                    $hook,
                                    $scheduled_date ? $scheduled_date->format('Y-m-d H:i:s') : 'N/A'
                                ));*/
                            }
                        }
                    }
                    
                    if ($total_found == 0) {
                        $warnings[] = 'No actions found in agile_events_processing group in any status. This suggests actions may not have been scheduled or were cleaned up.';
                    }
                }
            }
        }

        // Log issues and warnings
        // if (!empty($issues)) {
        //     foreach ($issues as $issue) {
        //         agile_tix::agile_tix_log_event('DIAGNOSIS ISSUE: ' . $issue);
        //     }
        // }
        // if (!empty($warnings)) {
        //     foreach ($warnings as $warning) {
        //         agile_tix::agile_tix_log_event('DIAGNOSIS WARNING: ' . $warning);
        //     }
        // }

        // Store diagnostics for potential admin notice (optional)
        if (!empty($issues) || !empty($warnings)) {
            update_option('agile_tix_as_diagnostics', array(
                'issues' => $issues,
                'warnings' => $warnings,
                'timestamp' => time()
            ));
        } else {
            delete_option('agile_tix_as_diagnostics');
        }
    }

}
