<?php
/**
 * KMQ Promotions App
 *
 * @category   WordPress_Plugin
 * @package    Common
 * @subpackage Suppliers
 * @author     miniOrange <info@miniorange.com>
 * @license    MIT/Expat
 * @link       https://plugins.miniorange.com/woocommerce-api-product-sync-with-woocommerce-rest-apis
 */

namespace MOWCPS\Common\Suppliers;

use WP_Error;
use MOWCPS\Common\Abstracts\Base_Supplier_App;
use MOWCPS\Common\Interfaces\Supplier_App_Interface;
use MOWCPS\Common\Constants\Constants;
use MOWCPS\Common\Services\API\API_Service;
use MOWCPS\Common\Services\Authorization\Authorization_Service;
use MOWCPS\Common\Utils\Utils;
use MOWCPS\Common\Constants\Plugin_Filters;

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

/**
 * Class Kmq
 *
 * Handles KMQ Promotions supplier app operations
 */
class Kmq extends Base_Supplier_App implements Supplier_App_Interface {
	/**
	 * Constructor
	 */	
	public function __construct() {
		parent::__construct( Constants::SUPPLIER_APP_TYPE_KMQ );
	}

	/**
	 * Perform KMQ-specific connection test
	 *
	 * @param array $supplier_data Supplier data.
	 * @return array Test result.
	 */
	public function perform_connection_test( $supplier_data ) {
		// Validate supplier-specific configuration using existing validation method.
		$validation_result = $this->validate_supplier_specific_configuration( $supplier_data );
		if ( is_wp_error( $validation_result ) ) {
			return $this->get_test_result(
				false,
				sprintf( Constants::SUPPLIER_AUTH_FAILED, $this->supplier_name, $validation_result->get_error_message() ),
			);
		}

		// Load and process configuration with dynamic parameters.
		$processed_config = $this->load_and_process_configuration( $supplier_data );
		if ( is_wp_error( $processed_config ) ) {
			return $this->get_test_result(
				false,
				sprintf( Constants::SUPPLIER_CONFIG_LOADING_FAILED, $this->supplier_name, $processed_config->get_error_message() ),
			);
		}

		// Get authorization configuration.
		$authorization = $processed_config[ Constants::AUTHORIZATION ] ?? array();

		$auth_service = new Authorization_Service();
		$headers      = $auth_service->generate_headers( $authorization, 0 );

		if ( is_wp_error( $headers ) ) {
			return $this->get_test_result(
				false,
				sprintf( Constants::SUPPLIER_AUTH_FAILED, $this->supplier_name, $headers->get_error_message() ),
			);
		}

		// Test with the highest priority connection.
		$connections      = $processed_config['connections'] ?? array();
		$test_connection  = $this->find_test_connection( $connections );

		if ( empty( $test_connection ) ) {
			return $this->get_test_result(
				false,
				sprintf( Constants::SUPPLIER_NO_TEST_ENDPOINT, $this->supplier_name ),
			);
		}

		$config       = $test_connection['configuration'];
		$endpoint     = $config['endpoint'];
		$method       = $config['method'];
		$headers      = array_merge( $headers, $config['headers'] ?? array() );
		$body_config  = $config['body'];
		$body_type    = $body_config['type'] ?? '';
		$body_data    = $body_config['data'] ?? array();
		$body         = is_array( $body_data ) ? wp_json_encode( $body_data ) : $body_data;

		if ( empty( $endpoint ) ) {
			return $this->get_test_result(
				false,
				sprintf( Constants::SUPPLIER_NO_TEST_ENDPOINT_AVAILABLE, $this->supplier_name ),
			);
		}

		$api_request = array(
			'endpoint' => $endpoint,
			'method'   => $method,
			'headers'  => $headers,
			'body'     => ( Constants::HTTP_REQUEST_METHOD_GET === $method ) ? null : $body,
			'timeout'  => 60,
		);

		$response = API_Service::make_api_call( $api_request['endpoint'], $api_request );

		$response_code    = wp_remote_retrieve_response_code( $response );
		$response_message = wp_remote_retrieve_response_message( $response );
		$raw_body         = wp_remote_retrieve_body( $response );

		if ( is_wp_error( $response ) ) {
			return $this->get_test_result(
				false,
				sprintf( Constants::SUPPLIER_AUTH_FAILED, $this->supplier_name, $response->get_error_message() ),
				$response_code ?? null,
			);
		}

		if ( 'no data' === strtolower( trim( $raw_body, " \t\n\r\0\x0B\"" ) ) ) {
			return $this->get_test_result(
				false,
				sprintf( Constants::SUPPLIER_AUTH_FAILED, $this->supplier_name, 'No data returned, please check your token.' ),
				$response_code,
			);
		}

		$response_body = json_decode( $raw_body, true );

		if ( ! Utils::is_status_success( $response ) ) {
			return $this->get_test_result(
				false,
				sprintf( Constants::SUPPLIER_AUTH_FAILED, $this->supplier_name, $response_message ?? 'Connection failed' ),
				$response_code,
				$response_body,
			);
		}

		return $this->get_test_result(
			true,
			sprintf( Constants::SUPPLIER_AUTH_SUCCESSFUL, $this->supplier_name ),
			$response_code,
			$response_body,
		);
	}

	/**
	 * Validate KMQ-specific configuration
	 *
	 * @param array $supplier_data Supplier data to validate.
	 * @return bool|WP_Error True if valid, WP_Error if invalid.
	 */
	public function validate_supplier_specific_configuration( $supplier_data ) {
		if ( empty( $supplier_data['token'] ) ) {
			return new WP_Error(
				Constants::ERROR_INVALID_SUPPLIER_CONFIG,
				'Token is required for ' . $this->supplier_name . '.',
				array( 'status' => Constants::HTTP_BAD_REQUEST )
			);
		}

		return true;
	}

	/**
	 * Modify categories for KMQ
	 *
	 * @param array $arguments Arguments.
	 * @return array Modified categories.
	 */
	public static function modify_categories( $arguments ) {
		if ( Plugin_Filters::EVENT_ALTER_PRODUCTS_CATEGORY === $arguments['event_specifier'] ) {
			$key                     = array_key_first( $arguments['categories'] );
			$categories              = ! empty( $key ) ? explode( '|', (string) $key ) : array();
			$arguments['categories'] = array_fill_keys( $categories, array() );
		}
		return $arguments;
	}
}
