<?php

namespace WeDevs\Wpuf\Pro\AI_Review;

use WeDevs\Wpuf\Pro\AI_Review\Scheduler;
use WeDevs\Wpuf\Pro\AI_Review\Helper;

/**
 * AI Review Retry Handler - Manages manual retry requests
 *
 * @since 4.2.9
 */
class Retry_Handler {

	/**
	 * Handle manual retry request via AJAX
	 *
	 * @since 4.2.9
	 *
	 * @param int  $post_id       Post ID to retry
	 * @param bool $verify_nonce  Whether to verify post-specific nonce (default true, set to false for REST API)
	 *
	 * @return array Result with success/error status
	 */
	public static function handle_manual_retry( $post_id, $verify_nonce = true ): array {
		// Check permissions
		if ( ! current_user_can( 'manage_options' ) ) {
			return [
				'success' => false,
				'message' => __( 'Unauthorized', 'wpuf-pro' )
			];
		}

		// Verify nonce (skip for REST API which uses X-WP-Nonce header)
		if ( $verify_nonce ) {
			$nonce = isset( $_POST['nonce'] ) ? wp_unslash( $_POST['nonce'] ) : '';
			if ( ! wp_verify_nonce( $nonce, 'wpuf_ai_review_retry_' . $post_id ) ) {
				return [
					'success' => false,
					'message' => __( 'Invalid security token', 'wpuf-pro' )
				];
			}
		}

		// Get form settings for this post
		$form_id = get_post_meta( $post_id, '_wpuf_form_id', true );
		if ( ! $form_id ) {
			return [
				'success' => false,
				'message' => __( 'Form not found for this post', 'wpuf-pro' )
			];
		}

		$form = new \WeDevs\Wpuf\Admin\Forms\Form( $form_id );
		$form_settings = $form->get_settings();

		// Check if AI review is enabled before proceeding
		$ai_review_enabled = ! empty( $form_settings['ai_review_enabled'] ) && wpuf_is_checkbox_or_toggle_on( $form_settings['ai_review_enabled'] );

		if ( ! $ai_review_enabled ) {
			return [
				'success' => false,
				'message' => __( 'AI Review is not enabled for this form. Please enable it in form settings.', 'wpuf-pro' )
			];
		}

		// Clear any existing review data (re-review from scratch)
		delete_post_meta( $post_id, 'wpuf_ai_post_review' );
		delete_post_meta( $post_id, 'wpuf_ai_review_status' );

		// Schedule retry via Action Scheduler
		$scheduler = new Scheduler();
		$scheduled = $scheduler->schedule_review( $post_id, $form_settings, [], 10 );

		if ( $scheduled ) {
			Helper::save_pending_review( $post_id );
			return [
				'success' => true,
				'message' => __( 'Review scheduled for retry', 'wpuf-pro' )
			];
		}

		// Provide more specific error message
		$error_message = __( 'Failed to schedule retry', 'wpuf-pro' );
		if ( empty( $form_settings['ai_review_prompt'] ) ) {
			$error_message = __( 'AI Review prompt is not configured for this form.', 'wpuf-pro' );
		}

		return [
			'success' => false,
			'message' => $error_message
		];
	}

	/**
	 * Generate nonce for retry action
	 *
	 * @since 4.2.9
	 *
	 * @param int $post_id Post ID
	 *
	 * @return string Nonce value
	 */
	public static function create_retry_nonce( $post_id ): string {
		return wp_create_nonce( 'wpuf_ai_review_retry_' . $post_id );
	}
}
