<?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' ] );

		// Prism demo: one-time notice when the store first becomes "locked"
		// (customised after a demo install — DemoImportService::dirtyReasons).
		add_action( 'admin_notices', [ self::class, 'demoLockNotice' ] );
		add_action( 'admin_init', [ self::class, 'dismissDemoLockNotice' ] );
	}

	/** Render the demo-lock notice once; dismissing stores '2' so it never returns. */
	public static function demoLockNotice(): void {
		if ( '1' !== get_option( DemoImportService::OPT_LOCK_NOTICE, '' ) || ! current_user_can( 'manage_options' ) ) {
			return;
		}
		$url = wp_nonce_url( add_query_arg( 'tc_dismiss_demo_lock', '1' ), 'tc_dismiss_demo_lock' );
		echo '<div class="notice notice-info"><p>'
			. esc_html__( 'You have started customising your TitanCart store, so the demo theme content is now locked — switching to another demo would overwrite your work. You can still clear the sample orders, customers and reviews from Theme Options.', 'titancart-lite' )
			. ' <a href="' . esc_url( $url ) . '">' . esc_html__( 'Got it', 'titancart-lite' ) . '</a></p></div>';
	}

	public static function dismissDemoLockNotice(): void {
		if ( isset( $_GET['tc_dismiss_demo_lock'] ) && current_user_can( 'manage_options' ) && check_admin_referer( 'tc_dismiss_demo_lock' ) ) {
			update_option( DemoImportService::OPT_LOCK_NOTICE, '2', false );
		}
	}

	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();
	}
}
