<?php
/**
 * FajaedeSEO Cron Tasks
 */

defined('ABSPATH') or exit;

// Clean up old monthly cron if it exists
$fajaedeseo_old_timestamp = wp_next_scheduled('fajaedeseo_monthly_accounting_report');
if ($fajaedeseo_old_timestamp) {
    wp_unschedule_event($fajaedeseo_old_timestamp, 'fajaedeseo_monthly_accounting_report');
}

if (!wp_next_scheduled('fajaedeseo_twicedaily_cron')) {
    wp_schedule_event(time(), 'twicedaily', 'fajaedeseo_twicedaily_cron');
}

add_action('fajaedeseo_twicedaily_cron', 'fajaedeseo_run_cron_jobs');

function fajaedeseo_run_cron_jobs() {
    // Prevent overlapping cron runs
    if ( get_transient( 'fajaedeseo_cron_running' ) ) {
        return;
    }
    set_transient( 'fajaedeseo_cron_running', true, 30 * MINUTE_IN_SECONDS );

    if (class_exists('FajaedeSEO_Sitemap_Generator')) {
        try {
            $sitemap = new \FajaedeSEO_Sitemap_Generator();
            $sitemap->regenerate_sitemap_cache(true);
        } catch ( Throwable $e ) {
            set_transient( 'fajaedeseo_sitemap_failed', '1', HOUR_IN_SECONDS );
            update_option( 'fajaedeseo_last_sitemap_error', $e->getMessage() );
        }
    }

    // Wis de globe cache zodat deze automatisch 2 keer per dag ververst wordt
    delete_transient('fajaedeseo_globe_visitor_data'); 

    delete_transient( 'fajaedeseo_cron_running' );
}

add_filter('cron_schedules', 'fajaedeseo_add_cron_schedules');
function fajaedeseo_add_cron_schedules(array $schedules): array {
    // Weekly schedule - will be checked if today is Thursday
    if (!isset($schedules['weekly_thursday'])) {
        $schedules['weekly_thursday'] = ['interval' => 7 * 24 * 60 * 60, 'display' => __('Every Thursday', 'fajaedeseo-ai')];
    }
    return $schedules;
}

if (!wp_next_scheduled('fajaedeseo_weekly_thursday_accounting_report')) {
    // Schedule for the next Thursday at 09:00 AM
    $fajaedeseo_next_thursday = fajaedeseo_get_next_thursday_timestamp();
    wp_schedule_event($fajaedeseo_next_thursday, 'weekly_thursday', 'fajaedeseo_weekly_thursday_accounting_report');
}

/**
 * Get timestamp for next Thursday at 09:00 AM
 */
function fajaedeseo_get_next_thursday_timestamp(): int {
    $today = strtotime('today', time());
    $current_day = (int) gmdate('w', $today); // 0 = Sunday, 4 = Thursday
    $days_until_thursday = (4 - $current_day + 7) % 7;
    if ($days_until_thursday === 0) {
        $days_until_thursday = 7; // If today is Thursday, schedule for next Thursday
    }
    $next_thursday = strtotime('+' . $days_until_thursday . ' days 09:00', $today);
    return (int) $next_thursday;
}