<?php
/**
 * File Path: includes/admin/tabs/class-mbs-tab-import-export.php
 *
 * Import / Export Tab (Parent Orchestrator)
 *
 * Thin orchestrator that registers all AJAX actions and coordinates child modules.
 * Render output delegated to MBS_Tab_Import_Export_Render (R-20).
 *
 * @package MyBookShowroom
 * @since   1.0.0
 */

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

class MBS_Tab_Import_Export {

	/** @var MBS_Tab_Child_Export */
	private $export;

	/** @var MBS_Tab_Child_Import_ISBN */
	private $import_isbn;

	/** @var MBS_Tab_Child_Import_WXR */
	private $import_wxr;

	/** @var MBS_Tab_Child_Import_Competitors */
	private $import_competitors;

	/** @var MBS_Tab_Child_Import_CSV */
	private $import_csv;

	/** @var MBS_Tab_Child_Settings_Import */
	private $settings_import;

	/** @var MBS_Tab_Child_Import_EPUB */
	private $import_epub;

	/** @var MBS_Tab_Child_Archive */
	private $archive;

	public function __construct() {
		$this->export              = new MBS_Tab_Child_Export();
		$this->import_isbn         = new MBS_Tab_Child_Import_ISBN();
		$this->import_wxr          = new MBS_Tab_Child_Import_WXR();
		$this->import_competitors  = new MBS_Tab_Child_Import_Competitors();
		$this->import_csv          = new MBS_Tab_Child_Import_CSV();
		$this->settings_import     = new MBS_Tab_Child_Settings_Import();
		$this->import_epub         = new MBS_Tab_Child_Import_EPUB();
		$this->archive             = new MBS_Tab_Child_Archive();

		// Register all AJAX actions from children
		add_action( 'wp_ajax_mbs_import_csv_headers',      array( $this->import_csv, 'handle_ajax_mbs_import_csv_headers' ) );
		add_action( 'wp_ajax_mbs_import_csv',              array( $this->import_csv, 'handle_ajax_mbs_import_csv' ) );
		add_action( 'wp_ajax_mbs_sideload_covers',         array( $this->import_csv, 'handle_ajax_mbs_sideload_covers' ) );
		add_action( 'wp_ajax_mbs_download_csv_template',   array( $this->import_csv, 'handle_ajax_mbs_download_csv_template' ) );

		// ISBN & API importers (MBS_Tab_Child_Import_ISBN).
		add_action( 'wp_ajax_mbs_import_google_books',     array( $this->import_isbn, 'handle_ajax_mbs_import_google_books' ) );
		add_action( 'wp_ajax_mbs_import_open_library',     array( $this->import_isbn, 'handle_ajax_mbs_import_open_library' ) );
		add_action( 'wp_ajax_mbs_import_amazon',           array( $this->import_isbn, 'handle_ajax_mbs_import_amazon' ) );
		add_action( 'wp_ajax_mbs_import_candidates',       array( $this->import_isbn, 'handle_ajax_mbs_import_candidates' ) );
		add_action( 'wp_ajax_mbs_save_amazon_credentials', array( $this->import_isbn, 'handle_ajax_mbs_save_amazon_credentials' ) );
		add_action( 'wp_ajax_mbs_save_google_books_api_key', array( $this->import_isbn, 'handle_ajax_mbs_save_google_books_api_key' ) );

		// WXR guided import: Pass 1 (analyze) + Pass 2 (run) (MBS_Tab_Child_Import_WXR).
		add_action( 'wp_ajax_mbs_import_wxr_analyze', array( $this->import_wxr, 'handle_ajax_mbs_import_wxr_analyze' ) );
		add_action( 'wp_ajax_mbs_import_wxr_run',     array( $this->import_wxr, 'handle_ajax_mbs_import_wxr_run' ) );

		// Competitor one-click importers (MBS_Tab_Child_Import_Competitors).
		add_action( 'wp_ajax_mbs_import_mybooktable',        array( $this->import_competitors, 'handle_ajax_mbs_import_mybooktable' ) );
		add_action( 'wp_ajax_mbs_import_wp_books_gallery',   array( $this->import_competitors, 'handle_ajax_mbs_import_wp_books_gallery' ) );
		add_action( 'wp_ajax_mbs_import_genesis_author_pro', array( $this->import_competitors, 'handle_ajax_mbs_import_genesis_author_pro' ) );
		add_action( 'wp_ajax_mbs_import_rs_wp_books',        array( $this->import_competitors, 'handle_ajax_mbs_import_rs_wp_books' ) );
		add_action( 'wp_ajax_mbs_import_gs_bookshowcase',    array( $this->import_competitors, 'handle_ajax_mbs_import_gs_bookshowcase' ) );
		add_action( 'wp_ajax_mbs_import_novelist',           array( $this->import_competitors, 'handle_ajax_mbs_import_novelist' ) );

		add_action( 'wp_ajax_mbs_export_csv',            array( $this->export, 'handle_ajax_mbs_export_csv' ) );
			add_action( 'wp_ajax_mbs_export_xlsx',           array( $this->export, 'handle_ajax_mbs_export_xlsx' ) );
		add_action( 'wp_ajax_mbs_export_settings',       array( $this->export, 'handle_ajax_mbs_export_settings' ) );
		add_action( 'wp_ajax_mbs_export_covers_zip',     array( $this->export, 'handle_ajax_mbs_export_covers_zip' ) );

		// EPUB Import (MBS_Tab_Child_Import_EPUB).
		add_action( 'wp_ajax_mbs_epub_parse',        array( $this->import_epub, 'handle_ajax_mbs_epub_parse' ) );
		add_action( 'wp_ajax_mbs_epub_import',       array( $this->import_epub, 'handle_ajax_mbs_epub_import' ) );
		add_action( 'wp_ajax_mbs_epub_cover_thumb',  array( $this->import_epub, 'handle_ajax_mbs_epub_cover_thumb' ) );

		add_action( 'wp_ajax_mbs_import_settings_preview', array( $this->settings_import, 'handle_ajax_mbs_import_settings_preview' ) );
		add_action( 'wp_ajax_mbs_import_settings_apply',   array( $this->settings_import, 'handle_ajax_mbs_import_settings_apply' ) );

		// Archive Import (MBS_Tab_Child_Archive — IEF Phase 6). Export via MBS_Exporter_Zip.
		add_action( 'wp_ajax_mbs_archive_import_start',   array( $this->archive, 'handle_ajax_mbs_archive_import_start' ) );
		add_action( 'wp_ajax_mbs_archive_import_book',    array( $this->archive, 'handle_ajax_mbs_archive_import_book' ) );
		add_action( 'wp_ajax_mbs_archive_import_media',   array( $this->archive, 'handle_ajax_mbs_archive_import_media' ) );

		add_action( 'admin_init', array( $this, 'register' ) );
	}

	public function register(): void {
		// Register the main option group for the entire Import/Export tab
		// This prevents the "not in the allowed options list" error on form submit
		register_setting( 'mbs_import_export', 'mbs_setting_import_field_authority' ); // phpcs:ignore PluginCheck.CodeAnalysis.SettingSanitization.register_settingMissing -- settings registered via Settings API in parent tab class; checker cannot trace cross-file registration

		// PA-API credentials (Story 9-1).
		// Key and secret are stored encrypted; no sanitize_callback needed here —
		// encryption and sanitization are handled in the AJAX handler before storage.
		register_setting( 'mbs_import_export', 'mbs_setting_import_amazon_api_key_encrypted' ); // phpcs:ignore PluginCheck.CodeAnalysis.SettingSanitization.register_settingMissing -- settings registered via Settings API in parent tab class; checker cannot trace cross-file registration
		register_setting( 'mbs_import_export', 'mbs_setting_import_amazon_api_secret_encrypted' ); // phpcs:ignore PluginCheck.CodeAnalysis.SettingSanitization.register_settingMissing -- settings registered via Settings API in parent tab class; checker cannot trace cross-file registration
		register_setting( 'mbs_import_export', 'mbs_setting_amazon_partner_tag', array(
			'sanitize_callback' => 'sanitize_text_field',
		) );

		// INSIGHTS-3: Press Kit public-download toggle and cover-ratio test mode.
		register_setting( 'mbs_import_export', 'mbs_press_kit_public', array(
			'sanitize_callback' => 'absint',
			'default'           => 0,
		) );
		register_setting( 'mbs_import_export', 'mbs_press_kit_test_mode', array(
			'sanitize_callback' => 'absint',
			'default'           => 0,
		) );
	}

	public function render(): void {
		MBS_Tab_Import_Export_Render::render();
	}

	/**
	 * Enqueue tab-specific CSS and JS when the import-export tab is active.
	 *
	 * Called by MBS_Settings::enqueue_assets() via the per-tab delegate loop.
	 *
	 * @param string $current_tab The active settings tab slug.
	 */
	public function enqueue( string $current_tab ): void {
		if ( 'import-export' !== $current_tab ) {
			return;
		}

		wp_enqueue_style(
			'mbs-admin-settings-imp-exp',
			plugins_url( 'assets/css/mbs-admin-settings-imp-exp.css', MBS_DIR . 'bookshowroom.php' ),
			array( 'mbs-admin-settings' ),
			MBS_VERSION
		);

		// Component stylesheets — split from mbs-admin-settings-imp-exp.css (Session 100).
		$imp_exp_components = array(
			'tab-wrapper', 'scenario-cards', 'panel', 'hint-box', 'coming-soon',
			'csv-import', 'export-panel', 'settings-panel', 'result-report',
			'pa-api', 'responsive', 'migration-card', 'migration-panel',
		);
		foreach ( $imp_exp_components as $component ) {
			wp_enqueue_style(
				'mbs-imp-exp-' . $component,
				plugins_url( 'assets/css/admin/imp-exp/imp-exp-' . $component . '.css', MBS_DIR . 'bookshowroom.php' ),
				array( 'mbs-admin-settings-imp-exp' ),
				MBS_VERSION
			);
		}

		// REF-23: mbs-admin-imp-exp.js is now the shared-utilities layer.
		// Four focused modules are enqueued after it; each depends on this handle.
		wp_enqueue_script(
			'mbs-admin-imp-exp',
			plugins_url( 'assets/js/adminjs/mbs-admin-imp-exp.js', MBS_DIR . 'bookshowroom.php' ),
			array( 'jquery', 'mbs-admin-csv-import' , 'wp-i18n' ),
			MBS_VERSION,
			true
		);
		wp_set_script_translations( 'mbs-admin-imp-exp', 'my-book-showroom', MBS_DIR . 'languages' );

		wp_localize_script( 'mbs-admin-imp-exp', 'MBS_ImpExp', array(
			'isPro' => mbs_is_pro(),
		) );

		wp_enqueue_script(
			'mbs-imp-exp-panel-switcher',
			plugins_url( 'assets/js/adminjs/mbs-imp-exp-panel-switcher.js', MBS_DIR . 'bookshowroom.php' ),
			array( 'mbs-admin-imp-exp' ),
			MBS_VERSION,
			true
		);

		wp_enqueue_script(
			'mbs-import-covers',
			plugins_url( 'assets/js/adminjs/mbs-import-covers.js', MBS_DIR . 'bookshowroom.php' ),
			array( 'mbs-admin-imp-exp' , 'wp-i18n' ),
			MBS_VERSION,
			true
		);
		wp_set_script_translations( 'mbs-import-covers', 'my-book-showroom', MBS_DIR . 'languages' );

		wp_enqueue_script(
			'mbs-import-isbn',
			plugins_url( 'assets/js/adminjs/mbs-import-isbn.js', MBS_DIR . 'bookshowroom.php' ),
			array( 'mbs-admin-imp-exp', 'mbs-import-covers' , 'wp-i18n' ),
			MBS_VERSION,
			true
		);
		wp_set_script_translations( 'mbs-import-isbn', 'my-book-showroom', MBS_DIR . 'languages' );

		wp_enqueue_script(
			'mbs-import-amazon',
			plugins_url( 'assets/js/adminjs/mbs-import-amazon.js', MBS_DIR . 'bookshowroom.php' ),
			array( 'mbs-admin-imp-exp', 'mbs-import-covers' , 'wp-i18n' ),
			MBS_VERSION,
			true
		);
		wp_set_script_translations( 'mbs-import-amazon', 'my-book-showroom', MBS_DIR . 'languages' );

		// Migration panel relay — MyBookTable direct import (Story 14-1b).
		wp_enqueue_script(
			'mbs-admin-migrate',
			plugins_url( 'assets/js/adminjs/mbs-admin-migrate.js', MBS_DIR . 'bookshowroom.php' ),
			array( 'mbs-admin-imp-exp', 'mbs-imp-exp-panel-switcher' , 'wp-i18n' ),
			MBS_VERSION,
			true
		);
		wp_set_script_translations( 'mbs-admin-migrate', 'my-book-showroom', MBS_DIR . 'languages' );

		// EPUB Import module (EPUB-001).
		wp_enqueue_script(
			'mbs-import-epub',
			plugins_url( 'assets/js/adminjs/mbs-import-epub.js', MBS_DIR . 'bookshowroom.php' ),
			array( 'mbs-admin-imp-exp' , 'wp-i18n' ),
			MBS_VERSION,
			true
		);
		wp_set_script_translations( 'mbs-import-epub', 'my-book-showroom', MBS_DIR . 'languages' );

		// WXR guided migration (Story 14-2).
		wp_enqueue_script(
			'mbs-import-wxr',
			plugins_url( 'assets/js/adminjs/mbs-import-wxr.js', MBS_DIR . 'bookshowroom.php' ),
			array( 'mbs-admin-imp-exp' , 'wp-i18n' ),
			MBS_VERSION,
			true
		);
		wp_set_script_translations( 'mbs-import-wxr', 'my-book-showroom', MBS_DIR . 'languages' );

		// Shared import progress module -- all import flows (ZIP, MyBookTable, WXR, CSV, ISBN, Amazon).
		wp_enqueue_script(
			'mbs-import-progress',
			plugins_url( 'assets/js/adminjs/mbs-import-progress.js', MBS_DIR . 'bookshowroom.php' ),
			array(),
			MBS_VERSION,
			true
		);

		// Archive Import / Export module (IEF Phase 6).
		wp_enqueue_script(
			'mbs-archive-import-export',
			plugins_url( 'assets/js/adminjs/mbs-archive-import-export.js', MBS_DIR . 'bookshowroom.php' ),
			array( 'mbs-admin-imp-exp', 'mbs-import-progress', 'wp-i18n' ),
			MBS_VERSION,
			true
		);
		wp_set_script_translations( 'mbs-archive-import-export', 'my-book-showroom', MBS_DIR . 'languages' );
		wp_localize_script( 'mbs-archive-import-export', 'MBS_Archive', array(
			'ajaxUrl' => admin_url( 'admin-ajax.php' ),
			'nonce'   => wp_create_nonce( 'mbs_import_export' ),
			'isPro'   => mbs_is_pro(),
		) );
	}

	// ── Architecture note ─────────────────────────────────────────────────────
	// The parent orchestrator registers the wp_ajax_ hooks but performs
	// NO nonce or current_user_can() checks itself. This is intentional.
	// Each child handler (Import_ISBN, Import_WXR, Import_Competitors, Import_CSV, Export,
	// Settings_Import) is responsible for its own security via MBS_Ajax_Import_Export_Guard:
	//   - check_ajax_referer() / check_admin_referer()
	//   - current_user_can( 'manage_options' )
	//
	// This keeps the parent thin and avoids duplicated security code.
	// New child handlers MUST implement their own checks — there is no
	// fallback in the parent.
	//
	// See child classes for the actual security implementation.
}
