<?php

if ( ! defined( 'ABSPATH' ) ) { exit; }

class AIEO_Remote_Export_Cron {

	const HOOK = 'aieo_remote_export_run';

	const SCHEDULE_15MIN  = 'aieo_remote_export_15min';
	const SCHEDULE_HOURLY = 'hourly';
	const SCHEDULE_DAILY  = 'daily';

	const RUNTIME_BUDGET_SEC = 55;

	
	public static function register() {
		add_filter( 'cron_schedules', array( __CLASS__, 'register_schedules' ) );
		add_action( self::HOOK, array( __CLASS__, 'run' ) );
		self::apply_schedule();
	}

	
	public static function register_schedules( $schedules ) {
		if ( empty( $schedules[ self::SCHEDULE_15MIN ] ) ) {
			$schedules[ self::SCHEDULE_15MIN ] = array(
				'interval' => 15 * MINUTE_IN_SECONDS,
				'display'  => __( 'Every 15 minutes (AIEO Remote Export)', 'ai-eshop-optimizer' ),
			);
		}
		return $schedules;
	}

	
	public static function apply_schedule() {
		$settings  = AIEO_Remote_Export_Manager::get_settings();
		$frequency = isset( $settings['frequency'] ) ? (string) $settings['frequency'] : 'hourly';
		$wp_sched  = self::frequency_to_schedule( $frequency );

		$next = wp_next_scheduled( self::HOOK );
		
		$crons = _get_cron_array();
		$current_recurrence = null;
		if ( is_array( $crons ) ) {
			foreach ( $crons as $ts => $hooks ) {
				if ( isset( $hooks[ self::HOOK ] ) && is_array( $hooks[ self::HOOK ] ) ) {
					$entry = reset( $hooks[ self::HOOK ] );
					if ( isset( $entry['schedule'] ) ) {
						$current_recurrence = $entry['schedule'];
						break;
					}
				}
			}
		}

		if ( $current_recurrence === $wp_sched && $next ) {
			return; 
		}

		if ( $next ) { wp_unschedule_event( $next, self::HOOK ); }
		wp_schedule_event( time() + 60, $wp_sched, self::HOOK );
	}

	private static function frequency_to_schedule( $frequency ) {
		switch ( $frequency ) {
			case '15min':
				return self::SCHEDULE_15MIN;
			case 'daily':
				return self::SCHEDULE_DAILY;
			case 'hourly':
			default:
				return self::SCHEDULE_HOURLY;
		}
	}

	public static function unschedule() {
		$ts = wp_next_scheduled( self::HOOK );
		if ( $ts ) { wp_unschedule_event( $ts, self::HOOK ); }
	}

	
	
	

	
	public static function run() {
		if ( ! class_exists( 'AIEO_Remote_Export_Manager' ) ) { return array(); }
		if ( ! AIEO_Remote_Export_Manager::is_configured() ) { return array(); }

		$settings = AIEO_Remote_Export_Manager::get_settings();
		$cid      = (int) $settings['connection_id'];
		$tables   = (array) $settings['tables'];
		$batch    = (int) $settings['batch_size'];
		$started  = microtime( true );

		$summary = array();

		foreach ( $tables as $slug ) {
			$summary[ $slug ] = array( 'exported' => 0, 'iterations' => 0, 'status' => 'ok', 'error' => null );

			
			for ( $i = 0; $i < 100; $i++ ) {
				if ( ( microtime( true ) - $started ) > self::RUNTIME_BUDGET_SEC ) {
					$summary[ $slug ]['status'] = 'time_budget_exhausted';
					break 2;
				}
				$res = AIEO_Remote_Export_Manager::export_pending_rows( $slug, null, $batch, $cid );
				$summary[ $slug ]['iterations']++;
				if ( is_wp_error( $res ) ) {
					$summary[ $slug ]['status'] = 'error';
					$summary[ $slug ]['error']  = $res->get_error_message();
					aieo_debug_log( 'AIEO_Remote_Export_Cron: ' . $slug . ' failed — ' . $res->get_error_message() );
					break;
				}
				$summary[ $slug ]['exported'] += (int) $res;
				if ( (int) $res === 0 ) {
					$summary[ $slug ]['status'] = 'drained';
					break;
				}
			}
		}

		aieo_debug_log( 'AIEO_Remote_Export_Cron: tick complete — ' . wp_json_encode( $summary ) );
		return $summary;
	}
}
