<?php

namespace EDPW\Core\Controllers\Admin;

use EDPW\Core\Helpers\EmailTemplate;
use EDPW\Core\Helpers\Input;
use EDPW\Core\Helpers\Plugin;
use EDPW\Core\Helpers\Util;
use EDPW\Core\Helpers\WC;

defined( 'ABSPATH' ) || exit;

class AddOn {
	private static $addons_list = [];
	private static $remote_url = 'https://static.flycart.net/email_customizer_advance/add-ons.json';

	/**
	 * Get external add-ons from local assets file.
	 * @return array
	 */
	private static function getRemoteAddonsList(): array {
		$addons = get_transient( 'edpw_remote_addons_list' );
		if ( empty( $addons ) ) {
			$addons   = [];
			$response = wp_remote_get( self::$remote_url );
			if ( ! is_wp_error( $response ) ) {
				$addons = (array) json_decode( wp_remote_retrieve_body( $response ), true );
				set_transient( 'edpw_remote_addons_list', $addons, 24 * 60 * 60 );
			}
		}

		return $addons;
	}

	/**
	 * Get add-on list.
	 * @return array
	 */
	protected static function getAddonList() {
		if ( ! empty( self::$addons_list ) ) {
			return self::$addons_list;
		}
		$addons = apply_filters( 'edpw_addon_list', array_merge( self::getRemoteAddonsList(), self::getInternalAddonsList() ) );
		if ( empty( $addons ) ) {
			return [];
		}
		$default_data = [
			'name'         => '',
			'description'  => '',
			'icon_url'     => '',
			'download_url' => '',
			'plugin_file'  => '',
			'document_url' => '',
			'page_url'     => '',
			'requires'     => [
				'wp'        => '',
				'wc'        => '',
				'edpw_core' => '',
				'edpw_pro'  => '',
			],
			'is_pro'       => false,
			'is_external'  => true,
		];

		$active_addons     = (array) get_option( 'edpw_active_addons', [] );
		$available_plugins = array_keys( get_plugins() );
		foreach ( $addons as $slug => $addon ) {
			$addon             = array_merge( $default_data, $addon );
			$addon['page_url'] = self::parseAddonUrl( $addon['page_url'] ?? '', $slug );
			if ( ! empty( $addon['is_external'] ) ) {
				$addon['is_active']    = in_array( $slug, $active_addons ) || Plugin::isActive( $addon['plugin_file'] );
				$addon['is_installed'] = ! empty( $addon['plugin_file'] ) && in_array( $addon['plugin_file'], $available_plugins );
			} else {
				$addon['is_active']    = in_array( $slug, $active_addons );
				$addon['is_installed'] = true;
			}
			$addons[ $slug ] = $addon;
		}

		return self::$addons_list = $addons;
	}

	/**
	 * Get active add-ons.
	 * @return void
	 */
	public static function getActiveAddonList() {
		if ( ! WC::isSecurityValid( 'edpw-addon-nonce' ) ) {
			wp_send_json_error( [ 'message' => esc_html__( 'Basic check failed', 'email-editor-plus' ) ] );
		}

		$search       = (string) Input::get( 'search' );
		$limit        = (int) Input::get( 'limit', 5 );
		$offset       = (int) Input::get( 'offset', 0 );
		$items        = [];
		$offset_count = $total_count = 0;
		foreach ( self::getAddonList() as $slug => $addon ) {
			$addon['add_on_slug'] = $slug;
			if ( ! isset( $addon['is_active'] ) || ! $addon['is_active'] ) {
				continue;
			}
			if ( ! empty( $search ) && ! EmailTemplate::isSearchHaveIt( $search, (object) $addon, [ 'name' ] ) ) {
				continue;
			}
			$total_count += 1;
			if ( count( $items ) >= $limit ) {
				continue;
			}
			if ( ! empty( $offset ) && $offset > $offset_count ) {
				$offset_count ++;
				continue;
			}
			$offset_count ++;
			$items[] = $addon;
		}
		wp_send_json_success( [
			'search'      => $search,
			'limit'       => $limit,
			'total_count' => $total_count,
			'items'       => $items
		] );
	}

	/**
	 * Get available add-ons.
	 * @return void
	 */
	public static function getAvailableAddonList() {
		if ( ! WC::isSecurityValid( 'edpw-addon-nonce' ) ) {
			wp_send_json_error( [ 'message' => esc_html__( 'Basic check failed', 'email-editor-plus' ) ] );
		}
		$search       = (string) Input::get( 'search' );
		$limit        = (int) Input::get( 'limit', 5 );
		$offset       = (int) Input::get( 'offset', 0 );
		$items        = [];
		$offset_count = $total_count = 0;
		foreach ( self::getAddonList() as $slug => $addon ) {
			$addon['add_on_slug'] = $slug;
			if ( isset( $addon['is_active'] ) && $addon['is_active'] ) {
				continue;
			}
			if ( ! empty( $search ) && ! EmailTemplate::isSearchHaveIt( $search, (object) $addon, [ 'name' ] ) ) {
				continue;
			}
			$total_count += 1;
			if ( count( $items ) >= $limit ) {
				continue;
			}
			if ( ! empty( $offset ) && $offset > $offset_count ) {
				$offset_count ++;
				continue;
			}
			$offset_count ++;
			$items[] = $addon;
		}
		wp_send_json_success( [
			'search'      => $search,
			'limit'       => $limit,
			'total_count' => $total_count,
			'items'       => $items
		] );
	}

	/**
	 * Get internal add-ons.
	 * @return array
	 */
	private static function getInternalAddonsList(): array {
		return [
			'ebct-booking-compatibility'      => [
				'name'         => esc_html__( 'WooCommerce Bookings', 'email-editor-plus' ),
				'description'  => esc_html__( 'Adds support for customizing emails sent by WooCommerce Booking plugin.', 'email-editor-plus' ),
				'icon_url'     => Util::getImageUrl( 'ebct-booking-compatibility' ),
				'page_url'     => '',
				'document_url' => '',
				'is_external'  => false,
				'is_pro'       => true,
				'dependencies' => [
					'booking' => [
						'name' => 'WooCommerce Bookings',
						'url'  => 'https://woocommerce.com/products/woocommerce-bookings/',
						'file' => 'woocommerce-bookings/woocommerce-bookings.php'
					]
				]
			],
			'wlct-loyalty-compatibility'      => [
				'name'         => esc_html__( 'WPLoyalty', 'email-editor-plus' ),
				'description'  => esc_html__( 'Adds support for customizing emails sent by WPLoyalty plugin.', 'email-editor-plus' ),
				'icon_url'     => Util::getImageUrl( 'wlct-loyalty-compatibility' ),
				'page_url'     => '',
				'document_url' => '',
				'is_external'  => false,
				'is_pro'       => true,
				'dependencies' => [
					'loyalty' => [
						'name' => 'WPLoyalty - WooCommerce Loyalty Points, Rewards and Referral',
						'url'  => 'https://wployalty.net/',
						'file' => [
							'WPLoyaltyPro'  => 'wp-loyalty-rules/wp-loyalty-rules.php',
							'WPLoyaltyFree' => 'wployalty/wp-loyalty-rules-lite.php'
						]
					]
				]
			],
			'esct-subscription-compatibility' => [
				'name'         => esc_html__( 'WooCommerce Subscriptions', 'email-editor-plus' ),
				'description'  => esc_html__( 'Adds support for customizing emails sent by WooCommerce Subscriptions plugin.', 'email-editor-plus' ),
				'icon_url'     => Util::getImageUrl( 'esct-subscription-compatibility' ),
				'page_url'     => '',
				'document_url' => '',
				'is_external'  => false,
				'is_pro'       => true,
				'dependencies' => [
					'subscription' => [
						'name' => 'Woo Subscriptions',
						'url'  => 'https://woocommerce.com/products/woocommerce-subscriptions/',
						'file' => 'woocommerce-subscriptions/woocommerce-subscriptions.php'
					]
				]
			]
		];
	}

	/**
	 * Parse addon url.
	 *
	 * @param string $url Default url.
	 * @param string $slug add-on slug.
	 *
	 * @return string
	 */
	private static function parseAddonUrl( string $url, string $slug ): string {
		$addon_page = admin_url( 'admin.php?page=' . $slug );

		return str_replace( '{addon_page}', $addon_page, $url );
	}

	/**
	 * Toggle activate addon.
	 * @return void
	 */
	public static function toggleAddonActivate() {
		if ( ! WC::isSecurityValid( 'edpw-addon-nonce' ) ) {
			wp_send_json_error( [ 'message' => esc_html__( 'Basic check failed', 'email-editor-plus' ) ] );
		}
		$action = Input::get( 'perform_action' );
		$slug   = Input::get( 'slug' );
		$addons = self::getAddonList();
		if ( ! is_string( $action ) || ! is_string( $slug ) || ! isset( $addons[ $slug ] ) || ! in_array( $action, [
				'activate',
				'deactivate'
			] ) ) {
			wp_send_json_error( [ 'message' => esc_html__( 'Invalid request', 'email-editor-plus' ) ] );
		}
		if ( ! empty( $addons[ $slug ]['is_external'] ) ) {
			$message = '';
			if ( $action == 'activate' ) {
				if ( ! empty( $addons[ $slug ]['is_pro'] ) && ! EmailTemplate::isPro() ) {
					wp_send_json_error( [ 'message' => esc_html__( 'You will require the PRO version for this add-on', 'email-editor-plus' ) ] );
				}
				$message = esc_html__( 'Need to activate add-on', 'email-editor-plus' );
			} elseif ( $action == 'deactivate' ) {
				$message = esc_html__( 'Need to de-activate add-on', 'email-editor-plus' );
			}
			$response = apply_filters( 'edpw_external_add_on_status', [
				'success' => false,
				'data'    => [ 'message' => $message ]
			], $action, $slug, $addons );
			wp_send_json( $response );
		} else {
			$active_addons = (array) get_option( 'edpw_active_addons', [] );
			if ( $action == 'activate' && ! in_array( $slug, $active_addons ) ) {
				if ( ! empty( $addons[ $slug ]['dependencies'] ) ) {
					$need_add_ons = [];

					foreach ( $addons[ $slug ]['dependencies'] as $dependency ) {
						if ( ! empty( $dependency['file'] ) ) {
							$is_need_to_add = false;
							if ( is_array( $dependency['file'] ) ) {
								// PRO or Free Required check
								$is_need_to_add = true;
								foreach ( $dependency['file'] as $plugin_file ) {
									if ( Plugin::isActive( $plugin_file ) ) {
										$is_need_to_add = false;
										break;
									}
								}
							} elseif ( ! Plugin::isActive( $dependency['file'] ) ) {
								$is_need_to_add = true;
							}
							if ( $is_need_to_add ) {
								$need_add_ons[] = $dependency['name'];
							}
						}
					}
					if ( ! empty( $need_add_ons ) ) {
						// translators: 1. %s will replace a require plugin list
						wp_send_json_error( [ 'message' => sprintf( esc_html__( 'Sorry, you need %s plugin', 'email-editor-plus' ), implode( ',', $need_add_ons ) ) ] );
					}
				}

				if ( ! empty( $addons[ $slug ]['is_pro'] ) && ! EmailTemplate::isPro() ) {
					wp_send_json_error( [ 'message' => esc_html__( 'You will require the PRO version to activate this add-on', 'email-editor-plus' ) ] );
				}
				$active_addons[] = $slug;
			} elseif ( $action == 'deactivate' && in_array( $slug, $active_addons ) ) {
				if ( ( $key = array_search( $slug, $active_addons ) ) !== false ) {
					unset( $active_addons[ $key ] );
				}
			}
			update_option( 'edpw_active_addons', $active_addons );
			wp_send_json_success( [
				'message' => ( $action == 'activate' )
					? esc_html__( 'Add-on has been activated', 'email-editor-plus' )
					: esc_html__( 'Add-on deactivated', 'email-editor-plus' )
			] );
		}
	}
}