<?php
namespace WPUltimateSecurity\UltimateSecurity\Bootstrap\Lifecycle;

use WPUltimateSecurity\UltimateSecurity\Support\Helpers\DateHelper;

class Deactivator
{
    public static function deactivate()
    {
        self::paused_crons();

        wp_clear_scheduled_hook('ultimate_security_change_salt_keys');

        // wp_clear_scheduled_hook( 'myplugin_hourly_event' );



        // wp_unschedule_hook( 'ultimate_security_reset_expired_lockouts' );

        $timestamp = wp_next_scheduled('ultimate_security_cleanup_event');
        if ($timestamp) {
            wp_unschedule_event($timestamp, 'ultimate_security_cleanup_event');
        }
        update_option( 'ultimate_security_paused_crons', true );

    }

    public static function paused_crons()
    {
        $free_crons = ['ultimate_security_daily_9am_task', 'ultimate_security_send_update_success_email', 'ultimate_security_change_salt_keys', 'ultimate_security_url_guard_cleanup', 'ultimate_security_rate_limit_cleanup', 'ultimate_security_reset_expired_lockouts'];

        $crons = _get_cron_array();
        $response = [];

        if (!$crons) {
            return;
        }

        foreach ($crons as $timestamp => $cron) {
            foreach ($cron as $hook => $instances) {
                // Only show your plugin's events
                if (strpos($hook, 'ultimate_security') !== 0) {
                    continue;
                }

                // Skip orphaned hooks (no function hooked to this event)
                if (!has_action($hook)) {
                    continue;
                }

                foreach ($instances as $sig => $details) {
                    $next_run = ($timestamp > time())
                        ? "In " . human_time_diff(time(), $timestamp)
                        : "Missed";

                    // Get last manual run time from transient
                    $last_run_data = get_transient('ultimate_security_cron_last_run_' . md5($hook));
                    $last_run = null;
                    if ($last_run_data && isset($last_run_data['timestamp'])) {
                        $last_run = DateHelper::humanDiff($last_run_data['timestamp']);
                    }
                    if (in_array($hook, $free_crons)) {
                        wp_unschedule_hook( $hook );
                        $response[] = [
                            'event' => $hook,
                            'next_run' => $next_run,
                            'schedule' => $details['schedule'] ?? 'One-time',
                            'action' => 'Run Manually',
                            'last_manual_run' => $last_run,
                        ];
                    }
                }
            }
        }
        update_option('ultimate_security_crons', $response);
        // error_log('[ultimate_security]' . print_r($ultimate_security_crons, true));
    }
}
