<?php
/**
 * Setup Hub Accounts CPT
 *
 * @package northmill-online-shared
 */

declare(strict_types=1);

namespace Northmill_Online_Shared\Abstracts\Hub_API\Hub_Accounts;

use Northmill_Online_Shared\Abstract_Shared_Base;
use Northmill_Online_Shared\Abstracts\Hub_API\Abstract_API_Base;
use Northmill_Online_Shared\Abstracts\Hub_API\Hub_Accounts\Models\Hub_Account_Model;
use Northmill_Online_Shared\Abstracts\Hub_API\Hub_Accounts\Shipping\Shipping_Zones;
use Northmill_Online_Shared\Helpers\Hook_Helpers;
use Northmill_Online_Shared\Modules\Admin\Pages\Page\Admin_Settings;

defined( 'ABSPATH' ) || exit;

/**
 * Setup Hub Accounts CPT
 */
class Hub_Account_Setup {

	/**
	 * Cache for whether multiple stocks are enabled.
	 *
	 * @var bool|null
	 */
	private static ?bool $is_multiple_stocks_enabled = null;

	/**
	 * Constructor
	 */
	public static function setup(): void {
		add_action(
			'init',
			array( __CLASS__, 'register_ctp' )
		);

		if ( self::is_setting_up_hub_accounts() ) {
			add_filter(
				'northmill_shared_instance_setting_up_hub_accounts',
				function () {
					return Abstract_Shared_Base::base_instance();
				}
			);
		}
	}

	/**
	 * Get whether the package is responsible for setting up Hub Accounts.
	 *
	 * @return bool
	 */
	public static function is_setting_up_hub_accounts(): bool {
		return Hook_Helpers::apply_scoped_filters(
			'northmill_online_shared_is_setting_up_hub_accounts',
			false,
			Abstract_Shared_Base::base_instance()->package_info->get_service_name()
		);
	}

	/**
	 * Check if stock accounts are used.
	 *
	 * @return bool
	 */
	public static function is_stock_accounts_used(): bool {
		return (bool) Hook_Helpers::apply_scoped_filters(
			'northmill_online_shared_hub_accounts_use_stock_accounts',
			true
		);
	}

	/**
	 * Register CPT
	 */
	public static function register_ctp(): void {
		$labels = array(
			'name'               => _x( 'Hub Accounts', 'Post type general name', 'northmill-online-shared' ),
			'singular_name'      => _x( 'Hub Account', 'Post type singular name', 'northmill-online-shared' ),
			'menu_name'          => _x( 'Hub Accounts', 'Admin Menu text', 'northmill-online-shared' ),
			'name_admin_bar'     => _x( 'Hub Account', 'Add New on Toolbar', 'northmill-online-shared' ),
			'add_new'            => __( 'Add New', 'northmill-online-shared' ),
			'add_new_item'       => __( 'Add New Hub Account', 'northmill-online-shared' ),
			'new_item'           => __( 'New Hub Account', 'northmill-online-shared' ),
			'edit_item'          => __( 'Edit Hub Account', 'northmill-online-shared' ),
			'view_item'          => __( 'View Hub Account', 'northmill-online-shared' ),
			'all_items'          => __( 'All Hub Accounts', 'northmill-online-shared' ),
			'search_items'       => __( 'Search Hub Accounts', 'northmill-online-shared' ),
			'parent_item_colon'  => __( 'Parent Hub Accounts:', 'northmill-online-shared' ),
			'not_found'          => __( 'No accounts found.', 'northmill-online-shared' ),
			'not_found_in_trash' => __( 'No accounts found in Trash.', 'northmill-online-shared' ),
		);

		$args = array(
			'labels'             => $labels,
			'public'             => false,
			'publicly_queryable' => true,
			'show_ui'            => Abstract_Shared_Base::base_instance()->debug->is_on(),
			'show_in_menu'       => Abstract_Shared_Base::base_instance()->debug->is_on(),
			'query_var'          => true,
			'rewrite'            => false,
			'has_archive'        => false,
			'hierarchical'       => false,
			'supports'           => array( 'title', 'custom-fields' ),
		);

		register_post_type( WP_Repository::CPT_KEY, $args );
	}

	/**
	 * Render Hub account fields for settings page.
	 *
	 * @param array|null             $field_iterators Array of field iterators.
	 * @param Hub_Account_Model|null $account         Hub account model to render fields for.
	 * @param string                 $env             Environment to render fields for.
	 * @param bool                   $is_template     Whether to render fields as template.
	 *
	 * @return void
	 */
	public static function render_backoffice_account_fields(
		?array &$field_iterators,
		?Hub_Account_Model $account = null,
		string $env = 'test',
		bool $is_template = false
	): void {

		$args =
			array(
				'row_desc'    => '',
				'tbody_id'    => '',
				'tbody_class' => '',
			);

		if ( ! $is_template ) {
			$is_hub_account = is_a( $account, Hub_Account_Model::class );

			$args['api_url']                  = $account->url ?? '';
			$args['api_user']                 = $account->user ?? '';
			$args['api_pass']                 = $account->pass ?? '';
			$args['api_env']                  = $account->env ?? $env;
			$args['is_main']                  = empty( $account ) || $account->is_main();
			$args['display_name']             = $is_hub_account ? ( $account->display_name ?? '' ) : '';
			$args['account_enabled']          = empty( $account ) || $account->is_enabled();
			$args['allowed_shipping_methods'] = $is_hub_account ? $account->allowed_shipping_methods : array();
		} else {
			$args['tbody_id']                 = 'hub-account-template';
			$args['api_url']                  = '';
			$args['api_user']                 = '';
			$args['api_pass']                 = '';
			$args['api_env']                  = 'template';
			$args['is_main']                  = false;
			$args['display_name']             = '';
			$args['account_enabled']          = true;
			$args['allowed_shipping_methods'] = array();
		}

		$args['connection_status'] = ! empty( $account ) ? Helpers::get_connection_status( $account ) : '';

		if ( $args['is_main'] ) {
			$args['row_desc'] = __( 'Account that data is synced from, as set in sync option below.', 'northmill-online-shared' );

			if ( 'prod' === $args['api_env'] ) {
				$args['row_title'] = __( 'Production main account', 'northmill-online-shared' );
			} else {
				$args['row_title'] = __( 'Test main account', 'northmill-online-shared' );
			}
		} elseif ( 'prod' === $args['api_env'] ) {
			$args['row_title'] = __( 'Production stock account', 'northmill-online-shared' );
		} else {
			$args['row_title'] = __( 'Test stock account', 'northmill-online-shared' );
		}

		$args['tbody_id'] = $args['tbody_id'] ? 'id="' . esc_attr( $args['tbody_id'] ) . '"' : '';

		if ( empty( $field_iterators ) ) {
			$field_iterators = array(
				'test'     => 0,
				'prod'     => 0,
				'template' => 0,
			);
		}
		$current_iterator = $args['is_main'] ? 'main' : $field_iterators[ $args['api_env'] ]++;

		switch ( $args['api_env'] ) {
			case 'test':
				$args['tbody_class'] .= ' hub-account-test';
				break;
			case 'prod':
				$args['tbody_class'] .= ' hub-account-prod';
				break;
		}

		$current_env_iterator_id = '[' . $args['api_env'] . '][' . $current_iterator . ']';

		$name_base = Admin_Settings::get_settings_id() . '[' . Options_Page_Processing::OPTIONS_PAGE_KEY . ']' . $current_env_iterator_id;

		$args['url_input_id']          = $name_base . '[api_url]';
		$args['user_input_id']         = $name_base . '[api_user]';
		$args['pass_input_id']         = $name_base . '[api_pass]';
		$args['display_name_input_id'] = $name_base . '[api_display_name]';
		$args['enabled_input_id']      = $name_base . '[enabled]';
		$args['shipping_methods_id']   = $name_base . '[allowed_shipping_methods][]';

		$args['make_input_required'] = ! $args['is_main'] && ! $is_template;

		$args['api_url_options'] = Abstract_API_Base::get_api_url_options( $env );

		$args['shipping_methods_multi_select'] = Shipping_Zones::get_shipping_methods_multi_select(
			$args['shipping_methods_id'],
			'hub-account-user-allowed-shipping-methods multi-account-field',
			$args['allowed_shipping_methods'],
			$args['make_input_required']
		);

		Abstract_Shared_Base::base_instance()->template_loader->get_admin_template_part(
			'settings/hub-account-field',
			$args,
			false
		);
	}

	/**
	 * Check if functionality for multiple stocks is enabled.
	 *
	 * @param string|null $env Flo API environment. Defaults to environment set in options.
	 *
	 * @return bool
	 */
	public static function is_multiple_stocks_enabled( ?string $env = 'current' ): bool {

		if ( is_null( self::$is_multiple_stocks_enabled ) ) {
			$env = Envs::validate_env( $env );

			self::$is_multiple_stocks_enabled = ! empty( WP_Repository::get_stock_accounts( $env ) );
		}

		return self::$is_multiple_stocks_enabled;
	}

	/**
	 * Clear the is_multiple_stocks_enabled cache.
	 */
	public static function clear_is_multiple_stocks_enabled(): void {
		self::$is_multiple_stocks_enabled = null;
	}
}
