<?php

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

if ( class_exists( 'AIEO_SEO_Primary_Term', false ) ) {
	return; 
}

class AIEO_SEO_Primary_Term {

	const CACHE_GROUP = 'aieo_seo';
	const CACHE_TTL   = HOUR_IN_SECONDS;

	
	public static function register() {
		static $done = false;
		if ( $done ) {
			return;
		}
		$done = true;
		if ( self::competitor_active() || ! self::engine_enabled() ) {
			return;
		}
		add_filter( 'post_link_category', array( __CLASS__, 'filter_primary_category' ), 10, 3 );
		add_filter( 'wc_product_post_type_link_product_cat', array( __CLASS__, 'filter_primary_category' ), 10, 3 );
	}

	
	public static function filter_primary_category( $category, $categories = null, $post = null ) {
		$post = get_post( $post );
		if ( ! $post instanceof WP_Post ) {
			return $category;
		}
		$taxonomy = self::canonical_taxonomy_for( (string) $post->post_type );
		if ( '' === $taxonomy ) {
			return $category;
		}
		$cat_id = self::get_primary_cat_id( (string) $post->post_type, (int) $post->ID );
		if ( $cat_id <= 0 ) {
			return $category;
		}
		$term = get_term( $cat_id, $taxonomy );
		if ( ! $term instanceof WP_Term ) {
			return $category;
		}
		
		
		
		
		
		
		
		if ( ! has_term( $cat_id, $taxonomy, $post ) ) {
			return $category;
		}
		return $term;
	}

	
	public static function get_primary_cat_id( $object_type, $object_id ) {
		if ( '' === $object_type || $object_id <= 0 ) {
			return 0;
		}
		$key    = 'pcat:' . $object_type . ':' . $object_id;
		$cached = wp_cache_get( $key, self::CACHE_GROUP );
		if ( false !== $cached ) {
			return (int) $cached;
		}
		global $wpdb;
		$t  = $wpdb->prefix . 'aieo_seo_posts';
		
		$id = $wpdb->get_var( $wpdb->prepare( "SELECT primary_cat_id FROM `{$t}` WHERE object_type = %s AND object_id = %d", $object_type, $object_id ) );
		$id = ( null === $id ) ? 0 : (int) $id;
		wp_cache_set( $key, $id, self::CACHE_GROUP, self::CACHE_TTL );
		return $id;
	}

	
	public static function bust_cache( $object_type, $object_id ) {
		wp_cache_delete( 'pcat:' . (string) $object_type . ':' . (int) $object_id, self::CACHE_GROUP );
	}

	
	public static function canonical_taxonomy_for( $post_type ) {
		if ( 'product' === (string) $post_type ) {
			return taxonomy_exists( 'product_cat' ) ? 'product_cat' : '';
		}
		if ( 'post' === (string) $post_type ) {
			return taxonomy_exists( 'category' ) ? 'category' : '';
		}
		return '';
	}

	
	public static function ensure_deepest_primary( $object_type, $object_id ) {
		$object_type = (string) $object_type;
		$taxonomy    = self::canonical_taxonomy_for( $object_type );
		if ( '' === $taxonomy ) {
			return; 
		}
		$object_id = (int) $object_id;
		if ( $object_id <= 0 || 'publish' !== get_post_status( $object_id ) ) {
			return; 
		}
		if ( self::get_primary_cat_id( $object_type, $object_id ) > 0 ) {
			return; 
		}
		
		
		
		global $wpdb;
		$tbl = $wpdb->prefix . 'aieo_seo_posts';
		
		$canon = $wpdb->get_var( $wpdb->prepare( "SELECT canonical_url FROM `{$tbl}` WHERE object_type = %s AND object_id = %d", $object_type, $object_id ) );
		if ( null !== $canon && '' !== trim( (string) $canon ) ) {
			return;
		}
		$deepest = self::deepest_term_id( $object_id, $taxonomy );
		if ( $deepest > 0 && class_exists( 'AIEO_SEO_Store' ) ) {
			AIEO_SEO_Store::set_primary_term( $object_type, $object_id, $taxonomy, $deepest );
			self::bust_cache( $object_type, $object_id );
		}
	}

	
	public static function deepest_term_id( $object_id, $taxonomy ) {
		$terms = get_the_terms( (int) $object_id, (string) $taxonomy );
		if ( ! is_array( $terms ) || empty( $terms ) ) {
			return 0;
		}
		$best       = 0;
		$best_depth = -1;
		foreach ( $terms as $t ) {
			if ( ! isset( $t->term_id ) ) {
				continue;
			}
			$depth = count( (array) get_ancestors( (int) $t->term_id, (string) $taxonomy, 'taxonomy' ) );
			if ( $depth > $best_depth || ( $depth === $best_depth && ( 0 === $best || (int) $t->term_id < $best ) ) ) {
				$best_depth = $depth;
				$best       = (int) $t->term_id;
			}
		}
		return $best;
	}

	

	private static function competitor_active() {
		return defined( 'AIOSEO_VERSION' ) || class_exists( 'AIOSEO\\Plugin\\Common\\Main', false )
			|| defined( 'WPSEO_VERSION' ) || class_exists( 'WPSEO_Options', false )
			|| defined( 'RANK_MATH_VERSION' ) || class_exists( 'RankMath', false );
	}

	private static function engine_enabled() {
		$opt = get_option( 'aieo_dmm_settings' );
		return is_array( $opt ) && ! empty( $opt['seo']['enabled'] );
	}
}
