<?php

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

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

class AIEO_SEO_Store {

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

	
	private static $columns = array(
		'title'                    => '%s',
		'description'              => '%s',
		'keyphrases'               => '%s',
		'focus_keyphrase'          => '%s',
		'focus_keyphrase_source'   => '%s',
		'canonical_url'            => '%s',
		'canonical_override'       => '%s',
		'primary_cat_id'           => '%d',
		'primary_term'             => '%s',
		'robots_default'           => '%d',
		'robots_noindex'           => '%d',
		'robots_nofollow'          => '%d',
		'robots_noarchive'         => '%d',
		'robots_nosnippet'         => '%d',
		'robots_noimageindex'      => '%d',
		'robots_noodp'             => '%d',
		'robots_notranslate'       => '%d',
		'robots_max_snippet'       => '%d',
		'robots_max_videopreview'  => '%d',
		'robots_max_imagepreview'  => '%s',
		'og_title'                 => '%s',
		'og_description'           => '%s',
		'og_object_type'           => '%s',
		'og_image_type'            => '%s',
		'og_image_custom_url'      => '%s',
		'og_image_url'             => '%s',
		'og_image_width'           => '%d',
		'og_image_height'          => '%d',
		'og_article_section'       => '%s',
		'og_article_tags'          => '%s',
		'twitter_use_og'           => '%d',
		'twitter_card'             => '%s',
		'twitter_image_type'       => '%s',
		'twitter_image_custom_url' => '%s',
		'twitter_image_url'        => '%s',
		'twitter_title'            => '%s',
		'twitter_description'      => '%s',
		'schema_type'              => '%s',
		'schema_type_options'      => '%s',
		'pillar_content'           => '%d',
		'og_image_id'              => '%d',
		'image_alt'                => '%s',
		'demand_score'             => '%f',
		'sitemap_priority'         => '%f',
		'sitemap_frequency'        => '%s',
		'indexable'                => '%d',
		'ai_state'                 => '%s',
		'ai_locked'                => '%d',
		'suggested_title'          => '%s',
		'suggested_description'    => '%s',
		'suggested_keyphrase'      => '%s',
		'suggested_at'             => '%s',
	);

	
	public static function table() {
		global $wpdb;
		return $wpdb->prefix . 'aieo_seo_posts';
	}

	
	public static function table_ok() {
		static $ok = null;
		if ( null === $ok ) {
			global $wpdb;
			$t  = self::table();
			$ok = ( (string) $wpdb->get_var( $wpdb->prepare( 'SHOW TABLES LIKE %s', $t ) ) === $t );
		}
		return (bool) $ok;
	}

	private static function cache_key( $object_type, $object_id ) {
		return 'row:' . $object_type . ':' . (int) $object_id;
	}

	
	public static function get( $object_type, $object_id ) {
		$object_type = (string) $object_type;
		$object_id   = (int) $object_id;
		if ( '' === $object_type || $object_id <= 0 ) {
			return null;
		}

		$key    = self::cache_key( $object_type, $object_id );
		$cached = wp_cache_get( $key, self::CACHE_GROUP );
		if ( false !== $cached ) {
			return is_array( $cached ) ? $cached : null;
		}

		if ( ! self::table_ok() ) {
			return null;
		}

		global $wpdb;
		$t   = self::table();
		
		$row = $wpdb->get_row(
			$wpdb->prepare( "SELECT * FROM `{$t}` WHERE object_type = %s AND object_id = %d", $object_type, $object_id ),
			ARRAY_A
		);

		
		
		
		wp_cache_set( $key, is_array( $row ) ? $row : '', self::CACHE_GROUP, self::CACHE_TTL );
		return is_array( $row ) ? $row : null;
	}

	
	public static function save( $object_type, $object_id, array $fields ) {
		$object_type = (string) $object_type;
		$object_id   = (int) $object_id;
		if ( '' === $object_type || $object_id <= 0 || ! self::table_ok() ) {
			return false;
		}

		$data    = array();
		$formats = array();
		foreach ( $fields as $col => $val ) {
			if ( ! isset( self::$columns[ $col ] ) ) {
				continue;
			}
			$data[ $col ] = $val;
			$formats[]    = self::$columns[ $col ];
		}
		if ( empty( $data ) ) {
			return false;
		}

		global $wpdb;
		$t  = self::table();
		$id = (int) $wpdb->get_var(
			$wpdb->prepare(
				
				"SELECT id FROM `{$t}` WHERE object_type = %s AND object_id = %d",
				$object_type,
				$object_id
			)
		);

		$now = current_time( 'mysql', true );
		if ( $id > 0 ) {
			$data['updated'] = $now;
			$formats[]       = '%s';
			$ok              = false !== $wpdb->update( $t, $data, array( 'id' => $id ), $formats, array( '%d' ) );
		} else {
			$data['object_type'] = $object_type;
			$data['object_id']   = $object_id;
			$data['created']     = $now;
			$data['updated']     = $now;
			$formats[]           = '%s';
			$formats[]           = '%d';
			$formats[]           = '%s';
			$formats[]           = '%s';
			$ok                  = false !== $wpdb->insert( $t, $data, $formats );
		}

		wp_cache_delete( self::cache_key( $object_type, $object_id ), self::CACHE_GROUP );
		if ( class_exists( 'AIEO_SEO_Primary_Term', false ) ) {
			AIEO_SEO_Primary_Term::bust_cache( $object_type, $object_id );
		}
		return $ok;
	}

	
	public static function delete( $object_type, $object_id ) {
		$object_type = (string) $object_type;
		$object_id   = (int) $object_id;
		if ( '' === $object_type || $object_id <= 0 || ! self::table_ok() ) {
			return false;
		}
		global $wpdb;
		$ok = false !== $wpdb->delete(
			self::table(),
			array( 'object_type' => $object_type, 'object_id' => $object_id ),
			array( '%s', '%d' )
		);
		wp_cache_delete( self::cache_key( $object_type, $object_id ), self::CACHE_GROUP );
		if ( class_exists( 'AIEO_SEO_Primary_Term', false ) ) {
			AIEO_SEO_Primary_Term::bust_cache( $object_type, $object_id );
		}
		return $ok;
	}

	
	
	

	
	public static function get_primary_term( $object_type, $object_id, $taxonomy ) {
		$row = self::get( $object_type, $object_id );
		if ( ! $row || empty( $row['primary_term'] ) ) {
			return 0;
		}
		$map = json_decode( (string) $row['primary_term'], true );
		if ( ! is_array( $map ) || ! isset( $map[ $taxonomy ] ) ) {
			return 0;
		}
		return (int) $map[ $taxonomy ];
	}

	
	public static function set_primary_term( $object_type, $object_id, $taxonomy, $term_id ) {
		$row = self::get( $object_type, $object_id );
		$map = array();
		if ( $row && ! empty( $row['primary_term'] ) ) {
			$decoded = json_decode( (string) $row['primary_term'], true );
			if ( is_array( $decoded ) ) {
				$map = $decoded;
			}
		}
		$term_id = (int) $term_id;
		if ( $term_id > 0 ) {
			$map[ $taxonomy ] = $term_id;
		} else {
			unset( $map[ $taxonomy ] );
		}
		$fields = array( 'primary_term' => empty( $map ) ? null : wp_json_encode( $map ) );
		
		
		if ( in_array( $taxonomy, array( 'product_cat', 'category' ), true ) ) {
			$fields['primary_cat_id'] = $term_id > 0 ? $term_id : null;
		}
		return self::save( $object_type, $object_id, $fields );
	}

	
	public static function get_primary_cat_id( $object_type, $object_id ) {
		$row = self::get( $object_type, $object_id );
		return ( $row && ! empty( $row['primary_cat_id'] ) ) ? (int) $row['primary_cat_id'] : 0;
	}

	
	
	

	
	public static function competitor_seo_plugin() {
		if ( defined( 'AIOSEO_VERSION' ) || class_exists( 'AIOSEO\\Plugin\\Common\\Main', false ) ) {
			return 'AIOSEO';
		}
		if ( defined( 'WPSEO_VERSION' ) || class_exists( 'WPSEO_Options', false ) ) {
			return 'Yoast SEO';
		}
		if ( defined( 'RANK_MATH_VERSION' ) || class_exists( 'RankMath', false ) ) {
			return 'Rank Math';
		}
		return '';
	}

	
	public static function is_active_provider() {
		if ( '' !== self::competitor_seo_plugin() ) {
			return false;
		}
		if ( ! class_exists( 'AIEO_DMM_Settings' ) ) {
			return false;
		}
		return (bool) AIEO_DMM_Settings::get( 'seo.enabled', false );
	}
}
