<?php

namespace SugarCalendarBookings\Support\License;

use Plugin_Upgrader;
use SugarCalendarBookings\Options;
use SugarCalendarBookings\Plugin;
use SugarCalendarBookings\Support\Bootable;
use SugarCalendarBookings\Support\DataProcessing\Sanitizer;
use SugarCalendarBookings\Support\DataProcessing\Validator;
use SugarCalendarBookings\Support\Helpers\Helpers;
use SugarCalendarBookings\Support\Helpers\WP;
use WP_Ajax_Upgrader_Skin;
use WP_Error;

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

/**
 * Sugar Calendar Bookings Connect.
 *
 * Sugar Calendar Bookings Connect is our service that makes it easy for non-techy users to
 * upgrade to Pro version without having to manually install Pro plugin.
 *
 * @since 1.2.0
 */
class Connect implements Bootable {

	/**
	 * Allow loading of the class.
	 *
	 * @since 1.2.0
	 *
	 * @return bool
	 */
	public function allow_load(): bool {

		// Only load Connect in Lite version.
		return ! Plugin::instance()->is_pro();
	}

	/**
	 * Hooks.
	 *
	 * @since 1.2.0
	 */
	public function hooks() {

		add_action( 'sugar_calendar_bookings_admin_area_enqueue_assets', [ $this, 'enqueue_scripts' ] );
		add_action( 'wp_ajax_sugar_calendar_bookings_connect_url', [ $this, 'ajax_generate_url' ] );
		// _nopriv_ is intentional — server-to-server callback with no cookies.
		// Gated by the OTH and the install URL host allowlist. Do not change to wp_ajax_.
		add_action( 'wp_ajax_nopriv_sugar_calendar_bookings_connect_process', [ $this, 'process' ] );
	}

	/**
	 * Enqueue connect JS file to admin area.
	 *
	 * @since 1.2.0
	 */
	public function enqueue_scripts() {

		wp_enqueue_style( 'sugar-calendar-bookings-vendor-jquery-confirm' );

		wp_enqueue_script(
			'sugar-calendar-bookings-admin-connect',
			SCBOOKINGS_PLUGIN_URL . 'assets/dist/admin/admin-connect.js',
			[ 'sugar-calendar-bookings-vendor-jquery-confirm' ],
			SCBOOKINGS_PLUGIN_VERSION,
			true
		);

		wp_localize_script(
			'sugar-calendar-bookings-admin-connect',
			'sugar_calendar_bookings_admin_connect',
			[
				'ajax_url'   => admin_url( 'admin-ajax.php' ),
				'plugin_url' => SCBOOKINGS_PLUGIN_URL,
				'nonce'      => wp_create_nonce( 'sugar_calendar_bookings_connect_url' ),
				'text'       => [
					'plugin_activate_btn' => esc_html__( 'Activate', 'sugar-calendar-bookings-scheduling-appointments-lite' ),
					'almost_done'         => esc_html__( 'Almost Done', 'sugar-calendar-bookings-scheduling-appointments-lite' ),
					'oops'                => esc_html__( 'Heads up!', 'sugar-calendar-bookings-scheduling-appointments-lite' ),
					'ok'                  => esc_html__( 'Continue', 'sugar-calendar-bookings-scheduling-appointments-lite' ),
					'server_error'        => esc_html__( 'Unfortunately there was a server connection error.', 'sugar-calendar-bookings-scheduling-appointments-lite' ),
				],
			]
		);
	}

	/**
	 * Generate and return Sugar Calendar Bookings Connect URL.
	 *
	 * @since 1.2.0
	 *
	 * @param string $key      The license key.
	 * @param string $oth      The One-time hash.
	 * @param string $redirect The redirect URL.
	 *
	 * @return bool|string
	 */
	public static function generate_url( $key, $oth = '', $redirect = '' ) {

		if ( empty( $key ) || Plugin::instance()->is_pro() ) {
			return false;
		}

		$oth        = ! empty( $oth ) ? $oth : hash( 'sha512', wp_rand() );
		$hashed_oth = hash_hmac( 'sha512', $oth, wp_salt() );

		$redirect = ! empty( $redirect ) ? $redirect : admin_url( 'admin.php?page=sugar-calendar-bookings-calendar' );

		update_option( 'sugar_calendar_bookings_connect_token', $oth );
		update_option( 'sugar_calendar_bookings_connect', $key );

		return add_query_arg(
			[
				'key'      => $key,
				'oth'      => $hashed_oth,
				'endpoint' => admin_url( 'admin-ajax.php' ),
				'version'  => SCBOOKINGS_PLUGIN_VERSION,
				'siteurl'  => admin_url(),
				'homeurl'  => site_url(),
				'redirect' => rawurldecode( base64_encode( $redirect ) ), // phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.obfuscation_base64_encode
				'v'        => 2,
			],
			'https://bookings.sugarcalendarapi.com/lite-plugin-upgrade'
		);
	}

	/**
	 * AJAX callback to generate and return the Sugar Calendar Bookings Connect URL.
	 *
	 * @since 1.2.0
	 */
	public function ajax_generate_url() { // phpcs:ignore Generic.Metrics.CyclomaticComplexity.TooHigh

		// Verify CSRF nonce before any state-changing operation. This handler
		// can flip Lite/Pro activation and writes connect options.
		if ( ! check_ajax_referer( 'sugar_calendar_bookings_connect_url', 'nonce', false ) ) {
			wp_send_json_error(
				[
					'message' => esc_html__( 'Invalid security token. Please refresh the page and try again.', 'sugar-calendar-bookings-scheduling-appointments-lite' ),
				]
			);
		}

		// Check for permissions.
		if ( ! current_user_can( 'install_plugins' ) ) {
			wp_send_json_error(
				[
					'message' => esc_html__( 'You are not allowed to install plugins.', 'sugar-calendar-bookings-scheduling-appointments-lite' ),
				]
			);
		}

		// Sanitize input data.
		$rules = [
			'key' => 'string',
		];

		$sanitized = Sanitizer::sanitize( $_POST, $rules );

		// Validate input data.
		$validation = Validator::validate(
			$sanitized,
			[
				'key' => 'required|string',
			]
		);

		if ( is_wp_error( $validation ) ) {
			wp_send_json_error(
				[
					'message' => esc_html__( 'Please enter your license key to connect.', 'sugar-calendar-bookings-scheduling-appointments-lite' ),
				]
			);
		}

		$key = $sanitized['key'];

		if ( Plugin::instance()->is_pro() ) {
			wp_send_json_error(
				[
					'message' => esc_html__( 'Only the Lite version can be upgraded.', 'sugar-calendar-bookings-scheduling-appointments-lite' ),
				]
			);
		}

		// Verify pro version is not installed.
		$active = activate_plugin( 'sugar-calendar-bookings-scheduling-appointments/sugar-calendar-bookings-scheduling-appointments.php', false, false, true );

		if ( ! is_wp_error( $active ) ) {

			// Deactivate Lite.
			deactivate_plugins( plugin_basename( SCBOOKINGS_PLUGIN_FILE ) );

			wp_send_json_success(
				[
					'message' => esc_html__( 'Sugar Calendar Bookings Pro was already installed, but was not active. We activated it for you.', 'sugar-calendar-bookings-scheduling-appointments-lite' ),
					'reload'  => true,
				]
			);
		}

		$url = self::generate_url( $key );

		if ( empty( $url ) ) {
			wp_send_json_error(
				[
					'message' => esc_html__( 'There was an error while generating an upgrade URL. Please try again.', 'sugar-calendar-bookings-scheduling-appointments-lite' ),
				]
			);
		}

		wp_send_json_success( [ 'url' => $url ] );
	}

	/**
	 * AJAX callback to process Sugar Calendar Bookings Connect.
	 *
	 * @since 1.2.0
	 */
	public function process() { // phpcs:ignore Generic.Metrics.CyclomaticComplexity.MaxExceeded,WPForms.PHP.HooksMethod.InvalidPlaceForAddingHooks

		$error = esc_html__( 'There was an error while installing an upgrade. Please download the plugin from sugarcalendar.com and install it manually.', 'sugar-calendar-bookings-scheduling-appointments-lite' );

		// Sanitize input data.
		$rules = [
			'oth'  => 'string',
			'file' => 'url',
		];

		$sanitized = Sanitizer::sanitize( $_REQUEST, $rules ); // phpcs:ignore WordPress.Security.NonceVerification

		// Validate input data.
		$validation = Validator::validate(
			$sanitized,
			[
				'oth'  => 'required|string',
				'file' => 'required|url',
			]
		);

		if ( is_wp_error( $validation ) ) {
			wp_send_json_error( $error );
		}

		$post_oth = $sanitized['oth'];
		$post_url = $sanitized['file'];

		// Verify oth.
		$oth = get_option( 'sugar_calendar_bookings_connect_token' );

		if ( empty( $oth ) ) {
			wp_send_json_error( $error );
		}

		if ( ! hash_equals( hash_hmac( 'sha512', $oth, wp_salt() ), $post_oth ) ) {
			wp_send_json_error( $error );
		}

		// Delete so cannot replay.
		delete_option( 'sugar_calendar_bookings_connect_token' );

		// Set the current screen to avoid undefined notices.
		set_current_screen( 'toplevel_page_scbookings-calendar' );

		// Prepare variables.
		$url = esc_url_raw( admin_url( 'admin.php?page=sugar-calendar-bookings-calendar' ) );

		// Verify pro not activated.
		if ( Plugin::instance()->is_pro() ) {
			wp_send_json_success( esc_html__( 'Plugin installed & activated.', 'sugar-calendar-bookings-scheduling-appointments-lite' ) );
		}

		// Verify pro not installed.
		$active = activate_plugin( 'sugar-calendar-bookings-scheduling-appointments/sugar-calendar-bookings-scheduling-appointments.php', $url, false, true );

		if ( ! is_wp_error( $active ) ) {
			deactivate_plugins( plugin_basename( SCBOOKINGS_PLUGIN_FILE ) );
			wp_send_json_success( esc_html__( 'Plugin installed & activated.', 'sugar-calendar-bookings-scheduling-appointments-lite' ) );
		}

		/*
		 * The `request_filesystem_credentials` function will output a credentials form in case of failure.
		 * We don't want that, since it will break AJAX response. So just hide output with a buffer.
		 */
		ob_start();
		// phpcs:ignore WPForms.Formatting.EmptyLineAfterAssigmentVariables.AddEmptyLine
		$creds = request_filesystem_credentials( $url, '', false, false, null );
		ob_end_clean();

		// Check for file system permissions.
		$perm_error = esc_html__( 'There was an error while installing the upgrade. Please check file system permissions and try again. Also, you can download the plugin from sugarcalendar.com and install it manually.', 'sugar-calendar-bookings-scheduling-appointments-lite' );

		if ( $creds === false || ! WP_Filesystem( $creds ) ) {
			wp_send_json_error( $perm_error );
		}

		/*
		 * We do not need any extra credentials if we have gotten this far, so let's install the plugin.
		 */

		// Do not allow WordPress to search/download translations, as this will break JS output.
		remove_action( 'upgrader_process_complete', [ 'Language_Pack_Upgrader', 'async_upgrade' ], 20 );

		// Import the plugin upgrader.
		Helpers::include_plugin_upgrader();

		// Create the plugin upgrader with our custom skin.
		$installer = new Plugin_Upgrader( new WP_Ajax_Upgrader_Skin() );

		// Error check.
		if ( ! method_exists( $installer, 'install' ) ) {
			wp_send_json_error( $error );
		}

		// Check license key.
		$key = get_option( 'sugar_calendar_bookings_connect', false );

		delete_option( 'sugar_calendar_bookings_connect' );

		if ( empty( $key ) ) {
			wp_send_json_error(
				new WP_Error(
					'403',
					esc_html__( 'There was an error while installing the upgrade. Please try again.', 'sugar-calendar-bookings-scheduling-appointments-lite' )
				)
			);
		}

		/**
		 * Filters the hosts allowed to serve the Lite-to-Pro install zip.
		 *
		 * Restrict installs to known hosts. Allowing arbitrary hosts here
		 * would turn this method into a generic remote plugin installer
		 * for anyone holding a valid OTH.
		 *
		 * @since 1.4.1
		 *
		 * @param string[] $allowed_hosts Hostnames (no scheme, no path).
		 */
		$allowed_hosts = apply_filters(
			'sugar_calendar_bookings_connect_process_install_allowed_hosts',
			[ 'bookings.sugarcalendarapi.com' ]
		);

		$post_url_host   = wp_parse_url( $post_url, PHP_URL_HOST );
		$is_allowed_host = false;

		if ( is_string( $post_url_host ) && $post_url_host !== '' ) {
			foreach ( (array) $allowed_hosts as $allowed ) {
				if ( ! is_string( $allowed ) || $allowed === '' ) {
					continue;
				}

				// Strict, case-insensitive host match (no subdomain wildcard).
				if ( strcasecmp( $post_url_host, $allowed ) === 0 ) {
					$is_allowed_host = true;
					break;
				}
			}
		}

		if ( ! $is_allowed_host ) {
			wp_send_json_error(
				esc_html__( 'The upgrade URL host is not allowed.', 'sugar-calendar-bookings-scheduling-appointments-lite' )
			);
		}

		$installer->install( $post_url );

		// Flush the cache and return the newly installed plugin basename.
		wp_cache_flush();

		$plugin_basename = $installer->plugin_info();

		if ( $plugin_basename ) {

			// Deactivate the lite version first.
			deactivate_plugins( plugin_basename( SCBOOKINGS_PLUGIN_FILE ) );

			// Activate the plugin silently.
			$activated = activate_plugin( $plugin_basename, '', false, true );

			if ( ! is_wp_error( $activated ) ) {

			// Save the license data, since it was verified on the connect page.
			$license = [
				'key'         => $key,
				'type'        => 'pro',
				'is_expired'  => false,
				'is_disabled' => false,
				'is_invalid'  => false,
			];

			Plugin::get( Options::class )->update( [ 'license' => $license ] );

				wp_send_json_success( esc_html__( 'Plugin installed & activated.', 'sugar-calendar-bookings-scheduling-appointments-lite' ) );
			} else {
				// Reactivate the lite plugin if pro activation failed.
				activate_plugin( plugin_basename( SCBOOKINGS_PLUGIN_FILE ), '', false, true );
				wp_send_json_error( esc_html__( 'Pro version installed but needs to be activated on the Plugins page.', 'sugar-calendar-bookings-scheduling-appointments-lite' ) );
			}
		}

		wp_send_json_error( $error );
	}
}
