<?php

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

class AIEO_SEO_Verify {

	
	public static function run_sample( $n_products = 8, $n_terms = 5, $n_pages = 3 ) {
		$targets = array();
		foreach ( (array) get_posts( array( 'post_type' => 'product', 'post_status' => 'publish', 'numberposts' => (int) $n_products, 'fields' => 'ids', 'suppress_filters' => false, 'no_found_rows' => true ) ) as $id ) {
			$targets[] = array( 'product', (int) $id );
		}
		$terms = get_terms( array( 'taxonomy' => 'product_cat', 'hide_empty' => true, 'number' => (int) $n_terms, 'fields' => 'ids' ) );
		if ( ! is_wp_error( $terms ) ) {
			foreach ( (array) $terms as $id ) {
				$targets[] = array( 'product_cat', (int) $id );
			}
		}
		foreach ( (array) get_posts( array( 'post_type' => 'page', 'post_status' => 'publish', 'numberposts' => (int) $n_pages, 'fields' => 'ids', 'suppress_filters' => false, 'no_found_rows' => true ) ) as $id ) {
			$targets[] = array( 'page', (int) $id );
		}

		$rows = array();
		$mismatch = 0;
		$canon_drift = 0;
		foreach ( $targets as $t ) {
			$pv = class_exists( 'AIEO_SEO_Head_Builder' ) ? AIEO_SEO_Head_Builder::preview( $t[0], $t[1] ) : null;
			if ( ! is_array( $pv ) ) {
				continue;
			}
			$live = self::fetch_live( $pv['permalink'] );
			$t_ok = self::norm( $pv['title'] ) === self::norm( $live['title'] );
			$c_ok = self::norm( $pv['canonical'] ) === self::norm( $live['canonical'] );
			$r_ok = self::norm( $pv['robots'] ) === self::norm( $live['robots'] );
			$canon_self = ( self::norm( $pv['canonical'] ) === self::norm( $pv['permalink'] ) );
			if ( ! $t_ok || ! $c_ok ) {
				$mismatch++;
			}
			if ( ! $canon_self ) {
				$canon_drift++;
			}
			$rows[] = array(
				'object'        => $pv['object_type'] . ' #' . $pv['object_id'] . ' — ' . $pv['name'],
				'url'           => $pv['permalink'],
				'title_aieo'    => $pv['title'],
				'title_live'    => $live['title'],
				'title_ok'      => $t_ok,
				'canon_aieo'    => $pv['canonical'],
				'canon_live'    => $live['canonical'],
				'canon_ok'      => $c_ok,
				'robots_aieo'   => $pv['robots'],
				'robots_live'   => $live['robots'],
				'robots_ok'     => $r_ok,
				'schema_aieo'   => implode( ', ', (array) $pv['schema_types'] ),
				'schema_live'   => $live['schema_type'],
				'canon_self_ok' => $canon_self,
				'fetch_ok'      => $live['ok'],
			);
		}
		return array(
			'rows'    => $rows,
			'summary' => array(
				'checked'      => count( $rows ),
				'mismatches'   => $mismatch,
				'canon_drift'  => $canon_drift,
			),
		);
	}

	
	private static function fetch_live( $url ) {
		$out = array( 'ok' => false, 'title' => '', 'canonical' => '', 'robots' => '', 'schema_type' => '' );
		if ( '' === (string) $url ) {
			return $out;
		}
		$resp = wp_remote_get( $url, array( 'timeout' => 12, 'redirection' => 2, 'sslverify' => false, 'headers' => array( 'Accept' => 'text/html' ) ) );
		if ( is_wp_error( $resp ) || 200 !== (int) wp_remote_retrieve_response_code( $resp ) ) {
			return $out;
		}
		$html = (string) wp_remote_retrieve_body( $resp );
		$head = ( false !== ( $p = stripos( $html, '</head>' ) ) ) ? substr( $html, 0, $p ) : $html;
		$out['ok'] = true;
		if ( preg_match( '#<title[^>]*>(.*?)</title>#is', $head, $m ) ) {
			$out['title'] = trim( html_entity_decode( wp_strip_all_tags( $m[1] ), ENT_QUOTES ) );
		}
		if ( preg_match( '#<link[^>]+rel=["\']canonical["\'][^>]*href=["\']([^"\']+)#i', $head, $m )
			|| preg_match( '#<link[^>]+href=["\']([^"\']+)["\'][^>]*rel=["\']canonical#i', $head, $m ) ) {
			$out['canonical'] = html_entity_decode( $m[1], ENT_QUOTES );
		}
		if ( preg_match( '#<meta[^>]+name=["\']robots["\'][^>]*content=["\']([^"\']+)#i', $head, $m ) ) {
			$out['robots'] = trim( $m[1] );
		}
		if ( preg_match( '#"@type"\s*:\s*"([A-Za-z]*Product[A-Za-z]*)"#', $head, $m ) ) {
			$out['schema_type'] = $m[1];
		} elseif ( preg_match( '#"@type"\s*:\s*"(CollectionPage|WebPage|Article|ProductGroup)"#', $head, $m ) ) {
			$out['schema_type'] = $m[1];
		}
		return $out;
	}

	private static function norm( $s ) {
		return trim( preg_replace( '/\s+/', ' ', (string) $s ) );
	}
}
