<?php

namespace MovieEngine\Admin;

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

/**
 * Cron Management Settings
 * Provides admin interface to manage WordPress cron events and Action Scheduler
 */
class CronSettings {

    public static function render() {
        if (isset($_POST['movie_engine_cron_action']) && check_admin_referer('movie_engine_cron_nonce')) {
            self::handle_cron_action();
        }

        $stats = self::get_cron_stats();
        $action_scheduler_stats = self::get_action_scheduler_stats();

        settings_errors('movie_engine_cron');
?>
        <div class="movie-engine-settings-wrapper">
            <div class="movie-engine-settings-header">
                <div class="movie-engine-header-content">
                    <div class="movie-engine-header-left">
                        <span class="movie-engine-logo">
                            <span class="dashicons dashicons-backup" style="font-size:28px;width:28px;height:28px;color:var(--movie-engine-admin-primary-color);margin-right:10px;"></span>
                            <h1><?php esc_html_e('Cron Management', 'cine-movie-engine'); ?></h1>
                        </span>
                    </div>
                    <div class="movie-engine-header-right">
                        <span class="me-cron-live-badge"><span class="me-cron-dot"></span><?php esc_html_e('Live Stats', 'cine-movie-engine'); ?></span>
                    </div>
                </div>
            </div>

            <?php /* ===== STAT CARDS ===== */ ?>
            <div class="movie-engine-dashboard-grid me-cron-stats-grid movie-engine-cron-management">

                <div class="me-cron-stat-card me-cron-stat-blue">
                    <div class="me-cron-stat-icon">
                        <span class="dashicons dashicons-clock"></span>
                    </div>
                    <div class="me-cron-stat-body">
                        <span class="me-cron-stat-value"><?php echo esc_html(number_format_i18n($stats['total_events'])); ?></span>
                        <span class="me-cron-stat-label"><?php esc_html_e('Total Cron Events', 'cine-movie-engine'); ?></span>
                    </div>
                </div>

                <div class="me-cron-stat-card me-cron-stat-orange">
                    <div class="me-cron-stat-icon">
                        <span class="dashicons dashicons-update"></span>
                    </div>
                    <div class="me-cron-stat-body">
                        <span class="me-cron-stat-value"><?php echo esc_html(number_format_i18n($stats['action_scheduler_events'])); ?></span>
                        <span class="me-cron-stat-label"><?php esc_html_e('Action Scheduler Events', 'cine-movie-engine'); ?></span>
                    </div>
                </div>

                <div class="me-cron-stat-card <?php echo ($action_scheduler_stats['pending'] > 100) ? 'me-cron-stat-red' : 'me-cron-stat-amber'; ?>">
                    <div class="me-cron-stat-icon">
                        <span class="dashicons dashicons-hourglass"></span>
                    </div>
                    <div class="me-cron-stat-body">
                        <span class="me-cron-stat-value"><?php echo esc_html(number_format_i18n($action_scheduler_stats['pending'])); ?></span>
                        <span class="me-cron-stat-label"><?php esc_html_e('Pending Actions', 'cine-movie-engine'); ?></span>
                    </div>
                </div>

                <div class="me-cron-stat-card me-cron-stat-green">
                    <div class="me-cron-stat-icon">
                        <span class="dashicons dashicons-yes-alt"></span>
                    </div>
                    <div class="me-cron-stat-body">
                        <span class="me-cron-stat-value"><?php echo esc_html(number_format_i18n($action_scheduler_stats['completed'])); ?></span>
                        <span class="me-cron-stat-label"><?php esc_html_e('Completed Actions', 'cine-movie-engine'); ?></span>
                    </div>
                </div>

            </div>

            <?php if ($stats['action_scheduler_events'] > 50 || $action_scheduler_stats['pending'] > 1000): ?>
                <div class="me-cron-alert">
                    <span class="dashicons dashicons-warning"></span>
                    <p><?php esc_html_e('High number of cron events detected. This may impact site performance. Consider running a cleanup below.', 'cine-movie-engine'); ?></p>
                </div>
            <?php endif; ?>

            <div class="movie-engine-cron-actions-grid movie-engine-cron-management">

                <?php /* ===== LEFT: ACTION CARDS ===== */ ?>
                <div class="me-cron-actions-col">

                    <div class="movie-engine-card me-cron-action-card">
                        <div class="movie-engine-card-header">
                            <h3>
                                <span class="dashicons dashicons-trash" style="color:#ef4444;"></span>
                                <?php esc_html_e('Cleanup Actions', 'cine-movie-engine'); ?>
                            </h3>
                            <span class="me-cron-section-badge me-badge-danger"><?php esc_html_e('Destructive', 'cine-movie-engine'); ?></span>
                        </div>
                        <div class="movie-engine-card-body">
                            <p class="me-cron-desc"><?php esc_html_e('Remove old or unnecessary cron events to free memory and improve performance.', 'cine-movie-engine'); ?></p>
                            <form method="post" action="<?php echo esc_url(admin_url('admin.php?page=movie-engine-cron')); ?>">
                                <?php wp_nonce_field('movie_engine_cron_nonce'); ?>
                                <div class="me-cron-btn-group">
                                    <button type="submit" name="movie_engine_cron_action" value="cleanup_orphaned" class="me-cron-action-btn me-cron-btn-danger">
                                        <span class="dashicons dashicons-trash"></span>
                                        <?php esc_html_e('Clean Orphaned Events', 'cine-movie-engine'); ?>
                                    </button>
                                    <button type="submit" name="movie_engine_cron_action" value="cleanup_action_scheduler" class="me-cron-action-btn me-cron-btn-warning">
                                        <span class="dashicons dashicons-update"></span>
                                        <?php esc_html_e('Clean Action Scheduler', 'cine-movie-engine'); ?>
                                    </button>
                                    <button type="submit" name="movie_engine_cron_action" value="limit_events" class="me-cron-action-btn me-cron-btn-neutral">
                                        <span class="dashicons dashicons-filter"></span>
                                        <?php esc_html_e('Limit Events (1000 max)', 'cine-movie-engine'); ?>
                                    </button>
                                </div>
                            </form>
                        </div>
                    </div>

                    <div class="movie-engine-card me-cron-action-card">
                        <div class="movie-engine-card-header">
                            <h3>
                                <span class="dashicons dashicons-database" style="color:#8b5cf6;"></span>
                                <?php esc_html_e('Action Scheduler Cleanup', 'cine-movie-engine'); ?>
                            </h3>
                            <span class="me-cron-section-badge me-badge-purple"><?php esc_html_e('Database', 'cine-movie-engine'); ?></span>
                        </div>
                        <div class="movie-engine-card-body">
                            <p class="me-cron-desc"><?php esc_html_e('Remove completed and failed actions from Action Scheduler database tables.', 'cine-movie-engine'); ?></p>
                            <form method="post" action="<?php echo esc_url(admin_url('admin.php?page=movie-engine-cron')); ?>">
                                <?php wp_nonce_field('movie_engine_cron_nonce'); ?>
                                <div class="me-cron-btn-group">
                                    <button type="submit" name="movie_engine_cron_action" value="cleanup_completed_actions" class="me-cron-action-btn me-cron-btn-success">
                                        <span class="dashicons dashicons-yes"></span>
                                        <?php esc_html_e('Delete Completed Actions', 'cine-movie-engine'); ?>
                                    </button>
                                    <button type="submit" name="movie_engine_cron_action" value="cleanup_failed_actions" class="me-cron-action-btn me-cron-btn-danger">
                                        <span class="dashicons dashicons-no"></span>
                                        <?php esc_html_e('Delete Failed Actions', 'cine-movie-engine'); ?>
                                    </button>
                                    <button type="submit" name="movie_engine_cron_action" value="cleanup_old_actions" class="me-cron-action-btn me-cron-btn-neutral">
                                        <span class="dashicons dashicons-clock"></span>
                                        <?php esc_html_e('Delete Actions Older Than 30 Days', 'cine-movie-engine'); ?>
                                    </button>
                                </div>
                            </form>
                        </div>
                    </div>

                </div>

                <?php /* ===== RIGHT: SETTINGS FORM ===== */ ?>
                <div class="me-cron-settings-col">
                    <div class="movie-engine-card me-cron-settings-card">
                        <div class="movie-engine-card-header">
                            <h3>
                                <span class="dashicons dashicons-admin-settings" style="color:#2563eb;"></span>
                                <?php esc_html_e('Cron Settings', 'cine-movie-engine'); ?>
                            </h3>
                        </div>
                        <div class="movie-engine-card-body">
                            <div class="me-cron-info-box">
                                <div class="me-cron-info-icon"><span class="dashicons dashicons-info-outline"></span></div>
                                <div class="me-cron-info-text">
                                    <strong><?php esc_html_e('What is WP Cron?', 'cine-movie-engine'); ?></strong>
                                    <p><?php esc_html_e('WordPress Cron schedules background tasks automatically. Over time these can accumulate and cause performance issues. These settings help automate cleanup.', 'cine-movie-engine'); ?></p>
                                </div>
                            </div>

                            <form method="post" action="options.php" class="me-cron-settings-form">
                                <?php
                                settings_fields('movie_engine_cron');
                                $options = get_option('movie_engine_cron_settings', [
                                    'auto_cleanup_enabled' => 0,
                                    'cleanup_frequency'    => 'daily',
                                    'max_cron_events'      => 1000,
                                    'cleanup_old_actions_days' => 30
                                ]);
                                ?>

                                <div class="me-cron-setting-row">
                                    <div class="me-cron-setting-label">
                                        <span class="dashicons dashicons-controls-repeat"></span>
                                        <div>
                                            <strong><?php esc_html_e('Automatic Cleanup', 'cine-movie-engine'); ?></strong>
                                            <span><?php esc_html_e('Run cleanup automatically on schedule', 'cine-movie-engine'); ?></span>
                                        </div>
                                    </div>
                                    <div class="me-cron-setting-control">
                                        <label class="me-cron-toggle">
                                            <input type="hidden" name="movie_engine_cron_settings[auto_cleanup_enabled]" value="0">
                                            <input type="checkbox"
                                                name="movie_engine_cron_settings[auto_cleanup_enabled]"
                                                value="1"
                                                <?php checked($options['auto_cleanup_enabled'] ?? 0, 1); ?>>
                                            <span class="me-cron-toggle-slider"></span>
                                        </label>
                                    </div>
                                </div>

                                <div class="me-cron-setting-row">
                                    <div class="me-cron-setting-label">
                                        <span class="dashicons dashicons-calendar-alt"></span>
                                        <div>
                                            <strong><?php esc_html_e('Cleanup Frequency', 'cine-movie-engine'); ?></strong>
                                            <span><?php esc_html_e('How often to run automatic cleanup', 'cine-movie-engine'); ?></span>
                                        </div>
                                    </div>
                                    <div class="me-cron-setting-control">
                                        <select name="movie_engine_cron_settings[cleanup_frequency]" class="me-cron-select">
                                            <option value="hourly" <?php selected($options['cleanup_frequency'] ?? 'daily', 'hourly'); ?>><?php esc_html_e('Hourly', 'cine-movie-engine'); ?></option>
                                            <option value="twicedaily" <?php selected($options['cleanup_frequency'] ?? 'daily', 'twicedaily'); ?>><?php esc_html_e('Twice Daily', 'cine-movie-engine'); ?></option>
                                            <option value="daily" <?php selected($options['cleanup_frequency'] ?? 'daily', 'daily'); ?>><?php esc_html_e('Daily', 'cine-movie-engine'); ?></option>
                                            <option value="weekly" <?php selected($options['cleanup_frequency'] ?? 'daily', 'weekly'); ?>><?php esc_html_e('Weekly', 'cine-movie-engine'); ?></option>
                                        </select>
                                    </div>
                                </div>

                                <div class="me-cron-setting-row">
                                    <div class="me-cron-setting-label">
                                        <span class="dashicons dashicons-filter"></span>
                                        <div>
                                            <strong><?php esc_html_e('Maximum Cron Events', 'cine-movie-engine'); ?></strong>
                                            <span><?php esc_html_e('Excess events removed during cleanup', 'cine-movie-engine'); ?></span>
                                        </div>
                                    </div>
                                    <div class="me-cron-setting-control">
                                        <input type="number"
                                            name="movie_engine_cron_settings[max_cron_events]"
                                            value="<?php echo esc_attr($options['max_cron_events'] ?? 1000); ?>"
                                            min="100" max="5000"
                                            class="me-cron-input">
                                    </div>
                                </div>

                                <div class="me-cron-setting-row">
                                    <div class="me-cron-setting-label">
                                        <span class="dashicons dashicons-clock"></span>
                                        <div>
                                            <strong><?php esc_html_e('Delete Actions Older Than (Days)', 'cine-movie-engine'); ?></strong>
                                            <span><?php esc_html_e('Old completed/failed/cancelled actions', 'cine-movie-engine'); ?></span>
                                        </div>
                                    </div>
                                    <div class="me-cron-setting-control">
                                        <input type="number"
                                            name="movie_engine_cron_settings[cleanup_old_actions_days]"
                                            value="<?php echo esc_attr($options['cleanup_old_actions_days'] ?? 30); ?>"
                                            min="1" max="365"
                                            class="me-cron-input">
                                    </div>
                                </div>

                                <div class="me-cron-form-footer">
                                    <?php submit_button(__('Save Settings', 'cine-movie-engine'), 'primary me-btn-primary', 'submit', false); ?>
                                    <button type="button" class="movie-engine-reset-section-btn me-reset-section-btn" data-tab="movie-engine-cron">
                                        <?php esc_html_e('Reset to Defaults', 'cine-movie-engine'); ?>
                                    </button>
                                </div>
                            </form>
                        </div>
                    </div>
                </div>

            </div>
        </div>
<?php
    }

    private static function get_cron_stats() {
        $crons = _get_cron_array();
        $total_events = 0;
        $action_scheduler_events = 0;

        if (!empty($crons)) {
            foreach ($crons as $timestamp => $cron) {
                foreach ($cron as $hook => $dings) {
                    $count = count($dings);
                    $total_events += $count;
                    if (strpos($hook, 'action_scheduler') === 0) {
                        $action_scheduler_events += $count;
                    }
                }
            }
        }

        return [
            'total_events' => $total_events,
            'action_scheduler_events' => $action_scheduler_events
        ];
    }

    private static function get_action_scheduler_stats() {
        global $wpdb;

        $cache_key = 'movie_engine_action_scheduler_stats';
        $stats = wp_cache_get($cache_key, 'movie_engine');

        if (false === $stats) {
            $stats = [
                'pending'   => 0,
                'completed' => 0,
                'failed'    => 0,
                'total'     => 0
            ];

            // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery
            if ($wpdb->get_var($wpdb->prepare("SHOW TABLES LIKE %s", "{$wpdb->prefix}actionscheduler_actions")) === ("{$wpdb->prefix}actionscheduler_actions")) {
                // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery
                $stats['pending'] = (int) $wpdb->get_var($wpdb->prepare("SELECT COUNT(*) FROM {$wpdb->prefix}actionscheduler_actions WHERE status = %s", 'pending'));
                // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery
                $stats['completed'] = (int) $wpdb->get_var($wpdb->prepare("SELECT COUNT(*) FROM {$wpdb->prefix}actionscheduler_actions WHERE status = %s", 'complete'));
                // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery
                $stats['failed'] = (int) $wpdb->get_var($wpdb->prepare("SELECT COUNT(*) FROM {$wpdb->prefix}actionscheduler_actions WHERE status = %s", 'failed'));
                // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery
                $stats['total'] = (int) $wpdb->get_var($wpdb->prepare("SELECT COUNT(*) FROM {$wpdb->prefix}actionscheduler_actions WHERE 1=%d", 1));
            }
            wp_cache_set($cache_key, $stats, 'movie_engine', 3600);
        }

        return $stats;
    }

    private static function handle_cron_action() {
        // phpcs:ignore WordPress.Security.NonceVerification.Missing
        $action = isset($_POST['movie_engine_cron_action']) ? sanitize_text_field(wp_unslash($_POST['movie_engine_cron_action'])) : '';
        $message = '';
        $type = 'success';

        switch ($action) {
            case 'cleanup_orphaned':
                \MovieEngine\Core\CronCleanup::cleanup_orphaned_crons();
                $message = esc_html__('Orphaned cron events have been cleaned up.', 'cine-movie-engine');
                break;

            case 'cleanup_action_scheduler':
                self::cleanup_action_scheduler_cron();
                $message = esc_html__('Action Scheduler cron events have been cleaned up.', 'cine-movie-engine');
                break;

            case 'limit_events':
                \MovieEngine\Core\CronCleanup::limit_cron_events(1000);
                $message = esc_html__('Cron events have been limited to 1000.', 'cine-movie-engine');
                break;

            case 'cleanup_completed_actions':
                $deleted = self::delete_action_scheduler_actions('complete');
                $message = sprintf(
                    /* translators: %d: number of completed actions */
                    esc_html__('%d completed actions have been deleted.', 'cine-movie-engine'),
                    $deleted
                );
                break;

            case 'cleanup_failed_actions':
                $deleted = self::delete_action_scheduler_actions('failed');
                $message = sprintf(
                    /* translators: %d: number of failed actions */
                    esc_html__('%d failed actions have been deleted.', 'cine-movie-engine'),
                    $deleted
                );
                break;

            case 'cleanup_old_actions':
                $options = get_option('movie_engine_cron_settings', []);
                $days = $options['cleanup_old_actions_days'] ?? 30;
                $deleted = self::delete_old_action_scheduler_actions($days);
                $message = sprintf(
                    /* translators: 1: number of actions, 2: number of days */
                    esc_html__('%1$d actions older than %2$d days have been deleted.', 'cine-movie-engine'),
                    $deleted,
                    $days
                );
                break;
        }

        if ($message) {
            add_settings_error(
                'movie_engine_cron',
                'cron_action',
                $message,
                $type
            );
        }
    }

    private static function cleanup_action_scheduler_cron() {
        $crons = _get_cron_array();
        if (empty($crons)) {
            return;
        }

        $cleaned = false;
        foreach ($crons as $timestamp => $cron) {
            foreach ($cron as $hook => $dings) {
                if (strpos($hook, 'action_scheduler') === 0) {
                    foreach ($dings as $sig => $data) {
                        wp_unschedule_event($timestamp, $hook, $data['args']);
                        $cleaned = true;
                    }
                }
            }
        }

        if ($cleaned) {
            _set_cron_array($crons);
        }
    }

    private static function delete_action_scheduler_actions($status) {
        global $wpdb;

        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
        if ($wpdb->get_var($wpdb->prepare("SHOW TABLES LIKE %s", "{$wpdb->prefix}actionscheduler_actions")) !== "{$wpdb->prefix}actionscheduler_actions") {
            return 0;
        }

        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
        $deleted = $wpdb->query($wpdb->prepare(
            "DELETE FROM {$wpdb->prefix}actionscheduler_actions WHERE status = %s",
            $status
        ));

        if ($deleted) {
            wp_cache_delete('movie_engine_action_scheduler_stats', 'movie_engine');
        }

        return $deleted ? $deleted : 0;
    }

    public static function delete_old_action_scheduler_actions($days = 30) {
        global $wpdb;

        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
        if ($wpdb->get_var($wpdb->prepare("SHOW TABLES LIKE %s", "{$wpdb->prefix}actionscheduler_actions")) !== "{$wpdb->prefix}actionscheduler_actions") {
            return 0;
        }

        $cutoff_date = gmdate('Y-m-d H:i:s', strtotime("-{$days} days"));

        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
        $deleted = $wpdb->query($wpdb->prepare(
            "DELETE FROM {$wpdb->prefix}actionscheduler_actions WHERE scheduled_date_gmt < %s AND status IN ('complete', 'failed', 'canceled')",
            $cutoff_date
        ));

        if ($deleted) {
            wp_cache_delete('movie_engine_action_scheduler_stats', 'movie_engine');
        }

        return $deleted ? $deleted : 0;
    }
}
