<?php

namespace MovieEngine\Core;

if (! defined("ABSPATH")) {
    exit; // Exit if accessed directly
}

/**
 * Cron Cleanup Utility
 * Helps prevent cron event list save errors by cleaning up orphaned events
 */
class CronCleanup {

    public static function cleanup_orphaned_crons() {
        $crons = _get_cron_array();

        if (empty($crons)) {
            return;
        }

        $cleaned = false;
        $current_time = time();

        foreach ($crons as $timestamp => $cron) {
            if ($timestamp < ($current_time - DAY_IN_SECONDS)) {
                foreach ($cron as $hook => $dings) {
                    foreach ($dings as $sig => $data) {
                        wp_unschedule_event($timestamp, $hook, $data['args']);
                        $cleaned = true;
                    }
                }
            }
        }

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

    public static function limit_cron_events($max_events = 1000) {
        $crons = _get_cron_array();

        if (empty($crons)) {
            return;
        }

        $total_events = 0;
        foreach ($crons as $timestamp => $cron) {
            foreach ($cron as $hook => $dings) {
                $total_events += count($dings);
            }
        }

        if ($total_events > $max_events) {
            ksort($crons);

            $removed = 0;
            $target_removal = $total_events - $max_events;

            foreach ($crons as $timestamp => $cron) {
                if ($removed >= $target_removal) {
                    break;
                }

                foreach ($cron as $hook => $dings) {
                    foreach ($dings as $sig => $data) {
                        if ($removed >= $target_removal) {
                            break 2;
                        }

                        if (strpos($hook, 'action_scheduler') === 0) {
                            continue;
                        }

                        wp_unschedule_event($timestamp, $hook, $data['args']);
                        $removed++;
                    }
                }
            }
        }
    }

    public static function fix_action_scheduler_cron() {
        $crons = _get_cron_array();

        if (empty($crons)) {
            return;
        }

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

        if ($action_scheduler_events > 100) {
            // Action Scheduler has many events.
        }
    }
}
