<?php
/**
 * Central cron hook wiring.
 *
 * @package WPLens
 */

namespace WPLens;

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

final class Cron {

	public static function register(): void {
		add_action( 'wplens_cron_log_pruner', array( __CLASS__, 'prune_logs' ) );
		add_action( 'wplens_cron_weekly_report', array( __CLASS__, 'run_weekly_report' ) );
		add_action( 'wplens_cron_citations_run', array( __CLASS__, 'run_citations' ) );
	}

	public static function prune_logs(): void {
		$settings  = \WPLens\Utils\Options::all();
		$retention = isset( $settings['crawler']['retention_days'] )
			? absint( $settings['crawler']['retention_days'] )
			: 90;

		if ( $retention < 1 ) {
			return;
		}

		global $wpdb;
		$table = $wpdb->prefix . 'wplens_crawler_log';
		// phpcs:disable WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared, PluginCheck.Security.DirectDB.UnescapedDBParameter
		$wpdb->query(
			$wpdb->prepare(
				"DELETE FROM {$table} WHERE visited_at < %s",
				gmdate( 'Y-m-d H:i:s', time() - $retention * DAY_IN_SECONDS )
			)
		);
		// phpcs:enable
	}

	public static function run_weekly_report(): void {
		$settings = \WPLens\Utils\Options::all();
		if ( empty( $settings['modules']['weekly_report'] ) ) {
			return;
		}
		if ( empty( $settings['reporting']['recipients'] ) ) {
			return;
		}

		$builder = new \WPLens\Reports\HtmlReportBuilder();
		$html    = $builder->build_weekly();

		$sender  = new \WPLens\Reports\EmailSender();
		$sender->send_weekly_report( $settings['reporting']['recipients'], $html );
	}

	public static function run_citations(): void {
		$settings = \WPLens\Utils\Options::all();
		if ( empty( $settings['modules']['citation_tracking'] ) ) {
			return;
		}

		$runner = new \WPLens\Citations\CitationRunner();
		$runner->run_active_queries();
	}
}
