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

/**
 * Countries Handler class.
 *
 * This class handles the countries 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 Countries_Handler {

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

	/**
	 * Get countries.
	 *
	 * This method returns the countries list.
	 *
	 * @return void
	 */
	public function get_countries() {
		// Check nonce for security.
		if ( ! isset( $_POST['nonce'] ) || ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['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 countries.
		$countries = $this->get_countries_data();

		wp_send_json_success( $countries );
	}

	/**
	 * Get countries data.
	 *
	 * @param  int $retry_count Number of retry attempts (default: 0).
	 * @return array An array of countries.
	 */
	private function get_countries_data( $retry_count = 0 ) {
		// Get API key.
		$api_key = Utils::get_api_service_key();

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

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

		// Check for errors.
		if ( is_wp_error( $response ) ) {
			// Log the error for debugging purposes only.
			// Return default countries as fallback.
			return $this->get_default_countries();
		}

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

		/*
		 * Throttled, not unauthorised. Authenticated endpoints allow 120
		 * requests a minute per credential. Returning the fallback keeps the
		 * screen usable, and returning early makes sure a 429 never reaches the
		 * 401 branch below and triggers a key rotation it does not need.
		 */
		if ( 429 === (int) $response_code ) {
			return $this->get_default_countries();
		}

		// Check for 401 Unauthorized error.
		if ( 401 === $response_code ) {
			// Refresh the API key, waiting only as long as the handshake needs
			// rather than a fixed ten seconds. See Activator::refresh_api_key().
			Activator::refresh_api_key();

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

			// If we've already retried twice, return default countries as fallback.
			return $this->get_default_countries();
		}

		// 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 default countries as fallback.
			return $this->get_default_countries();
		}

		// Return the result.
		return $result;
	}

	/**
	 * Get default countries.
	 *
	 * This method returns a hardcoded list of common countries as a fallback.
	 *
	 * @return array An array of default countries.
	 */
	private function get_default_countries() {
		return array(
			'North America' => array(
				'United States',
				'Canada',
				'Mexico',
			),
			'Europe'        => array(
				'United Kingdom',
				'Germany',
				'France',
				'Italy',
				'Spain',
			),
			'Asia'          => array(
				'China',
				'Japan',
				'India',
				'South Korea',
				'Singapore',
			),
			'Oceania'       => array(
				'Australia',
				'New Zealand',
			),
			'South America' => array(
				'Brazil',
				'Argentina',
				'Colombia',
			),
			'Africa'        => array(
				'South Africa',
				'Nigeria',
				'Egypt',
			),
		);
	}
}
