<?php
if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

class SftcyWordaiSearchConsole {
	const PAGE_SLUG = 'sc-wordai-search-console';
	const NONCE     = 'sftcy_wordai_search_console';

	public static function init() {
		add_action( 'admin_enqueue_scripts', array( __CLASS__, 'enqueue_assets' ) );
		foreach ( array( 'status', 'connect', 'refresh_properties', 'select_property', 'sync', 'disconnect' ) as $action ) {
			add_action( 'wp_ajax_sftcy_wordai_search_console_' . $action, array( __CLASS__, 'ajax_' . $action ) );
		}
	}

	public static function enqueue_assets( $hook ) {
		if ( false === strpos( (string) $hook, self::PAGE_SLUG ) ) {
			return;
		}

		wp_enqueue_style(
			'sftcy-wordai-google-fonts',
			'https://fonts.googleapis.com/css2?family=Poppins:wght@700;800&display=swap',
			array(),
			null
		);
		wp_enqueue_style(
			'sftcy-wordai-fontawesome',
			SFTCY_WORDAI_PLUGIN_URL . 'admin/css/fontawesome6-all.min.css',
			array(),
			filemtime( SFTCY_WORDAI_PLUGIN_DIR . 'admin/css/fontawesome6-all.min.css' ),
			'all'
		);
		wp_enqueue_style(
			'sftcy-wordai-style',
			SFTCY_WORDAI_PLUGIN_URL . 'admin/css/sc-wordai-misc-styles.css',
			array( 'sftcy-wordai-google-fonts' ),
			filemtime( SFTCY_WORDAI_PLUGIN_DIR . 'admin/css/sc-wordai-misc-styles.css' ),
			'all'
		);
		wp_enqueue_style(
			'sftcy-wordai-search-console',
			SFTCY_WORDAI_PLUGIN_URL . 'admin/css/sc-wordai-search-console.css',
			array( 'sftcy-wordai-style' ),
			filemtime( SFTCY_WORDAI_PLUGIN_DIR . 'admin/css/sc-wordai-search-console.css' )
		);
		wp_enqueue_style( 'wp-jquery-ui-dialog' );
		wp_enqueue_script(
			'sftcy-wordai-provider-dialog',
			SFTCY_WORDAI_PLUGIN_URL . 'admin/js/sc-wordai-provider-dialog.js',
			array( 'jquery', 'jquery-ui-dialog', 'jquery-ui-core' ),
			filemtime( SFTCY_WORDAI_PLUGIN_DIR . 'admin/js/sc-wordai-provider-dialog.js' ),
			true
		);
		wp_enqueue_script(
			'sftcy-wordai-search-console',
			SFTCY_WORDAI_PLUGIN_URL . 'admin/js/sc-wordai-search-console.js',
			array( 'jquery', 'jquery-ui-dialog', 'jquery-ui-core', 'sftcy-wordai-provider-dialog' ),
			filemtime( SFTCY_WORDAI_PLUGIN_DIR . 'admin/js/sc-wordai-search-console.js' ),
			true
		);
		$provider = SftcyWordaiBase::sc_wordai_get_current_ai_provider();
		$search_console_config = array(
				'ajaxUrl'    => admin_url( 'admin-ajax.php' ),
				'nonce'      => wp_create_nonce( self::NONCE ),
				'providerNonce' => wp_create_nonce( 'scwordai_wpnonce' ),
				'activeProvider' => $provider,
				'providerLabels' => array_map(
					static function( $meta ) {
						return isset( $meta['label'] ) ? $meta['label'] : '';
					},
					SftcyWordaiBase::sc_wordai_get_ai_providers()
				),
				'providerIcons' => array(
					'openai' => SFTCY_WORDAI_PLUGIN_URL . 'admin/css/images/openai-logo.svg',
					'google' => SFTCY_WORDAI_PLUGIN_URL . 'admin/css/images/gemini-logo.svg',
				),
				'upgradeUrl' => class_exists( 'SftcyWordaiFeatures' ) ? SftcyWordaiFeatures::wordai_get_upgrade_url() : 'https://softcoy.com/products/wordai-pro/checkout',
				'isPro'      => class_exists( 'SftcyWordaiFeatures' ) && ! SftcyWordaiFeatures::wordai_is_basic_tier(),
				'seoScanUrl' => admin_url( 'admin.php?page=' . ( class_exists( 'SftcyWordaiSeoScan' ) ? SftcyWordaiSeoScan::PAGE_SLUG : 'sc-wordai-seo-scan' ) ),
				'marketingOptIn' => (bool) get_option( 'sftcy_wordai_search_console_marketing_opt_in', false ),
		);
		wp_localize_script(
			'sftcy-wordai-search-console',
			'sftcyWordaiSearchConsole',
			$search_console_config
		);
		wp_add_inline_script(
			'sftcy-wordai-search-console',
			'window.sftcyWordaiSearchConsole = window.sftcyWordaiSearchConsole || ' . wp_json_encode( $search_console_config ) . ';',
			'before'
		);
	}

	public static function render_page() {
		if ( ! current_user_can( 'manage_options' ) ) {
			return;
		}
		include SFTCY_WORDAI_PLUGIN_DIR . 'admin/views/submenus-search-console.php';
	}

	public static function ajax_status() {
		self::authorize();
		$result = SftcyWordaiHostedServicesClient::request( 'GET', '/services/search-console/summary' );
		if ( is_wp_error( $result ) ) {
			self::send_error( $result );
		}
		if ( ! empty( $result['capabilities'] ) ) {
			set_transient( SftcyWordaiHostedServicesClient::CAPABILITIES_TRANSIENT, $result['capabilities'], HOUR_IN_SECONDS );
		}
		$result = self::enrich_summary( $result );
		wp_send_json_success( $result );
	}

	public static function ajax_connect() {
		self::authorize();
		$marketing_opt_in = ! empty( $_POST['marketing_opt_in'] );
		update_option( 'sftcy_wordai_search_console_marketing_opt_in', $marketing_opt_in, false );
		$data = SftcyWordaiHostedServicesClient::request(
			'POST',
			'/services/search-console/connect',
			array(
				'return_url'       => admin_url( 'admin.php?page=' . self::PAGE_SLUG ),
				'marketing_opt_in' => $marketing_opt_in,
			)
		);
		if ( is_wp_error( $data ) ) {
			self::send_error( $data );
		}
		wp_send_json_success( $data );
	}

	public static function ajax_select_property() {
		self::authorize();
		$data = SftcyWordaiHostedServicesClient::request(
			'PUT',
			'/services/search-console/property',
			array(
				'property_id' => absint( $_POST['property_id'] ?? 0 ),
				'selected'    => ! empty( $_POST['selected'] ),
			)
		);
		if ( is_wp_error( $data ) ) {
			self::send_error( $data );
		}
		wp_send_json_success( $data );
	}

	public static function ajax_refresh_properties() {
		self::authorize();
		$data = SftcyWordaiHostedServicesClient::request( 'POST', '/services/search-console/properties/refresh', array() );
		if ( is_wp_error( $data ) ) {
			self::send_error( $data );
		}
		wp_send_json_success( $data );
	}

	public static function ajax_sync() {
		self::authorize();
		$payload = array();
		if ( ! empty( $_POST['property_id'] ) ) {
			$payload['property_id'] = absint( $_POST['property_id'] );
		}
		$data = SftcyWordaiHostedServicesClient::request( 'POST', '/services/search-console/sync', $payload );
		if ( is_wp_error( $data ) ) {
			self::send_error( $data );
		}
		wp_send_json_success( $data );
	}

	public static function ajax_disconnect() {
		self::authorize();
		$data = SftcyWordaiHostedServicesClient::request( 'DELETE', '/services/search-console/connection' );
		if ( is_wp_error( $data ) ) {
			self::send_error( $data );
		}
		wp_send_json_success( $data );
	}

	private static function authorize() {
		check_ajax_referer( self::NONCE, 'nonce' );
		if ( ! current_user_can( 'manage_options' ) ) {
			wp_send_json_error( array( 'message' => __( 'You do not have permission to manage Search Console.', SFTCY_WORDAI_TEXT_DOMAIN ) ), 403 );
		}
	}

	private static function send_error( WP_Error $error ) {
		$data = $error->get_error_data();
		$status = is_array( $data ) && ! empty( $data['status'] ) ? absint( $data['status'] ) : 500;
		wp_send_json_error(
			array(
				'code'    => $error->get_error_code(),
				'message' => $error->get_error_message(),
			),
			$status
		);
	}

	private static function enrich_summary( $result ) {
		if ( empty( $result['opportunities'] ) || ! is_array( $result['opportunities'] ) ) {
			return $result;
		}

		if ( ! empty( $result['opportunities']['content_decay'] ) && is_array( $result['opportunities']['content_decay'] ) ) {
			foreach ( $result['opportunities']['content_decay'] as $index => $item ) {
				$result['opportunities']['content_decay'][ $index ] = self::enrich_opportunity_item( $item );
			}
		}

		if ( ! empty( $result['opportunities']['cannibalization'] ) && is_array( $result['opportunities']['cannibalization'] ) ) {
			foreach ( $result['opportunities']['cannibalization'] as $index => $item ) {
				if ( empty( $item['pages'] ) || ! is_array( $item['pages'] ) ) {
					continue;
				}
				foreach ( $item['pages'] as $page_index => $page ) {
					$item['pages'][ $page_index ] = self::enrich_opportunity_item( $page );
				}
				$result['opportunities']['cannibalization'][ $index ] = $item;
			}
		}

		return $result;
	}

	private static function enrich_opportunity_item( $item ) {
		$item = is_array( $item ) ? $item : array();
		$url  = ! empty( $item['page'] ) ? esc_url_raw( (string) $item['page'] ) : '';

		$item['local_post'] = $url ? self::local_post_from_url( $url ) : null;
		return $item;
	}

	private static function local_post_from_url( $url ) {
		$url = esc_url_raw( (string) $url );
		if ( '' === $url ) {
			return null;
		}

		$post_id = url_to_postid( $url );
		if ( ! $post_id ) {
			$site_host = wp_parse_url( home_url( '/' ), PHP_URL_HOST );
			$url_host  = wp_parse_url( $url, PHP_URL_HOST );
			$url_path  = wp_parse_url( $url, PHP_URL_PATH );
			if ( $site_host && $url_host && strtolower( $site_host ) === strtolower( $url_host ) && $url_path ) {
				$post_id = url_to_postid( home_url( $url_path ) );
			}
		}

		if ( ! $post_id ) {
			return null;
		}

		$post = get_post( $post_id );
		if ( ! $post ) {
			return null;
		}

		$post_type_obj = get_post_type_object( $post->post_type );
		$title         = get_the_title( $post );
		$seo_scan_url  = add_query_arg(
			array(
				'page'                => class_exists( 'SftcyWordaiSeoScan' ) ? SftcyWordaiSeoScan::PAGE_SLUG : 'sc-wordai-seo-scan',
				'wordai_post_type'    => $post->post_type,
				'wordai_search'       => $title,
				'wordai_focus_post'   => $post_id,
				'wordai_status'       => $post->post_status,
			),
			admin_url( 'admin.php' )
		);

		return array(
			'id'              => (int) $post_id,
			'title'           => $title ? wp_strip_all_tags( $title ) : __( '(no title)', SFTCY_WORDAI_TEXT_DOMAIN ),
			'post_type'       => $post->post_type,
			'post_type_label' => $post_type_obj && ! empty( $post_type_obj->labels->singular_name ) ? $post_type_obj->labels->singular_name : $post->post_type,
			'post_status'     => $post->post_status,
			'edit_url'        => get_edit_post_link( $post_id, 'raw' ),
			'view_url'        => get_permalink( $post_id ),
			'seo_scan_url'    => esc_url_raw( $seo_scan_url ),
		);
	}
}
