<?php
/**
 * File Path: includes/admin/tabs/class-mbs-tab-onix.php
 *
 * ONIX Settings Tab (Tab 15) -- My Book Showroom (supports 2.1, 3.0, 3.1)
 *
 * PUB-only. DOM is absent entirely for FREE and PRO tiers (no HTML comment).
 *
 * Provides:
 *   - Global ONIX settings (sender info, default language, publisher name,
 *     include-drafts toggle)
 *   - Export button: streams ONIX short-tag XML file to browser (2.1, 3.0, or 3.1)
 *   - Import file input: parses ONIX XML and reconciles catalog records (2.1, 3.0, or 3.1)
 *
 * Save flow:   admin_init handler (nonce: mbs_onix_settings_save / mbs_onix_settings_nonce)
 * Export flow: admin_init handler (nonce: mbs_onix_export / mbs_onix_export_nonce)
 * Import flow: admin_init handler (nonce: mbs_onix_import / mbs_onix_import_nonce)
 *
 * Spec: SPRINT-ONIX-EXPORT-IMPORT-Spec.md §4, §7, §8
 *
 * @package    My_Book_Showroom
 * @subpackage Includes/Admin/Tabs
 * @since      1.1.0
 */

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

// phpcs:disable WordPress.Security.ValidatedSanitizedInput -- input sanitized at point of use (sanitize_text_field, absint, wp_kses_post, etc.); false positives from PHPCS not tracing sanitization helpers called before this method
class MBS_Tab_Onix {

	// -------------------------------------------------------------------------
	// Common ISO 639-2/B language codes for the dropdown
	// -------------------------------------------------------------------------

	private const LANGUAGE_OPTIONS = array(
		'eng' => 'English',
		'fre' => 'French',
		'ger' => 'German',
		'spa' => 'Spanish',
		'ita' => 'Italian',
		'por' => 'Portuguese',
		'dut' => 'Dutch',
		'swe' => 'Swedish',
		'nor' => 'Norwegian',
		'dan' => 'Danish',
		'fin' => 'Finnish',
		'pol' => 'Polish',
		'rus' => 'Russian',
		'jpn' => 'Japanese',
		'zho' => 'Chinese',
		'ara' => 'Arabic',
		'kor' => 'Korean',
		'hin' => 'Hindi',
	);

	// -------------------------------------------------------------------------
	// Boot
	// -------------------------------------------------------------------------

	public function __construct() {
		add_action( 'admin_init', array( $this, 'handle_settings_save' ) );
		add_action( 'admin_init', array( $this, 'handle_export' ) );
		add_action( 'admin_init', array( $this, 'handle_import' ) );
	}

	// -------------------------------------------------------------------------
	// Render
	// -------------------------------------------------------------------------

	public function render(): void {
		if ( ! mbs_is_pub() ) {
			return;
		}

		$sender_name    = (string) get_option( 'mbs_setting_onix_sender_name', '' );
		$sender_contact = (string) get_option( 'mbs_setting_onix_sender_contact', '' );
		$sender_email   = (string) get_option( 'mbs_setting_onix_sender_email', '' );
		$default_lang   = (string) get_option( 'mbs_setting_onix_default_language', 'eng' );
		$publisher_name = (string) get_option( 'mbs_setting_onix_publisher_name', '' );
		$include_drafts = (string) get_option( 'mbs_setting_onix_include_drafts', '0' );
		$onix_version   = (string) get_option( 'mbs_setting_onix_version', '3.0' );

		// Copyright Page Defaults (Tab 7).
		$pub_address              = (string) get_option( 'mbs_pub_publisher_address', '' );
		$pub_country              = (string) get_option( 'mbs_pub_country_of_printing', 'United States of America' );
		$pub_copyright_disclaimer = (string) get_option( 'mbs_pub_copyright_disclaimer', '' );

		// Import result transient (displayed once after redirect).
		$import_result = get_transient( 'mbs_onix_import_result_' . get_current_user_id() );
		if ( false !== $import_result ) {
			delete_transient( 'mbs_onix_import_result_' . get_current_user_id() );
		}
		// Pre-compute class constant for template (self:: not available in static closure).
		$language_options = self::LANGUAGE_OPTIONS;
		mbs_get_template_part( 'admin/tab-onix', compact(
			'sender_name', 'sender_contact', 'sender_email',
			'default_lang', 'publisher_name', 'include_drafts', 'onix_version',
			'language_options', 'import_result',
			'pub_address', 'pub_country', 'pub_copyright_disclaimer'
		) );
	}

	// -------------------------------------------------------------------------
	// Asset enqueuing
	// -------------------------------------------------------------------------

	/**
	 * Enqueue assets for the Publisher Tools (ONIX) settings tab.
	 *
	 * Loads mbs-admin-onix.css and mbs-admin-onix-settings.js only when
	 * the ONIX tab is active. Called from MBS_Settings::enqueue_assets()
	 * which delegates to tab objects that implement this method.
	 *
	 * @param string $current_tab Active tab slug.
	 * @return void
	 * @since 1.3.0
	 */
	public function enqueue( string $current_tab ): void {
		if ( 'onix' !== $current_tab ) {
			return;
		}

		wp_enqueue_style(
			'mbs-onix-metabox',
			plugins_url( 'assets/css/mbs-admin-onix.css', MBS_DIR . 'bookshowroom.php' ),
			array(),
			(string) ( @filemtime( MBS_ASSETS_DIR . 'css/mbs-admin-onix.css' ) ?: MBS_VERSION )
		);

		wp_enqueue_script(
			'mbs-onix-settings',
			plugins_url( 'assets/js/adminjs/mbs-admin-onix-settings.js', MBS_DIR . 'bookshowroom.php' ),
			array(),
			(string) ( @filemtime( MBS_ASSETS_DIR . 'js/adminjs/mbs-admin-onix-settings.js' ) ?: MBS_VERSION ),
			true
		);
	}

	// -------------------------------------------------------------------------
	// Settings save handler
	// -------------------------------------------------------------------------

	public function handle_settings_save(): void {
		if ( ! isset( $_POST['mbs_onix_settings_nonce'] ) ) {
			return;
		}
		if ( ! wp_verify_nonce(
			sanitize_text_field( wp_unslash( $_POST['mbs_onix_settings_nonce'] ) ),
			'mbs_onix_settings_save'
		) ) {
			return;
		}
		if ( ! current_user_can( 'manage_options' ) ) {
			return;
		}
		if ( ! mbs_is_pub() ) {
			return;
		}

		update_option( 'mbs_setting_onix_sender_name',
			sanitize_text_field( wp_unslash( $_POST['mbs_onix_sender_name'] ?? '' ) ), false );
		update_option( 'mbs_setting_onix_sender_contact',
			sanitize_text_field( wp_unslash( $_POST['mbs_onix_sender_contact'] ?? '' ) ), false );
		update_option( 'mbs_setting_onix_sender_email',
			sanitize_email( wp_unslash( $_POST['mbs_onix_sender_email'] ?? '' ) ), false );

		$lang_raw = sanitize_text_field( wp_unslash( $_POST['mbs_onix_default_language'] ?? 'eng' ) );
		update_option( 'mbs_setting_onix_default_language',
			MBS_Onix_Field_Map::sanitize_language_code( $lang_raw ), false );

		update_option( 'mbs_setting_onix_publisher_name',
			sanitize_text_field( wp_unslash( $_POST['mbs_onix_publisher_name'] ?? '' ) ), false );
		update_option( 'mbs_setting_onix_include_drafts',
			isset( $_POST['mbs_onix_include_drafts'] ) ? '1' : '0', false );

		$version_raw = sanitize_text_field( wp_unslash( $_POST['mbs_onix_version'] ?? '3.0' ) );
		update_option( 'mbs_setting_onix_version',
			in_array( $version_raw, array( '3.1', '3.0', '2.1' ), true ) ? $version_raw : '3.0', false );

		// Copyright Page Defaults.
		update_option( 'mbs_pub_publisher_address',
			sanitize_textarea_field( wp_unslash( $_POST['mbs_pub_publisher_address'] ?? '' ) ), false );
		update_option( 'mbs_pub_country_of_printing',
			sanitize_text_field( wp_unslash( $_POST['mbs_pub_country_of_printing'] ?? 'United States of America' ) ), false );
		update_option( 'mbs_pub_copyright_disclaimer',
			sanitize_textarea_field( wp_unslash( $_POST['mbs_pub_copyright_disclaimer'] ?? '' ) ), false );

		wp_safe_redirect( add_query_arg( array(
			'page'                    => 'my-book-showroom-settings',
			'tab'                     => 'onix',
			'mbs_onix_settings_saved' => '1',
		), admin_url( 'admin.php' ) ) );
		exit;
	}

	// -------------------------------------------------------------------------
	// Export handler
	// -------------------------------------------------------------------------

	public function handle_export(): void {
		if ( ! isset( $_POST['mbs_onix_export_nonce'] ) ) {
			return;
		}
		if ( ! wp_verify_nonce(
			sanitize_text_field( wp_unslash( $_POST['mbs_onix_export_nonce'] ) ),
			'mbs_onix_export'
		) ) {
			wp_die( esc_html__( 'Security check failed.', 'my-book-showroom' ) );
		}
		if ( ! current_user_can( 'manage_options' ) ) {
			wp_die( esc_html__( 'Insufficient permissions.', 'my-book-showroom' ) );
		}
		if ( ! mbs_is_pub() ) {
			wp_die( esc_html__( 'ONIX export requires a PUB license.', 'my-book-showroom' ) );
		}

		$include_drafts = '1' === get_option( 'mbs_setting_onix_include_drafts', '0' );
		$onix_version   = (string) get_option( 'mbs_setting_onix_version', '3.0' );
		if ( '2.1' === $onix_version ) {
			$exporter = new MBS_Onix_Exporter_21();
		} elseif ( '3.1' === $onix_version ) {
			$exporter = new MBS_Onix_Exporter_31();
		} else {
			$exporter = new MBS_Onix_Exporter_30();
		}
		$exporter->export_to_browser( $include_drafts );
		exit;
	}

	// -------------------------------------------------------------------------
	// Import handler
	// -------------------------------------------------------------------------

	public function handle_import(): void {
		if ( ! isset( $_POST['mbs_onix_import_nonce'] ) ) {
			return;
		}
		if ( ! wp_verify_nonce(
			sanitize_text_field( wp_unslash( $_POST['mbs_onix_import_nonce'] ) ),
			'mbs_onix_import'
		) ) {
			wp_die( esc_html__( 'Security check failed.', 'my-book-showroom' ) );
		}
		if ( ! current_user_can( 'manage_options' ) ) {
			wp_die( esc_html__( 'Insufficient permissions.', 'my-book-showroom' ) );
		}
		if ( ! mbs_is_pub() ) {
			wp_die( esc_html__( 'ONIX import requires a PUB license.', 'my-book-showroom' ) );
		}

		// File validation.
		if ( empty( $_FILES['mbs_onix_file']['tmp_name'] ) ) {
			wp_die( esc_html__( 'No file was uploaded.', 'my-book-showroom' ) );
		}

		$file      = $_FILES['mbs_onix_file'];
		// R3-009: Use wp_check_filetype_and_ext() (file-content inspection) instead of
		// browser-supplied $file['type'], which is attacker-controlled and untrustworthy.
		$check  = wp_check_filetype_and_ext(
			$file['tmp_name'],
			sanitize_file_name( wp_unslash( $file['name'] ?? '' ) )
		);
		$ext_ok = in_array( $check['ext'] ?? '', array( 'xml' ), true );

		if ( ! $ext_ok ) {
			wp_die( esc_html__( 'Only .xml files are accepted.', 'my-book-showroom' ) );
		}
		if ( (int) ( $file['size'] ?? 0 ) > 10 * 1024 * 1024 ) {
			wp_die( esc_html__( 'File exceeds the 10 MB limit.', 'my-book-showroom' ) );
		}

		// Read file content (from tmp path; not stored in wp-content per Rule S14-4 pattern).
		$xml_string = (string) file_get_contents( $file['tmp_name'] );
		if ( '' === $xml_string ) {
			wp_die( esc_html__( 'The uploaded file is empty.', 'my-book-showroom' ) );
		}

		$importer = new MBS_Onix_Importer();
		$result   = $importer->import( $xml_string );

		// Store result in a per-user transient; display after redirect.
		set_transient( 'mbs_onix_import_result_' . get_current_user_id(), $result, HOUR_IN_SECONDS );

		wp_safe_redirect( add_query_arg( array(
			'page' => 'my-book-showroom-settings',
			'tab'  => 'onix',
		), admin_url( 'admin.php' ) ) );
		exit;
	}
}
