<?php

namespace MovieEngine\Core;

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

/**
 * Cron Manager
 * Handles WordPress cron event management, cleanup, and error prevention
 */
class CronManager {

    public static function init() {
        add_action('movie_engine_cleanup_cron', [__CLASS__, 'run_scheduled_cleanup']);
        add_filter('pre_update_option_cron', [__CLASS__, 'handle_cron_save_error'], 10, 2);
        add_filter('cron_schedules', [__CLASS__, 'register_custom_schedules']);
    }

    public static function run_scheduled_cleanup() {
        $options = get_option('movie_engine_cron_settings', [
            'auto_cleanup_enabled' => 1,
            'max_cron_events' => 1000,
            'cleanup_old_actions_days' => 30
        ]);

        if (!($options['auto_cleanup_enabled'] ?? 1)) {
            return;
        }

        CronCleanup::cleanup_orphaned_crons();
        CronCleanup::limit_cron_events($options['max_cron_events'] ?? 1000);
        CronCleanup::fix_action_scheduler_cron();

        require_once MOVIE_ENGINE_PATH . 'includes/Admin/CronSettings.php';
        if (class_exists('\MovieEngine\Admin\CronSettings')) {
            $deleted = \MovieEngine\Admin\CronSettings::delete_old_action_scheduler_actions($options['cleanup_old_actions_days'] ?? 30);
            if ($deleted > 0) {
                // Actions cleaned up successfully.
            }
        }
    }

    public static function handle_cron_save_error($value, $old_value) {
        if (!is_array($value) || empty($value)) {
            return $value;
        }

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

        $options = get_option('movie_engine_cron_settings', []);
        $max_events = absint($options['max_cron_events'] ?? 1000);

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

            $truncated = [];
            $count = 0;

            foreach ($value as $timestamp => $cron) {
                if (!is_array($cron)) continue;

                $timestamp_events = [];

                foreach ($cron as $hook => $dings) {
                    if (!is_array($dings)) continue;

                    if (strpos($hook, 'action_scheduler') === 0) {
                        if (!isset($timestamp_events[$hook])) {
                            $timestamp_events[$hook] = [];
                        }
                        $timestamp_events[$hook] = $dings;
                        $count += count($dings);
                        continue;
                    }

                    foreach ($dings as $sig => $data) {
                        if ($count >= $max_events) break 3;

                        if (!isset($timestamp_events[$hook])) {
                            $timestamp_events[$hook] = [];
                        }
                        $timestamp_events[$hook][$sig] = $data;
                        $count++;
                    }
                }

                if (!empty($timestamp_events)) {
                    $truncated[$timestamp] = $timestamp_events;
                }

                if ($count >= $max_events) {
                    break;
                }
            }

            return $truncated;
        }

        return $value;
    }

    public static function register_custom_schedules($schedules) {
        if (!isset($schedules['movie_engine_every_minute'])) {
            $display = function_exists('__') && did_action('init')
                ? esc_html__('Every Minute', 'cine-movie-engine')
                : 'Every Minute';

            $schedules['movie_engine_every_minute'] = [
                'interval' => 60,
                'display'  => $display,
            ];
        }
        return $schedules;
    }

    public static function schedule_cleanup() {
        if (!wp_next_scheduled('movie_engine_cleanup_cron')) {
            wp_schedule_event(time(), 'daily', 'movie_engine_cleanup_cron');
        }
    }

    public static function unschedule_cleanup() {
        wp_clear_scheduled_hook('movie_engine_cleanup_cron');
    }
}
