<?php

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

final class IComm_SM_Cron {

	public const SYNC_HOOK = 'icomm_sm_sync_metrics';
	public const REPORT_HOOK = 'icomm_sm_send_client_report';

	public static function init(): void {
		add_action(self::SYNC_HOOK, [__CLASS__, 'run_sync']);
		add_action(self::REPORT_HOOK, [__CLASS__, 'run_client_report']);
	}

	public static function schedule_if_needed(): void {
		if (IComm_SM_Features::can_use('auto_sync') && !wp_next_scheduled(self::SYNC_HOOK)) {
			wp_schedule_event(time() + 600, 'daily', self::SYNC_HOOK);
		}
		if (IComm_SM_Features::can_use('client_email') && !wp_next_scheduled(self::REPORT_HOOK)) {
			wp_schedule_event(time() + 900, 'daily', self::REPORT_HOOK);
		}
	}

	public static function unschedule(): void {
		foreach ([self::SYNC_HOOK, self::REPORT_HOOK] as $hook) {
			$ts = wp_next_scheduled($hook);
			while ($ts) {
				wp_unschedule_event($ts, $hook);
				$ts = wp_next_scheduled($hook);
			}
		}
	}

	/**
	 * @return array{ok:bool}
	 */
	public static function run_sync(): array {
		if (!IComm_SM_Settings::is_gsc_ready()) {
			return ['ok' => false];
		}
		$days = IComm_SM_Features::sync_days();
		$with_ga4 = IComm_SM_Features::can_use('ga4_metrics') && IComm_SM_Settings::is_ga4_ready();
		$res = IComm_SM_Remote::sync($days, $with_ga4);
		if (empty($res['ok'])) {
			// Persist a helpful error for the dashboard/connections UI.
			$s = IComm_SM_Settings::get();
			$err = isset($res['error']) ? trim((string) $res['error']) : '';
			if ($err === '') {
				$err = 'sync_failed';
			}
			$s['gsc_last_error'] = $err;
			if ($with_ga4) {
				$s['ga4_last_error'] = $err;
			}
			IComm_SM_Settings::save($s);
			return ['ok' => false];
		}
		$applied = IComm_SM_Remote::apply_sync_to_db($res);
		if (!empty($applied['ok']) && class_exists('IComm_SM_Alerts')) {
			IComm_SM_Alerts::after_successful_sync();
		}
		return $applied;
	}

	public static function run_client_report(): void {
		if (!IComm_SM_Features::can_use('client_email')) {
			return;
		}
		$s = IComm_SM_Settings::get();
		if (empty($s['client_report_enabled'])) {
			return;
		}
		$day = max(1, min(28, (int) ($s['client_report_day'] ?? 1)));
		if ((int) wp_date('j') !== $day) {
			return;
		}
		IComm_SM_Report_Builder::send_monthly_email();
	}
}
