<?php
/**
 * Postomatic Plugin - Autopilot Handler class.
 *
 * PHP Version 5.6
 *
 * @package  Postomatic
 * @category Plugin
 * @license  GPL-2.0-or-later https://www.gnu.org/licenses/gpl-2.0.html
 * @link     https://buildomatics.com/postomatics
 * @since    1.0.0
 */

namespace Postomatic\Api;

use Postomatic\Constants;
use Postomatic\Utils;
use Postomatic\Core\Activator;

/**
 * Autopilot Handler class.
 *
 * This class handles the autopilot AJAX functionality.
 *
 * @category Plugin
 * @license  GPL-2.0-or-later https://www.gnu.org/licenses/gpl-2.0.html
 * @link     https://buildomatics.com/postomatics
 * @since    1.0.0
 */
class Autopilot_Handler {

	/**
	 * Constructor.
	 */
	public function __construct() {
		add_action( 'wp_ajax_postomatic_get_autopilots', array( $this, 'get_autopilots' ) );
		add_action( 'wp_ajax_postomatic_create_autopilot', array( $this, 'create_autopilot' ) );
		add_action( 'wp_ajax_postomatic_delete_autopilot', array( $this, 'delete_autopilot' ) );
	}

	/**
	 * Get autopilots.
	 *
	 * This method returns the autopilot tasks list.
	 *
	 * @param  int $retry_count Number of retry attempts (default: 0).
	 * @return void
	 */
	public function get_autopilots( $retry_count = 0 ) {
		// Check nonce for security.
		if ( ! isset( $_POST['nonce'] ) || ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['nonce'] ) ), 'postomatic_admin_nonce' ) ) {
			wp_send_json_error( 'Invalid nonce', 403 );

			return;
		}

		// Check if user has permission.
		if ( ! current_user_can( 'edit_posts' ) ) {
			wp_send_json_error( 'Permission denied', 403 );

			return;
		}
		$api_key = Utils::get_api_service_key();

		// Make a direct request to the API endpoint.
		$api_url = Constants::API_AUTOPILOT_EXTERNAL;
		$args    = array(
			'headers' => array(
				'Api-Key'      => $api_key,
				'Content-Type' => 'application/json',
			),
			'timeout' => 30,
		);

		// Make the request.
		$response = wp_remote_get( $api_url, $args );

		// Check if the request was successful.
		if ( is_wp_error( $response ) ) {
			// Get the error message from the WP_Error object.
			$error_message = $response->get_error_message();
			wp_send_json_error( $error_message, 403 );

			return;
		}

		// Get the response code.
		$response_code = wp_remote_retrieve_response_code( $response );

		// Check for 401 Unauthorized error.
		if ( 401 === $response_code ) {
			// Call Activator::activate() to refresh the API key.
			Activator::activate();

			// Sleep for 15 seconds.
			sleep( 10 );

			// Retry up to 2 times (retry_count < 2).
			if ( 2 > $retry_count ) { // Yoda condition.
				// Retry the request with incremented retry count.
				return $this->get_autopilots( $retry_count + 1 );
			}

			// If we've already retried twice, return an error.
			wp_send_json_error(
				esc_html__( 'Authorization failed after multiple attempts.', 'postomatic' ),
				401
			);

			return;
		}

		if ( 200 !== $response_code ) {
			// Get the response body to check for error message.
			$body = wp_remote_retrieve_body( $response );
			$data = json_decode( $body, true );

			// Check if the response contains status=false and a message.
			if ( isset( $data['status'] ) && false === $data['status'] && isset( $data['message'] ) ) { // Yoda condition.
				wp_send_json_error( $data['message'], 403 );
			} else {
				wp_send_json_error( 'Failed to fetch autopilots. Response code: ' . $response_code, 403 );
			}

			return;
		}

		// Get the response body.
		$body = wp_remote_retrieve_body( $response );
		$data = json_decode( $body, true );
		// Send the response as JSON.
		wp_send_json_success( $data['data'] );
	}

	/**
	 * Create autopilot task.
	 *
	 * This method creates a new autopilot task.
	 *
	 * @param  int $retry_count Number of retry attempts (default: 0).
	 * @return void
	 */
	public function create_autopilot( $retry_count = 0 ) {
		// Check nonce for security.
		if ( ! isset( $_POST['nonce'] ) || ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['nonce'] ) ), 'postomatic_admin_nonce' ) ) {
			wp_send_json_error( 'Invalid nonce', 403 );

			return;
		}

		// Check if user has permission.
		if ( ! current_user_can( 'edit_posts' ) ) {
			wp_send_json_error( 'Permission denied', 403 );

			return;
		}

		// Get task data from the request.
		if ( ! isset( $_POST['task'] ) ) {
			wp_send_json_error( 'Task data is required.', 403 );

			return;
		}
		$task_data = json_decode( sanitize_text_field( wp_unslash( $_POST['task'] ) ), true );
		if ( ! $task_data ) {
			wp_send_json_error( 'Invalid task data.', 403 );

			return;
		}

		$api_key = Utils::get_api_service_key();

		// Make a direct request to the API endpoint.
		$api_url = Constants::API_AUTOPILOT_EXTERNAL;
		$args    = array(
			'method'      => 'POST',
			'headers'     => array(
				'Api-Key'      => $api_key,
				'Content-Type' => 'application/json',
				'Accept'       => 'application/json',
			),
			'body'        => wp_json_encode( $task_data ),
			'timeout'     => 30,
			'data_format' => 'body', // Ensure data is sent as raw body content.
		);

		// Make the request.
		$response = wp_remote_post( $api_url, $args );

		// Check if the request was successful.
		if ( is_wp_error( $response ) ) {
			// Get the error message from the WP_Error object.
			$error_message = $response->get_error_message();
			wp_send_json_error( $error_message, 403 );

			return;
		}

		// Get the response code.
		$response_code = wp_remote_retrieve_response_code( $response );

		// Check for 401 Unauthorized error.
		if ( 401 === $response_code ) {
			// Call Activator::activate() to refresh the API key.
			Activator::activate();

			// Sleep for 15 seconds.
			sleep( 10 );

			// Retry up to 2 times (retry_count < 2).
			if ( 2 > $retry_count ) { // Yoda condition.
				// Retry the request with incremented retry count.
				return $this->create_autopilot( $retry_count + 1 );
			}

			// If we've already retried twice, return an error.
			wp_send_json_error(
				esc_html__( 'Authorization failed after multiple attempts.', 'postomatic' ),
				401
			);

			return;
		}

		if ( 201 !== $response_code ) {
			// Get the response body to check for error message.
			$body = wp_remote_retrieve_body( $response );
			$data = json_decode( $body, true );

			// Check if the response contains status=false and a message.
			if ( isset( $data['status'] ) && false === $data['status'] && isset( $data['message'] ) ) { // Yoda condition.
				wp_send_json_error( $data['message'], 403 );
			} else {
				wp_send_json_error( 'Failed to create autopilot. Response code: ' . $response_code, 403 );
			}

			return;
		}

		// Get the response body.
		$body = wp_remote_retrieve_body( $response );
		$data = json_decode( $body, true );
		// Send the response as JSON.
		wp_send_json_success( $data['data'] );
	}

	/**
	 * Delete autopilot task.
	 *
	 * This method deletes an autopilot task.
	 *
	 * @param  int $retry_count Number of retry attempts (default: 0).
	 * @return void
	 */
	public function delete_autopilot( $retry_count = 0 ) {
		// Check nonce for security.
		if ( ! isset( $_POST['nonce'] ) || ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['nonce'] ) ), 'postomatic_admin_nonce' ) ) {
			wp_send_json_error( 'Invalid nonce', 403 );

			return;
		}

		// Check if user has permission.
		if ( ! current_user_can( 'edit_posts' ) ) {
			wp_send_json_error( 'Permission denied', 403 );

			return;
		}

		// Get task ID from the request.
		if ( ! isset( $_POST['task_id'] ) ) {
			wp_send_json_error( 'Task ID is required', 403 );

			return;
		}

		$task_id = isset( $_POST['task_id'] ) ? sanitize_text_field( wp_unslash( $_POST['task_id'] ) ) : '';

		$api_key = Utils::get_api_service_key();

		// Make a direct request to the API endpoint.
		$api_url = Constants::API_AUTOPILOT_EXTERNAL . '/' . $task_id;
		$args    = array(
			'method'      => 'DELETE',
			'headers'     => array(
				'Api-Key'      => $api_key,
				'Content-Type' => 'application/json',
				'Accept'       => 'application/json',
			),
			'timeout'     => 30,
			'data_format' => 'body', // Ensure data is sent as raw body content.
		);

		// Make the request.
		$response = wp_remote_request( $api_url, $args );

		// Check if the request was successful.
		if ( is_wp_error( $response ) ) {
			// Get the error message from the WP_Error object.
			$error_message = $response->get_error_message();
			wp_send_json_error( $error_message, 403 );

			return;
		}

		// Get the response code.
		$response_code = wp_remote_retrieve_response_code( $response );

		// Check for 401 Unauthorized error.
		if ( 401 === $response_code ) {
			// Call Activator::activate() to refresh the API key.
			Activator::activate();

			// Sleep for 15 seconds.
			sleep( 10 );

			// Retry up to 2 times (retry_count < 2).
			if ( 2 > $retry_count ) { // Yoda condition.
				// Retry the request with incremented retry count.
				return $this->delete_autopilot( $retry_count + 1 );
			}

			// If we've already retried twice, return an error.
			wp_send_json_error(
				esc_html__( 'Authorization failed after multiple attempts.', 'postomatic' ),
				401
			);

			return;
		}

		if ( 200 !== $response_code ) {
			// Get the response body to check for error message.
			$body = wp_remote_retrieve_body( $response );
			$data = json_decode( $body, true );

			// Check if the response contains status=false and a message.
			if ( isset( $data['status'] ) && false === $data['status'] && isset( $data['message'] ) ) { // Yoda condition.
				wp_send_json_error( $data['message'], 403 );
			} else {
				wp_send_json_error( 'Failed to delete autopilot. Response code: ' . $response_code, 403 );
			}

			return;
		}

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

		// Send the response as JSON with success status and message.
		wp_send_json_success(
			array(
				'status'  => true,
				'message' => 'AutoPilot task has been deleted successfully!',
			)
		);
	}
}
