<?php
namespace Prodigy\Includes;

use Prodigy\admin\Prodigy_Admin_Setup_Wizard;
use Prodigy\Includes\Api\V1\Prodigy_Api_Main;
use Prodigy\Includes\Content\Prodigy_Request_Maker;
use Prodigy\Includes\Helpers\Prodigy_Logger;
use Prodigy\Includes\Synchronization\Prodigy_Synchronization;

/**
 * Store connection class
 */
class Prodigy_Connection {

	/**
	 * @var Prodigy_Request_Maker
	 */
	private Prodigy_Request_Maker $prodigy_request_maker;

	/**
	 * @param Prodigy_Request_Maker $prodigy_request_maker
	 */
	public function __construct( Prodigy_Request_Maker $prodigy_request_maker ) {
		$this->prodigy_request_maker = $prodigy_request_maker;
	}

	/**
	 * @param string $token
	 *
	 * @return string
	 */
	public function is_store_already_connected( string $token ): string {
		$current_token = get_option( Prodigy_Admin_Setup_Wizard::OPTION_STORE_KEY );
		return $current_token && $current_token === $token;
	}

	/**
	 * @return bool
	 */
	public function has_connected_store(): bool {
		$store_key         = get_option( Prodigy_Admin_Setup_Wizard::OPTION_STORE_KEY );
		$hosted_system_url = get_option( Prodigy_Admin_Setup_Wizard::OPTION_URL_DOMAIN_HOSTED_SYSTEM );

		return ! empty( $store_key ) && ! empty( $hosted_system_url );
	}

	/**
	 * @param string $token
	 *
	 * @return bool
	 */
	public function connect_store( string $token ): bool {
		if ( PRODIGY_DEBUG_MODE ) {
			Prodigy_Logger::add_record( Prodigy_Logger::TYPE_INFO, 'Site URL ' . get_home_url() );
		}
		$params = array(
			'api_key'                   => $token,
			'url'                       => get_home_url(),
			'products_callback_path'    => '/wp-json/' . get_prodigy_plugin_directory_name() . '/v1' . Prodigy_Api_Main::API_PRODUCTS_PATH,
			'categories_callback_path'  => '/wp-json/' . get_prodigy_plugin_directory_name() . '/v1' . Prodigy_Api_Main::API_CATEGORIES_PATH,
			'attributes_callback_path'  => '/wp-json/' . get_prodigy_plugin_directory_name() . '/v1' . Prodigy_Api_Main::API_TAXONOMIES_PATH,
			'import_callback_path'      => '/wp-json/' . get_prodigy_plugin_directory_name() . '/v1' . Prodigy_Api_Main::API_IMPORT,
			'cache_reset_callback_path' => '/wp-json/' . get_prodigy_plugin_directory_name() . '/v1' . Prodigy_Api_Main::API_CATALOG_PATH . '/reset',
			'settings_callback_path'    => '/wp-json/' . get_prodigy_plugin_directory_name() . '/v1' . Prodigy_Api_Main::API_SETTINGS_PATH,
			'category_page_path'        => '/' . Prodigy::get_prodigy_category_slug(),
			'product_page_path'         => '/' . Prodigy::get_prodigy_product_slug(),
		);

		$response_connection = $this->prodigy_request_maker->do_connect_request( $params );
		if ( $response_connection['code'] === \WP_Http::OK && ! array_key_exists( 'error', $response_connection ) ) {
			$this->set_plugin_settings( $token, $response_connection );

			return true;
		}

		return false;
	}

	/**
	 * @param string $token
	 * @param array  $response_connection
	 *
	 * @return void
	 */
	private function set_plugin_settings( string $token, array $response_connection ): void {
		update_option( Prodigy_Admin_Setup_Wizard::OPTION_STORE_KEY, $token );
		update_option( Prodigy_Admin_Setup_Wizard::OPTION_DOMAIN_HOSTED_SYSTEM, $response_connection['data']['attributes']['name'] );
		update_option( Prodigy_Admin_Setup_Wizard::OPTION_URL_DOMAIN_HOSTED_SYSTEM, $response_connection['data']['attributes']['subdomain'] );
		update_option( Prodigy_Admin_Setup_Wizard::OPTION_STEP_WIZARD, Prodigy_Admin_Setup_Wizard::DEFAULT_STEP );
		update_option( Prodigy_Synchronization::PRODIGY_PROCESS_TYPE_AUTO_SYNC, Prodigy_Synchronization::PRODIGY_AUTO_SYNC );
	}

	/** Transient key for rate limiting disconnect API calls (avoid uncontrolled repeated requests). */
	const TRANSIENT_DISCONNECT_RATE = 'prodigy_disconnect_rate_limit';

	/** Rate limit window in seconds (no duplicate disconnect API call within this time). */
	const DISCONNECT_RATE_SECONDS = 120;

	/**
	 * @return bool
	 */
	public function disconnect_store(): bool {
		$rate_key   = self::TRANSIENT_DISCONNECT_RATE;
		$store_key  = get_option( Prodigy_Admin_Setup_Wizard::OPTION_STORE_KEY, '' );
		$rate_limit = get_transient( $rate_key );

		if ( $rate_limit && empty( $store_key ) ) {
			return true;
		}

		$request_disconnection = $this->prodigy_request_maker->do_disconnect_store_request();

		if ( $request_disconnection['code'] === \WP_Http::NO_CONTENT ) {
			set_transient( $rate_key, 1, self::DISCONNECT_RATE_SECONDS );
			update_option( Prodigy_Admin_Setup_Wizard::OPTION_STORE_KEY, '' );
			return true;
		}
		$errors = $this->prodigy_request_maker->get_list_errors( $request_disconnection );
		if ( PRODIGY_DEBUG_MODE ) {
			Prodigy_Logger::add_record( Prodigy_Logger::TYPE_ERROR, implode( ', ', $errors ) );
		}

		return false;
	}
}
