<?php
/**
 * Local SEO module — main initialization class.
 *
 * @package SEOvaultSEO\LocalSEO
 */

namespace SEOvaultSEO\LocalSEO;

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

class LocalSEOInit {

	public static function init() {
		// Post type registration always runs (admin needs it).
		PostType::init();

		if ( is_admin() ) {
			AdminPage::init();
			LocationMetaBox::init();
			ImportExport::init();
		}

		// Gate frontend output.
		if ( ! \SEOvaultSEO\Compatibility\Detector::should_output_seo() ) {
			return;
		}

		Shortcodes::init();
		GeoTags::init();
		KmlSitemap::init();

		add_action( 'wp_head', array( __CLASS__, 'output_schema' ), 21 );

		register_activation_hook( SEOVAULT_SEO_FILE, array( __CLASS__, 'activate' ) );
		register_deactivation_hook( SEOVAULT_SEO_FILE, array( __CLASS__, 'deactivate' ) );
	}

	public static function activate() {
		PostType::register_post_type();
		PostType::register_taxonomy();
		flush_rewrite_rules();
	}

	public static function deactivate() {
		flush_rewrite_rules();
	}

	public static function add_submenu( $submenus ) {
		$submenus[] = array(
			'id'         => 'seovault-local-seo',
			'page_title' => __( 'Local SEO', 'seovault-ai' ),
			'callback'   => array( AdminPage::class, 'render_page' ),
		);
		return $submenus;
	}

	public static function output_schema() {
		if ( is_admin() && ! wp_doing_ajax() ) {
			return;
		}

		if ( ! self::is_enabled() ) {
			return;
		}

		$generator = new SchemaGenerator();
		$schema    = $generator->get_schema_for_current_page();

		if ( empty( $schema ) ) {
			return;
		}

		echo '<script type="application/ld+json" id="seovaultseo-local-schema">' .
			wp_json_encode( $schema, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS | JSON_HEX_QUOT ) .
			'</script>' . "\n";
	}

	public static function get_settings() {
		return get_option( 'seovaultseo_local_settings', array() );
	}

	public static function update_settings( $settings ) {
		return update_option( 'seovaultseo_local_settings', $settings, false );
	}

	public static function is_enabled() {
		$settings = self::get_settings();
		return isset( $settings['enabled'] ) && 'on' === $settings['enabled'];
	}
}
