<?php
if (!defined('ABSPATH')) exit;

// Obtener el estado del cron job
function easy_gpt_get_cron_status() {
    $timestamp = wp_next_scheduled('easy_gpt_process_pending_generations');
    return $timestamp ? 'Active' : 'Inactive';
}

// Obtener el estado del cron de moderación
function easy_gpt_get_moderation_cron_status() {
    $timestamp = wp_next_scheduled('easy_gpt_moderation_cron');
    return $timestamp ? 'Active' : 'Inactive';
}

// Obtener la próxima ejecución del cron job
function easy_gpt_get_next_execution() {
    $timestamp = wp_next_scheduled('easy_gpt_process_pending_generations');
    return $timestamp ? get_date_from_gmt(gmdate('Y-m-d H:i:s', $timestamp), 'Y-m-d H:i:s') : 'N/A';
}

// Obtener la próxima ejecución del cron de moderación
function easy_gpt_get_next_moderation_execution() {
    $timestamp = wp_next_scheduled('easy_gpt_moderation_cron');
    return $timestamp ? get_date_from_gmt(gmdate('Y-m-d H:i:s', $timestamp), 'Y-m-d H:i:s') : 'N/A';
}

function easy_gpt_get_auto_reply_cron_status() {
    $timestamp = wp_next_scheduled('easy_gpt_auto_reply_cron');
    return $timestamp ? 'Active' : 'Inactive';
}

function easy_gpt_get_next_auto_reply_execution() {
    $timestamp = wp_next_scheduled('easy_gpt_auto_reply_cron');
    return $timestamp ? get_date_from_gmt(gmdate('Y-m-d H:i:s', $timestamp), 'Y-m-d H:i:s') : 'N/A';
}

function easy_gpt_get_cron_autorestart_map() {
    return [
        'easy_gpt_process_pending_generations' => [
            'option'   => 'easy_gpt_autorestart_batch_cron',
            'interval' => 'easy_gpt_custom_interval',
        ],
        'easy_gpt_moderation_cron' => [
            'option'   => 'easy_gpt_autorestart_moderation_cron',
            'interval' => 'easy_gpt_moderation_interval',
        ],
        'easy_gpt_auto_reply_cron' => [
            'option'   => 'easy_gpt_autorestart_auto_reply_cron',
            'interval' => 'easy_gpt_auto_reply_interval',
        ],
        'easy_gpt_run_article_refresh' => [
            'option'   => 'easy_gpt_autorestart_refresh_cron',
            'callback' => 'easy_gpt_schedule_refresher_cron',
        ],
        'easy_gpt_run_article_translation' => [
            'option'   => 'easy_gpt_autorestart_translation_cron',
            'interval' => function () {
                $minutes = easy_gpt_get_translation_cron_frequency_minutes();
                return $minutes ? 'easy_gpt_translation_' . $minutes : false;
            },
        ],
    ];
}

function easy_gpt_save_cron_autorestart_settings() {
    if (!isset($_POST['easy_gpt_save_cron_autorestart'])) {
        return;
    }

    $map = easy_gpt_get_cron_autorestart_map();

    foreach ($map as $hook => $data) {
        update_option(
            $data['option'],
            isset($_POST[$data['option']]) ? '1' : '0'
        );
    }

    wp_redirect($_SERVER['REQUEST_URI']);
    exit;
}
add_action('admin_init', 'easy_gpt_save_cron_autorestart_settings');

function easy_gpt_ensure_selected_crons_are_scheduled() {
    $map = easy_gpt_get_cron_autorestart_map();

    foreach ($map as $hook => $data) {
        if (get_option($data['option'], '0') !== '1') {
            continue;
        }

        if (wp_next_scheduled($hook)) {
            continue;
        }

        add_filter('cron_schedules', 'easy_gpt_custom_cron_schedules');

        if (!empty($data['callback']) && function_exists($data['callback'])) {
            call_user_func($data['callback']);
            error_log("[EasyGPT] Cron restored automatically via callback: {$hook}");
            continue;
        }

        $interval = $data['interval'];

        if (is_callable($interval)) {
            $interval = call_user_func($interval);
        }

        if (!$interval) {
            error_log("[EasyGPT] Could not restore cron {$hook}: invalid interval.");
            continue;
        }

        wp_schedule_event(time() + 60, $interval, $hook);
        error_log("[EasyGPT] Cron restored automatically: {$hook}");
    }
}
add_action('init', 'easy_gpt_ensure_selected_crons_are_scheduled');

// Activar/desactivar el cron y guardar el intervalo personalizado
function easy_gpt_toggle_cron() {
    if (
        isset($_POST['easy_gpt_toggle_cron']) ||
        isset($_POST['easy_gpt_toggle_moderation_cron']) ||
        isset($_POST['easy_gpt_toggle_auto_reply_cron']) ||
        isset($_POST['easy_gpt_toggle_refresh_cron']) ||
        isset($_POST['easy_gpt_toggle_translation_cron'])
    ) {
        // Cron para generación de artículos
        if (isset($_POST['easy_gpt_toggle_cron'])) {
            $interval = isset($_POST['easy_gpt_cron_interval']) ? intval($_POST['easy_gpt_cron_interval']) : 5;
            if ($interval < 1) $interval = 5;

            update_option('easy_gpt_cron_interval', $interval);
            add_filter('cron_schedules', 'easy_gpt_custom_cron_schedules');

            if (easy_gpt_get_cron_status() === 'Active') {
                easy_gpt_unschedule_cron_jobs();
                update_option('easy_gpt_autorestart_batch_cron', '0');
            } else {
                wp_clear_scheduled_hook('easy_gpt_process_pending_generations');
                wp_schedule_event(time(), 'easy_gpt_custom_interval', 'easy_gpt_process_pending_generations');
            }
        }

        // Cron para moderación de comentarios
        if (isset($_POST['easy_gpt_toggle_moderation_cron'])) {
            $interval = isset($_POST['easy_gpt_moderation_cron_interval']) ? intval($_POST['easy_gpt_moderation_cron_interval']) : 60;
            if ($interval < 1) $interval = 60;

            update_option('easy_gpt_moderation_cron_interval', $interval);
            add_filter('cron_schedules', 'easy_gpt_custom_cron_schedules');

            if (easy_gpt_get_moderation_cron_status() === 'Active') {
                wp_clear_scheduled_hook('easy_gpt_moderation_cron');
                update_option('easy_gpt_autorestart_moderation_cron', '0');
            } else {
                wp_schedule_event(time(), 'easy_gpt_moderation_interval', 'easy_gpt_moderation_cron');
            }
        }

        // Cron para respuestas automáticas
        if (isset($_POST['easy_gpt_toggle_auto_reply_cron'])) {
            $interval = isset($_POST['easy_gpt_auto_reply_cron_interval']) ? intval($_POST['easy_gpt_auto_reply_cron_interval']) : 10;
            if ($interval < 1) $interval = 10;

            update_option('easy_gpt_auto_reply_cron_interval', $interval);
            add_filter('cron_schedules', 'easy_gpt_custom_cron_schedules');

            if (easy_gpt_get_auto_reply_cron_status() === 'Active') {
                wp_clear_scheduled_hook('easy_gpt_auto_reply_cron');
                update_option('easy_gpt_autorestart_auto_reply_cron', '0');
            } else {
                wp_schedule_event(time(), 'easy_gpt_auto_reply_interval', 'easy_gpt_auto_reply_cron');
            }
        }

        // Cron para traducción
        if (isset($_POST['easy_gpt_toggle_translation_cron'])) {
            error_log('[EasyGPT] 🔧 Toggle Translation Cron detected via POST');
            $hook = 'easy_gpt_run_article_translation';

            if (wp_next_scheduled($hook)) {
                wp_clear_scheduled_hook($hook);
                update_option('easy_gpt_autorestart_translation_cron', '0');
                error_log('[EasyGPT] 🔴 Translation cron cleared (manual toggle)');
            } else {
                add_filter('cron_schedules', 'easy_gpt_custom_cron_schedules');

                $minutes = easy_gpt_get_translation_cron_frequency_minutes();
                if ($minutes) {
                    $key = 'easy_gpt_translation_' . $minutes;
                    wp_schedule_event(time(), $key, $hook);
                    error_log("[EasyGPT] 🟢 Translation cron scheduled every {$minutes} minutes (manual toggle)");
                } else {
                    error_log("[EasyGPT] ⚠️ Translation cron not scheduled: invalid or missing frequency.");
                }
            }
        }

        // Cron para refresh
        if (isset($_POST['easy_gpt_toggle_refresh_cron'])) {
            $hook = 'easy_gpt_run_article_refresh';

            if (wp_next_scheduled($hook)) {
                wp_clear_scheduled_hook($hook);
                update_option('easy_gpt_autorestart_refresh_cron', '0');
            } else {
                easy_gpt_schedule_refresher_cron();
            }
        }

        wp_redirect($_SERVER['REQUEST_URI']);
        exit;
    }
}
add_action('admin_init', 'easy_gpt_toggle_cron');

// Definir intervalo personalizado basado en la opción guardada
function easy_gpt_custom_cron_schedules($schedules) {
    // === Batch generation ===
    $interval = intval(get_option('easy_gpt_cron_interval', 5)) * 60;
    $schedules['easy_gpt_custom_interval'] = [
        'interval' => $interval,
        'display'  => __('Custom Interval', 'easy-gpt-for-wp')
    ];

    // === Comment moderation ===
    $moderation_interval = intval(get_option('easy_gpt_moderation_cron_interval', 60)) * 60;
    $schedules['easy_gpt_moderation_interval'] = [
        'interval' => $moderation_interval,
        'display'  => __('Moderation Interval', 'easy-gpt-for-wp')
    ];

    // === Auto replies ===
    $auto_reply_interval = intval(get_option('easy_gpt_auto_reply_cron_interval', 60)) * 60;
    $schedules['easy_gpt_auto_reply_interval'] = [
        'interval' => $auto_reply_interval,
        'display'  => __('Auto Reply Interval', 'easy-gpt-for-wp')
    ];

    // === Dynamic translation interval ===
    if (function_exists('easy_gpt_get_translation_cron_frequency_minutes')) {
        $minutes = easy_gpt_get_translation_cron_frequency_minutes();
        if ($minutes && $minutes > 0) {
            $key = 'easy_gpt_translation_' . $minutes;
            $schedules[$key] = [
                'interval' => $minutes * 60,
                'display'  => "Translation every {$minutes} minutes"
            ];
        }
    }

    // === Manual/debug testing every minute ===
    $schedules['every_minute'] = [
        'interval' => 60,
        'display'  => __('Every Minute', 'easy-gpt-for-wp')
    ];

    return $schedules;
}
add_filter('cron_schedules', 'easy_gpt_custom_cron_schedules');

function easy_gpt_get_translation_cron_frequency_minutes($options = null) {
    if (!$options) {
        $options = get_option('easy_gpt_options');
    }

    $interval = $options['easy_gpt_translation_interval'] ?? 'weekly';
    $posts_per_interval = intval($options['easy_gpt_translation_limit_per_interval'] ?? 1);
    if ($posts_per_interval < 1) return null;

    $interval_days = [
        'daily' => 1,
        'weekly' => 7,
        'monthly' => 30,
    ];

    $days = isset($interval_days[$interval]) ? $interval_days[$interval] : 7;

    $total_minutes = $days * 24 * 60;
    $minutes_between = floor($total_minutes / $posts_per_interval);

    return max(5, $minutes_between);
}

// Mostrar página de estado del cron
function easy_gpt_status_page() {
    $status = easy_gpt_get_cron_status();
    $next_execution = easy_gpt_get_next_execution();

    $moderation_status = easy_gpt_get_moderation_cron_status();
    $next_moderation_execution = easy_gpt_get_next_moderation_execution();

    $auto_reply_status = easy_gpt_get_auto_reply_cron_status();
    $next_auto_reply_execution = easy_gpt_get_next_auto_reply_execution();

    $current_interval = get_option('easy_gpt_cron_interval', 5);
    $current_moderation_interval = get_option('easy_gpt_moderation_cron_interval', 60);
    $current_auto_reply_interval = get_option('easy_gpt_auto_reply_cron_interval', 60);

    $refresh_status = wp_next_scheduled('easy_gpt_run_article_refresh') ? 'Active' : 'Inactive';
    $next_refresh_execution = wp_next_scheduled('easy_gpt_run_article_refresh');

    $translation_status = wp_next_scheduled('easy_gpt_run_article_translation') ? 'Active' : 'Inactive';
    $next_translation_execution = wp_next_scheduled('easy_gpt_run_article_translation');

    $autorestart_options = [
        'batch'       => get_option('easy_gpt_autorestart_batch_cron', '0'),
        'moderation'  => get_option('easy_gpt_autorestart_moderation_cron', '0'),
        'auto_reply'  => get_option('easy_gpt_autorestart_auto_reply_cron', '0'),
        'refresh'     => get_option('easy_gpt_autorestart_refresh_cron', '0'),
        'translation' => get_option('easy_gpt_autorestart_translation_cron', '0'),
    ];
    ?>

    <div class="wrap easy-gpt-status">
        <h2>Easy GPT - Cron Jobs Status</h2>

        <div class="easy-gpt-cron-box">
            <h3>Batch Generation Cron</h3>
            <p><strong>Status:</strong> <span class="easy-gpt-status-<?php echo strtolower($status); ?>"> <?php echo esc_html($status); ?></span></p>
            <p><strong>Next Execution:</strong> <?php echo esc_html($next_execution); ?></p>

            <form method="post" class="easy-gpt-form">
                <input type="hidden" name="easy_gpt_toggle_cron" value="1">
                <label for="easy_gpt_cron_interval">Execution Interval (minutes, recommended: 5):</label>
                <input type="number" name="easy_gpt_cron_interval" id="easy_gpt_cron_interval" value="<?php echo esc_attr($current_interval); ?>" min="1">
                <br>
                <button type="submit" class="easy-gpt-toggle-btn" data-status="<?php echo strtolower($status); ?>">
                    <?php echo $status === 'Active' ? 'Stop Cron Job' : 'Start Cron Job'; ?>
                </button>
            </form>

            <form method="post" class="easy-gpt-autorestart-form">
                <input type="hidden" name="easy_gpt_save_cron_autorestart" value="1">
                <label>
                    <input type="checkbox" name="easy_gpt_autorestart_batch_cron" value="1" <?php checked($autorestart_options['batch'], '1'); ?>>
                    Auto-restart this cron if it stops unexpectedly
                </label>
                <br>
                <button type="submit" class="easy-gpt-save-btn">Save auto-restart setting</button>
            </form>
        </div>

        <div class="easy-gpt-cron-box">
            <h3>Comment Moderation Cron</h3>
            <p><strong>Status:</strong> <span class="easy-gpt-status-<?php echo strtolower($moderation_status); ?>"> <?php echo esc_html($moderation_status); ?></span></p>
            <p><strong>Next Execution:</strong> <?php echo esc_html($next_moderation_execution); ?></p>

            <form method="post" class="easy-gpt-form">
                <input type="hidden" name="easy_gpt_toggle_moderation_cron" value="1">
                <label for="easy_gpt_moderation_cron_interval">Execution Interval (minutes, default: 60):</label>
                <input type="number" name="easy_gpt_moderation_cron_interval" id="easy_gpt_moderation_cron_interval" value="<?php echo esc_attr($current_moderation_interval); ?>" min="1">
                <br>
                <button type="submit" class="easy-gpt-toggle-btn" data-status="<?php echo strtolower($moderation_status); ?>">
                    <?php echo $moderation_status === 'Active' ? 'Stop Cron Job' : 'Start Cron Job'; ?>
                </button>
            </form>

            <form method="post" class="easy-gpt-autorestart-form">
                <input type="hidden" name="easy_gpt_save_cron_autorestart" value="1">
                <label>
                    <input type="checkbox" name="easy_gpt_autorestart_moderation_cron" value="1" <?php checked($autorestart_options['moderation'], '1'); ?>>
                    Auto-restart this cron if it stops unexpectedly
                </label>
                <br>
                <button type="submit" class="easy-gpt-save-btn">Save auto-restart setting</button>
            </form>
        </div>

        <div class="easy-gpt-cron-box">
            <h3>Auto Reply Cron</h3>
            <p><strong>Status:</strong> <span class="easy-gpt-status-<?php echo strtolower($auto_reply_status); ?>"> <?php echo esc_html($auto_reply_status); ?></span></p>
            <p><strong>Next Execution:</strong> <?php echo esc_html($next_auto_reply_execution); ?></p>

            <form method="post" class="easy-gpt-form">
                <input type="hidden" name="easy_gpt_toggle_auto_reply_cron" value="1">
                <label for="easy_gpt_auto_reply_cron_interval">Execution Interval (minutes, default: 60):</label>
                <input type="number" name="easy_gpt_auto_reply_cron_interval" id="easy_gpt_auto_reply_cron_interval" value="<?php echo esc_attr($current_auto_reply_interval); ?>" min="1">
                <br>
                <button type="submit" class="easy-gpt-toggle-btn" data-status="<?php echo strtolower($auto_reply_status); ?>">
                    <?php echo $auto_reply_status === 'Active' ? 'Stop Cron Job' : 'Start Cron Job'; ?>
                </button>
            </form>

            <form method="post" class="easy-gpt-autorestart-form">
                <input type="hidden" name="easy_gpt_save_cron_autorestart" value="1">
                <label>
                    <input type="checkbox" name="easy_gpt_autorestart_auto_reply_cron" value="1" <?php checked($autorestart_options['auto_reply'], '1'); ?>>
                    Auto-restart this cron if it stops unexpectedly
                </label>
                <br>
                <button type="submit" class="easy-gpt-save-btn">Save auto-restart setting</button>
            </form>
        </div>

        <div class="easy-gpt-cron-box">
            <h3>Article Refresher Cron</h3>
            <p><strong>Status:</strong>
                <span class="easy-gpt-status-<?php echo strtolower($refresh_status); ?>">
                    <?php echo esc_html($refresh_status); ?>
                </span>
            </p>
            <p><strong>Next Execution:</strong>
                <?php echo $next_refresh_execution
                    ? esc_html(get_date_from_gmt(gmdate('Y-m-d H:i:s', $next_refresh_execution), 'Y-m-d H:i:s'))
                    : 'N/A'; ?>
            </p>
            <p style="font-size: 13px; color: #555;">
                The interval for this cron is calculated automatically based on your Article Refresher settings.
            </p>

            <form method="post" class="easy-gpt-form">
                <input type="hidden" name="easy_gpt_toggle_refresh_cron" value="1">
                <button type="submit" class="easy-gpt-toggle-btn" data-status="<?php echo strtolower($refresh_status); ?>">
                    <?php echo $refresh_status === 'Active' ? 'Stop Cron Job' : 'Start Cron Job'; ?>
                </button>
            </form>

            <form method="post" class="easy-gpt-autorestart-form">
                <input type="hidden" name="easy_gpt_save_cron_autorestart" value="1">
                <label>
                    <input type="checkbox" name="easy_gpt_autorestart_refresh_cron" value="1" <?php checked($autorestart_options['refresh'], '1'); ?>>
                    Auto-restart this cron if it stops unexpectedly
                </label>
                <br>
                <button type="submit" class="easy-gpt-save-btn">Save auto-restart setting</button>
            </form>
        </div>

        <div class="easy-gpt-cron-box">
            <h3>Article Translation Cron</h3>
            <p><strong>Status:</strong>
                <span class="easy-gpt-status-<?php echo strtolower($translation_status); ?>">
                    <?php echo esc_html($translation_status); ?>
                </span>
            </p>
            <p><strong>Next Execution:</strong>
                <?php echo $next_translation_execution
                    ? esc_html(get_date_from_gmt(gmdate('Y-m-d H:i:s', $next_translation_execution), 'Y-m-d H:i:s'))
                    : 'N/A'; ?>
            </p>
            <p style="font-size: 13px; color: #555;">
                This cron translates one article at a time based on your Translation settings.
            </p>

            <form method="post" class="easy-gpt-form">
                <input type="hidden" name="easy_gpt_toggle_translation_cron" value="1">
                <button type="submit" class="easy-gpt-toggle-btn" data-status="<?php echo strtolower($translation_status); ?>">
                    <?php echo $translation_status === 'Active' ? 'Stop Cron Job' : 'Start Cron Job'; ?>
                </button>
            </form>

            <form method="post" class="easy-gpt-autorestart-form">
                <input type="hidden" name="easy_gpt_save_cron_autorestart" value="1">
                <label>
                    <input type="checkbox" name="easy_gpt_autorestart_translation_cron" value="1" <?php checked($autorestart_options['translation'], '1'); ?>>
                    Auto-restart this cron if it stops unexpectedly
                </label>
                <br>
                <button type="submit" class="easy-gpt-save-btn">Save auto-restart setting</button>
            </form>
        </div>
    </div>

    <style>
        .easy-gpt-status {
            background: #f9f9f9;
            padding: 20px;
            border-radius: 8px;
            max-width: 700px;
        }
        .easy-gpt-cron-box {
            background: #fff;
            padding: 15px;
            border: 1px solid #ddd;
            border-radius: 8px;
            margin-bottom: 20px;
        }
        .easy-gpt-status-active {
            color: green;
            font-weight: bold;
        }
        .easy-gpt-status-inactive {
            color: red;
            font-weight: bold;
        }
        .easy-gpt-cron-box h3 {
            background: #3582c4;
            padding: 10px;
            color: white;
            border-radius: 5px;
        }
        .easy-gpt-toggle-btn {
            margin-top: 10px;
            border: none;
            border-radius: 5px;
            padding: 10px;
            cursor: pointer;
        }
        .easy-gpt-toggle-btn[data-status="active"] {
            background-color: #d63638;
            color: #fff;
            font-weight: bold;
        }
        .easy-gpt-toggle-btn[data-status="inactive"] {
            background-color: #54b465;
            color: #fff;
            font-weight: bold;
        }
        .easy-gpt-autorestart-form {
            margin-top: 14px;
            padding: 10px;
            background: #f6f7f7;
            border-left: 4px solid #3582c4;
        }
        .easy-gpt-save-btn {
            margin-top: 8px;
            padding: 6px 10px;
            border-radius: 4px;
            border: 1px solid #bbb;
            background: #fff;
            cursor: pointer;
        }
        .loading-dots span {
            opacity: 0.2;
            animation: blink 1s infinite;
            display: inline-block;
        }
        .loading-dots span:nth-child(1) {
            animation-delay: 0s;
        }
        .loading-dots span:nth-child(2) {
            animation-delay: 0.2s;
        }
        .loading-dots span:nth-child(3) {
            animation-delay: 0.4s;
        }
        @keyframes blink {
            0% { opacity: 0.2; }
            50% { opacity: 1; }
            100% { opacity: 0.2; }
        }
    </style>

    <script>
    document.addEventListener('DOMContentLoaded', function() {
        var forms = document.querySelectorAll('.easy-gpt-form, .easy-gpt-autorestart-form');

        forms.forEach(function(form) {
            form.addEventListener('submit', function(e) {
                var button = form.querySelector('button[type="submit"]');

                if (!button) {
                    return;
                }

                button.disabled = true;
                var originalText = button.innerHTML;
                button.innerHTML = originalText + ' <span class="loading-dots"><span>.</span><span>.</span><span>.</span></span>';
            });
        });
    });
    </script>

    <?php
}