<?php
/**
 * License activation and validation (Ultimate Bundle).
 *
 * @package EasySite_Pro
 */

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

/**
 * Whether license enforcement is required.
 *
 * @return bool
 */
function easysite_license_required() {
	if ( defined( 'EASYSITE_DEV_MODE' ) && EASYSITE_DEV_MODE ) {
		return false;
	}
	if ( ! EASYSITE_BUNDLE ) {
		return false;
	}
	// Local dev when no license server is configured and no key has been entered.
	if ( ! apply_filters( 'easysite_license_api_url', '' ) && ! get_option( 'easysite_license_key', '' ) ) {
		return false;
	}
	return true;
}

/**
 * Check if license is active.
 *
 * @return bool
 */
function easysite_license_is_active() {
	if ( ! easysite_license_required() ) {
		return true;
	}
	$key = get_option( 'easysite_license_key', '' );
	if ( ! $key ) {
		return false;
	}
	$status = get_option( 'easysite_license_status', '' );
	if ( 'valid' === $status ) {
		return true;
	}
	return (bool) get_option( 'easysite_license_status', false );
}

/**
 * Ultimate bundle features available (tier + license).
 *
 * @return bool
 */
function easysite_bundle_active() {
	return easysite_is_bundle() && easysite_license_is_active();
}

/**
 * Activate license key remotely or locally.
 *
 * @param string $key License key.
 * @return true|WP_Error
 */
function easysite_license_activate( $key ) {
	$key = sanitize_text_field( $key );
	if ( ! $key ) {
		return new WP_Error( 'empty_key', __( 'Please enter a license key.', 'easysite-pro' ) );
	}

	$api_url = apply_filters( 'easysite_license_api_url', '' );
	if ( $api_url ) {
		$response = wp_remote_post(
			$api_url,
			array(
				'timeout' => 20,
				'body'    => array(
					'license_key' => $key,
					'site_url'    => home_url( '/' ),
					'action'      => 'activate',
				),
			)
		);
		if ( is_wp_error( $response ) ) {
			return $response;
		}
		$data = json_decode( wp_remote_retrieve_body( $response ), true );
		if ( empty( $data['success'] ) ) {
			$msg = isset( $data['message'] ) ? $data['message'] : __( 'Activation failed.', 'easysite-pro' );
			return new WP_Error( 'activation_failed', $msg );
		}
	} elseif ( ! preg_match( '/^ESITE-[A-Z0-9]{4}-[A-Z0-9]{4}$/i', $key ) ) {
		return new WP_Error( 'invalid_format', __( 'Invalid license key format. Use ESITE-XXXX-XXXX or connect your license server.', 'easysite-pro' ) );
	}

	update_option( 'easysite_license_key', $key );
	update_option( 'easysite_license_status', 'valid' );
	update_option( 'easysite_license_activated', time() );
	return true;
}

/**
 * Deactivate license.
 */
function easysite_license_deactivate() {
	$key = get_option( 'easysite_license_key', '' );
	$api_url = apply_filters( 'easysite_license_api_url', '' );
	if ( $key && $api_url ) {
		wp_remote_post(
			$api_url,
			array(
				'timeout' => 15,
				'body'    => array(
					'license_key' => $key,
					'site_url'    => home_url( '/' ),
					'action'      => 'deactivate',
				),
			)
		);
	}
	delete_option( 'easysite_license_key' );
	delete_option( 'easysite_license_status' );
}

/**
 * Weekly license check cron.
 */
function easysite_license_cron_check() {
	if ( ! easysite_license_required() || ! get_option( 'easysite_license_key' ) ) {
		return;
	}
	$api_url = apply_filters( 'easysite_license_api_url', '' );
	if ( ! $api_url ) {
		return;
	}
	$response = wp_remote_post(
		$api_url,
		array(
			'timeout' => 15,
			'body'    => array(
				'license_key' => get_option( 'easysite_license_key' ),
				'site_url'    => home_url( '/' ),
				'action'      => 'check',
			),
		)
	);
	if ( is_wp_error( $response ) ) {
		return;
	}
	$data = json_decode( wp_remote_retrieve_body( $response ), true );
	update_option( 'easysite_license_status', ! empty( $data['success'] ) ? 'valid' : 'invalid' );
}
add_action( 'easysite_license_check_event', 'easysite_license_cron_check' );

/**
 * Schedule license check.
 */
function easysite_license_schedule() {
	if ( ! wp_next_scheduled( 'easysite_license_check_event' ) ) {
		wp_schedule_event( time(), 'weekly', 'easysite_license_check_event' );
	}
}
add_action( 'wp', 'easysite_license_schedule' );

/**
 * License settings page.
 */
function easysite_license_menu() {
	if ( ! easysite_is_bundle() ) {
		return;
	}
	add_submenu_page(
		'easysite-setup',
		__( 'License', 'easysite-pro' ),
		__( 'License', 'easysite-pro' ),
		'manage_options',
		'easysite-license',
		'easysite_render_license_page'
	);
}
add_action( 'admin_menu', 'easysite_license_menu', 99 );

/**
 * Render license page.
 */
function easysite_render_license_page() {
	if ( isset( $_POST['easysite_license_action'] ) && isset( $_POST['easysite_license_nonce'] ) && wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['easysite_license_nonce'] ) ), 'easysite_license' ) ) {
		$action = sanitize_key( wp_unslash( $_POST['easysite_license_action'] ) );
		if ( 'activate' === $action ) {
			$key = isset( $_POST['license_key'] ) ? sanitize_text_field( wp_unslash( $_POST['license_key'] ) ) : '';
			$result = easysite_license_activate( $key );
			if ( is_wp_error( $result ) ) {
				echo '<div class="notice notice-error"><p>' . esc_html( $result->get_error_message() ) . '</p></div>';
			} else {
				echo '<div class="notice notice-success"><p>' . esc_html__( 'License activated!', 'easysite-pro' ) . '</p></div>';
			}
		} elseif ( 'deactivate' === $action ) {
			easysite_license_deactivate();
			echo '<div class="notice notice-success"><p>' . esc_html__( 'License deactivated.', 'easysite-pro' ) . '</p></div>';
		}
	}

	$key    = get_option( 'easysite_license_key', '' );
	$active = easysite_license_is_active();
	?>
	<div class="wrap">
		<h1><?php esc_html_e( 'EasySite Pro License', 'easysite-pro' ); ?></h1>
		<?php if ( $active ) : ?>
			<p class="easysite-license-status easysite-license-status--active"><?php esc_html_e( 'Your Ultimate Bundle license is active.', 'easysite-pro' ); ?></p>
		<?php else : ?>
			<p class="easysite-license-status easysite-license-status--inactive"><?php esc_html_e( 'Activate your license to unlock Ultimate Bundle features.', 'easysite-pro' ); ?></p>
		<?php endif; ?>
		<form method="post">
			<?php wp_nonce_field( 'easysite_license', 'easysite_license_nonce' ); ?>
			<table class="form-table">
				<tr>
					<th><label for="license_key"><?php esc_html_e( 'License key', 'easysite-pro' ); ?></label></th>
					<td><input type="text" name="license_key" id="license_key" class="regular-text" value="<?php echo esc_attr( $key ); ?>" placeholder="ESITE-XXXX-XXXX" /></td>
				</tr>
			</table>
			<p class="submit">
				<button type="submit" name="easysite_license_action" value="activate" class="button button-primary"><?php esc_html_e( 'Activate', 'easysite-pro' ); ?></button>
				<?php if ( $key ) : ?>
					<button type="submit" name="easysite_license_action" value="deactivate" class="button"><?php esc_html_e( 'Deactivate', 'easysite-pro' ); ?></button>
				<?php endif; ?>
			</p>
		</form>
	</div>
	<?php
}

/**
 * Admin notice when license inactive.
 */
function easysite_license_admin_notice() {
	if ( ! easysite_license_required() || easysite_license_is_active() || ! current_user_can( 'manage_options' ) ) {
		return;
	}
	$url = admin_url( 'admin.php?page=easysite-license' );
	echo '<div class="notice notice-warning"><p>' . wp_kses_post( sprintf( __( 'EasySite Ultimate Bundle: <a href="%s">Activate your license</a> to unlock all features.', 'easysite-pro' ), esc_url( $url ) ) ) . '</p></div>';
}
add_action( 'admin_notices', 'easysite_license_admin_notice' );
