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

/**
 * Languages Handler class.
 *
 * This class handles the languages 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 Languages_Handler {

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

	/**
	 * Get languages.
	 *
	 * This method returns the languages list.
	 *
	 * @return void
	 */
	public function get_languages() {
		$nonce = isset( $_POST['nonce'] ) ? sanitize_key( wp_unslash( $_POST['nonce'] ) ) : '';
		// Check nonce for security.
		if ( empty( $nonce ) || ! wp_verify_nonce( $nonce, 'postomatic_admin_nonce' ) ) {
			wp_send_json_error( 'Invalid nonce' );

			return;
		}

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

			return;
		}

		// Get languages.
		$languages = $this->get_languages_data();

		wp_send_json_success( $languages );
	}

	/**
	 * Get languages data.
	 *
	 * @return array An array of languages.
	 */
	private function get_languages_data() {
		// Get API key.
		$api_key = Utils::get_api_service_key();

		// Create a mock request object similar to how it's done in Autopilot_Handler::get_autopilots().
		$request = new \WP_REST_Request( 'GET', Constants::API_LANGUAGES_LIST );
		$request->set_header( 'Api-Key', $api_key );

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

		// If we got a WP_Error, return default languages.
		if ( is_wp_error( $response ) ) {
			// Return default languages as fallback.
			return $this->get_default_languages();
		}

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

		// Check if response is successful.
		if ( empty( $result ) ) {
			// Return default languages as fallback.
			return $this->get_default_languages();
		}

		// Process the result based on its structure.
		if ( is_array( $result ) ) {
			// If result has a data property that is an array (from our WP_REST_Response).
			if ( isset( $result['data'] ) && is_array( $result['data'] ) ) {
				$data = $result['data'];
				// If data is a simple array, return it directly.

				if ( isset( $data[0] ) ) {
					return $data;
				}

				// If data is an object with key-value pairs.
				$languages = array();
				foreach ( $data as $key => $value ) {
					if ( is_string( $value ) ) {
						$languages[] = array(
							'code' => $key,
							'name' => $value,
						);
					}
				}

				if ( ! empty( $languages ) ) {
					return $languages;
				}
			}
		}

		// Return default languages as fallback.
		return $this->get_default_languages();
	}

	/**
	 * Handle the languages 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 WP_Error on failure.
	 */
	private function handle_languages_request( $request, $retry_count = 0 ) {
		// Get the API key from the request headers.
		$api_key = $request->get_header( 'Api-Key' );

		// Get the URL from the request.
		$api_url = Constants::API_LANGUAGES_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 ) ) {
			return $response; // Return the WP_Error.
		}

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

		/*
		 * Throttled, not unauthorised. Authenticated endpoints allow 120
		 * requests a minute per credential. A 429 must not be mistaken for a bad
		 * key — that would trigger a pointless key rotation, which is itself rate
		 * limited — and must not be retried immediately.
		 */
		if ( 429 === (int) $response_code ) {
			return new \WP_Error(
				'rate_limited',
				esc_html__( 'Too many requests to the Postomatic service. Please try again in a moment.', 'postomatic' ),
				array(
					'status'      => 429,
					'retry_after' => Utils::get_retry_after_seconds( $response ),
				)
			);
		}

		// 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 ( $retry_count < 2 ) {
				// 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_languages_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(
				'rest_invalid_response',
				esc_html__( 'Invalid response from languages API.', 'postomatic' ),
				array( 'status' => $response_code )
			);
		}

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

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

	/**
	 * Get default languages.
	 *
	 * This method returns a hardcoded list of common languages as a fallback.
	 *
	 * @return array An array of default languages.
	 */
	private function get_default_languages() {
		return array();
	}
}
