<?php
// DESCRIPTION: Generates realistic sample data for test sync operations based on field
// type definitions from the data source events registry.

namespace SheetWise\Sync;

class TestDataGenerator {

	/**
	 * Generate sample values for a given data source hook
	 *
	 * Returns an associative array of field_key => sample_value based on
	 * the field type definitions from swise_get_data_source_events().
	 *
	 * @since 2.0.0
	 *
	 * @param string $hook The data source hook name (e.g. 'user_register')
	 *
	 * @return array Associative array of field_key => sample_value
	 */
	public function generate( $hook ) {
		$all_events = swise_get_data_source_events();

		if ( ! isset( $all_events[ $hook ] ) ) {
			return [];
		}

		$fields = $all_events[ $hook ];
		$values = [];

		foreach ( $fields as $key => $field ) {
			$type  = $field['type'] ?? 'text';
			$label = $field['label'] ?? $key;

			$values[ $key ] = $this->generate_value( $type, $key, $label );
		}

		/**
		 * Filter the generated test data for a specific hook
		 *
		 * @since 2.0.0
		 *
		 * @param array  $values The generated sample values
		 * @param string $hook   The data source hook name
		 */
		return apply_filters( 'swise_test_data_' . $hook, $values );
	}

	/**
	 * Generate a complete set of values ready for the Sheets API for a specific integration
	 *
	 * Loads the integration, generates sample data for its hook, then maps
	 * through the event_code templates to produce the final row values.
	 *
	 * @since 2.0.0
	 *
	 * @param int $integration_id The integration post ID
	 *
	 * @return array|null Array with 'values', 'sheet_id', 'hook', or null on failure
	 */
	public function generate_for_integration( $integration_id ) {
		$integration = get_post( $integration_id );

		if ( ! $integration ) {
			return null;
		}

		$content = json_decode( $integration->post_content );

		if ( ! $content || empty( $content->source ) || empty( $content->sheet ) || empty( $content->event_codes ) ) {
			return null;
		}

		$hook        = $content->source;
		$sample_data = $this->generate( $hook );

		if ( empty( $sample_data ) ) {
			return null;
		}

		$all_events     = swise_get_data_source_events();
		$default_events = isset( $all_events[ $hook ] ) ? array_keys( $all_events[ $hook ] ) : [];

		// Build the submitted values array in the same order as default events
		$submitted_values = [];
		foreach ( $default_events as $event ) {
			$submitted_values[] = isset( $sample_data[ $event ] ) ? $sample_data[ $event ] : '';
		}

		// Wrap keys in [[ ]]
		$placeholders = array_map(
			function ( $event ) {
				return "[[$event]]";
			},
			$default_events
		);

		// Map through event code templates
		$values = [];
		foreach ( $content->event_codes as $event_code ) {
			$values[] = str_replace( $placeholders, $submitted_values, $event_code );
		}

		return [
			'values'   => $values,
			'sheet_id' => $content->sheet,
			'hook'     => $hook,
		];
	}

	/**
	 * Generate a complete set of values ready for the Sheets API from inline config
	 *
	 * Used by the test sync endpoint when the integration hasn't been saved yet
	 * (e.g. on the create form). Accepts the same data that would normally be
	 * read from the integration post.
	 *
	 * @since 2.0.0
	 *
	 * @param string $source      The data source hook name (e.g. 'user_register')
	 * @param string $sheet_id    The Google Spreadsheet ID
	 * @param array  $event_codes The value template strings for each column
	 *
	 * @return array|null Array with 'values', 'sheet_id', 'hook', or null on failure
	 */
	public function generate_from_config( $source, $sheet_id, $event_codes ) {
		if ( empty( $source ) || empty( $sheet_id ) || empty( $event_codes ) ) {
			return null;
		}

		$sample_data = $this->generate( $source );

		if ( empty( $sample_data ) ) {
			return null;
		}

		$all_events     = swise_get_data_source_events();
		$default_events = isset( $all_events[ $source ] ) ? array_keys( $all_events[ $source ] ) : [];

		// Build the submitted values array in the same order as default events
		$submitted_values = [];
		foreach ( $default_events as $event ) {
			$submitted_values[] = isset( $sample_data[ $event ] ) ? $sample_data[ $event ] : '';
		}

		// Wrap keys in [[ ]]
		$placeholders = array_map(
			function ( $event ) {
				return "[[$event]]";
			},
			$default_events
		);

		// Map through event code templates
		$values = [];
		foreach ( $event_codes as $event_code ) {
			$values[] = str_replace( $placeholders, $submitted_values, $event_code );
		}

		return [
			'values'   => $values,
			'sheet_id' => $sheet_id,
			'hook'     => $source,
		];
	}

	/**
	 * Generate a sample value based on field type
	 *
	 * @since 2.0.0
	 *
	 * @param string $type  The field type (number, email, text, date-time, textarea, url)
	 * @param string $key   The field key
	 * @param string $label The field label
	 *
	 * @return string
	 */
	private function generate_value( $type, $key, $label ) {
		switch ( $type ) {
			case 'number':
				return (string) wp_rand( 1, 9999 );

			case 'email':
				return 'test.user@example.com';

			case 'date-time':
				return current_time( 'mysql' );

			case 'textarea':
				return sprintf(
					/* translators: %s: field label */
					__( 'Sample content for %s', 'sheet-wise' ),
					$label
				);

			case 'url':
				return 'https://example.com';

			case 'text':
			default:
				return sprintf(
					/* translators: %s: field label */
					__( 'Test %s', 'sheet-wise' ),
					$label
				);
		}
	}
}
