<?php
/**
 * One-shot repair endpoint for rebuilding theme setup when activation
 * hooks didn't run cleanly the first time.
 *
 * Visit:  /wp-admin/admin.php?page=northfield-repair
 *
 * The page checks what's missing and shows a single "Run repair" button.
 * Actions:
 *   1. Create missing content pages with correct templates.
 *   2. Rebuild the Primary + Footer navigation menus.
 *   3. Set the static front page + posts page.
 *   4. Re-import events (covers Moorside + anything newly added to JSON).
 *   5. Flush rewrite rules so CPT + custom page URLs resolve.
 *
 * All steps are idempotent — safe to run multiple times.
 *
 * @package Northfield_Theatre
 * @since 1.0.0
 */

/**
 * Register the repair admin page under Tools.
 */
function northfield_register_repair_page() {
	add_management_page(
		__( 'Northfield Repair', 'northfield-theatre' ),
		__( 'Northfield Repair', 'northfield-theatre' ),
		'manage_options',
		'northfield-repair',
		'northfield_render_repair_page'
	);
}
add_action( 'admin_menu', 'northfield_register_repair_page' );

/**
 * Render the repair page UI + handle the POST action.
 */
function northfield_render_repair_page() {
	if ( ! current_user_can( 'manage_options' ) ) {
		wp_die( esc_html__( 'You do not have permission to access this page.', 'northfield-theatre' ) );
	}

	$result = null;
	if ( isset( $_POST['northfield_repair_action'] ) && check_admin_referer( 'northfield_repair' ) ) {
		$result = northfield_run_repair();
	}

	echo '<div class="wrap">';
	echo '<h1>Northfield Theatre — Setup Repair</h1>';
	echo '<p>This tool rebuilds the theme\'s content pages, navigation menus, front page configuration, and event import. Safe to run any number of times.</p>';

	if ( $result ) {
		echo '<div class="notice notice-success"><p><strong>Repair complete.</strong></p><ul>';
		foreach ( $result as $line ) {
			echo '<li>' . esc_html( $line ) . '</li>';
		}
		echo '</ul></div>';
	}

	// Show current state.
	$state = northfield_repair_state();
	echo '<h2>Current state</h2>';
	echo '<table class="widefat striped" style="max-width:600px"><tbody>';
	foreach ( $state as $label => $value ) {
		echo '<tr><th scope="row">' . esc_html( $label ) . '</th><td>' . esc_html( $value ) . '</td></tr>';
	}
	echo '</tbody></table>';

	echo '<form method="post" style="margin-top:1.5em">';
	wp_nonce_field( 'northfield_repair' );
	echo '<button type="submit" name="northfield_repair_action" value="1" class="button button-primary button-hero">Run repair</button>';
	echo '</form>';
	echo '</div>';
}

/**
 * Summary of the current setup state for the admin UI.
 *
 * @return array Label => value pairs.
 */
function northfield_repair_state() {
	$required_pages = array(
		'home', 'whats-on', 'visit', 'access', 'basket', 'checkout',
		'seating-plan', 'our-story', 'contact', 'moorside', 'news',
	);
	$missing = array();
	foreach ( $required_pages as $slug ) {
		if ( ! get_page_by_path( $slug ) ) {
			$missing[] = $slug;
		}
	}

	$nav_menus = wp_get_nav_menus();
	$locations = get_theme_mod( 'nav_menu_locations', array() );

	$events    = wp_count_posts( 'nt_event' );
	$instances = wp_count_posts( 'nt_instance' );

	$front_page_id = (int) get_option( 'page_on_front' );
	$front_page    = $front_page_id ? get_post( $front_page_id ) : null;

	$posts_page_id = (int) get_option( 'page_for_posts' );
	$posts_page    = $posts_page_id ? get_post( $posts_page_id ) : null;

	return array(
		'Active theme'       => get_stylesheet(),
		'Pages required'     => count( $required_pages ) . ' (' . ( count( $required_pages ) - count( $missing ) ) . ' present)',
		'Pages missing'      => $missing ? implode( ', ', $missing ) : 'none',
		'Nav menus'          => $nav_menus ? count( $nav_menus ) . ': ' . implode( ', ', wp_list_pluck( $nav_menus, 'name' ) ) : 'none',
		'Menu locations set' => $locations ? implode( ', ', array_keys( $locations ) ) : 'none',
		'Front page'         => $front_page ? $front_page->post_title . ' (#' . $front_page->ID . ')' : 'not set (show_on_front: ' . get_option( 'show_on_front' ) . ')',
		'Posts page'         => $posts_page ? $posts_page->post_title . ' (#' . $posts_page->ID . ')' : 'not set',
		'Events imported'    => isset( $events->publish ) ? $events->publish : 0,
		'Instances imported' => isset( $instances->publish ) ? $instances->publish : 0,
		'Events in JSON'     => count( northfield_load_json( 'events.json' ) ),
		'Instances in JSON'  => count( northfield_load_json( 'instances.json' ) ),
	);
}

/**
 * Execute the full repair process.
 *
 * @return string[] Log lines describing what was done.
 */
function northfield_run_repair() {
	$log = array();

	// 1. Ensure all content pages exist with correct templates.
	$pages = array(
		'home'         => array( 'Home', '' ),
		'whats-on'     => array( "What's On", 'page-whats-on.php' ),
		'visit'        => array( 'Your Visit', 'page-visit.php' ),
		'access'       => array( 'Access', 'page-access.php' ),
		'basket'       => array( 'Basket', 'page-basket.php' ),
		'checkout'     => array( 'Checkout', 'page-checkout.php' ),
		'seating-plan' => array( 'Seating Plan', 'page-seating.php' ),
		'our-story'    => array( 'Our Story', 'page-our-story.php' ),
		'contact'      => array( 'Contact', 'page-contact.php' ),
		'moorside'    => array( 'Moorside Town Hall', 'page-moorside.php' ),
		'news'         => array( 'News', '' ),
		'take-part'    => array( 'Take Part', 'page-take-part.php' ),
		'hire'         => array( 'Hire', 'page-hire.php' ),
	);

	$page_ids = array();
	foreach ( $pages as $slug => $info ) {
		list( $title, $template ) = $info;
		$existing = get_page_by_path( $slug );
		if ( $existing ) {
			$page_ids[ $slug ] = $existing->ID;
			// Ensure template is correct.
			if ( $template ) {
				$current_template = get_post_meta( $existing->ID, '_wp_page_template', true );
				if ( $current_template !== $template ) {
					update_post_meta( $existing->ID, '_wp_page_template', $template );
					$log[] = "Updated template on '$slug' → $template";
				}
			}
		} else {
			$page_id = wp_insert_post( array(
				'post_title'   => $title,
				'post_name'    => $slug,
				'post_type'    => 'page',
				'post_status'  => 'publish',
				'post_content' => '',
			) );
			if ( ! is_wp_error( $page_id ) ) {
				if ( $template ) {
					update_post_meta( $page_id, '_wp_page_template', $template );
				}
				$page_ids[ $slug ] = $page_id;
				$log[] = "Created page '$slug'" . ( $template ? " (template: $template)" : '' );
			} else {
				$log[] = "ERROR creating '$slug': " . $page_id->get_error_message();
			}
		}
	}

	// 2. Static front page + posts page.
	if ( ! empty( $page_ids['home'] ) ) {
		update_option( 'show_on_front', 'page' );
		update_option( 'page_on_front', $page_ids['home'] );
		$log[] = 'Set static front page → Home (#' . $page_ids['home'] . ')';
	}
	if ( ! empty( $page_ids['news'] ) ) {
		update_option( 'page_for_posts', $page_ids['news'] );
		$log[] = 'Set posts page → News (#' . $page_ids['news'] . ')';
	}

	// 3. Rebuild primary + footer menus.
	$primary = wp_get_nav_menu_object( 'Primary Navigation' );
	if ( ! $primary ) {
		$primary_id = wp_create_nav_menu( 'Primary Navigation' );
		if ( ! is_wp_error( $primary_id ) ) {
			$log[] = "Created 'Primary Navigation' menu";
			northfield_populate_primary_menu( $primary_id, $page_ids );
			$log[] = 'Populated Primary Navigation with menu items';
		}
	} else {
		$primary_id = $primary->term_id;
	}

	$footer = wp_get_nav_menu_object( 'Footer Navigation' );
	if ( ! $footer ) {
		$footer_id = wp_create_nav_menu( 'Footer Navigation' );
		if ( ! is_wp_error( $footer_id ) ) {
			$log[] = "Created 'Footer Navigation' menu";
			$footer_items = array(
				'whats-on', 'visit', 'access', 'our-story', 'news', 'contact',
			);
			$footer_titles = array(
				'whats-on' => "What's On",
				'visit'    => 'Your Visit',
				'access'   => 'Access',
				'our-story' => 'Our Story',
				'news'     => 'News',
				'contact'  => 'Contact',
			);
			$pos = 0;
			foreach ( $footer_items as $slug ) {
				if ( empty( $page_ids[ $slug ] ) ) {
					continue;
				}
				$pos += 10;
				wp_update_nav_menu_item( $footer_id, 0, array(
					'menu-item-title'     => $footer_titles[ $slug ],
					'menu-item-object-id' => $page_ids[ $slug ],
					'menu-item-object'    => 'page',
					'menu-item-type'      => 'post_type',
					'menu-item-status'    => 'publish',
					'menu-item-position'  => $pos,
				) );
			}
			$log[] = 'Populated Footer Navigation with menu items';
		}
	} else {
		$footer_id = $footer->term_id;
	}

	// 4. Assign menu locations.
	$locations = get_theme_mod( 'nav_menu_locations', array() );
	if ( ! empty( $primary_id ) ) {
		$locations['primary'] = (int) $primary_id;
	}
	if ( ! empty( $footer_id ) ) {
		$locations['footer'] = (int) $footer_id;
	}
	set_theme_mod( 'nav_menu_locations', $locations );
	$log[] = 'Assigned menu locations: primary + footer';

	// 5. Re-import events to pick up any newly added ones in events.json
	//    (uses same logic as import-events.php; skip-if-exists per json_id).
	if ( function_exists( 'northfield_import_events' ) ) {
		$summary = northfield_import_events();
		if ( ! empty( $summary['events_created'] ) || ! empty( $summary['instances_created'] ) ) {
			$log[] = sprintf(
				'Imported: %d new events, %d new instances (skipped %d existing)',
				$summary['events_created'],
				$summary['instances_created'],
				$summary['events_skipped']
			);
		} else {
			$log[] = 'Event import: everything already in sync';
		}
	}

	// 6. Flush rewrite rules so CPT + page URLs resolve.
	flush_rewrite_rules();
	$log[] = 'Flushed rewrite rules';

	// Mark the admin_init guard so it doesn't repeat this work.
	update_option( 'northfield_pages_ensured_v1', 1 );

	return $log;
}

/**
 * Populate the Primary Navigation menu with items. Called from
 * northfield_run_repair() after the menu is created.
 *
 * @param int   $menu_id  The menu ID to populate.
 * @param array $page_ids Map of page slug → post ID.
 */
function northfield_populate_primary_menu( $menu_id, $page_ids ) {
	$items = array(
		array(
			'title' => "What's On",
			'slug'  => 'whats-on',
		),
		array(
			'title'    => 'Your Visit',
			'slug'     => 'visit',
			'children' => array(
				array( 'title' => 'Getting Here', 'url' => home_url( '/visit/#getting-here' ) ),
				array( 'title' => 'Seating Plan', 'slug' => 'seating-plan' ),
				array( 'title' => 'Access', 'slug' => 'access' ),
				array( 'title' => 'Eat & Drink', 'url' => home_url( '/visit/#eat-drink' ) ),
				array( 'title' => 'FAQs', 'url' => home_url( '/visit/#faqs' ) ),
			),
		),
		array( 'title' => 'Take Part', 'slug' => 'take-part' ),
		array(
			'title'    => 'Our Story',
			'slug'     => 'our-story',
			'children' => array(
				array( 'title' => 'About Northfield', 'slug' => 'our-story' ),
				array( 'title' => 'Moorside Town Hall', 'slug' => 'moorside' ),
				array( 'title' => 'Contact', 'slug' => 'contact' ),
			),
		),
		array( 'title' => 'News', 'slug' => 'news' ),
		array( 'title' => 'Hire', 'slug' => 'hire' ),
	);

	$position = 0;
	foreach ( $items as $item ) {
		$position += 10;
		$parent_db_id = 0;

		if ( ! empty( $item['slug'] ) && ! empty( $page_ids[ $item['slug'] ] ) ) {
			$parent_db_id = wp_update_nav_menu_item( $menu_id, 0, array(
				'menu-item-title'     => $item['title'],
				'menu-item-object-id' => $page_ids[ $item['slug'] ],
				'menu-item-object'    => 'page',
				'menu-item-type'      => 'post_type',
				'menu-item-status'    => 'publish',
				'menu-item-position'  => $position,
			) );
		} elseif ( ! empty( $item['url'] ) ) {
			$parent_db_id = wp_update_nav_menu_item( $menu_id, 0, array(
				'menu-item-title'    => $item['title'],
				'menu-item-url'      => $item['url'],
				'menu-item-type'     => 'custom',
				'menu-item-status'   => 'publish',
				'menu-item-position' => $position,
			) );
		}

		if ( ! empty( $item['children'] ) && ! is_wp_error( $parent_db_id ) ) {
			foreach ( $item['children'] as $child ) {
				$position += 10;
				if ( ! empty( $child['slug'] ) && ! empty( $page_ids[ $child['slug'] ] ) ) {
					wp_update_nav_menu_item( $menu_id, 0, array(
						'menu-item-title'      => $child['title'],
						'menu-item-object-id'  => $page_ids[ $child['slug'] ],
						'menu-item-object'     => 'page',
						'menu-item-type'       => 'post_type',
						'menu-item-parent-id'  => $parent_db_id,
						'menu-item-status'     => 'publish',
						'menu-item-position'   => $position,
					) );
				} elseif ( ! empty( $child['url'] ) ) {
					wp_update_nav_menu_item( $menu_id, 0, array(
						'menu-item-title'     => $child['title'],
						'menu-item-url'       => $child['url'],
						'menu-item-type'      => 'custom',
						'menu-item-parent-id' => $parent_db_id,
						'menu-item-status'    => 'publish',
						'menu-item-position'  => $position,
					) );
				}
			}
		}
	}
}
