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

/**
 * Speakers Handler class.
 *
 * This class handles the speakers 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 Speakers_Handler {

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

	/**
	 * Get speakers.
	 *
	 * This method returns the speakers list.
	 *
	 * @return void
	 */
	public function get_speakers() {
		$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 speakers.
		$speakers = $this->get_speakers_data();

		wp_send_json_success( $speakers );
	}

	/**
	 * Get speakers data.
	 *
	 * @return array An array of speakers.
	 */
	private function get_speakers_data() {
		// Try to get speakers data from transient first.
		$speakers_data = get_transient( 'postomatic_speakers_data' );

		if ( false !== $speakers_data ) {
			return $speakers_data;
		}

		// If no transient, try to get from options.
		$speakers_data = get_option( 'postomatic_speakers_data' );

		if ( false !== $speakers_data && ! empty( $speakers_data ) ) {
			// Set transient for future requests.
			set_transient( 'postomatic_speakers_data', $speakers_data, HOUR_IN_SECONDS );

			return $speakers_data;
		}

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

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

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

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

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

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

		// 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] ) ) {
					// Store the speakers data in options and transient for future use.
					update_option( 'postomatic_speakers_data', $data );
					set_transient( 'postomatic_speakers_data', $data, HOUR_IN_SECONDS );

					return $data;
				}
			} elseif ( isset( $result[0] ) ) {
				// If result is a direct array (not wrapped in data property).
				// Store the speakers data in options and transient for future use.
				update_option( 'postomatic_speakers_data', $result );
				set_transient( 'postomatic_speakers_data', $result, HOUR_IN_SECONDS );

				return $result;
			}
		}

		// Return default speakers as fallback.
		return $this->get_default_speakers();
	}

	/**
	 * Handle speakers 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_speakers_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_SPEAKERS_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 $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 15 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_speakers_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 - handle both direct array and data-wrapped responses.
		$response_data = array(
			'status' => true,
			'data'   => $result,
		);

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

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