<?php
/**
 * Import mock event data from JSON files into WordPress custom post types.
 *
 * Can be triggered:
 *   1. On theme activation (auto-import if no events exist)
 *   2. Via the admin Tools > Import Events page
 *   3. Via WP-CLI: wp eval 'northfield_import_events();'
 *
 * @package Northfield_Theatre
 * @since 1.0.0
 */

/**
 * Import all events and instances from JSON into WordPress CPTs.
 *
 * @param bool $force If true, delete existing imported events first.
 * @return array Summary of what was imported.
 */
function northfield_import_events( $force = false ) {
	$events    = northfield_load_json( 'events.json' );
	$instances = northfield_load_json( 'instances.json' );

	if ( empty( $events ) ) {
		return array( 'error' => 'No events found in events.json' );
	}

	$summary = array(
		'events_created'    => 0,
		'events_skipped'    => 0,
		'instances_created' => 0,
		'errors'            => array(),
	);

	// If force import, delete existing imported events.
	if ( $force ) {
		northfield_delete_imported_events();
	}

	// Ensure taxonomy terms exist.
	northfield_create_default_event_categories();

	foreach ( $events as $event_data ) {
		// Check if event already imported.
		$existing = get_posts( array(
			'post_type'   => 'nt_event',
			'meta_key'    => '_nt_event_json_id',
			'meta_value'  => $event_data['id'],
			'numberposts' => 1,
			'post_status' => 'any',
		) );

		if ( ! empty( $existing ) && ! $force ) {
			$summary['events_skipped']++;
			continue;
		}

		// Create the event post.
		$post_id = wp_insert_post( array(
			'post_type'    => 'nt_event',
			'post_title'   => $event_data['name'],
			'post_name'    => $event_data['slug'],
			'post_content' => northfield_convert_description_to_blocks( $event_data['description'] ),
			'post_excerpt' => $event_data['summary'],
			'post_status'  => 'publish',
		) );

		if ( is_wp_error( $post_id ) ) {
			$summary['errors'][] = sprintf( 'Failed to create event "%s": %s', $event_data['name'], $post_id->get_error_message() );
			continue;
		}

		// Set meta fields.
		update_post_meta( $post_id, '_nt_event_json_id', $event_data['id'] );
		update_post_meta( $post_id, '_nt_summary', $event_data['summary'] );
		update_post_meta( $post_id, '_nt_age_guidance', $event_data['ageGuidance'] );
		update_post_meta( $post_id, '_nt_run_time', (int) $event_data['runTime'] );
		update_post_meta( $post_id, '_nt_content_warnings', implode( ', ', $event_data['warnings'] ) );
		update_post_meta( $post_id, '_nt_venue', $event_data['venue'] );
		update_post_meta( $post_id, '_nt_min_price', (float) $event_data['minPrice'] );
		update_post_meta( $post_id, '_nt_max_price', (float) $event_data['maxPrice'] );
		update_post_meta( $post_id, '_nt_is_featured', $event_data['featured'] ? '1' : '0' );
		update_post_meta( $post_id, '_nt_sale_status', $event_data['saleStatus'] );
		update_post_meta( $post_id, '_nt_availability', $event_data['availability'] );

		// Set category taxonomy.
		wp_set_object_terms( $post_id, $event_data['category'], 'event_category' );

		// Set tags.
		if ( ! empty( $event_data['tags'] ) ) {
			wp_set_object_terms( $post_id, $event_data['tags'], 'post_tag' );
		}

		$summary['events_created']++;

		// Import instances for this event.
		foreach ( $instances as $instance_data ) {
			if ( $instance_data['eventId'] !== $event_data['id'] ) {
				continue;
			}

			$datetime     = new DateTime( $instance_data['datetime'] );
			$instance_title = $event_data['name'] . ' — ' . $datetime->format( 'D j M Y, g:ia' );

			$instance_post_id = wp_insert_post( array(
				'post_type'   => 'nt_instance',
				'post_title'  => $instance_title,
				'post_status' => 'publish',
			) );

			if ( is_wp_error( $instance_post_id ) ) {
				$summary['errors'][] = sprintf( 'Failed to create instance "%s": %s', $instance_data['id'], $instance_post_id->get_error_message() );
				continue;
			}

			update_post_meta( $instance_post_id, '_nt_instance_json_id', $instance_data['id'] );
			update_post_meta( $instance_post_id, '_nt_event_json_id', $instance_data['eventId'] );
			update_post_meta( $instance_post_id, '_nt_datetime', $instance_data['datetime'] );
			update_post_meta( $instance_post_id, '_nt_venue', $instance_data['venue'] );
			update_post_meta( $instance_post_id, '_nt_availability', $instance_data['availability'] );
			update_post_meta( $instance_post_id, '_nt_available_seats', (int) $instance_data['availableSeats'] );
			update_post_meta( $instance_post_id, '_nt_total_seats', (int) $instance_data['totalSeats'] );
			update_post_meta( $instance_post_id, '_nt_sale_status', $instance_data['saleStatus'] );

			$summary['instances_created']++;
		}
	}

	return $summary;
}

/**
 * Convert a plain-text description (with \n\n paragraph breaks) to
 * Gutenberg paragraph blocks.
 *
 * @param string $description The plain text description.
 * @return string Gutenberg block markup.
 */
function northfield_convert_description_to_blocks( $description ) {
	$paragraphs = preg_split( '/\n\n+/', $description );
	$blocks     = array();

	foreach ( $paragraphs as $paragraph ) {
		$paragraph = trim( $paragraph );
		if ( ! empty( $paragraph ) ) {
			$blocks[] = '<!-- wp:paragraph -->';
			$blocks[] = '<p>' . esc_html( $paragraph ) . '</p>';
			$blocks[] = '<!-- /wp:paragraph -->';
			$blocks[] = '';
		}
	}

	return implode( "\n", $blocks );
}

/**
 * Delete all imported events and instances.
 *
 * Used before a force re-import.
 */
function northfield_delete_imported_events() {
	$post_types = array( 'nt_event', 'nt_instance' );

	foreach ( $post_types as $post_type ) {
		$posts = get_posts( array(
			'post_type'   => $post_type,
			'numberposts' => -1,
			'post_status' => 'any',
			'fields'      => 'ids',
		) );

		foreach ( $posts as $post_id ) {
			wp_delete_post( $post_id, true );
		}
	}
}

/**
 * Auto-import events on theme activation if none exist.
 */
function northfield_maybe_import_on_activation() {
	$existing = get_posts( array(
		'post_type'   => 'nt_event',
		'numberposts' => 1,
		'post_status' => 'any',
	) );

	if ( empty( $existing ) ) {
		northfield_import_events();
	}
}
add_action( 'after_switch_theme', 'northfield_maybe_import_on_activation', 20 );

/**
 * Add an admin page under Tools for manual import.
 */
function northfield_add_import_admin_page() {
	add_management_page(
		__( 'Import Events', 'northfield-theatre' ),
		__( 'Import Events', 'northfield-theatre' ),
		'manage_options',
		'northfield-import-events',
		'northfield_import_admin_page_render'
	);
}
add_action( 'admin_menu', 'northfield_add_import_admin_page' );

/**
 * Render the admin import page.
 */
function northfield_import_admin_page_render() {
	$summary = null;

	if ( isset( $_POST['northfield_import_action'] ) && check_admin_referer( 'northfield_import_events' ) ) {
		$force   = isset( $_POST['force_import'] );
		$summary = northfield_import_events( $force );
	}

	?>
	<div class="wrap">
		<h1><?php esc_html_e( 'Import Northfield Theatre Events', 'northfield-theatre' ); ?></h1>
		<p><?php esc_html_e( 'Import event data from the theme\'s JSON mock data files into WordPress custom post types.', 'northfield-theatre' ); ?></p>

		<?php if ( $summary ) : ?>
			<div class="notice notice-success">
				<p>
					<strong><?php esc_html_e( 'Import complete:', 'northfield-theatre' ); ?></strong>
					<?php
					printf(
						/* translators: %1$d: events created, %2$d: events skipped, %3$d: instances created */
						esc_html__( '%1$d events created, %2$d events skipped, %3$d instances created.', 'northfield-theatre' ),
						$summary['events_created'],
						$summary['events_skipped'],
						$summary['instances_created']
					);
					?>
				</p>
				<?php if ( ! empty( $summary['errors'] ) ) : ?>
					<ul>
						<?php foreach ( $summary['errors'] as $error ) : ?>
							<li style="color: red;"><?php echo esc_html( $error ); ?></li>
						<?php endforeach; ?>
					</ul>
				<?php endif; ?>
			</div>
		<?php endif; ?>

		<?php
		$event_count    = wp_count_posts( 'nt_event' );
		$instance_count = wp_count_posts( 'nt_instance' );
		$published_events    = isset( $event_count->publish ) ? $event_count->publish : 0;
		$published_instances = isset( $instance_count->publish ) ? $instance_count->publish : 0;
		?>
		<p>
			<?php
			printf(
				/* translators: %1$d: event count, %2$d: instance count */
				esc_html__( 'Currently in database: %1$d events, %2$d instances.', 'northfield-theatre' ),
				$published_events,
				$published_instances
			);
			?>
		</p>

		<form method="post">
			<?php wp_nonce_field( 'northfield_import_events' ); ?>
			<table class="form-table">
				<tr>
					<th scope="row"><?php esc_html_e( 'Force re-import', 'northfield-theatre' ); ?></th>
					<td>
						<label>
							<input type="checkbox" name="force_import" value="1" />
							<?php esc_html_e( 'Delete all existing events and instances before importing. This cannot be undone.', 'northfield-theatre' ); ?>
						</label>
					</td>
				</tr>
			</table>
			<p class="submit">
				<button type="submit" name="northfield_import_action" value="1" class="button button-primary">
					<?php esc_html_e( 'Import Events', 'northfield-theatre' ); ?>
				</button>
			</p>
		</form>
	</div>
	<?php
}
