<?php
/**
 * Catalog extensions admin screen helpers.
 *
 * @package ecommerce-product-catalog/includes
 */

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

/**
 * Registers the extensions submenu page.
 *
 * Here product settings are defined and managed.
 *
 * @version        1.1.4
 * @package        ecommerce-product-catalog/includes
 * @author         impleCode
 *
 * @return void
 */
function register_product_extensions() {
	ic_epc_extensions_screen()->register_menu();
}

add_action( 'product_settings_menu', 'register_product_extensions' );

add_action( 'init', 'ic_epc_extensions_screen_pages', 0 );
add_action( 'init', 'ic_epc_extensions_screen', 1 );

/**
 * Returns the catalog extensions screen instance.
 *
 * @return IC_Settings_Screen
 */
function ic_epc_extensions_screen() {
	static $screen = null;

	if ( null === $screen ) {
		$screen = new IC_Settings_Screen(
			array(
				'parent_slug'             => 'edit.php?post_type=al_product',
				'page_title'              => sprintf(
					/* translators: %s: catalog plugin name. */
					__( 'Extensions for %s', 'ecommerce-product-catalog' ),
					IC_CATALOG_PLUGIN_NAME
				),
				'menu_title'              => '<span class="extensions">' . __( 'Extensions', 'ecommerce-product-catalog' ) . '</span>',
				'capability'              => 'manage_product_settings',
				'menu_slug'               => 'extensions.php',
				'menu_priority'           => 11,
				'title'                   => sprintf(
					/* translators: %s: catalog plugin name. */
					__( 'Extensions for %s', 'ecommerce-product-catalog' ),
					IC_CATALOG_PLUGIN_NAME
				),
				'top_callback'            => 'ic_epc_render_extensions_screen_top',
				'tabs'                    => array(),
				'show_tabs'               => false,
				'content_container_class' => 'table-wrapper',
				'content_container_style' => '',
				'after_content_callback'  => 'ic_epc_render_extensions_screen_spacer',
				'show_logo'               => true,
			)
		);
	}

	return $screen;
}

/**
 * Registers page-backed content tabs for the extensions screen.
 *
 * @return array
 */
function ic_epc_extensions_screen_pages() {
	return array(
		ic_epc_extensions_settings_page(),
		ic_epc_extensions_help_settings_page(),
	);
}

/**
 * Returns the page-backed extensions list tab.
 *
 * @return IC_Settings_Page
 */
function ic_epc_extensions_settings_page() {
	static $page = null;

	if ( null === $page ) {
		$page = new IC_Settings_Page(
			array(
				'title'                   => __( 'Add-ons & Integrations', 'ecommerce-product-catalog' ),
				'screen'                  => 'extensions.php',
				'screen_tab'              => 'extensions',
				'screen_tab_label'        => __( 'Add-ons & Integrations', 'ecommerce-product-catalog' ),
				'screen_tab_menu_item_id' => 'extensions',
				'screen_tab_default'      => true,
				'container_class'         => 'setting-content submenu extensions-content',
				'content_callback'        => 'ic_epc_render_extensions_page_content',
				'helpers'                 => ic_epc_extensions_helper_boxes(),
				'show_title'              => false,
				'show_form'               => false,
			)
		);
	}

	return $page;
}

/**
 * Returns the page-backed extensions help tab.
 *
 * @return IC_Settings_Page
 */
function ic_epc_extensions_help_settings_page() {
	static $page = null;

	if ( null === $page ) {
		$page = new IC_Settings_Page(
			array(
				'title'                   => __( 'Help', 'ecommerce-product-catalog' ),
				'screen'                  => 'extensions.php',
				'screen_tab'              => 'help',
				'screen_tab_label'        => __( 'Help', 'ecommerce-product-catalog' ),
				'screen_tab_menu_item_id' => 'help',
				'container_class'         => 'setting-content submenu extensions-help-content',
				'content_callback'        => 'ic_epc_render_extensions_help_page_content',
				'helpers'                 => ic_epc_extensions_help_helper_boxes(),
				'show_title'              => false,
				'show_form'               => false,
			)
		);
	}

	return $page;
}

/**
 * Renders the extensions admin page.
 *
 * @return void
 */
function product_extensions() {
	ic_epc_extensions_screen()->render();
}

/**
 * Renders the extensions screen top content.
 *
 * @return void
 */
function ic_epc_render_extensions_screen_top() {
	?>
	<?php do_action( 'ic_cat_extensions_page_start' ); ?>
	<hr class="wp-header-end">
	<h3>
		<?php
		// phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- Trusted translated admin HTML with a single line break.
		echo __( 'All premium extensions come with premium support provided by the dev team.<br>Feel free to contact impleCode for configuration help, troubleshooting, installation assistance and any other plugin support at any time!', 'ecommerce-product-catalog' );
		?>
	</h3>
	<?php
	// phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- HTML is generated by the settings renderer.
	ic_product_settings_html();
}

/**
 * Returns the active extensions screen content tab.
 *
 * @return string
 */
function ic_epc_extensions_request_tab() {
	// phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Read-only tab routing parameter.
	return isset( $_GET['tab'] ) ? sanitize_key( wp_unslash( $_GET['tab'] ) ) : '';
}

/**
 * Renders the active extensions screen body.
 *
 * @return void
 */
function ic_epc_render_extensions_page_content() {
	$tab = ic_epc_extensions_request_tab();

	if ( 'product-extensions' === $tab || '' === $tab ) {
		?>
				<div class="extension-list">
					<?php
					start_implecode_install();
					start_free_implecode_install();
					$extensions = get_site_transient( 'implecode_extensions_data' );
					if ( false === $extensions ) {
						$extensions_remote_url = apply_filters( 'ic_extensions_remote_url', 'provide_extensions' );
						$extensions            = wp_remote_get( 'https://app.implecode.com/index.php?' . $extensions_remote_url );
						if ( ! is_wp_error( $extensions ) && 200 === wp_remote_retrieve_response_code( $extensions ) ) {
							$extensions = json_decode( wp_remote_retrieve_body( $extensions ), true );
							if ( $extensions ) {
								set_site_transient( 'implecode_extensions_data', $extensions, WEEK_IN_SECONDS );
							}
						} else {
							$extensions = implecode_extensions();
						}
					}
					$all_ic_plugins = array();
					if ( function_exists( 'get_implecode_active_plugins' ) ) {
						$all_ic_plugins = get_implecode_active_plugins();
					}
					$all_ic_plugins = array_merge( get_implecode_active_free_plugins(), $all_ic_plugins );

					$not_active_ic_plugins = get_implecode_not_active_plugins();

					do_action( 'ic_before_extensions_list', $tab );
					$extensions         = apply_filters( 'ic_cat_extensions', $extensions );
					$count              = 1;
					$extensions_by_type = array();
					$number             = 2;
					foreach ( $extensions as $extension ) {
						$extension['type'] = isset( $extension['type'] ) ? $extension['type'] : 'premium';
						if ( 0 === $count % $number && ! empty( $extensions_by_type ) ) {
							if ( ! empty( $extensions_by_type[0] ) ) {
								// phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- HTML is generated by extension_box().
								echo extension_box( $extensions_by_type[0], $all_ic_plugins, $not_active_ic_plugins );
								unset( $extensions_by_type[0] );
								++$number;
							}
							if ( ! empty( $extensions_by_type ) ) {
								$extensions_by_type = array_values( $extensions_by_type );
							}
							++$count;
						} elseif ( 'free' === $extension['type'] ) {
							$extensions_by_type[] = $extension;
							continue;
						}
						// phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- HTML is generated by extension_box().
						echo extension_box( $extension, $all_ic_plugins, $not_active_ic_plugins );
						++$count;
					}
					// phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- HTML is generated by the affiliate content renderer.
					ic_show_affiliate_content();
					?>
				</div>
					<?php
	} elseif ( 'new-product-extensions' === $tab ) {
		?>
					<div class="extension-list">
		<?php
		start_implecode_install();
			$extensions = get_site_transient( 'implecode_new_extensions_data' );
		if ( false === $extensions ) {
			$extensions = wp_remote_get( 'https://app.implecode.com/index.php?provide_extensions&new=1' );
			if ( ! is_wp_error( $extensions ) || 200 !== wp_remote_retrieve_response_code( $extensions ) ) {
				$extensions = json_decode( wp_remote_retrieve_body( $extensions ), true );
				if ( $extensions ) {
					set_site_transient( 'implecode_new_extensions_data', $extensions, 60 * 60 * 24 * 7 );
				}
			} else {
				$extensions = implecode_extensions();
			}
		}
		$all_ic_plugins = '';
		if ( function_exists( 'get_implecode_active_plugins' ) ) {
			$all_ic_plugins = get_implecode_active_plugins();
		}
			$not_active_ic_plugins = get_implecode_not_active_plugins();
			do_action( 'ic_before_extensions_list', $tab );
		foreach ( $extensions as $extension ) {
			// phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- HTML is generated by extension_box().
			echo extension_box( $extension, $all_ic_plugins, $not_active_ic_plugins );
		}
		?>
					</div>
					<?php
	} elseif ( 'all-product-extensions' === $tab ) {
		?>
				<div class="extension-list">
		<?php
		start_implecode_install();
		$extensions = get_site_transient( 'implecode_extensions_data' );
		if ( false === $extensions ) {
			$extensions = wp_remote_get( 'https://app.implecode.com/index.php?provide_extensions' );
			if ( ! is_wp_error( $extensions ) || 200 !== wp_remote_retrieve_response_code( $extensions ) ) {
				$extensions = json_decode( wp_remote_retrieve_body( $extensions ), true );
				if ( $extensions ) {
					set_site_transient( 'implecode_extensions_data', $extensions, 60 * 60 * 24 * 7 );
				}
			} else {
				$extensions = implecode_extensions();
			}
		}
		$all_ic_plugins = '';
		if ( function_exists( 'get_implecode_active_plugins' ) ) {
			$all_ic_plugins = get_implecode_active_plugins();
		}
		$not_active_ic_plugins = get_implecode_not_active_plugins();
		do_action( 'ic_before_extensions_list', $tab );
		$extensions = apply_filters( 'ic_cat_extensions', $extensions );

		foreach ( $extensions as $extension ) {
			// phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- HTML is generated by extension_box().
			echo extension_box( $extension, $all_ic_plugins, $not_active_ic_plugins );
		}
		?>
				</div>
					<?php
	}
}

/**
 * Renders the extensions help page content.
 *
 * @return void
 */
function ic_epc_render_extensions_help_page_content() {
	do_action( 'ic_extensions_page_help_top' );
	?>
				<div class="help">
	<?php
	do_action( 'ic_extensions_page_help_text' );
	?>
					<h3><?php esc_html_e( 'Getting Started', 'ecommerce-product-catalog' ); ?></h3>
					<ol>
						<li>Go to the <a
									href="<?php echo esc_url( admin_url( 'edit.php?post_type=al_product&page=product-settings.php&tab=product-settings' ) ); ?>">general
								settings page</a></li>
						<li>Select your main catalog page and the template</li>
						<li><a href="<?php echo esc_url( admin_url( 'post-new.php?post_type=al_product' ) ); ?>">Add your first
								product</a> and check how it looks like by clicking the generated link after you publish
							it
						</li>
						<li>Select what should be shown on main listing page (Main listing shows option)</li>
						<li>Select what should be shown on category pages (Categories Settings)</li>
						<li>Check your main listing page and click the categories and product pages</li>
						<li>Make necessary adjustments in <a
									href="<?php echo esc_url( admin_url( 'edit.php?post_type=al_product&page=product-settings.php&tab=product-settings' ) ); ?>">General
								settings</a>, <a
									href="<?php echo esc_url( admin_url( 'edit.php?post_type=al_product&page=product-settings.php&tab=attributes-settings&submenu=attributes' ) ); ?>">Attributes</a>,
							<a href="<?php echo esc_url( admin_url( 'edit.php?post_type=al_product&page=product-settings.php&tab=shipping-settings&submenu=shipping' ) ); ?>">Shipping</a>,
							<a href="<?php echo esc_url( admin_url( 'edit.php?post_type=al_product&page=product-settings.php&tab=design-settings&submenu=archive-design' ) ); ?>">Catalog
								Design</a> and <a
									href="<?php echo esc_url( admin_url( 'edit.php?post_type=al_product&page=product-settings.php&tab=names-settings&submenu=single-names' ) ); ?>">Front-end
								Labels</a></li>
						<li>Use the search box on the top of this page if you need more information</li>
						<li>Check the <a
									href="<?php echo esc_url( admin_url( 'edit.php?post_type=al_product&page=extensions.php' ) ); ?>">Add-ons
								and Integrations</a> for more free and premium features
						</li>
						<li>Use free <a target="_blank"
										href="https://wordpress.org/support/plugin/ecommerce-product-catalog/">support
								forum</a> or <a target="_blank"
												href="https://implecode.com/support/#cam=help-tab&key=premium-support">premium
								support service</a> to get professional help
						</li>
						<li>That's it. Enjoy!</li>
					</ol>
					<h3><?php esc_html_e( 'How to get help?', 'ecommerce-product-catalog' ); ?></h3>
					<p>The developers provide both free and premium support:</p>
					<a class="button-secondary" target="_blank"
						href="https://wordpress.org/support/plugin/ecommerce-product-catalog/">Free Support Forum</a>
					<a class="button-secondary" target="_blank"
						href="https://implecode.com/support/#cam=help-tab&key=support">Premium Support Service</a>
					<h3><?php esc_html_e( 'How to Install the extension?', 'ecommerce-product-catalog' ); ?></h3>
					<ol>
						<li>Go to the <a
									href="<?php echo esc_url( admin_url( 'edit.php?post_type=al_product&page=extensions.php' ) ); ?>">extensions
								page</a></li>
						<li>Click the "Get your key" button on the extension that you want to install;</li>
						<li>You will be redirected to the impleCode website. Read the extension description, choose
							license type, click the Add to Cart button and fill the form;
						</li>
						<li>Your license key will be immediately sent to you by email provided in the previous step;
						</li>
						<li>Copy and Paste the license key to the license key field on the extension that you want to
							install;
						</li>
						<li>Click the install button and wait until the installation process is done. The installer will
							establish a secure connection with impleCode to get the installation files;
						</li>
						<li>Click the activation button;</li>
						<li>That's it. Enjoy!</li>
					</ol>
					<p>In case you prefer to install the extension manually you will get also the installation files in
						the customer panel. See <a
								href="https://implecode.com/wordpress/product-catalog/plugin-installation-guide/#cam=extensions-help&key=manual-installation#manual">manual
							installation guide</a> for this.</p>
					<p>Please see the <a href="https://implecode.com/faq/#cam=extensions-help&key=faq">FAQ</a> for
						additional information</p>
				</div>
				<?php
}

/**
 * Returns helper box configs shared by the extension list tabs.
 *
 * @return array
 */
function ic_epc_extensions_helper_boxes() {
	return array(
		array(
			'box_type_class' => 'text',
			'descriptions'   => array( __( 'All extensions are designed to work with each other smoothly.', 'ecommerce-product-catalog' ) ),
		),
		array(
			'box_type_class' => 'text',
			'descriptions'   => array( __( 'Some extensions give even more features when combined with another one.', 'ecommerce-product-catalog' ) ),
		),
		array(
			'box_type_class' => 'text',
			'descriptions'   => array( __( 'Click on the extension to see full features list.', 'ecommerce-product-catalog' ) ),
		),
		array(
			'box_type_class' => 'text',
			'descriptions'   => array( __( 'Paste your license key and click the install button to start the extension installation process.', 'ecommerce-product-catalog' ) ),
		),
	);
}

/**
 * Returns helper box configs for the extensions help tab.
 *
 * @return array
 */
function ic_epc_extensions_help_helper_boxes() {
	return array(
		array(
			'box_type_class' => 'text',
			'descriptions'   => array( __( 'The installation process takes less than 10 seconds.', 'ecommerce-product-catalog' ) ),
		),
		array(
			'box_type_class' => 'text',
			'descriptions'   => array(
				sprintf(
					/* translators: %s: support URL. */
					__( 'You can take advantage of premium support and <a href="%s">send support tickets</a> to impleCode developers once you have your license key.', 'ecommerce-product-catalog' ),
					'https://implecode.com/support/?support_type=support'
				),
			),
		),
	);
}

/**
 * Renders spacing between the extensions body and shared logo row.
 *
 * @return void
 */
function ic_epc_render_extensions_screen_spacer() {
	?>
	<div style="clear:both; height: 50px;"></div>
	<?php
}

/**
 * Returns the bundled premium extensions registry.
 *
 * @return array
 */
function implecode_extensions() {
	$extensions = array(
		'implecode-product-sidebar'   => array(
			'url'  => 'premium-support',
			'name' => 'Premium Toolset',
			'desc' => 'Product sidebar, product tags, enhanced category widget and premium email support.',
			'comp' => 'simple',
			'slug' => 'implecode-product-sidebar',
		),
		'implecode-shopping-cart'     => array(
			'url'  => 'shopping-cart',
			'name' => 'Shopping Cart',
			'desc' => 'Full featured shopping cart with advanced customisation options. Transform your product catalog into a Web Store!',
			'comp' => 'simple',
			'slug' => 'implecode-shopping-cart',
		),
		'implecode-quote-cart'        => array(
			'url'  => 'quote-cart',
			'name' => 'Quote Cart',
			'desc' => 'Allow your users to send a quote for multiple products. Quote Cart adds a store like experience even for products without price!',
			'comp' => 'simple',
			'slug' => 'implecode-quote-cart',
		),
		'implecode-quote-form'        => array(
			'url'  => 'quote-form',
			'name' => 'Single Product Quote Form',
			'desc' => 'Improve the conversion rate with quote/inquiry button which redirects to fully customizable product quote form.',
			'comp' => 'simple',
			'slug' => 'implecode-quote-form',
		),
		'implecode-order-form'        => array(
			'url'  => 'order-form',
			'name' => 'Single Product Order Form',
			'desc' => 'This powerful extension allows you to sell individual products with buy now button and fully customizable order form.',
			'comp' => 'simple',
			'slug' => 'implecode-order-form',
		),
		'implecode-paypal-gateway'    => array(
			'url'  => 'paypal-gateway',
			'name' => 'PayPal Gateway',
			'desc' => 'Boost the conversion rate with a robust PayPal shopping cart, buy now button or order form implementation.',
			'comp' => 'simple',
			'slug' => 'implecode-paypal-gateway',
		),
		'2checkout-gateway'           => array(
			'url'  => '2checkout-gateway',
			'name' => '2Checkout Gateway',
			'desc' => 'Take credit card payments with 2Checkout Gateway.',
			'comp' => 'simple',
			'slug' => '2checkout-gateway',
		),
		'catalog-users-manager'       => array(
			'url'  => 'catalog-users-manager',
			'name' => 'Catalog Users Manager',
			'desc' => 'Manage catalog visibility options depending on logged in visitor.',
			'comp' => 'simple',
			'slug' => 'catalog-users-manager',
		),
		'implecode-printable-coupons' => array(
			'url'  => 'printable-coupons',
			'name' => 'Printable Coupons',
			'desc' => 'Sell printable coupons for your products or for certain value directly from the website. Generate customized coupons!',
			'comp' => 'simple',
			'slug' => 'implecode-printable-coupons',
		),
		'product-page-customizer'     => array(
			'url'  => 'product-page-customizer',
			'name' => 'Product Page Customizer',
			'desc' => 'Customize product page with simple settings. Change product page elements, their size, position and colors easily in a few seconds.',
			'comp' => 'simple',
			'slug' => 'product-page-customizer',
		),
		'product-gallery-advanced'    => array(
			'url'  => 'product-gallery-advanced',
			'name' => 'Product Gallery Advanced',
			'desc' => 'Add unlimited number of product images and show them in a robust product slider or beautiful light-box presentation.',
			'comp' => 'simple',
			'slug' => 'product-gallery-advanced',
		),
		'custom-product-order'        => array(
			'url'  => 'custom-product-order',
			'name' => 'Custom Product Order',
			'desc' => 'Sort products by priority, lowest price, highest price or randomly. New options in sort drop-down. Assign featured products.',
			'comp' => 'simple',
			'slug' => 'custom-product-order',
		),
		'implecode-upload-pdf'        => array(
			'url'  => 'upload-pdf',
			'name' => 'Upload PDF',
			'desc' => 'Easily attach unlimited PDF files to the products, upload to server and provide to clients on product pages.',
			'comp' => 'simple',
			'slug' => 'implecode-upload-pdf',
		),
		'product-pdf'                 => array(
			'url'  => 'product-pdf',
			'name' => 'Product Print & PDF',
			'desc' => 'Print product pages with one click. Export product pages to PDF files with easy.',
			'comp' => 'simple',
			'slug' => 'product-pdf',
		),
		'product-manufacturers'       => array(
			'url'  => 'product-manufacturers',
			'name' => 'Product Manufacturers',
			'desc' => 'Manage product manufacturers & brands in separate screen and easily assign them to products. It has never been so simple!',
			'comp' => 'simple',
			'slug' => 'product-manufacturers',
		),
		'implecode-product-search'    => array(
			'url'  => 'product-search-pro',
			'name' => 'Product Search PRO',
			'desc' => 'Improve WordPress default search engine to provide better product search results. Show product search form with a shortcode.',
			'comp' => 'adv',
			'slug' => 'implecode-product-search',
		),
		'smart-multiple-catalogs'     => array(
			'url'  => 'smart-multiple-catalogs',
			'name' => 'Smart Multiple Catalogs',
			'desc' => 'Create completely separate, multiple catalogs at one website. Assign separate categories, parent URLs, manage them from different...',
			'comp' => 'simple',
			'slug' => 'smart-multiple-catalogs',
		),
		'smarter-product-urls'        => array(
			'url'  => 'smarter-product-urls',
			'name' => 'Smarter Product URLs',
			'desc' => 'Set up SEO and USER friendly product page URLs. Add product category in product page URLs.',
			'comp' => 'adv',
			'slug' => 'smarter-product-urls',
		),
		'implecode-product-locations' => array(
			'url'  => 'product-locations',
			'name' => 'Product Locations',
			'desc' => 'Easily manage product locations and get product quotes to multiple email addresses directly from product pages.',
			'comp' => 'simple',
			'slug' => 'implecode-product-locations',
		),
		'product-attributes-pro'      => array(
			'url'  => 'product-attributes-pro',
			'name' => 'Product Attributes PRO',
			'desc' => 'Filter products by attributes. Select attributes values with a drop-down, checkbox or radio button.',
			'comp' => 'simple',
			'slug' => 'product-attributes-pro',
		),
		'advanced-shipping-table'     => array(
			'url'  => 'advanced-shipping-tables',
			'name' => 'Advanced Shipping Tables',
			'desc' => 'Calculates shipping based on Shopping Cart total and checkout fields values.',
			'comp' => 'simple',
			'slug' => 'advanced-shipping-table',
		),
		'implecode-product-csv'       => array(
			'url'  => 'product-csv',
			'name' => 'Product CSV',
			'desc' => 'Import, Export & Update products all fields and attributes with a simple CSV file.',
			'comp' => 'simple',
			'slug' => 'implecode-product-csv',
		),
		'multiple-product-price'      => array(
			'url'  => 'multiple-prices',
			'name' => 'Multiple Pricing',
			'desc' => 'Set multiple, automatically calculated or manually inserted prices for each product.',
			'comp' => 'simple',
			'slug' => 'multiple-product-price',
		),
		'implecode-product-discounts' => array(
			'url'  => 'product-discounts',
			'name' => 'Product Discounts',
			'desc' => 'Apply percentage or value discounts for catalog products. Show the discount offers with a robust widget or shortcode and more!',
			'comp' => 'simple',
			'slug' => 'implecode-product-discounts',
		),
		'table-view'                  => array(
			'url'  => 'table-view',
			'name' => 'Table View',
			'desc' => 'Show products in nicely formatted table with customizable columns.',
			'comp' => 'simple',
			'slug' => 'table-view',
		),
		'classic-list-button'         => array(
			'url'  => 'classic-list-button',
			'name' => 'Classic List with Button',
			'desc' => 'Premium product listing theme for your catalog. Easily set image size, description name and button position.',
			'comp' => 'simple',
			'slug' => 'classic-list-button',
		),
		'slim-classic-grid'           => array(
			'url'  => 'slim-grid',
			'name' => 'Slim Grid Theme',
			'desc' => 'Premium Grid Theme for product listing. Has additional settings for size, per row elements, description length and price.',
			'comp' => 'simple',
			'slug' => 'slim-classic-grid',
		),
		'no-image-grid'               => array(
			'url'  => 'no-image-grid',
			'name' => 'No Image Grid Theme',
			'desc' => 'Premium Grid Theme for product listing. Best for products without image.',
			'comp' => 'simple',
			'slug' => 'no-image-grid',
		),
		'side-grid'                   => array(
			'url'  => 'side-grid',
			'name' => 'Side Grid',
			'desc' => 'Premium product listing grid with image on the left side.',
			'comp' => 'simple',
			'slug' => 'side-grid',
		),
	);

	return $extensions;
}

/**
 * Returns affiliate extension entries displayed on the extensions screen.
 *
 * @return array
 */
function implecode_affiliate_extensions() {
	$extensions = array(
		array(
			'url'  => 'https://wpml.org/purchase/?aid=89119&affiliate_key=x7MQob0JrgTA',
			'name' => 'WPML - Multilingual Catalog',
			'desc' => 'eCommerce Product Catalog is fully compatible with WPML - the WordPress Multilingual plugin. WPML lets you add languages to your existing sites and includes advanced translation management.',
			'comp' => 'simple',
		),
	);

	return $extensions;
}

add_action( 'ic_epc_loaded', 'initialize_affiliate_scripts', 20 );

/**
 * Defines affiliate constants in the admin context.
 *
 * @return void
 */
function initialize_affiliate_scripts() {
	if ( is_admin() ) {
		if ( ! defined( 'ICL_AFFILIATE_ID' ) ) {
			define( 'ICL_AFFILIATE_ID', '89119' );
		}
		if ( ! defined( 'ICL_AFFILIATE_KEY' ) ) {
			define( 'ICL_AFFILIATE_KEY', 'x7MQob0JrgTA' );
		}
	}
}

/**
 * Outputs affiliate extension content.
 *
 * @return void
 */
function ic_show_affiliate_content() {
}

/**
 * Builds the premium extension box markup.
 *
 * @param array $extension             Extension configuration.
 * @param array $all_ic_plugins        Active impleCode plugins.
 * @param array $not_active_ic_plugins Installed but inactive impleCode plugins.
 *
 * @return string
 */
function extension_box( $extension, $all_ic_plugins, $not_active_ic_plugins ) {
	$name = $extension['name'];
	$url  = $extension['url'];
	$desc = $extension['desc'];
	$comp = $extension['comp'];
	$slug = $extension['slug'];
	$type = ! empty( $extension['type'] ) ? $extension['type'] : 'premium';
	if ( 'free' === $type ) {
		return free_extension_box( $name, $url, $desc, $comp, $slug, $all_ic_plugins, $not_active_ic_plugins );
	}
	if ( 'adv' === $comp && 'simple' === get_integration_type() ) {
		$comp_txt   = __( 'Advanced Mode Required', 'ecommerce-product-catalog' );
		$comp_class = 'wrong';
	} else {
		$comp_txt   = __( 'Ready to Install', 'ecommerce-product-catalog' );
		$comp_class = 'good';
	}

	$return      = '<div class="extension ' . $slug . '">
	<a class="extension-name" href="https://implecode.com/wordpress/plugins/' . $url . '/#cam=extensions&key=' . $url . '"><h3><span>' . $name . '</span></h3><span class="click-span">' . __( 'Click for more', 'ecommerce-product-catalog' ) . '</span></a>
	<p>' . $desc . '</p>';
	$disabled    = '';
	$current_key = get_option( 'custom_license_code' );
	if ( ! current_user_can( 'install_plugins' ) ) {
		$disabled    = 'disabled';
		$current_key = '';
	}
	if ( ! empty( $all_ic_plugins ) && is_ic_plugin_active( $slug, $all_ic_plugins ) ) {
		$return .= '<p><a href="https://implecode.com/support/" class="button-primary">Support</a> <a href="https://implecode.com/docs/" class="button-primary">Docs</a> <span class="comp installed">' . __( 'Active Extension', 'ecommerce-product-catalog' ) . '</span></p>';
	} elseif ( ! empty( $not_active_ic_plugins ) && is_ic_plugin_active( $slug, $not_active_ic_plugins ) ) {
			$plugin_file = ic_cat_get_plugin_file( $slug );
			$return     .= '<p><a ' . $disabled . ' href="' . wp_nonce_url( 'plugins.php?ic_cat_activation=1&action=activate&amp;plugin=' . rawurlencode( $plugin_file ), 'activate-plugin_' . $plugin_file ) . '" class="button-primary">Activate Now</a><span class="comp info">' . __( 'Installed Extension', 'ecommerce-product-catalog' ) . '</span></p>';
	} elseif ( 'wrong' === $comp_class ) {
			$return .= '<p><a href="https://implecode.com/wordpress/plugins/' . $url . '/#cam=extensions&key=' . $url . '" class="button-primary">See the Extension</a><span class="comp ' . $comp_class . '">' . $comp_txt . '</span></p>';
	} else {
		$return .= '<form class="license_form" action=""><input type="hidden" name="implecode_install" value="1"><input type="hidden" name="url" value="' . $url . '"><input type="hidden" name="slug" value="' . $slug . '"><input type="hidden" name="post_type" value="al_product"><input type="hidden" name="page" value="extensions.php"><input type="text" name="license_key" ' . $disabled . ' class="wide" placeholder="License Key..." value="' . $current_key . '">';
		$return .= wp_nonce_field( 'install-implecode-plugin_' . $slug, '_wpnonce', 0, 0 );
		$return .= '<p class="submit"><input type="submit" ' . $disabled . ' value="Install" class="button-primary"><span class="comp ' . $comp_class . '">' . $comp_txt . '</span> <a href="https://implecode.com/wordpress/plugins/' . $url . '/#cam=extensions&key=' . $url . '" class="button-secondary right">Get your key</a></form></p>';
	}
	$return .= '</div>';

	return $return;
}

/**
 * Returns the main plugin file path for a plugin slug.
 *
 * @param string $slug Plugin slug.
 *
 * @return string
 */
function ic_cat_get_plugin_file( $slug ) {
	if ( 'catalog-booster-for-woocommerce' === $slug ) {
		$file_name = 'woocommerce-catalog-booster';
	} else {
		$file_name = $slug;
	}
	$plugin_file = $slug . '/' . $file_name . '.php';

	return $plugin_file;
}

/**
 * Builds the free extension box markup.
 *
 * @param string $name                  Extension name.
 * @param string $url                   Extension URL slug.
 * @param string $desc                  Extension description.
 * @param string $comp                  Compatibility mode.
 * @param string $slug                  Extension slug.
 * @param array  $all_ic_plugins        Active impleCode plugins.
 * @param array  $not_active_ic_plugins Installed but inactive impleCode plugins.
 *
 * @return string
 */
function free_extension_box( $name, $url, $desc, $comp, $slug, $all_ic_plugins, $not_active_ic_plugins ) {
	if ( 'adv' === $comp && 'simple' === get_integration_type() ) {
		$comp_txt   = __( 'Advanced Mode Required', 'ecommerce-product-catalog' );
		$comp_class = 'wrong';
	} elseif ( 'price' === $comp && ! function_exists( 'is_ic_price_enabled' ) ) {
		$comp_txt   = __( 'Price Required', 'ecommerce-product-catalog' );
		$comp_class = 'wrong';
	} else {
		$comp_txt   = __( 'Ready to Install', 'ecommerce-product-catalog' );
		$comp_class = 'good';
	}

	$return      = '<div class="extension free ' . $url . '">
	<a class="extension-name" href="https://wordpress.org/plugins/' . $url . '"><h3><span>' . $name . '</span></h3><span class="click-span">' . __( 'Click for more', 'ecommerce-product-catalog' ) . '</span></a>
	<p>' . $desc . '</p>';
	$disabled    = '';
	$current_key = get_option( 'custom_license_code' );
	if ( ! current_user_can( 'install_plugins' ) ) {
		$disabled    = 'disabled';
		$current_key = '';
	}
	if ( ! empty( $all_ic_plugins ) && is_ic_plugin_active( $slug, $all_ic_plugins ) ) {
		$return .= '<p><a href="https://wordpress.org/support/plugin/' . $url . '" class="button-primary">Support</a> <a href="https://implecode.com/docs/" class="button-primary">Docs</a> <span class="comp installed">' . __( 'Active Extension', 'ecommerce-product-catalog' ) . '</span></p>';
	} elseif ( ! empty( $not_active_ic_plugins ) && is_ic_plugin_active( $slug, $not_active_ic_plugins ) ) {
			$return .= '<p><a ' . $disabled . ' href="' . wp_nonce_url( 'plugins.php?ic_cat_activation=1&action=activate&amp;plugin=' . rawurlencode( ic_cat_get_plugin_file( $slug ) ), 'activate-plugin_' . ic_cat_get_plugin_file( $slug ) ) . '" class="button-primary">Activate Now</a><span class="comp info">' . __( 'Installed Extension', 'ecommerce-product-catalog' ) . '</span></p>';
	} elseif ( 'wrong' === $comp_class ) {
			$return .= '<p><a href="https://wordpress.org/plugins/' . $url . '" class="button-primary">See the Extension</a><span class="comp ' . $comp_class . '">' . $comp_txt . '</span></p>';
	} else {
		$return .= '<form class="license_form" action=""><input type="hidden" name="free_implecode_install" value="1"><input type="hidden" name="url" value="' . $url . '"><input type="hidden" name="slug" value="' . $slug . '"><input type="hidden" name="post_type" value="al_product"><input type="hidden" name="page" value="extensions.php"><input type="hidden" name="tab" value="product-extensions">';
		$return .= wp_nonce_field( 'install-implecode-plugin_' . $slug, '_wpnonce', 0, 0 );
		$return .= '<p class="submit"><input type="submit" ' . $disabled . ' value="Install" class="button-primary"><span class="comp ' . $comp_class . '">' . $comp_txt . '</span></form></p>';
	}
	$return .= '</div>';

	return $return;
}

/**
 * Builds the affiliate extension box markup.
 *
 * @param string $name Extension name.
 * @param string $url  Extension URL.
 * @param string $desc Extension description.
 * @param string $comp Compatibility mode.
 *
 * @return string
 */
function extension_affiliate_box( $name, $url, $desc, $comp ) {

	if ( 'adv' === $comp && 'simple' === get_integration_type() ) {
		$comp_txt   = __( 'Advanced Mode Required', 'ecommerce-product-catalog' );
		$comp_class = 'wrong';
	} else {
		$comp_txt   = __( 'Ready to Install', 'ecommerce-product-catalog' );
		$comp_class = 'good';
	}

	$return = '<div class="extension affiliate">
	<a class="extension-name" href="' . $url . '"><h3><span>' . $name . '</span></h3><span class="click-span">' . __( 'Click for more', 'ecommerce-product-catalog' ) . '</span></a>
	<p>' . $desc . '</p>';
	if ( ! empty( $url ) ) {
		$return .= '<p><a href="' . $url . '" class="button-primary">Get ' . $name . '</a></p>';
	}
	$return .= '</div>';

	return $return;
}

/**
 * Checks whether a plugin slug exists in the impleCode plugin list.
 *
 * @param string $slug           Plugin slug.
 * @param array  $all_ic_plugins Plugin records.
 *
 * @return bool
 */
function is_ic_plugin_active( $slug, $all_ic_plugins ) {
	foreach ( $all_ic_plugins as $val ) {
		if ( $val['slug'] === $slug ) {
			return true;
		}
	}

	return false;
}

/**
 * Starts the premium extension installation flow.
 *
 * @return void
 */
function start_implecode_install() {
	$request_slug        = '';
	$request_license_key = '';
	$request_url         = '';
	$request_nonce       = '';
	// phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Read-only install request routing.
	if ( isset( $_GET['slug'] ) ) {
		// phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Read-only install request routing.
		$request_slug = sanitize_text_field( wp_unslash( $_GET['slug'] ) );
	}
	// phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Read-only install request routing.
	if ( isset( $_GET['license_key'] ) ) {
		// phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Read-only install request routing.
		$request_license_key = sanitize_text_field( wp_unslash( $_GET['license_key'] ) );
	}
	// phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Read-only install request routing.
	if ( isset( $_GET['url'] ) ) {
		// phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Read-only install request routing.
		$request_url = sanitize_text_field( wp_unslash( $_GET['url'] ) );
	}
	// phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Read-only install request routing.
	if ( isset( $_GET['_wpnonce'] ) ) {
		// phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Read-only install request routing.
		$request_nonce = sanitize_text_field( wp_unslash( $_GET['_wpnonce'] ) );
	}
	$upgrade_url = 'https://implecode.com/wordpress/plugins/' . rawurlencode( $request_url ) . '/#cam=extensions&key=' . rawurlencode( $request_url );
	// phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Read-only install request routing.
	if ( isset( $_GET['implecode_install'] ) && ! empty( $request_slug ) && ! empty( $request_license_key ) && current_user_can( 'install_plugins' ) ) {
		if ( ! wp_verify_nonce( $request_nonce, 'install-implecode-plugin_' . $request_slug ) ) {
			return;
		}
		$api = implecode_installation_url();
		if ( is_wp_error( $api ) ) {
			$error_messages = $api->get_error_messages();
			$wp_errors      = implode( "\n", $error_messages );
			echo '<div id="message error" class="error product-adder-message messages-connect"><div class="squeezer"><h4><strong>' . esc_html__( 'There is a problem with the connection. Please contact your server administrator with the following error:', 'ecommerce-product-catalog' ) . '</strong></h4><p>' . esc_html( $wp_errors ) . '</p></div></div>';
		} elseif ( 'error' !== $api ) {
			add_filter( 'install_plugin_complete_actions', 'implecode_install_actions', 10, 3 );
			echo '<div class="extension_installer">';
			include_once ABSPATH . 'wp-admin/includes/class-wp-upgrader.php';
			$upgrader = new Plugin_Upgrader( new Plugin_Installer_Skin( array( 'api' => $api ) ) );
			$upgrader->install( $api->download_url );
			echo '</div>';
		} elseif ( ! is_license_key_prevalidated( $request_license_key ) ) {
			$message = sprintf(
				/* translators: %s: extension purchase URL. */
				__( 'This is not a valid license key! Get it <a href="%s">here</a>.', 'ecommerce-product-catalog' ),
				esc_url( $upgrade_url )
			);
			// phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- Message markup is escaped during assembly.
			echo '<div id="message error" class="error product-adder-message messages-connect"><div class="squeezer"><h4><strong>' . $message . '</strong></h4></div></div>';
		} else {
			$message = sprintf(
				/* translators: %s: extension upgrade URL. */
				__( 'The supplied license key is not valid for this extension! Upgrade it <a href="%s">here</a>.', 'ecommerce-product-catalog' ),
				esc_url( $upgrade_url )
			);
			// phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- Message markup is escaped during assembly.
			echo '<div id="message error" class="error product-adder-message messages-connect"><div class="squeezer"><h4><strong>' . $message . '</strong></h4></div></div>';
		}
	// phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Read-only install request routing.
	} elseif ( isset( $_GET['implecode_install'] ) && ! empty( $request_slug ) && empty( $request_license_key ) && current_user_can( 'install_plugins' ) ) {
		$message = sprintf(
			/* translators: %s: extension purchase URL. */
			__( 'You need to provide the license key to activate the extension. Get yours <a href="%s">here</a>.', 'ecommerce-product-catalog' ),
			esc_url( $upgrade_url )
		);
		// phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- Message markup is escaped during assembly.
		echo '<div id="message error" class="error product-adder-message messages-connect"><div class="squeezer"><h4><strong>' . $message . '</strong></h4></div></div>';
	} elseif ( ! current_user_can( 'install_plugins' ) ) {
		echo '<div id="message error" class="error product-adder-message messages-connect"><div class="squeezer"><h4><strong>' . esc_html__( 'You don\'t have permission to install and activate extensions.', 'ecommerce-product-catalog' ) . '</strong></h4></div></div>';
	}
}

/**
 * Starts installation for a plugin hosted on WordPress.org.
 *
 * @return void
 */
function start_free_implecode_install() {
	$request_slug  = '';
	$request_nonce = '';
	// phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Read-only install request routing.
	if ( isset( $_GET['slug'] ) ) {
		// phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Read-only install request routing.
		$request_slug = sanitize_text_field( wp_unslash( $_GET['slug'] ) );
	}
	// phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Read-only install request routing.
	if ( isset( $_GET['_wpnonce'] ) ) {
		// phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Read-only install request routing.
		$request_nonce = sanitize_text_field( wp_unslash( $_GET['_wpnonce'] ) );
	}
	// phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Read-only install request routing.
	if ( isset( $_GET['free_implecode_install'] ) && ! empty( $request_slug ) && current_user_can( 'install_plugins' ) ) {
		if ( ! wp_verify_nonce( $request_nonce, 'install-implecode-plugin_' . $request_slug ) ) {
			return;
		}
		$slug = $request_slug;
		$url  = implecode_free_installation_url( $slug );
		if ( 'error' !== $url ) {
			add_filter( 'install_plugin_complete_actions', 'implecode_install_actions', 10, 3 );
			echo '<div class="extension_installer">';
			include_once ABSPATH . 'wp-admin/includes/class-wp-upgrader.php';
			$upgrader = new Plugin_Upgrader(
				new Plugin_Installer_Skin(
					array(
						'url' => $url,
					)
				)
			);
			$upgrader->install( $url );
			echo '</div>';
		} else {
			$url     = 'https://downloads.wordpress.org/plugin/' . $slug . '.latest-stable.zip';
			$message = sprintf(
				/* translators: %s: direct download URL. */
				__( 'Automatic installation is currently unavailable because your website cannot connect to WordPress.org. You can <a href="%s">download the extension manually</a> and install it via Plugins > Add New > Upload Plugin.', 'ecommerce-product-catalog' ),
				esc_url( $url )
			);
			// phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- Message markup is escaped during assembly.
			echo '<div id="message error" class="error product-adder-message messages-connect"><div class="squeezer"><h4><strong>' . $message . '</strong></h4></div></div>';
		}
	}
}

/**
 * Filters extension installation actions.
 *
 * @param array  $install_actions Available install actions.
 * @param object $api             Plugin API response.
 * @param string $plugin_file     Plugin file path.
 *
 * @return array
 */
function implecode_install_actions( $install_actions, $api, $plugin_file ) {
	if ( ! empty( $plugin_file ) ) {
		$disabled = '';
		if ( ! current_user_can( 'install_plugins' ) ) {
			$disabled = 'disabled';
		}
		$install_actions['activate_plugin'] = '<style>.extension_installer .button.button-primary:first-of-type{display: none;}</style><a ' . $disabled . ' href="' . wp_nonce_url( 'plugins.php?ic_cat_activation=1&action=activate&amp;plugin=' . rawurlencode( $plugin_file ), 'activate-plugin_' . $plugin_file ) . '" class="button-primary">Activate Now</a>';
	}
	$install_actions['plugins_page'] = '';

	return $install_actions;
}

/**
 * Returns active free impleCode plugins.
 *
 * @return array
 */
function get_implecode_active_free_plugins() {
	$all_active = get_option( 'active_plugins' );
	if ( ! function_exists( 'get_plugins' ) ) {
		require_once ABSPATH . 'wp-admin/includes/plugin.php';
	}
	$all_plugins = get_plugins();
	if ( empty( $all_plugins ) ) {
		return array();
	}
	$i          = 0;
	$ic_plugins = array();
	foreach ( $all_active as $active_name ) {
		if ( ! isset( $all_plugins[ $active_name ] ) ) {
			continue;
		}
		if ( 'impleCode' === $all_plugins[ $active_name ]['Author'] && 'eCommerce Product Catalog for WordPress' !== $all_plugins[ $active_name ]['Name'] && 'Product Catalog Simple' !== $all_plugins[ $active_name ]['Name'] ) {
			$ic_plugins[ $i ]['dir_file'] = $active_name;
			$active_name                  = explode( '/', $active_name );
			$ic_plugins[ $i ]['slug']     = $active_name[0];
		}
		++$i;
	}

	return $ic_plugins;
}

/**
 * Returns premium extension installation metadata.
 *
 * @return object|string|WP_Error
 */
function implecode_installation_url() {
	// phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Nonce is verified before calling this helper.
	$license_key = isset( $_GET['license_key'] ) ? sanitize_text_field( wp_unslash( $_GET['license_key'] ) ) : '';
	// phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Nonce is verified before calling this helper.
	$slug = isset( $_GET['slug'] ) ? sanitize_key( wp_unslash( $_GET['slug'] ) ) : '';
	if ( is_license_key_prevalidated( $license_key ) ) {
		$options = array(
			'timeout' => 10, // Seconds.
		);
		$url     = 'https://implecode.com/?action=get_metadata&slug=' . $slug . '&license_key=' . $license_key;
		$connect = wp_remote_get(
			$url,
			$options
		);
		if ( ! is_wp_error( $connect ) && ! empty( $connect['body'] ) ) {
			$plugin_info = json_decode( $connect['body'] );
			if ( isset( $plugin_info->download_url ) && '' !== $plugin_info->download_url ) {
				update_option( 'custom_license_code', $license_key, false );
				$license_owner = url_to_array( $plugin_info->license_owner );
				update_option( 'implecode_license_owner', array_to_url( $license_owner ), false );
				update_option( 'no_implecode_license_error', 0, false );
				$active_license = maybe_unserialize( get_option( 'license_active_plugins' ) );
				if ( empty( $active_license ) ) {
					$active_license = array();
				}
				$active_license[] = $slug;
				update_option( 'license_active_plugins', maybe_serialize( $active_license ), false );

				return $plugin_info;
			}
		} elseif ( is_wp_error( $connect ) ) {
			return $connect;
		}
	}

	return 'error';
}

/**
 * Returns installation URL from WordPress repository.
 *
 * @param string $slug Plugin slug.
 *
 * @return string
 */
function implecode_free_installation_url( $slug ) {
	$url      = 'https://downloads.wordpress.org/plugin/' . $slug . '.latest-stable.zip';
	$response = wp_remote_head( $url );
	if ( is_wp_error( $response ) || 404 === wp_remote_retrieve_response_code( $response ) ) {
		return 'error';
	} else {
		return $url;
	}
}

/**
 * Returns inactive impleCode plugins.
 *
 * @return array
 */
function get_implecode_not_active_plugins() {
	$all_active = get_option( 'active_plugins' );
	if ( ! function_exists( 'get_plugins' ) ) {
		require_once ABSPATH . 'wp-admin/includes/plugin.php';
	}
	$all_plugins = get_plugins();
	$i           = 0;
	$ic_plugins  = array();
	foreach ( $all_active as $active_name ) {
		unset( $all_plugins[ $active_name ] );
	}
	foreach ( $all_plugins as $not_active_name => $not_active_plugin ) {
		if ( 'Norbert Dreszer' === $not_active_plugin['Author'] || ( 'impleCode' === $not_active_plugin['Author'] && 'eCommerce Product Catalog by impleCode' !== $not_active_plugin['Name'] && 'Post Type X' !== $not_active_plugin['Name'] ) ) {
			$ic_plugins[ $i ]['dir_file'] = $not_active_name;
			$not_active_name              = explode( '/', $not_active_name );
			$ic_plugins[ $i ]['slug']     = $not_active_name[0];
		}
		++$i;
	}

	return $ic_plugins;
}

/**
 * Checks whether the license key uses the expected segment count.
 *
 * @param string $license_key License key.
 *
 * @return bool
 */
function is_license_key_prevalidated( $license_key ) {
	$license_key = explode( '-', $license_key );
	if ( 8 === count( $license_key ) ) {
		return true;
	}

	return false;
}

add_filter( 'ic_settings_screen_tabs', 'add_product_catalog_extensions_url', 55, 2 );

/**
 * Adds extensions, help, and upgrade links to the settings screen tabs.
 *
 * @param array              $tabs Existing settings screen tabs.
 * @param IC_Settings_Screen $screen Settings screen instance.
 *
 * @return array
 */
function add_product_catalog_extensions_url( $tabs, $screen = null ) {
	if ( function_exists( 'ic_epc_is_settings_screen_instance' ) ) {
		if ( ! ic_epc_is_settings_screen_instance( $screen ) ) {
			return $tabs;
		}
	} elseif ( ! is_object( $screen ) || ! method_exists( $screen, 'menu_slug' ) || 'product-settings.php' !== $screen->menu_slug() ) {
		return $tabs;
	}

	if ( current_user_can( 'install_plugins' ) ) {
		$tabs['extensions'] = array(
			'label'           => __( 'Add-ons & Integrations', 'ecommerce-product-catalog' ),
			'menu_item_id'    => 'extensions',
			'url'             => admin_url( 'edit.php?post_type=al_product&page=extensions.php' ),
			'active_callback' => 'ic_epc_extensions_tab_active',
		);
	}
	// phpcs:ignore WordPress.WP.Capabilities.Unknown -- Custom capability registered by the plugin.
	if ( current_user_can( 'manage_product_settings' ) ) {
		$tabs['help'] = array(
			'label'           => __( 'Help', 'ecommerce-product-catalog' ),
			'menu_item_id'    => 'help',
			'url'             => admin_url( 'edit.php?post_type=al_product&page=extensions.php&tab=help' ),
			'active_callback' => 'ic_epc_help_tab_active',
		);
	}

	if ( ! function_exists( 'start_implecode_updater' ) && false === get_site_transient( 'implecode_hide_extensions_box' ) ) {
		$tabs['upgrade-now'] = array(
			'label'           => __( 'Upgrade Now!', 'ecommerce-product-catalog' ),
			'menu_item_id'    => 'upgrade-now',
			'url'             => 'https://implecode.com/choose-a-plan/#cam=bundles&key=settings-top-menu',
			'class'           => 'upgrade-now',
			'target'          => '_blank',
			'title'           => __( 'Now you can get multiple extensions at once with the lowest price ever.', 'ecommerce-product-catalog' ),
			'active_callback' => '__return_false',
		);
	}

	return $tabs;
}

/**
 * Returns true when the extensions tab should be active.
 *
 * @param string $tab_key Current tab key.
 * @param array  $tab Current tab config.
 * @param mixed  $_screen Screen instance.
 *
 * @return bool
 */
function ic_epc_extensions_tab_active( $tab_key = '', $tab = array(), $_screen = null ) {
	if ( is_object( $_screen ) && method_exists( $_screen, 'menu_slug' ) && 'product-settings.php' !== $_screen->menu_slug() ) {
		return false;
	}

	// phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Read-only admin routing check.
	$page = isset( $_GET['page'] ) ? sanitize_text_field( wp_unslash( $_GET['page'] ) ) : '';
	// phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Read-only admin routing check.
	$tab = isset( $_GET['tab'] ) ? sanitize_key( wp_unslash( $_GET['tab'] ) ) : '';

	return 'extensions.php' === $page && 'help' !== $tab;
}

/**
 * Returns true when the help tab should be active.
 *
 * @param string $tab_key Current tab key.
 * @param array  $tab Current tab config.
 * @param mixed  $_screen Screen instance.
 *
 * @return bool
 */
function ic_epc_help_tab_active( $tab_key = '', $tab = array(), $_screen = null ) {
	if ( is_object( $_screen ) && method_exists( $_screen, 'menu_slug' ) && 'product-settings.php' !== $_screen->menu_slug() ) {
		return false;
	}

	// phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Read-only admin routing check.
	$page = isset( $_GET['page'] ) ? sanitize_text_field( wp_unslash( $_GET['page'] ) ) : '';
	// phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Read-only admin routing check.
	$tab = isset( $_GET['tab'] ) ? sanitize_key( wp_unslash( $_GET['tab'] ) ) : '';

	return 'extensions.php' === $page && 'help' === $tab;
}

add_action( 'ic_before_extensions_list', 'extensions_bundle_box', 5 );

/**
 * Shows bundle box before extensions list.
 *
 * @return void
 */
function extensions_bundle_box() {
	if ( ! function_exists( 'start_implecode_updater' ) ) {
		echo '<div class="bundle-box">' . esc_html__( 'Do you need multiple extensions?', 'ecommerce-product-catalog' ) . ' <a href="' . esc_url( 'https://implecode.com/choose-a-plan/#cam=bundles&key=extensions-bundle-box' ) . '">' . esc_html__( 'Check out extensions bundles', 'ecommerce-product-catalog' ) . '</a></div>';
	}
}

/**
 * Returns impleCode plugins available in the WordPress repository that are active on the website.
 *
 * @return array
 */
function get_free_implecode_active_plugins() {
	$all_active = get_option( 'active_plugins' );
	if ( ! function_exists( 'get_plugins' ) ) {
		require_once ABSPATH . 'wp-admin/includes/plugin.php';
	}
	$all_plugins = get_plugins();
	$i           = 0;
	$ic_plugins  = array();
	foreach ( $all_active as $active_name ) {
		if ( 'impleCode' === $all_plugins[ $active_name ]['Author'] && 'eCommerce Product Catalog by impleCode' !== $all_plugins[ $active_name ]['Name'] ) {
			$ic_plugins[ $i ]['dir_file'] = $active_name;
			$active_name                  = explode( '/', $active_name );
			$ic_plugins[ $i ]['slug']     = $active_name[0];
		}
		++$i;
	}

	return $ic_plugins;
}

/**
 * Returns impleCode plugins available in the WordPress repository that are not active on the website.
 *
 * @return array
 */
function get_implecode_free_not_active_plugins() {
	$all_active = get_option( 'active_plugins' );
	if ( ! function_exists( 'get_plugins' ) ) {
		require_once ABSPATH . 'wp-admin/includes/plugin.php';
	}
	$all_plugins = get_plugins();
	$i           = 0;
	$ic_plugins  = array();
	foreach ( $all_active as $active_name ) {
		unset( $all_plugins[ $active_name ] );
	}
	foreach ( $all_plugins as $not_active_name => $not_active_plugin ) {
		if ( 'impleCode' === $not_active_plugin['Author'] && 'eCommerce Product Catalog by impleCode' !== $not_active_plugin['Name'] ) {
			$ic_plugins[ $i ]['dir_file'] = $not_active_name;
			$not_active_name              = explode( '/', $not_active_name );
			$ic_plugins[ $i ]['slug']     = $not_active_name[0];
		}
		++$i;
	}

	return $ic_plugins;
}

add_filter( 'ic_cat_extensions', 'ic_epc_free_extensions' );

/**
 * Adds EPC free extensions to the extensions list.
 *
 * @param array|null $existing_extensions Existing extensions.
 *
 * @return array
 */
function ic_epc_free_extensions( $existing_extensions = null ) {
	$new_extensions = array();
	$extensions     = get_site_transient( 'implecode_epc_free_extensions_data' );
	if ( false === $extensions ) {
		$extensions = wp_remote_get( 'https://app.implecode.com/index.php?provide_extensions&free_epc=1' );
		if ( ! is_wp_error( $extensions ) && 200 === wp_remote_retrieve_response_code( $extensions ) ) {
			$extensions = json_decode( wp_remote_retrieve_body( $extensions ), true );
			if ( $extensions ) {
				set_site_transient( 'implecode_epc_free_extensions_data', $extensions, 60 * 60 * 24 * 7 );
			}
		} else {
			$extensions = implecode_free_extensions();
		}
	}
	foreach ( $extensions as $extension ) {
		$extension['type'] = isset( $extension['type'] ) ? $extension['type'] : 'premium';
		if ( 'catalog-booster-for-woocommerce' === $extension['slug'] && ! class_exists( 'WooCommerce' ) ) {
			continue;
		}
		$new_extensions[] = $extension;
	}

	return array_merge( $new_extensions, (array) $existing_extensions );
}

/**
 * Returns the fallback list of free extensions.
 *
 * @return array
 */
function implecode_free_extensions() {
	$free_extensions = array(
		'reviews-plus'                    => array(
			'url'  => 'reviews-plus',
			'name' => 'Product Reviews',
			'desc' => 'Add reviews support for your catalog items. Use it for all or selected products.',
			'comp' => 'simple',
			'slug' => 'reviews-plus',
			'type' => 'free',
		),
		'mailer-dragon'                   => array(
			'url'  => 'mailer-dragon',
			'name' => 'Catalog Newsletter',
			'desc' => 'Let users subscribe for product-related newsletters.',
			'comp' => 'simple',
			'slug' => 'mailer-dragon',
			'type' => 'free',
		),
		'catalog-booster-for-woocommerce' => array(
			'url'  => 'catalog-booster-for-woocommerce',
			'name' => 'WooCommerce Catalog',
			'desc' => 'Display WooCommerce products with ' . IC_CATALOG_PLUGIN_NAME . ' layout.',
			'comp' => 'simple',
			'slug' => 'catalog-booster-for-woocommerce',
			'type' => 'free',
		),
	);

	return $free_extensions;
}

add_action( 'activated_plugin', 'ic_cat_extension_page_activation' );

/**
 * Redirects to the extensions page after plugin activation.
 *
 * @return void
 */
function ic_cat_extension_page_activation() {
	// phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Read-only redirect flag.
	if ( ! empty( $_GET['ic_cat_activation'] ) ) {
		wp_safe_redirect( admin_url( 'edit.php?post_type=al_product&page=extensions.php&ic_cat_extension_activated=1' ) );
		exit;
	}
}

add_action( 'ic_cat_extensions_page_start', 'ic_cat_extension_activated_message' );

/**
 * Displays the extension activated notice.
 *
 * @return void
 */
function ic_cat_extension_activated_message() {
	// phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Read-only admin notice flag.
	if ( ! empty( $_GET['ic_cat_extension_activated'] ) ) {
		?>
			<div id="message" class="updated notice is-dismissible">
				<p><?php esc_html_e( 'Extension activated.', 'ecommerce-product-catalog' ); ?></p></div>
			<?php
	}
}

add_action( 'ic_cat_extensions_page_start', 'ic_show_extensions_page_renewal', 5 );

/**
 * Displays the renewal button on the extensions page.
 *
 * @return void
 */
function ic_show_extensions_page_renewal() {
	ic_license_renewal_button( null, 'page-title-action' );
}

if ( ! function_exists( 'ic_license_renewal_button' ) ) {

	/**
	 * Outputs the license renewal button.
	 *
	 * @param string|null $license_key License key.
	 * @param string      $button      Button CSS classes.
	 * @param string|null $label       Button label.
	 *
	 * @return void
	 */
	function ic_license_renewal_button( $license_key = null, $button = 'button-primary', $label = null ) {
		if ( ! function_exists( 'get_implecode_active_plugins' ) || ! function_exists( 'array_to_url' ) ) {
			return;
		}
		if ( empty( $license_key ) ) {
			$license_key = get_option( 'custom_license_code', '' );
		}
		$license_products = get_implecode_active_plugins( true );
		if ( empty( $label ) ) {
			$label = __( 'Renew License', 'ecommerce-product-catalog' );
		}
		$renewal_url = add_query_arg(
			array(
				'license_renewal'  => $license_key,
				'license_products' => array_to_url( $license_products ),
			),
			'https://implecode.com/wordpress/plugins/'
		) . '#cam=dashboard&key=renewal';
		echo '<a href="' . esc_url( $renewal_url ) . '" class="' . esc_attr( $button ) . ' ic-renewal-button" style="margin-top: 10px;">' . esc_html( $label ) . '</a>';
	}

}

add_action( 'ic_catalog_admin_priority_notices', 'ic_license_renewal_notice' );

/**
 * Displays the license renewal notice.
 *
 * @return void
 */
function ic_license_renewal_notice() {
	if ( ! function_exists( 'get_implecode_active_plugins' ) ) {
		return;
	}
	if ( ic_is_license_valid() ) {
		if ( ic_license_will_expire_soon() ) {
			$message = __( 'Your license will expire soon. Use the button below to prevent it, so the updates work without any interruptions.', 'ecommerce-product-catalog' );
		} elseif ( ic_license_will_expire_soon( false ) ) {
			ic_license_reverify_schedule();
		}
	} else {
		$message  = __( 'Your license is expired. The latest security and feature updates cannot be applied without an active license.', 'ecommerce-product-catalog' );
		$message .= '<br>' . __( 'Use the button below to fix it.', 'ecommerce-product-catalog' );
	}
	if ( empty( $message ) ) {
		return;
	}
	?>
	<div class="error notice-updated is-dismissible ic-notice" data-ic_dismissible="notice-ic-catalog-renewal">
		<div class="squeezer">
			<?php
				// phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- Message is assembled from translated strings and trusted markup.
				echo '<p>' . $message . '</p>';
			echo '<p>';
			ic_license_renewal_button();
			echo '</p>';
			do_action( 'ic_license_expiration_message' );
			?>
		</div>
	</div>
	<?php
	remove_action( 'admin_notices', 'license_key_expired' );
}

add_action( 'ic_license_expiration_message', 'ic_license_reverify_schedule' );
add_action( 'ic_license_reverify_schedule', 'ic_license_reverify_schedule' );

/**
 * Schedules or runs license reverification.
 *
 * @return void
 */
function ic_license_reverify_schedule() {
	if ( ! function_exists( 'check_all_implecode_license' ) ) {
		wp_unschedule_hook( 'ic_license_reverify_schedule' );

		return;
	}
	if ( current_filter() !== 'ic_license_reverify_schedule' ) {
		if ( ! wp_next_scheduled( 'ic_license_reverify_schedule' ) ) {
			wp_schedule_event( time() + MINUTE_IN_SECONDS, 'twicedaily', 'ic_license_reverify_schedule' );
		}

		return;
	}
	check_all_implecode_license();
	$unschedule = false;
	$reschedule = false;
	if ( ! function_exists( 'get_implecode_active_plugins' ) || ( ic_is_license_valid() && ! ic_license_will_expire_soon( false ) ) ) {
		$unschedule = true;
		if ( ic_license_is_subscription() ) {
			$reschedule = 'weekly';
		}
	} elseif ( function_exists( 'get_implecode_active_plugins' ) && ! ic_is_license_valid() ) {
		$unschedule = true;
		$reschedule = 'weekly';
	} elseif ( ic_license_will_expire_soon( false ) ) {
		$unschedule = true;
		$reschedule = 'twicedaily';
	}
	if ( $unschedule ) {
		wp_unschedule_hook( 'ic_license_reverify_schedule' );
	}
	if ( $reschedule ) {
		$schedules = wp_get_schedules();
		if ( ! empty( $schedules[ $reschedule ]['interval'] ) ) {
			if ( 'weekly' === $reschedule ) {
				$time = time() + HOUR_IN_SECONDS + DAY_IN_SECONDS;
			} else {
				$time = time() + $schedules[ $reschedule ]['interval'];
			}
			wp_schedule_event( $time, $reschedule, 'ic_license_reverify_schedule' );
		}
	}
}

/**
 * Returns the license expiry date.
 *
 * @return string|false
 */
function ic_license_valid_until() {
	$license_owner_param = get_option( 'implecode_license_owner' );
	$license_owner       = url_to_array( $license_owner_param );
	if ( ! empty( $license_owner['valid_until'] ) ) {
		return $license_owner['valid_until'];
	}

	return false;
}

/**
 * Returns the valid-until timestamp when the license is active.
 *
 * @return int|false
 */
function ic_is_license_valid() {
	$valid_until = ic_license_valid_until();
	if ( empty( $valid_until ) ) {
		return false;
	}
	$valid_until_time = strtotime( $valid_until );
	$current_time     = (int) gmdate( 'U' );
	if ( $valid_until_time + DAY_IN_SECONDS >= $current_time ) {
		return $valid_until_time;
	} else {
		return false;
	}
}

/**
 * Checks whether the license will expire soon.
 *
 * @param bool $check_is_sub Whether to skip subscriptions.
 *
 * @return bool
 */
function ic_license_will_expire_soon( $check_is_sub = true ) {
	if ( $check_is_sub && ic_license_is_subscription() ) {
		return false;
	}
	$valid_until_time = ic_is_license_valid();
	if ( $valid_until_time ) {
		$current_time = (int) gmdate( 'U' );
		$in_to_weeks  = $valid_until_time - ( WEEK_IN_SECONDS * 2 );
		if ( $current_time > $in_to_weeks ) {
			return true;
		}
	}

	return false;
}

/**
 * Checks whether the current license is a subscription.
 *
 * @return bool
 */
function ic_license_is_subscription() {
	$license_owner_param = get_option( 'implecode_license_owner' );
	$license_owner       = url_to_array( $license_owner_param );
	if ( ! empty( $license_owner['subscription'] ) ) {
		return true;
	}

	return false;
}

add_action( 'ic_catalog_admin_priority_notices', 'ic_epc_newsletter_notice' );

/**
 * Displays a dismissible WordPress admin notice for a newsletter subscription with promotional content.
 *
 * @param IC_Catalog_Notices|null $ic_notices Notice manager.
 *
 * @return void
 */
function ic_epc_newsletter_notice( $ic_notices = null ) {
	if ( ( ! empty( $ic_notices ) && $ic_notices->get_notice_status( 'notice-ic-catalog-newsletter', 'temp' ) ) || function_exists( 'start_implecode_updater' ) || is_ic_edit_product_screen() || is_ic_new_product_screen()) {

		return;
	}
	?>
	<div id="notice-ic-catalog-newsletter"
		class="updated notice notice-updated is-dismissible ic-notice notice-ic-catalog-newsletter"
		data-ic_dismissible="notice-ic-catalog-newsletter" data-ic_dismissible_type="temp" style="display: none;">
		<div class="squeezer"></div>
		<script>
			async function ic_epc_newsletter_notice() {
				try {
					const response = await fetch('https://implecode.com/wp-json/ic-mailer/v1/forms?custom=epc_newsletter');
					if (!response.ok) {
						throw new Error('Network response was not ok');
					}
					const data = await response.json();  // Change to .json()
					if (data.length > 0) {
						//jQuery('#ic-mailer-forms-container').append(data);
						jQuery('#notice-ic-catalog-newsletter .squeezer').append(data);
						jQuery('.notice-ic-catalog-newsletter').show();
					}
				} catch (error) {
					console.error('Error loading forms:', error);
					document.getElementById('ic-mailer-forms-container').innerHTML =
							'<div class="ic-notice-error"><?php echo esc_js( __( 'Error loading form. Please try again later.', 'ecommerce-product-catalog' ) ); ?></div>';
				}
			}

			ic_epc_newsletter_notice();
		</script>
	</div>

	<?php
}
