<?php
/**
 * Pre-flight check: list pages on this site that have
 * `hero_style = 'default'` but are NOT Services descendants.
 *
 * These are the pages whose visible hero behavior changes when the
 * Services-descendant gate is introduced in `isServicesDescendant()`
 * (see `lib/extras.php`).
 *
 * Run from the WordPress root:
 *
 *     php bin/check-affected-pages.php
 *
 * Or, if the WordPress install is at a different path, point
 * `wp-load.php` resolution accordingly (see the bootstrap below).
 *
 * @package CWC
 */

if ( ! defined( 'ABSPATH' ) ) {
	// We are not inside WordPress. Try to bootstrap from the WordPress root.
	// This script lives at wp-content/themes/<theme>/bin/, so the WordPress
	// root (which contains wp-load.php) is four levels up.
	$wp_load = dirname( __DIR__, 4 ) . '/wp-load.php';
	if ( ! file_exists( $wp_load ) ) {
		fwrite( STDERR, "Could not locate wp-load.php at {$wp_load}. Run this script from the WordPress root or set up ABSPATH first.\n" );
		exit( 1 );
	}
	require_once $wp_load;
}

if ( ! function_exists( 'get_field' ) ) {
	fwrite( STDERR, "ACF is not active; this script needs Advanced Custom Fields to read `hero_style`.\n" );
	exit( 1 );
}

if ( ! function_exists( 'CWC\\isServicesDescendant' ) ) {
	fwrite( STDERR, "CWC\\isServicesDescendant() is not loaded. Make sure the active theme is community-works-collaborative.\n" );
	exit( 1 );
}

/**
 * Query every published page and check whether its hero would be affected.
 */
function cwc_check_affected_pages() {
	$query = new WP_Query(
		array(
			'post_type'      => 'page',
			'post_status'    => 'publish',
			'posts_per_page' => -1,
			'orderby'        => 'menu_order title',
			'order'          => 'ASC',
			'no_found_rows'  => true,
		)
	);

	$affected = array();
	$skipped_due_to_error = 0;

	while ( $query->have_posts() ) {
		$query->the_post();
		$post = get_post();

		$hero_style = get_field( 'hero_style', $post->ID );

		if ( 'default' !== $hero_style ) {
			continue;
		}

		$is_services_descendant = \CWC\isServicesDescendant( $post );
		if ( is_wp_error( $is_services_descendant ) ) {
			++$skipped_due_to_error;
			continue;
		}

		if ( $is_services_descendant ) {
			continue;
		}

		$affected[] = array(
			'ID'    => (int) $post->ID,
			'title' => get_the_title( $post ),
			'url'   => get_permalink( $post ),
			'slug'  => $post->post_name,
		);
	}

	wp_reset_postdata();

	return array(
		'affected'              => $affected,
		'skipped_due_to_error'  => $skipped_due_to_error,
	);
}

$result = cwc_check_affected_pages();
$affected = $result['affected'];

echo "Pages with hero_style = 'default' that are NOT Services descendants\n";
echo "==================================================================\n\n";

if ( empty( $affected ) ) {
	echo "None. Every page that uses the default hero is a Services descendant (or the Services page itself).\n";
} else {
	printf( "Found %d affected page(s):\n\n", count( $affected ) );

	$rows = array();
	$rows[] = array( 'ID', 'Slug', 'Title', 'URL' );

	foreach ( $affected as $page ) {
		$rows[] = array(
			(string) $page['ID'],
			$page['slug'],
			$page['title'],
			$page['url'],
		);
	}

	// Compute column widths for aligned output.
	$widths = array();
	foreach ( array( 0, 1, 2, 3 ) as $col ) {
		$widths[ $col ] = 0;
		foreach ( $rows as $row ) {
			$widths[ $col ] = max( $widths[ $col ], strlen( $row[ $col ] ) );
		}
	}

	$format = '| %-' . $widths[0] . 's | %-' . $widths[1] . 's | %-' . $widths[2] . 's | %-' . $widths[3] . "s |\n";

	$separator = '+';
	foreach ( $widths as $w ) {
		$separator .= str_repeat( '-', $w + 2 ) . '+';
	}
	$separator .= "\n";

	echo $separator;
	foreach ( $rows as $i => $row ) {
		printf( $format, ...$row );
		if ( 0 === $i ) {
			echo $separator;
		}
	}
	echo $separator;
}

if ( $result['skipped_due_to_error'] > 0 ) {
	printf(
		"\nWarning: %d page(s) could not be evaluated due to errors. Re-run with WP_DEBUG enabled for details.\n",
		$result['skipped_due_to_error']
	);
}

echo "\n";
