<?php
/**
 * Postomatic Plugin - Plan 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;

/**
 * Plan Handler class.
 *
 * This class handles the plan data 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 Plan_Handler {

	/**
	 * Constructor.
	 */
	public function __construct() {
		add_action( 'wp_ajax_postomatic_get_active_plan', array( $this, 'get_active_plan' ) );
	}

	/**
	 * Get active plan.
	 *
	 * This method returns the active plan data.
	 *
	 * @return void
	 */
	public function get_active_plan() {
		// 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 plan data.
		$plan_data = $this->get_plan_data();

		wp_send_json_success( $plan_data );
	}

	/**
	 * Get plan data.
	 *
	 * @return array An array of plan data.
	 */
	private function get_plan_data() {
		// Default plan data.
		$default_data = array();

		// Get API key.
		$api_key = Utils::get_api_service_key();

		// Create a mock request object.
		$request = new \WP_REST_Request( 'GET', Constants::API_PLAN_ACTIVE );
		$request->set_header( 'Api-Key', $api_key );

		// Make the request.
		$response = $this->handle_plan_data_request( $request );

		// If we got a WP_Error, return default plan data.
		if ( is_wp_error( $response ) ) {
			return $default_data;
		}

		// Get the data from the response.
		$result = $response->get_data();

		// Check if response is successful.
		if ( empty( $result ) || ! isset( $result['data'] ) ) {
			return $default_data;
		}

		// Ensure the result has all the expected properties.
		$plan_data = $result['data'];

		// Return the plan data.
		return $plan_data;
	}

	/**
	 * Handle plan data request.
	 *
	 * @param  \WP_REST_Request $request     The request object.
	 * @param  int              $retry_count Number of retry attempts (default: 0).
	 * @return \WP_REST_Response|\WP_Error The response object or error.
	 */
	public function handle_plan_data_request( $request, $retry_count = 0 ) {
		// Validate the API key.
		$api_key = $request->get_header( 'Api-Key' );
		if ( empty( $api_key ) || Utils::get_api_service_key() !== $api_key ) {
			return new \WP_Error(
				'invalid_api_key',
				'Invalid or missing API key.',
				array( 'status' => 403 )
			);
		}

		// Set API URL.
		$api_url = Constants::API_PLAN_ACTIVE;

		// Send request to API.
		$response = wp_remote_get(
			$api_url,
			array(
				'method'      => 'GET',
				'timeout'     => 45,
				'redirection' => 5,
				'httpversion' => '1.0',
				'blocking'    => true,
				'headers'     => array(
					'Content-Type' => 'application/json',
					'Api-Key'      => $api_key,
				),
				'cookies'     => array(),
			)
		);

		// Check for errors.
		if ( is_wp_error( $response ) ) {
			return $response;
		}

		// Get 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 10 seconds.
			sleep( 10 );

			// Retry up to 2 times (retry_count < 2).
			if ( 2 > $retry_count ) {
				// Update the API key in the request with the refreshed one.
				$request->set_header( 'Api-Key', Utils::get_api_service_key() );

				// Retry the request with incremented retry count.
				return $this->handle_plan_data_request( $request, $retry_count + 1 );
			}

			// If we've already retried twice, return an error.
			return new \WP_Error(
				'authorization_failed',
				esc_html__( 'Authorization failed after multiple attempts.', 'postomatic' ),
				array( 'status' => 401 )
			);
		}

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

		// Check if response is successful.
		if ( 200 !== $response_code || JSON_ERROR_NONE !== json_last_error() ) {
			return new \WP_Error(
				'invalid_response',
				'Invalid response from API (code: ' . $response_code . ').',
				array( 'status' => $response_code )
			);
		}

		// Structure the response.
		$response_data = array(
			'status' => true,
			'data'   => $result,
		);

		// Return the structured response.
		return new \WP_REST_Response( $response_data, 200 );
	}
}
