<?php

namespace RadiusTheme\RadiusBooking\ExportImport\Exporters;

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

use RadiusTheme\RadiusBooking\ExportImport\Contracts\ExporterInterface;
use RadiusTheme\RadiusBooking\Models\Settings;

/**
 * Class SettingsExporter
 *
 * Exports all plugin settings from wp_options.
 * Bypasses Settings::export() to avoid the double-suffix bug in getAllKeys().
 *
 * @package RadiusTheme\RadiusBooking\ExportImport\Exporters
 */
class SettingsExporter implements ExporterInterface {

	/**
	 * {@inheritDoc}
	 */
	public function getModuleName(): string {
		return 'settings';
	}

	/**
	 * {@inheritDoc}
	 */
	public function count(): int {
		return count( $this->getCleanKeys() );
	}

	/**
	 * {@inheritDoc}
	 *
	 * Returns the settings array directly (not wrapped in an array of records).
	 */
	public function export( int $offset = 0, int $limit = 500 ): array {
		$settings  = new Settings();
		$keys      = $this->getCleanKeys();
		$data      = array();

		foreach ( $keys as $key ) {
			$data[ $key ] = $settings->getSettings( $key );
		}

		return array(
			'exported_at'    => current_time( 'mysql' ),
			'plugin_version' => defined( 'RADIUS_BOOKING_VERSION' ) ? RADIUS_BOOKING_VERSION : '1.0.0',
			'settings'       => $data,
		);
	}

	/**
	 * Get clean setting keys (without prefix AND without _settings suffix).
	 *
	 * Settings::getAllKeys() strips only the 'rtrb_' prefix but keeps the '_settings' suffix,
	 * causing getSettings() to construct 'rtrb_key_settings_settings' (double suffix).
	 * This method strips both so keys are clean like 'statuses', 'dateTime', etc.
	 *
	 * @return array
	 */
	private function getCleanKeys(): array {
		$settings = new Settings();
		$raw_keys = $settings->getAllKeys();

		return array_map(
			function ( $key ) {
				// getAllKeys() returns e.g. 'statuses_settings' — strip the '_settings' suffix.
				return preg_replace( '/_settings$/', '', $key );
			},
			$raw_keys
		);
	}

	/**
	 * {@inheritDoc}
	 */
	public function getDependencies(): array {
		return array();
	}
}
