<?php

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

require_once AIEO_DIR . 'includes/seo/class-aieo-seo-store.php';
require_once AIEO_DIR . 'includes/seo/class-aieo-seo-score.php';
require_once AIEO_DIR . 'includes/seo/class-aieo-seo-ai-assist.php';

class AIEO_SEO_Post_Metabox {

	const NONCE = 'aieo_seo_metabox_nonce';

	public static function register() {
		add_action( 'add_meta_boxes', array( __CLASS__, 'add_box' ) );
		add_action( 'save_post', array( __CLASS__, 'save' ), 10, 2 );
		if ( class_exists( 'AIEO_SEO_AI_Assist' ) ) {
			AIEO_SEO_AI_Assist::register(); 
		}
	}

	
	private static function post_types() {
		$out = array();
		foreach ( get_post_types( array( 'public' => true ), 'names' ) as $t ) {
			if ( ! in_array( $t, array( 'attachment', 'revision', 'nav_menu_item' ), true ) ) {
				$out[] = $t;
			}
		}
		return $out;
	}

	
	private static function hierarchical_taxonomies( $post_type ) {
		$canonical_taxes = array( 'product_cat', 'category' );
		$out             = array();
		foreach ( get_object_taxonomies( $post_type, 'objects' ) as $tx ) {
			if ( in_array( $tx->name, $canonical_taxes, true ) && ! empty( $tx->public ) && ! empty( $tx->hierarchical ) ) {
				$out[ $tx->name ] = $tx;
			}
		}
		return $out;
	}

	public static function add_box() {
		foreach ( self::post_types() as $pt ) {
			add_meta_box( 'aieo-seo-box', __( 'AIEO SEO', 'ai-eshop-optimizer' ), array( __CLASS__, 'render' ), $pt, 'side', 'default' );
		}
	}

	public static function render( $post ) {
		$type = (string) $post->post_type;
		$row  = AIEO_SEO_Store::get( $type, (int) $post->ID );
		$row  = is_array( $row ) ? $row : array();

		$primary = array();
		if ( ! empty( $row['primary_term'] ) ) {
			$decoded = json_decode( (string) $row['primary_term'], true );
			if ( is_array( $decoded ) ) {
				$primary = $decoded;
			}
		}

		wp_nonce_field( self::NONCE, self::NONCE );
		echo '<div class="aieo-seo-metabox">';

		
		self::render_score_panel( $type, (int) $post->ID );

		
		
		foreach ( self::hierarchical_taxonomies( $type ) as $tax => $tx_obj ) {
			$assigned = get_the_terms( $post, $tax );
			if ( empty( $assigned ) || is_wp_error( $assigned ) ) {
				continue;
			}
			$current = isset( $primary[ $tax ] ) ? (int) $primary[ $tax ] : 0;
			$field   = 'aieo_seo_primary_' . $tax;
			echo '<p><label for="' . esc_attr( $field ) . '"><strong>';
			echo esc_html( sprintf(  __( 'Canonical %s', 'ai-eshop-optimizer' ), $tx_obj->labels->singular_name ) );
			echo '</strong></label><br>';
			echo '<select id="' . esc_attr( $field ) . '" name="' . esc_attr( $field ) . '" style="width:100%;">';
			echo '<option value="0">' . esc_html__( '— First assigned (default) —', 'ai-eshop-optimizer' ) . '</option>';
			foreach ( $assigned as $term ) {
				echo '<option value="' . (int) $term->term_id . '" ' . selected( $current, (int) $term->term_id, false ) . '>' . esc_html( $term->name ) . '</option>';
			}
			echo '</select></p>';
		}

		
		echo '<p><label for="aieo_seo_keyphrase"><strong>' . esc_html__( 'Focus keyphrase', 'ai-eshop-optimizer' ) . '</strong></label><br>';
		echo '<input type="text" id="aieo_seo_keyphrase" name="aieo_seo_keyphrase" class="widefat" value="' . esc_attr( isset( $row['focus_keyphrase'] ) ? $row['focus_keyphrase'] : '' ) . '"></p>';

		
		echo '<p><label for="aieo_seo_title"><strong>' . esc_html__( 'SEO title', 'ai-eshop-optimizer' ) . '</strong></label><br>';
		echo '<input type="text" id="aieo_seo_title" name="aieo_seo_title" class="widefat" value="' . esc_attr( isset( $row['title'] ) ? $row['title'] : '' ) . '"></p>';

		
		echo '<p><label for="aieo_seo_description"><strong>' . esc_html__( 'Meta description', 'ai-eshop-optimizer' ) . '</strong></label><br>';
		echo '<textarea id="aieo_seo_description" name="aieo_seo_description" class="widefat" rows="3">' . esc_textarea( isset( $row['description'] ) ? $row['description'] : '' ) . '</textarea></p>';

		
		
		if ( class_exists( 'AIEO_SEO_AI_Assist' ) && AIEO_SEO_AI_Assist::available() ) {
			echo '<p><button type="button" class="button" id="aieo-seo-ai-suggest" data-post="' . (int) $post->ID . '" data-nonce="' . esc_attr( wp_create_nonce( AIEO_SEO_AI_Assist::NONCE ) ) . '">' . esc_html__( 'Suggest with AI', 'ai-eshop-optimizer' ) . '</button> <span id="aieo-seo-ai-status" style="font-size:11px;color:#64748b;"></span></p>';
		}

		
		echo '<p><label for="aieo_seo_canonical"><strong>' . esc_html__( 'Canonical URL override', 'ai-eshop-optimizer' ) . '</strong></label><br>';
		echo '<input type="url" id="aieo_seo_canonical" name="aieo_seo_canonical" class="widefat" maxlength="300" placeholder="' . esc_attr__( 'Leave blank to use the canonical category URL', 'ai-eshop-optimizer' ) . '" value="' . esc_attr( isset( $row['canonical_override'] ) ? $row['canonical_override'] : '' ) . '">';
		echo '<span class="description">' . esc_html__( 'Max 300 characters, so it stays consistent with the product feeds / core vitals. (Longer canonicals still render in the page tag but are not propagated to product_url.)', 'ai-eshop-optimizer' ) . '</span></p>';

		
		echo '<p><label><input type="checkbox" name="aieo_seo_noindex" value="1" ' . checked( ! empty( $row['robots_noindex'] ), true, false ) . '> ' . esc_html__( 'No-index this page', 'ai-eshop-optimizer' ) . '</label></p>';

		self::render_ai_js();
		echo '</div>';
	}

	
	private static function render_score_panel( $type, $id ) {
		if ( ! class_exists( 'AIEO_SEO_Score' ) || ! AIEO_SEO_Score::enabled() ) {
			return; 
		}
		$r     = AIEO_SEO_Score::compute( $type, $id );
		$score = (int) $r['score'];
		$color = $score >= 80 ? '#15803d' : ( $score >= 50 ? '#b45309' : '#b91c1c' );
		echo '<div class="aieo-seo-score" style="margin:0 0 10px;padding:8px;border:1px solid #e2e8f0;border-radius:6px;">';
		echo '<div style="display:flex;align-items:center;gap:8px;">';
		echo '<span style="font-size:20px;font-weight:700;color:' . esc_attr( $color ) . ';">' . (int) $score . '</span>';
		echo '<span style="font-size:11px;color:#64748b;">' . esc_html__( 'SEO health / 100', 'ai-eshop-optimizer' );
		if ( 'product' === $type ) {
			echo ' · ' . esc_html( sprintf(  __( 'demand %d', 'ai-eshop-optimizer' ), (int) $r['demand'] ) );
		}
		echo '</span></div>';
		$issues = array();
		foreach ( (array) $r['breakdown'] as $c ) {
			if ( 'pass' !== ( $c['status'] ?? '' ) ) {
				$issues[] = $c;
			}
		}
		if ( ! empty( $issues ) ) {
			echo '<ul style="margin:6px 0 0;padding-left:16px;font-size:11px;color:#475569;list-style:disc;">';
			foreach ( $issues as $c ) {
				$icon = ( 'fail' === $c['status'] ) ? '✗' : '!';
				$line = $icon . ' ' . (string) $c['label'];
				if ( '' !== (string) ( $c['hint'] ?? '' ) ) {
					$line .= ' — ' . (string) $c['hint'];
				}
				echo '<li>' . esc_html( $line ) . '</li>';
			}
			echo '</ul>';
		} else {
			echo '<p style="margin:6px 0 0;font-size:11px;color:#15803d;">' . esc_html__( 'All checks pass.', 'ai-eshop-optimizer' ) . '</p>';
		}
		echo '</div>';
	}

	
	private static function render_ai_js() {
		if ( ! class_exists( 'AIEO_SEO_AI_Assist' ) || ! AIEO_SEO_AI_Assist::available() ) {
			return;
		}
		?>
		<script>
		(function(){
			var btn = document.getElementById('aieo-seo-ai-suggest');
			if (!btn) { return; }
			var st = document.getElementById('aieo-seo-ai-status');
			btn.addEventListener('click', function(){
				btn.disabled = true; st.textContent = <?php echo wp_json_encode( __( 'Thinking…', 'ai-eshop-optimizer' ) ); ?>;
				var fd = new FormData();
				fd.set('action', <?php echo wp_json_encode( AIEO_SEO_AI_Assist::ACTION ); ?>);
				fd.set('nonce', btn.getAttribute('data-nonce'));
				fd.set('post_id', btn.getAttribute('data-post'));
				fetch(<?php echo wp_json_encode( admin_url( 'admin-ajax.php' ) ); ?>, { method:'POST', credentials:'same-origin', body: fd })
					.then(function(r){ return r.json(); })
					.then(function(j){
						btn.disabled = false;
						if (!j || !j.success) { st.textContent = (j && j.data && j.data.message) || 'Failed.'; return; }
						var d = j.data,
							t  = document.getElementById('aieo_seo_title'),
							ds = document.getElementById('aieo_seo_description'),
							kp = document.getElementById('aieo_seo_keyphrase');
						if (t  && d.title)       { t.value  = d.title; }
						if (ds && d.description) { ds.value = d.description; }
						if (kp && d.keyphrase)   { kp.value = d.keyphrase; }
						st.style.color = '#15803d';
						st.textContent = <?php echo wp_json_encode( __( 'Done — review & Save.', 'ai-eshop-optimizer' ) ); ?>;
					})
					.catch(function(){ btn.disabled = false; st.textContent = 'Network error.'; });
			});
		})();
		</script>
		<?php
	}

	public static function save( $post_id, $post ) {
		
		if ( ! isset( $_POST[ self::NONCE ] ) || ! wp_verify_nonce( sanitize_key( wp_unslash( $_POST[ self::NONCE ] ) ), self::NONCE ) ) {
			return;
		}
		if ( wp_is_post_revision( $post_id ) || wp_is_post_autosave( $post_id ) ) {
			return;
		}
		if ( ! current_user_can( 'edit_post', $post_id ) ) {
			return;
		}

		$type    = (string) $post->post_type;
		$post_id = (int) $post_id;

		
		
		foreach ( self::hierarchical_taxonomies( $type ) as $tax => $tx_obj ) {
			$field = 'aieo_seo_primary_' . $tax;
			if ( ! isset( $_POST[ $field ] ) ) {
				continue;
			}
			$term_id = (int) $_POST[ $field ];
			
			
			
			if ( $term_id > 0 && ! has_term( $term_id, $tax, $post_id ) ) {
				$term_id = 0;
			}
			AIEO_SEO_Store::set_primary_term( $type, $post_id, $tax, $term_id );
		}

		
		
		$fields = array(
			'title'              => isset( $_POST['aieo_seo_title'] ) ? sanitize_text_field( wp_unslash( $_POST['aieo_seo_title'] ) ) : '',
			'description'        => isset( $_POST['aieo_seo_description'] ) ? sanitize_textarea_field( wp_unslash( $_POST['aieo_seo_description'] ) ) : '',
			'focus_keyphrase'    => isset( $_POST['aieo_seo_keyphrase'] ) ? sanitize_text_field( wp_unslash( $_POST['aieo_seo_keyphrase'] ) ) : '',
			'canonical_override' => isset( $_POST['aieo_seo_canonical'] ) ? esc_url_raw( wp_unslash( $_POST['aieo_seo_canonical'] ) ) : '',
			'robots_noindex'     => ! empty( $_POST['aieo_seo_noindex'] ) ? 1 : 0,
		);
		
		if ( '' !== $fields['focus_keyphrase'] ) {
			$fields['focus_keyphrase_source'] = 'manual';
		}
		AIEO_SEO_Store::save( $type, $post_id, $fields );
	}
}
