<?php
/**
 * WE88 — Plugin provisioner (shared)
 *
 * @package WE88_Dark_Gold
 */

defined( 'ABSPATH' ) || exit;

/**
 * Actionable fallback when the plugin isn't active (auto-provisioning was
 * skipped or failed). Shows a one-click Install/Activate CTA. Dismissible per
 * user. Reads active_plugins directly — is_plugin_active() may be unavailable
 * on some admin screens.
 */
function we88_dark_gold_plugin_dependency_notice(): void {
	if ( ! current_user_can( 'activate_plugins' ) ) {
		return;
	}

	$plugin_file = 'we88-portal/we88-portal.php';
	$active      = (array) get_option( 'active_plugins', [] );
	if ( in_array( $plugin_file, $active, true ) ) {
		return;
	}
	if ( get_user_meta( get_current_user_id(), 'we88_dg_dismiss_plugin_notice', true ) ) {
		return;
	}

	// A single stat() — cheaper than get_plugins(), which scans and parses the
	// header of every installed plugin on every admin page render.
	$installed  = file_exists( WP_PLUGIN_DIR . '/' . $plugin_file );
	$has_bundle = file_exists( get_theme_file_path( 'bundled/we88-portal.zip' ) );

	if ( $installed ) {
		$action = 'we88_dg_activate_plugin';
		$label  = __( 'Activate WE88 Portal', 'we88-express' );
	} elseif ( $has_bundle && current_user_can( 'install_plugins' ) ) {
		$action = 'we88_dg_install_plugin';
		$label  = __( 'Install & Activate WE88 Portal', 'we88-express' );
	} else {
		// No bundle and not installed — link to the upload screen.
		$action = '';
		$label  = __( 'Add the WE88 Portal plugin', 'we88-express' );
	}

	$cta = '' === $action
		? admin_url( 'plugin-install.php?tab=upload' )
		: wp_nonce_url( admin_url( 'admin-post.php?action=' . $action ), $action );

	$dismiss = wp_nonce_url(
		add_query_arg( 'we88_dg_dismiss', '1' ),
		'we88_dg_dismiss'
	);

	echo '<div class="notice notice-warning"><p><strong>WE88 Dark Gold:</strong> ';
	echo esc_html__( 'This theme pairs with the WE88 Portal plugin, which powers the login, games, balance and other portal widgets.', 'we88-express' );
	echo '</p><p>';
	printf(
		'<a href="%s" class="button button-primary">%s</a> ',
		esc_url( $cta ),
		esc_html( $label )
	);
	printf(
		'<a href="%s">%s</a>',
		esc_url( $dismiss ),
		esc_html__( 'Dismiss', 'we88-express' )
	);
	echo '</p></div>';
}
add_action( 'admin_notices', 'we88_dark_gold_plugin_dependency_notice' );

/**
 * Record per-user dismissal of the plugin notice.
 */
function we88_dark_gold_maybe_dismiss_notice(): void {
	if ( empty( $_GET['we88_dg_dismiss'] ) ) {
		return;
	}
	check_admin_referer( 'we88_dg_dismiss' );
	update_user_meta( get_current_user_id(), 'we88_dg_dismiss_plugin_notice', 1 );
	wp_safe_redirect( remove_query_arg( [ 'we88_dg_dismiss', '_wpnonce' ] ) );
	exit;
}
add_action( 'admin_init', 'we88_dark_gold_maybe_dismiss_notice' );

/**
 * admin-post handler: install the bundled plugin then activate it.
 */
function we88_dark_gold_handle_install_plugin(): void {
	if ( ! current_user_can( 'install_plugins' ) ) {
		wp_die( esc_html__( 'You are not allowed to install plugins.', 'we88-express' ) );
	}
	check_admin_referer( 'we88_dg_install_plugin' );

	$plugin_file = 'we88-portal/we88-portal.php';
	$installed   = file_exists( WP_PLUGIN_DIR . '/' . $plugin_file );

	if ( ! $installed ) {
		$zip = get_theme_file_path( 'bundled/we88-portal.zip' );
		if ( file_exists( $zip ) ) {
			require_once ABSPATH . 'wp-admin/includes/file.php';
			require_once ABSPATH . 'wp-admin/includes/misc.php';
			require_once ABSPATH . 'wp-admin/includes/plugin.php';
			require_once ABSPATH . 'wp-admin/includes/class-wp-upgrader.php';
			require_once ABSPATH . 'wp-admin/includes/class-automatic-upgrader-skin.php';

			if ( WP_Filesystem() ) {
				$upgrader  = new \Plugin_Upgrader( new \Automatic_Upgrader_Skin() );
				$installed = ( true === $upgrader->install( $zip ) );
			}
		}
	}

	// Only activate when the plugin is actually present. Activating after a
	// failed install would target a non-existent file and the redirect would
	// look like success; instead we fall through, leaving the plugin inactive
	// so the dependency notice re-appears with the CTA.
	if ( $installed ) {
		activate_plugin( $plugin_file );
	}
	wp_safe_redirect( admin_url( 'plugins.php' ) );
	exit;
}
add_action( 'admin_post_we88_dg_install_plugin', 'we88_dark_gold_handle_install_plugin' );

/**
 * admin-post handler: activate an already-installed plugin.
 */
function we88_dark_gold_handle_activate_plugin(): void {
	if ( ! current_user_can( 'activate_plugins' ) ) {
		wp_die( esc_html__( 'You are not allowed to activate plugins.', 'we88-express' ) );
	}
	check_admin_referer( 'we88_dg_activate_plugin' );
	activate_plugin( 'we88-portal/we88-portal.php' );
	wp_safe_redirect( admin_url( 'plugins.php' ) );
	exit;
}
add_action( 'admin_post_we88_dg_activate_plugin', 'we88_dark_gold_handle_activate_plugin' );

/**
 * Provision the WE88 Portal plugin the moment this theme is activated, so the
 * portal is ready to use immediately. Installs from the CI-bundled ZIP, then
 * activates. Every failure path degrades silently to the admin-notice fallback
 * below — this never fatals and never half-installs.
 */
function we88_dark_gold_provision_plugin(): void {
	if ( ! current_user_can( 'install_plugins' ) || ! current_user_can( 'activate_plugins' ) ) {
		return; // The fallback notice will guide a less-privileged admin.
	}

	$plugin_file = 'we88-portal/we88-portal.php';

	// Already active? Nothing to do (idempotent on re-activation).
	$active = (array) get_option( 'active_plugins', [] );
	if ( in_array( $plugin_file, $active, true ) ) {
		return;
	}

	require_once ABSPATH . 'wp-admin/includes/plugin.php';
	$installed = array_key_exists( $plugin_file, get_plugins() );

	if ( ! $installed ) {
		$zip = get_theme_file_path( 'bundled/we88-portal.zip' );
		if ( ! file_exists( $zip ) ) {
			return; // No bundle (e.g. dev checkout) — fall back to the notice.
		}

		require_once ABSPATH . 'wp-admin/includes/file.php';
		require_once ABSPATH . 'wp-admin/includes/misc.php';
		require_once ABSPATH . 'wp-admin/includes/class-wp-upgrader.php';
		require_once ABSPATH . 'wp-admin/includes/class-automatic-upgrader-skin.php';

		if ( ! WP_Filesystem() ) {
			return; // Host needs interactive FS credentials — fall back to the notice.
		}

		$upgrader = new \Plugin_Upgrader( new \Automatic_Upgrader_Skin() );
		$result   = $upgrader->install( $zip );
		if ( is_wp_error( $result ) || true !== $result ) {
			return;
		}
	}

	// activate_plugin() returns null on success, WP_Error on failure.
	activate_plugin( $plugin_file );
}
add_action( 'after_switch_theme', 'we88_dark_gold_provision_plugin' );
