<?php
/**
 * Wayl API Client
 *
 * Handles communication with the Wayl API.
 *
 * @package Wayl_Checkout
 * @since 1.2.0
 */

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

/**
 * Class WaylCHP_API
 */
class WaylCHP_API {
	/**
	 * API base URL
	 *
	 * @var string
	 */
	private $api_base = 'https://api.thewayl.com/api/v1';

	/**
	 * API key
	 *
	 * @var string
	 */
	private $api_key;

	/**
	 * Constructor
	 *
	 * @param string|null $api_key Optional API key, otherwise retrieved from options
	 */
	public function __construct( $api_key = null ) {
		// Use provided API key or get from options
		$this->api_key = $api_key ?: get_option( 'waylchp_api_key', '' );

		// Initialize logger
		WaylCHP_Logger::init();
	}

	/**
	 * Create a Wayl checkout link
	 *
	 * @param array $payload
	 * @return array|false Decoded response or false on failure
	 */
	public function create_checkout_link( array $payload ) {
		if ( empty( $this->api_key ) ) {
			WaylCHP_Logger::error( 'Wayl API key is not configured' );
			return false;
		}

		$url = $this->api_base . '/links';

		$args = array(
			'headers'     => array(
				'Content-Type'           => 'application/json',
				'X-WAYL-AUTHENTICATION' => $this->api_key,
			),
			'body'        => wp_json_encode( $payload ),
			'timeout'     => 30,
			'data_format' => 'body',
		);

		WaylCHP_Logger::info( 'Making Wayl API request to: ' . esc_url( $url ) );
		WaylCHP_Logger::debug( 'API Request payload: ' . wp_json_encode( $payload ) );

		$response = wp_remote_post( $url, $args );

		if ( is_wp_error( $response ) ) {
			$error_message = $response->get_error_message();
			WaylCHP_Logger::error( 'Wayl API Request failed: ' . esc_html( $error_message ) );
			return false;
		}

		$status_code = wp_remote_retrieve_response_code( $response );
		$body        = wp_remote_retrieve_body( $response );

		WaylCHP_Logger::info( 'Wayl API Response received - Status: ' . absint( $status_code ) );
		WaylCHP_Logger::debug( 'API Response body: ' . $body );

		if ( $status_code !== 200 && $status_code !== 201 ) {
			WaylCHP_Logger::error( "Wayl API returned non-success status: $status_code" );
			return false;
		}

		$data = json_decode( $body, true );

		if ( json_last_error() !== JSON_ERROR_NONE ) {
			WaylCHP_Logger::error( 'JSON decode error: ' . json_last_error_msg() );
			return false;
		}

		WaylCHP_Logger::info( 'Wayl API request completed successfully' );
		return $data;
	}

	/**
	 * Get available payment channels from Wayl API
	 *
	 * @return array|false Array of channels or false on failure
	 */
	public function get_payment_channels() {
		if ( empty( $this->api_key ) ) {
			WaylCHP_Logger::error( 'Wayl API key is not configured for channel fetch' );
			return false;
		}

		$url = $this->api_base . '/channels';

		$args = array(
			'headers' => array(
				'X-WAYL-AUTHENTICATION' => $this->api_key,
			),
			'timeout' => 15,
		);

		WaylCHP_Logger::info( 'Fetching Wayl payment channels from: ' . esc_url( $url ) );

		$response = wp_remote_get( $url, $args );

		if ( is_wp_error( $response ) ) {
			$error_message = $response->get_error_message();
			WaylCHP_Logger::error( 'Wayl channels API request failed: ' . esc_html( $error_message ) );
			return false;
		}

		$status_code = wp_remote_retrieve_response_code( $response );
		$body       = wp_remote_retrieve_body( $response );

		WaylCHP_Logger::debug( 'Wayl channels API response - Status: ' . absint( $status_code ) );

		if ( $status_code !== 200 ) {
			WaylCHP_Logger::error( 'Wayl channels API returned non-success status: ' . $status_code );
			return false;
		}

		$data = json_decode( $body, true );

		if ( json_last_error() !== JSON_ERROR_NONE ) {
			WaylCHP_Logger::error( 'JSON decode error for channels: ' . json_last_error_msg() );
			return false;
		}

		// Return channels array from response
		if ( isset( $data['data'] ) && is_array( $data['data'] ) ) {
			WaylCHP_Logger::info( 'Successfully fetched ' . count( $data['data'] ) . ' payment channels' );
			return $data['data'];
		}

		WaylCHP_Logger::warning( 'Channels API response missing data array' );
		return false;
	}

	/**
	 * Process refund via Wayl API
	 *
	 * @param string $reference_id Original payment reference ID (sent to Wayl during payment)
	 * @param int    $amount Refund amount in IQD (always the full order amount)
	 * @param string $reason Refund reason (provided by merchant)
	 * @return array|false Decoded response or false on failure
	 */
	public function process_refund( $reference_id, $amount, $reason = '' ) {
		// Always log refund API calls (critical operation) - force logging
		WaylCHP_Logger::info( '=== WAYL REFUND API CALL ===', true );

		if ( empty( $this->api_key ) ) {
			WaylCHP_Logger::error( 'Wayl API key is not configured for refund', true );
			return false;
		}

		$url = $this->api_base . '/refunds';

		// Build payload exactly as specified: referenceId, reason, amount
		$payload = array(
			'referenceId' => sanitize_text_field( $reference_id ),
			'amount'      => intval( $amount ),
			'reason'      => sanitize_text_field( $reason ),
		);

		$args = array(
			'headers'     => array(
				'Content-Type'           => 'application/json',
				'X-WAYL-AUTHENTICATION' => $this->api_key,
			),
			'body'        => wp_json_encode( $payload ),
			'timeout'     => 30,
			'data_format' => 'body',
		);

		WaylCHP_Logger::info( 'Refund API URL: ' . esc_url( $url ), true );
		WaylCHP_Logger::info( 'Refund API Request payload: ' . wp_json_encode( $payload ), true );
		WaylCHP_Logger::debug( 'Request headers: ' . wp_json_encode( $args['headers'] ), true );

		$response = wp_remote_post( $url, $args );

		if ( is_wp_error( $response ) ) {
			$error_code    = $response->get_error_code();
			$error_message = $response->get_error_message();
			WaylCHP_Logger::error( '=== REFUND API REQUEST ERROR ===', true );
			WaylCHP_Logger::error( 'Error Code: ' . esc_html( $error_code ), true );
			WaylCHP_Logger::error( 'Error Message: ' . esc_html( $error_message ), true );
			return false;
		}

		$status_code = wp_remote_retrieve_response_code( $response );
		$body        = wp_remote_retrieve_body( $response );
		$headers     = wp_remote_retrieve_headers( $response );

		WaylCHP_Logger::info( 'Refund API Response Status: ' . absint( $status_code ), true );
		WaylCHP_Logger::info( 'Refund API Response Body: ' . $body, true );
		WaylCHP_Logger::debug( 'Response Headers: ' . wp_json_encode( $headers ), true );

		if ( $status_code !== 200 && $status_code !== 201 ) {
			WaylCHP_Logger::error( '=== REFUND API ERROR RESPONSE ===', true );
			WaylCHP_Logger::error( 'HTTP Status Code: ' . absint( $status_code ), true );
			WaylCHP_Logger::error( 'Response Body: ' . $body, true );
			
			// Try to extract error message from response
			$error_data = json_decode( $body, true );
			if ( $error_data && isset( $error_data['message'] ) ) {
				WaylCHP_Logger::error( 'Error Message from API: ' . sanitize_text_field( $error_data['message'] ), true );
			}
			return false;
		}

		$data = json_decode( $body, true );

		if ( json_last_error() !== JSON_ERROR_NONE ) {
			WaylCHP_Logger::error( '=== JSON DECODE ERROR ===', true );
			WaylCHP_Logger::error( 'JSON Error: ' . json_last_error_msg(), true );
			WaylCHP_Logger::error( 'Response Body: ' . $body, true );
			return false;
		}

		WaylCHP_Logger::info( '=== REFUND API SUCCESS ===', true );
		WaylCHP_Logger::info( 'Decoded Response: ' . wp_json_encode( $data ), true );
		return $data;
	}

	/**
	 * Verify webhook signature
	 *
	 * @param string $payload
	 * @param string $signature
	 * @param string $secret
	 * @return bool
	 */
	public static function verify_webhook_signature( $payload, $signature, $secret ) {
		$expected_signature = hash_hmac( 'sha256', $payload, $secret );
		return hash_equals( $expected_signature, $signature );
	}
}

