<?php
/**
 * AJAX Handler Class.
 *
 * Manages all AJAX functionality for Postomatic.
 *
 * @package Postomatic
 * @subpackage Core
 * @since   1.0.0
 */

namespace Postomatic\Core;

// Prevent direct file access.
if ( ! defined( 'ABSPATH' ) ) {
	exit;
}


/**
 * Class Ajax_Handler.
 *
 * Handles all AJAX requests for the Postomatic plugin.
 */
class Ajax_Handler {

	/**
	 * Initialize the class and set up AJAX hooks.
	 *
	 * @return void
	 */
	public function init() {
		// Add initial check for admin-ajax.php - runs early in the request lifecycle.
		add_action( 'init', array( $this, 'check_admin_ajax' ), 1 );

		$this->register_hooks();
	}

	/**
	 * Perform initial check for admin-ajax.php requests.
	 *
	 * This method runs early in the AJAX request lifecycle to perform
	 * initial validation before any AJAX handlers are executed.
	 *
	 * @return void
	 */
	public function check_admin_ajax() {
		// Check if this is an admin-ajax.php request.
		if ( defined( 'DOING_AJAX' ) && DOING_AJAX ) {
			// Skip check for specific AJAX actions if needed.
			$action       = isset( $_REQUEST['action'] ) ? sanitize_text_field( wp_unslash( $_REQUEST['action'] ) ) : '';
			$skip_actions = array(
				// Add AJAX actions to skip if necessary.
			);

			if ( ! in_array( $action, $skip_actions, true ) ) {
				// Only perform additional checks for Postomatic AJAX actions.
				if ( 0 === strpos( $action, 'postomatic_' ) ) {
					// Verify the nonce instead of checking referer.
					$nonce_key = 'nonce';
					$nonce     = isset( $_REQUEST[ $nonce_key ] ) ? sanitize_text_field( wp_unslash( $_REQUEST[ $nonce_key ] ) ) : '';

					// Determine which nonce action to use based on the AJAX action.
					$nonce_action = 'postomatic_support_nonce';

					// Use admin nonce for autopilot-related actions.
					if ( strpos( $action, 'postomatic_autopilot' ) === 0 ||
						strpos( $action, 'postomatic_get_content_goal_types' ) === 0 ||
						strpos( $action, 'postomatic_get_products' ) === 0 ||
						strpos( $action, 'postomatic_get_credits' ) === 0 ||
						strpos( $action, 'postomatic_get_pricing_credits' ) === 0 ||
						strpos( $action, 'postomatic_get_credit_access' ) === 0 ||
						strpos( $action, 'postomatic_similar_titles_search' ) === 0 ||
						strpos( $action, 'postomatic_create_autopilot' ) === 0 ||
						strpos( $action, 'postomatic_get_autopilots' ) === 0 ||
						strpos( $action, 'postomatic_delete_autopilot' ) === 0 ||
						strpos( $action, 'postomatic_analyze_blog' ) === 0 ||
						strpos( $action, 'postomatic_get_languages' ) === 0 ||
						strpos( $action, 'save_one_time_code' ) === 0 ||
						strpos( $action, 'postomatic_get_active_plan' ) === 0 ||
						strpos( $action, 'postomatic_generate_post' ) === 0 ||
						strpos( $action, 'postomatic_delete_post' ) === 0 ||
						strpos( $action, 'postomatic_get_pricing_plans' ) === 0 ) {
						$nonce_action = 'postomatic_admin_nonce';
					}

					// If nonce verification fails, return error.
					if ( ! wp_verify_nonce( $nonce, $nonce_action ) ) {
						wp_send_json_error(
							array(
								'message' => 'Invalid request source',
							)
						);
						exit;
					}
				}
			}
		}
	}

	/**
	 * Register all AJAX hooks.
	 *
	 * @return void
	 */
	private function register_hooks() {
		add_action( 'wp_ajax_get_attachment_image_html', array( $this, 'postomatic_get_attachment_image_html' ) );
		add_action( 'wp_ajax_nopriv_get_attachment_image_html', array( $this, 'postomatic_get_attachment_image_html' ) ); // If you need this to work for non-logged in users.

		// Support ticket AJAX handlers.
		add_action( 'wp_ajax_postomatic_get_tickets', array( $this, 'get_support_tickets' ) );
		add_action( 'wp_ajax_postomatic_submit_ticket', array( $this, 'submit_support_ticket' ) );
		add_action( 'wp_ajax_postomatic_get_ticket', array( $this, 'get_single_support_ticket' ) );

		// Add nonce verification to the support ticket handlers.
		add_action( 'wp_ajax_nopriv_postomatic_get_tickets', array( $this, 'get_support_tickets' ) );
		add_action( 'wp_ajax_nopriv_postomatic_submit_ticket', array( $this, 'submit_support_ticket' ) );
		add_action( 'wp_ajax_nopriv_postomatic_get_ticket', array( $this, 'get_single_support_ticket' ) );
	}

	/**
	 * AJAX callback to get attachment image HTML using WordPress standards.
	 *
	 * @return void
	 */
	public function postomatic_get_attachment_image_html() {
		// Verify nonce.
		check_ajax_referer( 'get_attachment_image_html', '_ajax_nonce' );

		if ( isset( $_POST['attachment_id'] ) && is_numeric( $_POST['attachment_id'] ) ) {
			$attachment_id = intval( wp_unslash( $_POST['attachment_id'] ) );
			$size          = isset( $_POST['size'] ) ? sanitize_text_field( wp_unslash( $_POST['size'] ) ) : 'thumbnail';

			$image_html = wp_get_attachment_image(
				$attachment_id,
				$size,
				false,
				array(
					'style' => 'max-width: 45px; height: 45px; margin-left: 4px; vertical-align: middle;',
				)
			);

			// Return image with proper headers.
			echo wp_kses_post( $image_html );
		} else {
			wp_send_json_error( 'Invalid attachment ID' );
		}

		wp_die();
	}

	/**
	 * Get all support tickets for the current user.
	 *
	 * @return void
	 */
	public function get_support_tickets() {
		// Verify nonce.
		check_ajax_referer( 'postomatic_support_nonce', 'nonce' );

		// Get the API key.
		$api_key = \Postomatic\Utils::get_code_option();
		if ( empty( $api_key ) ) {
			wp_send_json_error( array( 'message' => 'API key not found' ) );
			wp_die();
		}

		// Make the API request.
		$api_url  = \Postomatic\Constants::API_BASE_URL_FRONT . '/api/services/postomatic/support';
		$response = wp_remote_get(
			$api_url,
			array(
				'headers' => array(
					'Api-Key'      => $api_key,
					'Content-Type' => 'application/json',
				),
			)
		);

		// Check for errors.
		if ( is_wp_error( $response ) ) {
			wp_send_json_error( array( 'message' => $response->get_error_message() ) );
			wp_die();
		}

		// Get the response body.
		$body = wp_remote_retrieve_body( $response );
		$data = json_decode( $body, true );

		// Return the response.
		wp_send_json_success(
			array(
				'tickets' => $data['data'],
				'plan'    => $data['plan'],
			)
		);
		wp_die();
	}

	/**
	 * Submit a new support ticket.
	 *
	 * @return void
	 */
	public function submit_support_ticket() {
		// Verify nonce.
		check_ajax_referer( 'postomatic_support_nonce', 'nonce' );

		// Get the API key.
		$api_key = \Postomatic\Utils::get_code_option();
		if ( empty( $api_key ) ) {
			wp_send_json_error( array( 'message' => 'API key not found' ) );
			wp_die();
		}

		// Get the form data.
		$title         = isset( $_POST['title'] ) ? sanitize_text_field( wp_unslash( $_POST['title'] ) ) : '';
		$description   = isset( $_POST['description'] ) ? sanitize_textarea_field( wp_unslash( $_POST['description'] ) ) : '';
		$high_priority = isset( $_POST['high_priority'] ) ? (bool) $_POST['high_priority'] : false;

		// Validate the form data.
		if ( empty( $title ) || empty( $description ) ) {
			wp_send_json_error( array( 'message' => 'Title and description are required' ) );
			wp_die();
		}

		// Prepare the data for the API request.
		$data = array(
			'title'         => $title,
			'description'   => $description,
			'high_priority' => $high_priority,
		);

		// Make the API request.
		$api_url  = \Postomatic\Constants::API_BASE_URL_FRONT . '/api/services/postomatic/support';
		$response = wp_remote_post(
			$api_url,
			array(
				'headers' => array(
					'Api-Key'      => $api_key,
					'Content-Type' => 'application/json',
				),
				'body'    => wp_json_encode( $data ),
			)
		);

		// Check for errors.
		if ( is_wp_error( $response ) ) {
			wp_send_json_error( array( 'message' => $response->get_error_message() ) );
			wp_die();
		}

		// Get the response body.
		$body = wp_remote_retrieve_body( $response );
		$data = json_decode( $body, true );

		// Return the response.
		wp_send_json_success( $data );
		wp_die();
	}

	/**
	 * Get a single support ticket by ID.
	 *
	 * @return void
	 */
	public function get_single_support_ticket() {
		// Verify nonce.
		check_ajax_referer( 'postomatic_support_nonce', 'nonce' );

		// Get the API key.
		$api_key = \Postomatic\Utils::get_code_option();
		if ( empty( $api_key ) ) {
			wp_send_json_error( array( 'message' => 'API key not found' ) );
			wp_die();
		}

		// Get the ticket ID from either GET or POST request.
		$ticket_id = '';
		if ( isset( $_GET['ticket_id'] ) ) {
			$ticket_id = sanitize_text_field( wp_unslash( $_GET['ticket_id'] ) );
		} elseif ( isset( $_POST['ticket_id'] ) ) {
			$ticket_id = sanitize_text_field( wp_unslash( $_POST['ticket_id'] ) );
		}

		if ( empty( $ticket_id ) ) {
			wp_send_json_error( array( 'message' => 'Ticket ID is required' ) );
			wp_die();
		}

		// Make the API request.
		$api_url  = \Postomatic\Constants::API_BASE_URL_FRONT . '/api/services/postomatic/support/' . $ticket_id;
		$response = wp_remote_get(
			$api_url,
			array(
				'headers' => array(
					'Api-Key'      => $api_key,
					'Content-Type' => 'application/json',
				),
			)
		);

		// Check for errors.
		if ( is_wp_error( $response ) ) {
			wp_send_json_error( array( 'message' => $response->get_error_message() ) );
			wp_die();
		}

		// Get the response body.
		$body = wp_remote_retrieve_body( $response );
		$data = json_decode( $body, true );

		// Return the response.
		wp_send_json_success( $data['data'] );
		wp_die();
	}
}
