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

/**
 * Recent Posts Handler class.
 *
 * This class handles the recent posts 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 Recent_Posts_Handler {

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

	/**
	 * Get recent posts.
	 *
	 * This method returns the recent posts list.
	 *
	 * @return void
	 */
	public function get_recent_posts() {
		$nonce = isset( $_POST['nonce'] ) ? sanitize_key( wp_unslash( $_POST['nonce'] ) ) : '';
		// Check nonce for security.
		if ( empty( $nonce ) || ! wp_verify_nonce( $nonce, 'postomatic_support_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 URL parameter for pagination if provided.
		$url = isset( $_POST['url'] ) ? sanitize_text_field( wp_unslash( $_POST['url'] ) ) : null;

		// Get recent posts.
		$recent_posts = $this->get_recent_posts_data( $url );

		wp_send_json_success( $recent_posts );
	}

	/**
	 * Get recent posts data.
	 *
	 * @param  string $url         Optional URL for pagination.
	 * @param  int    $retry_count Number of retry attempts (default: 0).
	 * @return array  An array of recent posts.
	 */
	private function get_recent_posts_data( $url = null, $retry_count = 0 ) {
		// Get API key.
		$api_key = Utils::get_api_service_key();

		// Set API URL.
		$api_url = $url ? $url : Constants::API_POSTS_RECENT_LIST;

		// 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 empty array as fallback.
			return array(
				'data' => array(),
				'meta' => array(
					'current_page' => 1,
					'last_page'    => 1,
					'total'        => 0,
					'per_page'     => 10,
				),
			);
		}

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

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

			// If we've already retried twice, return empty array as fallback.
			return array(
				'data' => array(),
				'meta' => array(
					'current_page' => 1,
					'last_page'    => 1,
					'total'        => 0,
					'per_page'     => 10,
				),
			);
		}

		// 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 empty array as fallback.
			return array(
				'data' => array(),
				'meta' => array(
					'current_page' => 1,
					'last_page'    => 1,
					'total'        => 0,
					'per_page'     => 10,
				),
			);
		}

		// Return the result.
		return $result;
	}
}
