<?php

namespace RadiusTheme\RadiusBooking\ExportImport;

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

/**
 * Class IdMapper
 *
 * Maps old IDs to new IDs during import to maintain foreign key relationships.
 * Persists across batch requests via WordPress transients.
 *
 * @package RadiusTheme\RadiusBooking\ExportImport
 */
class IdMapper {

	/**
	 * Transient prefix.
	 *
	 * @var string
	 */
	const TRANSIENT_PREFIX = 'rtrb_import_map_';

	/**
	 * Transient expiry in seconds (1 hour).
	 *
	 * @var int
	 */
	const TRANSIENT_EXPIRY = 3600;

	/**
	 * The unique session key for this import.
	 *
	 * @var string
	 */
	private string $session_key;

	/**
	 * The ID mappings: [ module => [ old_id => new_id ] ].
	 *
	 * @var array
	 */
	private array $map = array();

	/**
	 * Constructor.
	 *
	 * @param string $session_key Unique import session identifier.
	 */
	public function __construct( string $session_key ) {
		$this->session_key = $session_key;
		$this->load();
	}

	/**
	 * Add a mapping for a module.
	 *
	 * @param string $module Module name (e.g. 'category').
	 * @param int    $old_id The original ID from the export file.
	 * @param int    $new_id The new ID after import.
	 */
	public function addMapping( string $module, int $old_id, int $new_id ): void {
		if ( ! isset( $this->map[ $module ] ) ) {
			$this->map[ $module ] = array();
		}
		$this->map[ $module ][ $old_id ] = $new_id;
	}

	/**
	 * Get the new ID for an old ID in a given module.
	 *
	 * @param string $module Module name.
	 * @param int    $old_id The original ID.
	 *
	 * @return int|null The new ID, or null if not mapped.
	 */
	public function getNewId( string $module, int $old_id ): ?int {
		return $this->map[ $module ][ $old_id ] ?? null;
	}

	/**
	 * Get all mappings for a module.
	 *
	 * @param string $module Module name.
	 *
	 * @return array Associative array of old_id => new_id.
	 */
	public function getMappings( string $module ): array {
		return $this->map[ $module ] ?? array();
	}

	/**
	 * Get all mappings across all modules.
	 *
	 * @return array
	 */
	public function getAllMappings(): array {
		return $this->map;
	}

	/**
	 * Persist the current mappings to a WordPress transient.
	 */
	public function save(): void {
		set_transient(
			self::TRANSIENT_PREFIX . $this->session_key,
			$this->map,
			self::TRANSIENT_EXPIRY
		);
	}

	/**
	 * Load mappings from the WordPress transient.
	 */
	private function load(): void {
		$data = get_transient( self::TRANSIENT_PREFIX . $this->session_key );
		if ( is_array( $data ) ) {
			$this->map = $data;
		}
	}

	/**
	 * Delete the transient to clean up after import.
	 */
	public function cleanup(): void {
		delete_transient( self::TRANSIENT_PREFIX . $this->session_key );
		$this->map = array();
	}

	/**
	 * Generate a unique session key.
	 *
	 * @return string
	 */
	public static function generateSessionKey(): string {
		return wp_generate_password( 32, false );
	}
}
