<?php
/**
 * Generic SEO integration.
 *
 * @package SmartyPress_AI_Engine
 * @since 1.0.0
 */

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

/**
 * Fallback provider used when no dedicated SEO plugin is active.
 */
class SmartyPress_AI_Generic_SEO_Integration extends SmartyPress_AI_SEO_Provider_Integration {

	/**
	 * Get provider identifier.
	 *
	 * @return string
	 */
	public function get_id() {
		return 'generic';
	}

	/**
	 * Get provider label.
	 *
	 * @return string
	 */
	public function get_label() {
		return 'SmartyPress SEO';
	}

	/**
	 * Generic provider is always available.
	 *
	 * @return bool
	 */
	public function is_available() {
		return true;
	}

	/**
	 * Get normalized editor context.
	 *
	 * @param int $post_id Post ID.
	 * @return array
	 */
	public function get_editor_context( $post_id ) {
		$post_id = absint( $post_id );
		$post    = get_post( $post_id );

		if ( ! $post ) {
			return array();
		}

		return array(
			'provider'         => $this->get_id(),
			'provider_label'   => $this->get_label(),
			'post_id'          => $post_id,
			'post_type'        => $post->post_type,
			'score'            => 0,
			'focus_keywords'   => $this->normalize_keywords( get_post_meta( $post_id, '_smartypress_ai_focus_keywords', true ) ),
			'primary_keyword'  => '',
			'seo_title'        => get_the_title( $post_id ),
			'meta_description' => has_excerpt( $post_id ) ? get_the_excerpt( $post_id ) : '',
			'slug'             => (string) $post->post_name,
		);
	}

	/**
	 * Get supported tests and common groups.
	 *
	 * @return array
	 */
	public function get_supported_tests() {
		return array(
			'keywordInTitle'            => 'seo_title',
			'titleStartWithKeyword'     => 'seo_title',
			'titleHasNumber'            => 'seo_title',
			'titleHasPowerWords'        => 'seo_title',
			'titleSentiment'            => 'seo_title',
			'keywordInMetaDescription'  => 'meta_description',
			'keywordInPermalink'        => 'slug',
			'keywordInUrl'              => 'slug',
			'lengthPermalink'           => 'slug',
			'keywordIn10Percent'        => 'content',
			'keywordInContent'          => 'content',
			'keywordDensity'            => 'content',
			'lengthContent'             => 'content',
			'keywordInSubheadings'      => 'headings',
			'linksHasInternal'          => 'links',
			'linksHasExternals'         => 'links',
			'linksNotAllExternals'      => 'links',
			'contentHasTOC'             => 'readability',
			'contentHasShortParagraphs' => 'readability',
			'contentHasAssets'          => 'media',
			'keywordInImageAlt'         => 'media',
		);
	}

	/**
	 * Normalize failed tests.
	 *
	 * @param array $raw_tests Raw failed tests.
	 * @return array
	 */
	public function normalize_failed_tests( $raw_tests ) {
		$supported  = $this->get_supported_tests();
		$normalized = array();

		foreach ( (array) $raw_tests as $test ) {
			$id = isset( $test['id'] ) ? preg_replace( '/[^A-Za-z0-9_-]/', '', (string) $test['id'] ) : '';

			if ( '' === $id ) {
				continue;
			}

			$group = isset( $supported[ $id ] ) ? $supported[ $id ] : 'other';

			$normalized[] = array(
				'id'           => $id,
				'provider_id'  => $this->get_id(),
				'group'        => $group,
				'message'      => isset( $test['message'] ) ? sanitize_text_field( $test['message'] ) : '',
				'severity'     => isset( $test['severity'] ) ? sanitize_key( $test['severity'] ) : 'error',
				'fix_strategy' => 'fix_' . $group,
			);
		}

		return $normalized;
	}

	/**
	 * Apply metadata changes on the server side.
	 *
	 * @param int   $post_id Post ID.
	 * @param array $changes Normalized changes.
	 * @return array
	 */
	public function apply_metadata_changes( $post_id, $changes ) {
		$post_id = absint( $post_id );
		$updated = array();

		if ( ! current_user_can( 'edit_post', $post_id ) ) {
			return array(
				'success' => false,
				'updated' => $updated,
			);
		}

		if ( isset( $changes['focus_keywords'] ) && is_array( $changes['focus_keywords'] ) ) {
			update_post_meta( $post_id, '_smartypress_ai_focus_keywords', implode( ', ', array_map( 'sanitize_text_field', $changes['focus_keywords'] ) ) );
			$updated[] = 'focus_keywords';
		}

		if ( isset( $changes['slug'] ) && '' !== $changes['slug'] ) {
			wp_update_post(
				array(
					'ID'        => $post_id,
					'post_name' => sanitize_title( $changes['slug'] ),
				)
			);
			$updated[] = 'slug';
		}

		return array(
			'success' => true,
			'updated' => $updated,
		);
	}
}
