<?php

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

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

class AIEO_DMM_SEO_Health extends AIEO_DMM_Module_Base {

	public function get_id()       { return 'seo_health'; }
	public function get_label()    { return __( 'SEO Health', 'ai-eshop-optimizer' ); }
	public function get_priority() { return 5; }
	public function get_group()    { return 'seo'; }
	public function get_section()  { return 'health'; }

	public function register_hooks() {
		add_action( 'wp_ajax_aieo_seo_health_recompute', array( $this, 'ajax_recompute' ) );
		add_action( 'wp_ajax_aieo_seo_sugg_action', array( $this, 'ajax_sugg_action' ) );
		add_action( 'wp_ajax_aieo_seo_sugg_generate', array( $this, 'ajax_sugg_generate' ) );
	}

	
	public function ajax_sugg_action() {
		AIEO_DMM::verify_ajax_request();
		if ( ! current_user_can( 'manage_woocommerce' ) && ! current_user_can( 'manage_options' ) ) {
			wp_send_json_error( array( 'message' => __( 'Insufficient permissions.', 'ai-eshop-optimizer' ) ) );
		}
		if ( ! class_exists( 'AIEO_SEO_Write_Queue' ) ) {
			require_once AIEO_DIR . 'includes/seo/class-aieo-seo-write-queue.php';
		}
		
		$op   = isset( $_POST['op'] ) ? sanitize_key( wp_unslash( $_POST['op'] ) ) : '';
		$type = isset( $_POST['object_type'] ) ? sanitize_key( wp_unslash( $_POST['object_type'] ) ) : '';
		$id   = isset( $_POST['object_id'] ) ? (int) $_POST['object_id'] : 0;
		if ( 'approve_all' === $op ) {
			$n = 0;
			foreach ( AIEO_SEO_Write_Queue::pending( 200 ) as $p ) {
				if ( AIEO_SEO_Write_Queue::approve( (string) $p['object_type'], (int) $p['object_id'] ) ) {
					$n++;
				}
			}
			wp_send_json_success( array( 'message' => sprintf( __( 'Applied %d suggestions.', 'ai-eshop-optimizer' ), $n ) ) );
		}
		if ( '' === $type || $id <= 0 ) {
			wp_send_json_error( array( 'message' => __( 'Invalid object.', 'ai-eshop-optimizer' ) ) );
		}
		$ok = ( 'approve' === $op )
			? AIEO_SEO_Write_Queue::approve( $type, $id )
			: AIEO_SEO_Write_Queue::dismiss( $type, $id );
		if ( ! $ok ) {
			wp_send_json_error( array( 'message' => __( 'Nothing pending for that object.', 'ai-eshop-optimizer' ) ) );
		}
		wp_send_json_success();
	}

	
	public function ajax_sugg_generate() {
		AIEO_DMM::verify_ajax_request();
		if ( ! current_user_can( 'manage_woocommerce' ) && ! current_user_can( 'manage_options' ) ) {
			wp_send_json_error( array( 'message' => __( 'Insufficient permissions.', 'ai-eshop-optimizer' ) ) );
		}
		if ( ! class_exists( 'AIEO_SEO_Write_Queue' ) ) {
			require_once AIEO_DIR . 'includes/seo/class-aieo-seo-write-queue.php';
		}
		if ( ! AIEO_SEO_Write_Queue::available() ) {
			wp_send_json_error( array( 'message' => __( 'Needs both the AI (Rooster Content Connector token) and a DataForSEO connection.', 'ai-eshop-optimizer' ) ) );
		}
		$res = AIEO_SEO_Write_Queue::run( 3 ); 
		wp_send_json_success( array(
			'message' => sprintf(
				
				__( 'Drafted %1$d, auto-applied %2$d, skipped %3$s.', 'ai-eshop-optimizer' ),
				(int) $res['drafted'],
				(int) $res['applied'],
				is_int( $res['skipped'] ) ? (string) $res['skipped'] : (string) $res['skipped']
			),
		) );
	}

	
	public function ajax_recompute() {
		AIEO_DMM::verify_ajax_request();
		if ( ! current_user_can( 'manage_woocommerce' ) && ! current_user_can( 'manage_options' ) ) {
			wp_send_json_error( array( 'message' => __( 'Insufficient permissions.', 'ai-eshop-optimizer' ) ) );
		}
		if ( ! class_exists( 'AIEO_SEO_Score' ) ) {
			wp_send_json_error( array( 'message' => __( 'Score engine unavailable.', 'ai-eshop-optimizer' ) ) );
		}
		$cursor = array( 'phase' => 0, 'last_id' => 0 );
		if ( isset( $_POST['cursor'] ) ) {
			
			$decoded = json_decode( wp_unslash( $_POST['cursor'] ), true );
			if ( is_array( $decoded ) ) {
				$cursor = array(
					'phase'   => isset( $decoded['phase'] ) ? (int) $decoded['phase'] : 0,
					'last_id' => isset( $decoded['last_id'] ) ? (int) $decoded['last_id'] : 0,
				);
			}
		}
		$res = AIEO_SEO_Score::run_backfill( 200, $cursor );
		if ( ! empty( $res['done'] ) && class_exists( 'AIEO_SEO_Pillars' ) ) {
			AIEO_SEO_Pillars::rebuild(); 
		}
		wp_send_json_success( $res );
	}

	public function render_subtab() {
		
		$pillars_only = isset( $_GET['seo_view'] ) && 'pillars' === sanitize_key( wp_unslash( $_GET['seo_view'] ) );
		if ( ! class_exists( 'AIEO_SEO_Write_Queue' ) ) {
			require_once AIEO_DIR . 'includes/seo/class-aieo-seo-write-queue.php';
		}
		$this->render_template(
			'seo/health.php',
			array(
				'enabled'      => class_exists( 'AIEO_SEO_Score' ) && AIEO_SEO_Score::enabled(),
				'summary'      => self::summary(),
				'rows'         => self::rows( 100, $pillars_only ),
				'pillars_only' => $pillars_only,
				'suggestions'  => AIEO_SEO_Write_Queue::pending( 50 ),
				'wq_available' => AIEO_SEO_Write_Queue::available(),
				'nonce'        => wp_create_nonce( AIEO_DMM::NONCE_ACTION ),
				'ajax'         => admin_url( 'admin-ajax.php' ),
			)
		);
	}

	
	private static function summary() {
		global $wpdb;
		$sc = $wpdb->prefix . 'aieo_seo_scores';
		
		
		
		$row = $wpdb->get_row(
			"SELECT COUNT(*) AS total,
			        COALESCE( ROUND( AVG(s.score) ), 0 ) AS avg,
			        COALESCE( SUM( s.is_pillar = 1 ), 0 ) AS pillars,
			        COALESCE( SUM( s.fix_count > 0 ), 0 ) AS needswork
			 FROM `{$sc}` s
			 INNER JOIN {$wpdb->posts} wp ON wp.ID = s.object_id AND wp.post_type = s.object_type
			 WHERE wp.post_status = 'publish'",
			ARRAY_A
		);
		return array(
			'total'     => (int) ( $row['total'] ?? 0 ),
			'avg'       => (int) ( $row['avg'] ?? 0 ),
			'pillars'   => (int) ( $row['pillars'] ?? 0 ),
			'needswork' => (int) ( $row['needswork'] ?? 0 ),
		);
	}

	
	private static function rows( $limit, $pillars_only = false ) {
		
		
		$cache_key = 'aieo_seo_health_rows_' . (int) $limit . ( $pillars_only ? '_p' : '' );
		$cached    = get_transient( $cache_key );
		if ( is_array( $cached ) ) {
			return $cached;
		}
		global $wpdb;
		$sc      = $wpdb->prefix . 'aieo_seo_scores';
		$sp      = $wpdb->prefix . 'aieo_seo_posts';
		$pillars = $pillars_only ? ' AND s.is_pillar = 1' : '';
		
		
		
		
		$rows = $wpdb->get_results( $wpdb->prepare(
			"SELECT s.object_type, s.object_id, s.score, s.fix_count, s.is_pillar,
			        COALESCE( p.demand_score, 0 ) AS demand, wp.post_title
			 FROM `{$sc}` s
			 INNER JOIN {$wpdb->posts} wp ON wp.ID = s.object_id AND wp.post_type = s.object_type
			 LEFT JOIN `{$sp}` p ON p.object_type = s.object_type AND p.object_id = s.object_id
			 WHERE wp.post_status = 'publish'{$pillars}
			 ORDER BY demand DESC, s.score ASC
			 LIMIT %d",
			(int) $limit
		), ARRAY_A );
		$rows = is_array( $rows ) ? $rows : array();
		set_transient( $cache_key, $rows, 10 * MINUTE_IN_SECONDS );
		return $rows;
	}
}
