<?php
/**
 * File Path: includes/admin/tabs/imp-exp/class-mbs-tab-child-import-isbn.php
 *
 * Import / Export Tab — ISBN & API Import Child
 *
 * Handles API importers for ISBN lookup (Google Books, Open Library, Amazon PA-API)
 * and candidate processing. Google Books and Open Library are available on all
 * license tiers (FREE+). Amazon import is PRO-gated.
 *
 * Split from MBS_Tab_Child_Import_API (REF-004, Session 137).
 *
 * @package MyBookShowroom
 * @since   1.1.0
 */

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

// phpcs:disable WordPress.Security.NonceVerification -- nonce verified in parent class verify_save() / check_admin_referer() before $_POST access; PHPCS cannot trace cross-method nonce verification
// 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_Child_Import_ISBN {

	use MBS_Ajax_Import_Export_Guard;

	public function handle_ajax_mbs_import_google_books(): void {
		$this->verify_import_export_request();

		$raw_isbns = sanitize_textarea_field( wp_unslash( $_POST['isbns'] ?? '' ) );
		$isbns     = array_filter( array_map( 'trim', explode( "\n", $raw_isbns ) ) );

		if ( empty( $isbns ) ) {
			wp_send_json_error( array( 'message' => 'No ISBNs provided.' ) );
		}

		$result = MBS_Importer_Google_Books::fetch( $isbns );

		if ( ! $result['success'] ) {
			wp_send_json_error( array( 'message' => $result['error'] ) );
		}

		wp_send_json_success( $result );
	}

	public function handle_ajax_mbs_import_open_library(): void {
		$this->verify_import_export_request();

		$raw_isbns = sanitize_textarea_field( wp_unslash( $_POST['isbns'] ?? '' ) );
		$isbns     = array_filter( array_map( 'trim', explode( "\n", $raw_isbns ) ) );

		if ( empty( $isbns ) ) {
			wp_send_json_error( array( 'message' => 'No ISBNs provided.' ) );
		}

		$result = MBS_Importer_Open_Library::fetch( $isbns );

		if ( ! $result['success'] ) {
			wp_send_json_error( array( 'message' => $result['error'] ) );
		}

		wp_send_json_success( $result );
	}

	public function handle_ajax_mbs_import_amazon(): void {
		$this->verify_import_export_request();

		if ( ! mbs_is_pro() ) {
			wp_send_json_error( array( 'message' => 'Amazon import requires a PRO license.' ) );
		}

		$raw_codes = sanitize_textarea_field( wp_unslash( $_POST['codes'] ?? '' ) );
		$codes     = array_filter( array_map( 'trim', explode( "\n", $raw_codes ) ) );

		if ( empty( $codes ) ) {
			wp_send_json_error( array( 'message' => 'No ASIN/ISBN codes provided.' ) );
		}

		$result = MBS_Importer_Amazon::fetch( $codes );

		if ( ! $result['success'] ) {
			wp_send_json_error( array( 'message' => $result['error'] ) );
		}

		wp_send_json_success( $result );
	}

	/**
	 * Save PA-API credentials (Access Key, Secret Key, Partner Tag).
	 *
	 * Access Key and Secret Key are AES-256-CBC encrypted via MBS_Encryption::encrypt()
	 * before storage per SECURITY.md §2 and §4.
	 * Partner Tag is not a secret and is stored as plain sanitized text.
	 * Fields left blank are skipped — existing values are preserved.
	 */
	public function handle_ajax_mbs_save_amazon_credentials(): void {
		$this->verify_import_export_request();

		if ( ! mbs_is_pro() ) {
			wp_send_json_error( array( 'message' => 'Amazon import requires a PRO license.' ) );
		}

		$access_key  = sanitize_text_field( wp_unslash( $_POST['access_key']  ?? '' ) );
		$secret_key  = sanitize_text_field( wp_unslash( $_POST['secret_key']  ?? '' ) );
		$partner_tag = sanitize_text_field( wp_unslash( $_POST['partner_tag'] ?? '' ) );

		$updated = array();

		if ( '' !== $access_key ) {
			update_option( 'mbs_setting_import_amazon_api_key_encrypted', MBS_Encryption::encrypt( $access_key ) );
			$updated[] = 'access_key';
		}

		if ( '' !== $secret_key ) {
			update_option( 'mbs_setting_import_amazon_api_secret_encrypted', MBS_Encryption::encrypt( $secret_key ) );
			$updated[] = 'secret_key';
		}

		if ( '' !== $partner_tag ) {
			update_option( 'mbs_setting_amazon_partner_tag', $partner_tag );
			$updated[] = 'partner_tag';
		}

		if ( empty( $updated ) ) {
			wp_send_json_error( array( 'message' => __( 'No values provided — nothing was saved.', 'my-book-showroom' ) ) );
		}

		wp_send_json_success( array( 'message' => __( 'Credentials saved.', 'my-book-showroom' ) ) );
	}

	/**
	 * Save Google Books API key (encrypted per Cardinal Rule 2 / SECURITY.md §2).
	 *
	 * Key is stored as mbs_setting_import_google_books_api_key_encrypted via
	 * MBS_Encryption::encrypt(). An empty POST value is rejected; existing key is
	 * preserved if the user navigates away without entering a new value.
	 */
	public function handle_ajax_mbs_save_google_books_api_key(): void {
		$this->verify_import_export_request();

		$api_key = sanitize_text_field( wp_unslash( $_POST['api_key'] ?? '' ) );
		if ( '' === $api_key ) {
			wp_send_json_error( array( 'message' => __( 'API key cannot be empty.', 'my-book-showroom' ) ) );
		}

		update_option( 'mbs_setting_import_google_books_api_key_encrypted', MBS_Encryption::encrypt( $api_key ) );
		wp_send_json_success( array( 'message' => __( 'API key saved.', 'my-book-showroom' ) ) );
	}

	public function handle_ajax_mbs_import_candidates(): void {
		$this->verify_import_export_request();

		$raw = wp_unslash( $_POST['candidates_json'] ?? '' );
		if ( empty( $raw ) ) {
			wp_send_json_error( array( 'message' => 'No candidates received.' ) );
		}

		$candidates = json_decode( $raw, true );
		if ( ! is_array( $candidates ) ) {
			wp_send_json_error( array( 'message' => 'Candidates payload is not valid JSON.' ) );
		}

		$allowed_keys = array_merge(
			MBS_Child_Importer_CSV_Helpers::ACCEPTED_COLUMNS,
			array( 'post_content', 'cover_url', '_source', '_line' )
		);

		$sanitized = array();
		foreach ( $candidates as $c ) {
			if ( ! is_array( $c ) || empty( $c['title'] ) ) {
				continue;
			}
			$clean = array();
			foreach ( $allowed_keys as $key ) {
				if ( isset( $c[ $key ] ) ) {
					$clean[ $key ] = sanitize_text_field( (string) $c[ $key ] );
				}
			}
			if ( isset( $c['post_content'] ) ) {
				$clean['post_content'] = wp_kses_post( $c['post_content'] );
			}
			if ( isset( $c['cover_url'] ) ) {
				$clean['cover_url'] = esc_url_raw( $c['cover_url'] );
			}
			if ( ! empty( $clean['title'] ) ) {
				$sanitized[] = $clean;
			}
		}

		if ( empty( $sanitized ) ) {
			wp_send_json_error( array( 'message' => 'No valid candidates after sanitization.' ) );
		}

		$force_insert_keys = array();
		if ( ! empty( $_POST['force_insert_keys'] ) ) {
			$decoded = json_decode( wp_unslash( $_POST['force_insert_keys'] ), true );
			if ( is_array( $decoded ) ) {
				$force_insert_keys = array_map( 'sanitize_text_field', $decoded );
			}
		}

		$result = MBS_Parent_Importer_CSV::import_candidates( $sanitized, $force_insert_keys );

		if ( ! $result['success'] ) {
			wp_send_json_error( array( 'message' => $result['error'] ) );
		}

		wp_send_json_success( array(
			'inserted'   => $result['inserted'],
			'skipped'    => $result['skipped'],
			'duplicates' => $result['duplicates'],
			'errors'     => $result['errors'],
		) );
	}
}
