<?php
/**
 * TitanCart Import/Export Module — Module 13
 *
 * Bootstraps REST routes, WP-Cron hooks, and the titancart_process_import action
 * that drives background CSV import processing.
 *
 * Registration in Plugin::boot():
 *   ImportExportModule::init();  // Module 13 — Import/Export
 *
 * Activation / deactivation hooks (call from Installer):
 *   ImportExportModule::scheduleCron();
 *   ImportExportModule::clearCron();
 *
 * @package TitanCart\Modules\ImportExport
 */

namespace TitanCart\Modules\ImportExport;

use TitanCart\REST\ImportExport\ImportExportController;

defined( 'ABSPATH' ) || exit;

class ImportExportModule {

	public static function init(): void {
		// REST API routes.
		add_action( 'rest_api_init', [ self::class, 'registerRoutes' ] );

		// Background import processor — fired by wp_schedule_single_event().
		add_action( 'titancart_process_import', [ self::class, 'processImport' ] );

		// Cron schedule definition (shared with Reports module if already defined).
		add_filter( 'cron_schedules', [ self::class, 'addCronSchedule' ] );

		// Hourly export cleanup.
		add_action( 'titancart_export_cleanup_ie', [ self::class, 'runExportCleanup' ] );
	}

	public static function registerRoutes(): void {
		( new ImportExportController() )->register_routes();
	}

	/**
	 * WP-Cron callback: process the next batch of a queued import job.
	 *
	 * @param int $job_id
	 */
	public static function processImport( int $job_id ): void {
		( new ImportService() )->processJob( $job_id );
	}

	/**
	 * Ensure a titancart_hourly schedule exists.
	 */
	public static function addCronSchedule( array $schedules ): array {
		if ( ! isset( $schedules['titancart_hourly'] ) ) {
			$schedules['titancart_hourly'] = [
				'interval' => HOUR_IN_SECONDS,
				// Plain string ON PURPOSE (S468): cron_schedules is applied
				// pre-init whenever anything queries schedules at boot, and
				// translating here trips WP 6.7's just-in-time textdomain
				// notice. Dev-facing label (cron tooling only) — do not __().
				'display'  => 'TitanCart — Every Hour',
			];
		}
		return $schedules;
	}

	/**
	 * Schedule the export cleanup cron on plugin activation.
	 */
	public static function scheduleCron(): void {
		if ( ! wp_next_scheduled( 'titancart_export_cleanup_ie' ) ) {
			wp_schedule_event( time(), 'titancart_hourly', 'titancart_export_cleanup_ie' );
		}
	}

	/**
	 * Unschedule the export cleanup cron on plugin deactivation.
	 */
	public static function clearCron(): void {
		$ts = wp_next_scheduled( 'titancart_export_cleanup_ie' );
		if ( $ts ) {
			wp_unschedule_event( $ts, 'titancart_export_cleanup_ie' );
		}
	}

	public static function runExportCleanup(): void {
		( new ExportService() )->cleanupOldExports();
	}
}
