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

/**
 * Credit Scores Handler class.
 *
 * This class handles the credit scores 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 Credit_Scores_Handler {

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

	/**
	 * Get credit scores.
	 *
	 * This method returns the credit scores data.
	 *
	 * @return void
	 */
	public function get_credit_scores() {
		// 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 credit scores data.
		$credit_scores_data = $this->get_credit_scores_data();

		wp_send_json_success( $credit_scores_data );
	}

	/**
	 * Get credit scores data.
	 *
	 * @param  int $retry_count Number of retry attempts (default: 0).
	 * @return array An array of credit scores data.
	 */
	private function get_credit_scores_data( $retry_count = 0 ) {
		// Get data directly from API.
		$api_key = Utils::get_api_service_key();
		$api_url = Constants::API_CREDITS_SCORES_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.
			// error_log('Postomatic Credit Scores API Error: ' . $response->get_error_message()); // For debugging only.
			$sample_data = $this->get_sample_credit_scores_data();

			return $sample_data;
		}

		// 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_sample_credit_scores_data();
		}

		// 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 ) { // Yoda condition.
				// Retry the request with incremented retry count.
				return $this->get_credit_scores_data( $retry_count + 1 );
			}

			// If we've already retried twice, return sample data as fallback.
			return $this->get_sample_credit_scores_data();
		}

		// 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() ) {
			// Log the error for debugging purposes only.
			// error_log('Postomatic Credit Scores API Error: Invalid response (code: ' . $response_code . ')'); // For debugging only.
			$sample_data = $this->get_sample_credit_scores_data();

			return $sample_data;
		}

		// If result is empty or doesn't have the expected structure, return sample data.
		if ( empty( $result ) || ! isset( $result['data'] ) || empty( $result['data'] ) ) {
			// Log the error for debugging purposes only.
			// error_log('Postomatic Credit Scores API Error: Unexpected response structure'); // For debugging only.
			$sample_data = $this->get_sample_credit_scores_data();

			return $sample_data;
		}

		// Return the credit scores data.
		return $result;
	}

	/**
	 * Get sample credit scores data.
	 *
	 * This method returns sample credit scores data when the API is not available.
	 *
	 * @return array An array of sample credit scores data.
	 */
	private function get_sample_credit_scores_data() {
		// Create sample data for common form fields.
		$sample_data = array();

		return $sample_data;
	}
}
