<?php
/**
 * API Client Class
 *
 * @package PromoSDK
 */

// Exit if accessed directly.
if ( ! defined( 'ABSPATH' ) ) {
	exit;
}


if ( ! class_exists( 'API_Client' ) ) {
	/**
	 * API Client Class
	 *
	 * Handles API communication with LeetCampaign and caching.
	 *
	 * @since 1.0.0
	 */
	class API_Client {
		/**
		 * Configuration array
		 *
		 * @var array
		 */
		private $config = array();

		/**
		 * Constructor
		 *
		 * @param array $config Configuration array.
		 */
		public function __construct( $config ) {
			$this->config = $config;
		}

		/**
		 * Fetch promotional data for product
		 *
		 * @param string $product_slug Product identifier.
		 * @return array|null Promo data or null on failure.
		 */
		public function fetch_promo_data( $product_slug ) {
			// Try to get from cache first.
			$cache_key = "promo_sdk_{$product_slug}_data";
			$cached    = get_transient( $cache_key );

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

			// Build API endpoint URL.
			$api_url = $this->get_api_url( $product_slug );

			if ( empty( $api_url ) ) {
				return null;
			}

			// Make API request.
			$response = wp_remote_get(
				$api_url,
				array(
					'timeout' => 10,
					'headers' => array(
						'Accept' => 'application/json',
					),
				)
			);

			// Handle errors.
			if ( is_wp_error( $response ) ) {
				return null;
			}

			// Validate response code.
			$code = wp_remote_retrieve_response_code( $response );
			if ( 200 !== $code ) {
				return null;
			}

			// Parse and validate JSON.
			$body = wp_remote_retrieve_body( $response );
			$data = json_decode( $body, true );

			if ( ! is_array( $data ) || ! isset( $data['success'] ) || ! $data['success'] ) {
				return null;
			}

			// Check if campaign exists.
			if ( ! isset( $data['campaign'] ) || empty( $data['campaign'] ) ) {
				return null;
			}

			// Transform API response to SDK format.
			$transformed_data = $this->transform_api_response( $data );

			// Validate promo data.
			if ( ! $this->validate_promo_data( $transformed_data ) ) {
				return null;
			}

			// Cache successful response.
			$cache_duration = apply_filters( 'promo_sdk_cache_duration', $this->config['cache_duration'] );
			set_transient( $cache_key, $transformed_data, $cache_duration );

			return $transformed_data;
		}

		/**
		 * Clear cached data
		 *
		 * @param string $product_slug Product identifier.
		 * @return bool Success status.
		 */
		public function clear_cache( $product_slug ) {
			$cache_key = "promo_sdk_{$product_slug}_data";
			return delete_transient( $cache_key );
		}

		/**
		 * Get API URL for product
		 *
		 * @param string $product_slug Product identifier.
		 * @return string API URL.
		 */
		private function get_api_url( $product_slug ) {
			if ( empty( $this->config['api_endpoint'] ) ) {
				return '';
			}

			$url = add_query_arg(
				array(
					'product_slug' => sanitize_key( $product_slug ),
				),
				$this->config['api_endpoint']
			);

			return $url;
		}

		/**
		 * Transform API response to SDK format
		 *
		 * @param array $api_data API response data.
		 * @return array Transformed data.
		 */
		private function transform_api_response( $api_data ) {
			$campaign = $api_data['campaign'];
			$popup    = isset( $campaign['popup'] ) ? $campaign['popup'] : array();
			$notice   = isset( $campaign['notice'] ) ? $campaign['notice'] : array();

			// Helper function to get color with fallback to null (SDK will use defaults).
			$get_color = function ( $value ) {
				return ( isset( $value ) && ! empty( $value ) ) ? $value : null;
			};

			return array(
				'id'                       => $campaign['id'],
				'product_slug'             => $api_data['product_slug'],
				'popup_title'              => isset( $popup['title'] ) ? $popup['title'] : '',
				'popup_cta_text'           => isset( $popup['cta_text'] ) ? $popup['cta_text'] : '',
				'popup_percentage_off'     => isset( $popup['percentage_off'] ) ? $popup['percentage_off'] . '%' : '',
				'popup_button_text'        => isset( $popup['button_text'] ) ? $popup['button_text'] : '',
				'popup_button_url'         => isset( $popup['button_url'] ) ? $popup['button_url'] : '',
				'popup_button_text_color'  => $get_color( isset( $popup['button_text_color'] ) ? $popup['button_text_color'] : null ),
				'popup_button_bg_color'    => $get_color( isset( $popup['button_bg_color'] ) ? $popup['button_bg_color'] : null ),
				'notice_title'             => isset( $notice['title'] ) ? $notice['title'] : '',
				'notice_cta_text'          => isset( $notice['cta_text'] ) ? $notice['cta_text'] : '',
				'notice_percentage_off'    => isset( $notice['percentage_off'] ) ? $notice['percentage_off'] . '%' : '',
				'notice_button_text'       => isset( $notice['button_text'] ) ? $notice['button_text'] : '',
				'notice_button_url'        => isset( $notice['button_url'] ) ? $notice['button_url'] : '',
				'notice_button_text_color' => $get_color( isset( $notice['button_text_color'] ) ? $notice['button_text_color'] : null ),
				'notice_button_bg_color'   => $get_color( isset( $notice['button_bg_color'] ) ? $notice['button_bg_color'] : null ),
				'notice_enabled'           => isset( $notice['enabled'] ) ? $notice['enabled'] : false,
				'start_date'               => $campaign['start_date'],
				'end_date'                 => $campaign['end_date'],
				'is_recurring'             => isset( $campaign['is_recurring'] ) ? $campaign['is_recurring'] : false,
				'recurring_type'           => isset( $campaign['recurring_type'] ) ? $campaign['recurring_type'] : null,
				'recurring_interval'       => isset( $campaign['recurring_interval'] ) ? $campaign['recurring_interval'] : null,
			);
		}

		/**
		 * Validate promo data structure
		 *
		 * @param array $data Promo data.
		 * @return bool True if valid, false otherwise.
		 */
		private function validate_promo_data( $data ) {
			if ( ! is_array( $data ) ) {
				return false;
			}

			$required_fields = array(
				'id',
				'product_slug',
				'popup_title',
				'popup_button_text',
				'popup_button_url',
				'start_date',
				'end_date',
			);

			foreach ( $required_fields as $field ) {
				if ( ! isset( $data[ $field ] ) || empty( $data[ $field ] ) ) {
					return false;
				}
			}

			return true;
		}
	}
}
