<?php
/**
 * DBA Scheduler - WP-Cron based scheduling for daily post generation
 */
class DBA_Scheduler {

    private static $instance = null;

    public static function get_instance() {
        if (null === self::$instance) self::$instance = new self();
        return self::$instance;
    }

    private function __construct() {
        add_action('dba_daily_generation', array($this, 'run_daily_generation'));
        add_action('dba_daily_sitemap_refresh', array($this, 'run_sitemap_refresh'));
    }

    /**
     * Activate cron schedules
     */
    public static function activate() {
        // Daily generation at 6:00 AM UTC (7:00 AM Luxembourg winter / 8:00 AM summer)
        if (!wp_next_scheduled('dba_daily_generation')) {
            // Schedule for next occurrence of 06:00 UTC
            $next_run = strtotime('tomorrow 06:00:00 UTC');
            wp_schedule_event($next_run, 'daily', 'dba_daily_generation');
        }

        // Daily sitemap refresh at 05:00 UTC
        if (!wp_next_scheduled('dba_daily_sitemap_refresh')) {
            $next_run = strtotime('tomorrow 05:00:00 UTC');
            wp_schedule_event($next_run, 'daily', 'dba_daily_sitemap_refresh');
        }
    }

    /**
     * Deactivate cron schedules
     */
    public static function deactivate() {
        $hooks = array('dba_daily_generation', 'dba_daily_sitemap_refresh');
        foreach ($hooks as $hook) {
            $timestamp = wp_next_scheduled($hook);
            if ($timestamp) {
                wp_unschedule_event($timestamp, $hook);
            }
        }
    }

    /**
     * Daily generation run
     */
    public function run_daily_generation() {
        $schedule = get_option('dba_schedule_settings', array());

        if (empty($schedule['enabled'])) {
            error_log('DBA Scheduler: Auto-generation is DISABLED');
            return;
        }

        // Check if today is a posting day
        $posting_days = isset($schedule['posting_days']) ? $schedule['posting_days'] : array('monday', 'wednesday', 'saturday');
        $tz = isset($schedule['timezone']) ? $schedule['timezone'] : 'Europe/Luxembourg';

        try {
            $now = new DateTime('now', new DateTimeZone($tz));
            $today = strtolower($now->format('l'));
        } catch (Exception $e) {
            $today = strtolower(date('l'));
        }

        if (!in_array($today, $posting_days)) {
            error_log('DBA Scheduler: Today (' . $today . ') is not a posting day. Skipping.');
            return;
        }

        error_log('DBA Scheduler: Starting daily generation for ' . $today);

        // v2.15.0: Global conflict lock — prevent simultaneous OpenAI calls across modules
        if ( class_exists( 'DBA_Conflict_Center' ) && ! DBA_Conflict_Center::acquire( 'core', 'dba_daily_generation' ) ) {
            error_log( 'DBA Scheduler: Another module is generating — rescheduled +10min' );
            return;
        }

        // Increase execution limits
        @set_time_limit(600);
        @ini_set('memory_limit', '512M');

        try {
            $creator = DBA_Post_Creator::get_instance();
            $results = $creator->create_daily_batch();

            // Store results
            update_option('dba_last_run', array(
                'time'    => current_time('mysql'),
                'day'     => $today,
                'results' => $results,
            ));

            error_log('DBA Scheduler: Daily run complete - Created: ' . $results['created'] . ' Failed: ' . $results['failed']);
        } catch ( \Throwable $e ) {
            error_log( 'DBA Scheduler FATAL: ' . $e->getMessage() );
        }

        // v2.15.0: Always release lock (even after errors)
        if ( class_exists( 'DBA_Conflict_Center' ) ) DBA_Conflict_Center::release( 'core' );
    }

    /**
     * Daily sitemap refresh
     */
    public function run_sitemap_refresh() {
        $sitemap = DBA_Sitemap::get_instance();
        $sitemap->refresh_registry();
    }

    /**
     * Get next scheduled run info
     */
    public static function get_next_run_info() {
        $next = wp_next_scheduled('dba_daily_generation');
        if (!$next) return 'Not scheduled';

        $schedule = get_option('dba_schedule_settings', array());
        $tz = isset($schedule['timezone']) ? $schedule['timezone'] : 'Europe/Luxembourg';

        try {
            $dt = new DateTime('@' . $next);
            $dt->setTimezone(new DateTimeZone($tz));
            return $dt->format('l, F j, Y \a\t H:i') . ' (' . $tz . ')';
        } catch (Exception $e) {
            return date('Y-m-d H:i:s', $next) . ' UTC';
        }
    }

    /**
     * Get posting days as human string
     */
    public static function get_posting_days_string() {
        $schedule = get_option('dba_schedule_settings', array());
        $days = isset($schedule['posting_days']) ? $schedule['posting_days'] : array();
        return !empty($days) ? implode(', ', array_map('ucfirst', $days)) : 'None configured';
    }
}
