<?php
if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

/**
 * First-run welcome flow:
 * - Activator sets a transient → admin_init redirects once to Settings.
 * - Settings page renders a 2-step Quick-Start panel that auto-checks
 *   completed steps and disappears once both are done.
 */
class CCGAL_Welcome {

	const TRANSIENT_REDIRECT = 'ccgal_show_welcome';

	public static function init() {
		// Hook on admin_menu (not admin_init) with very late priority so the ccgal-settings
		// submenu is GUARANTEED to be registered when we issue the redirect — otherwise
		// WP rejects access to ?page=ccgal-settings with "Sorry, you are not allowed to
		// access this page." (especially noticeable on hosts with strict capability filters
		// or staging environments where plugin load order can be different).
		add_action( 'admin_menu', array( __CLASS__, 'maybe_redirect' ), 9999 );
	}

	public static function mark_for_redirect() {
		// Multisite-Bulk-Aktivierung NICHT redirecten — User würde sonst
		// für jede Site einzeln auf eine andere URL geworfen.
		if ( is_network_admin() ) {
			return;
		}
		// phpcs:ignore WordPress.Security.NonceVerification.Recommended -- WP-Activation hat keinen eigenen Nonce.
		if ( isset( $_GET['activate-multi'] ) ) {
			return;
		}
		set_transient( self::TRANSIENT_REDIRECT, 1, 30 );
	}

	public static function maybe_redirect() {
		if ( ! get_transient( self::TRANSIENT_REDIRECT ) ) {
			return;
		}

		// Don't fight Freemius's own activation / opt-in / skip-license flow — it
		// performs its own redirect to a Freemius-internal page. Our Welcome-redirect
		// firing on top of that lands the user on "Sorry, you are not allowed to view
		// this page". Defer our redirect to the next request once Freemius is out
		// of activation mode. Transient TTL is 30s, so we get one or two retries.
		if ( function_exists( 'ccgal_fs' ) ) {
			$fs = ccgal_fs();
			if ( is_object( $fs ) && method_exists( $fs, 'is_activation_mode' ) && $fs->is_activation_mode() ) {
				return; // keep transient — fire on next request
			}
		}

		delete_transient( self::TRANSIENT_REDIRECT );

		if ( wp_doing_ajax() || wp_doing_cron() || ( defined( 'REST_REQUEST' ) && REST_REQUEST ) ) {
			return;
		}
		if ( ! current_user_can( 'manage_options' ) ) {
			return;
		}
		// phpcs:ignore WordPress.Security.NonceVerification.Recommended
		if ( isset( $_GET['activate-multi'] ) ) {
			return;
		}

		// Use menu_page_url() — by this hook (admin_menu priority 9999) the submenu IS
		// registered, and menu_page_url returns the canonical URL with the correct
		// parent path. If for any reason the menu was not registered, fall back to a
		// safe URL that always exists (the CPT list page).
		$url = function_exists( 'menu_page_url' ) ? menu_page_url( 'ccgal-settings', false ) : '';
		if ( empty( $url ) ) {
			$url = admin_url( 'edit.php?post_type=' . CCGAL_CPT::POST_TYPE );
		}

		wp_safe_redirect( $url );
		exit;
	}

	public static function settings_url() {
		return admin_url( 'edit.php?post_type=' . CCGAL_CPT::POST_TYPE . '&page=ccgal-settings' );
	}

	public static function is_cloud_connected() {
		$drive   = class_exists( 'CCGAL_Google_OAuth' )  && CCGAL_Google_OAuth::is_connected();
		$dropbox = class_exists( 'CCGAL_Dropbox_OAuth' ) && CCGAL_Dropbox_OAuth::is_connected();
		return $drive || $dropbox;
	}

	public static function has_galleries() {
		$q = get_posts( array(
			'post_type'      => CCGAL_CPT::POST_TYPE,
			'post_status'    => array( 'publish', 'draft', 'private' ),
			'posts_per_page' => 1,
			'fields'         => 'ids',
			'no_found_rows'  => true,
		) );
		return ! empty( $q );
	}

	public static function is_complete() {
		return self::is_cloud_connected() && self::has_galleries();
	}

	public static function render_panel() {
		if ( self::is_complete() ) {
			return;
		}
		if ( ! current_user_can( 'manage_options' ) ) {
			return;
		}

		$drive_done   = class_exists( 'CCGAL_Google_OAuth' )  && CCGAL_Google_OAuth::is_connected();
		$dropbox_done = class_exists( 'CCGAL_Dropbox_OAuth' ) && CCGAL_Dropbox_OAuth::is_connected();
		$cloud_done   = $drive_done || $dropbox_done;
		$gallery_done = self::has_galleries();

		$new_gallery_url = admin_url( 'post-new.php?post_type=' . CCGAL_CPT::POST_TYPE );

		// Whitelist for the few mixed-HTML i18n strings below — link + inline code.
		$allowed_html = array(
			'a'    => array( 'href' => array(), 'target' => array(), 'rel' => array() ),
			'code' => array(),
		);
		?>
		<div class="ccgal-welcome-panel" id="ccgal-welcome">
			<div class="ccgal-welcome-header">
				<h2><?php esc_html_e( 'Welcome to Customer Cloud Gallery', 'customer-cloud-gallery' ); ?></h2>
				<p class="ccgal-welcome-lead">
					<?php esc_html_e( 'Two steps to your first client gallery — both can be skipped and resumed later.', 'customer-cloud-gallery' ); ?>
				</p>
			</div>

			<ol class="ccgal-welcome-steps">
				<li class="ccgal-welcome-step <?php echo esc_attr( $cloud_done ? 'is-done' : 'is-current' ); ?>">
					<span class="ccgal-step-num" aria-hidden="true"><?php echo $cloud_done ? '&#10003;' : '1'; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- hardcoded ternary of literal HTML entity vs. literal digit, no user data ?></span>
					<div class="ccgal-step-body">
						<strong><?php esc_html_e( 'Connect Google Drive or Dropbox', 'customer-cloud-gallery' ); ?></strong>
						<p>
							<?php esc_html_e( 'Pick whichever cloud you already use — you can add the second one later, both work in parallel.', 'customer-cloud-gallery' ); ?>
						</p>

						<?php if ( $drive_done && $dropbox_done ) : ?>
							<p class="ccgal-step-done-note">
								<?php esc_html_e( 'Both Google Drive and Dropbox are connected.', 'customer-cloud-gallery' ); ?>
							</p>
						<?php elseif ( $drive_done ) : ?>
							<p class="ccgal-step-done-note">
								<?php esc_html_e( 'Google Drive connected. You can also connect Dropbox below as a second provider — both work in parallel.', 'customer-cloud-gallery' ); ?>
							</p>
						<?php elseif ( $dropbox_done ) : ?>
							<p class="ccgal-step-done-note">
								<?php esc_html_e( 'Dropbox connected. You can also connect Google Drive below as a second provider — both work in parallel.', 'customer-cloud-gallery' ); ?>
							</p>
						<?php endif; ?>

						<?php if ( ! $drive_done ) { self::render_drive_setup_guide(); } ?>
						<?php if ( ! $dropbox_done ) { self::render_dropbox_setup_guide(); } ?>
					</div>
				</li>

				<li class="ccgal-welcome-step <?php echo esc_attr( $gallery_done ? 'is-done' : ( $cloud_done ? 'is-current' : '' ) ); ?>">
					<span class="ccgal-step-num" aria-hidden="true"><?php echo $gallery_done ? '&#10003;' : '2'; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- hardcoded ternary of literal HTML entity vs. literal digit, no user data ?></span>
					<div class="ccgal-step-body">
						<strong><?php esc_html_e( 'Create your first gallery', 'customer-cloud-gallery' ); ?></strong>
						<p>
							<?php esc_html_e( 'Add a new gallery, pick a folder from your connected cloud, set an optional password, and copy the shortcode into a WordPress page.', 'customer-cloud-gallery' ); ?>
						</p>
						<?php if ( ! $gallery_done ) : ?>
							<p>
								<a class="button button-primary" href="<?php echo esc_url( $new_gallery_url ); ?>">
									<?php esc_html_e( 'Create gallery', 'customer-cloud-gallery' ); ?>
								</a>
							</p>
						<?php else : ?>
							<p class="ccgal-step-done-note">
								<?php esc_html_e( 'You have at least one gallery — this welcome panel will hide automatically.', 'customer-cloud-gallery' ); ?>
							</p>
						<?php endif; ?>
					</div>
				</li>
			</ol>
		</div>
		<?php
	}

	/**
	 * Render the Drive step-by-step setup guide as a collapsed <details> block.
	 * Used both by the first-run welcome panel and by the Settings page Drive section,
	 * so a returning user can re-open the guide when adding the second provider.
	 */
	public static function render_drive_setup_guide() {
		$drive_redirect = class_exists( 'CCGAL_Google_OAuth' ) ? CCGAL_Google_OAuth::get_redirect_uri() : '';
		$allowed_html   = array(
			'a'    => array( 'href' => array(), 'target' => array(), 'rel' => array() ),
			'code' => array(),
		);
		?>
		<details class="ccgal-welcome-guide">
			<summary><?php esc_html_e( 'Google Drive — step-by-step', 'customer-cloud-gallery' ); ?></summary>
			<ol>
				<li>
					<?php
					echo wp_kses(
						sprintf(
							/* translators: %s: Google Cloud Console URL */
							__( 'Open the %s and sign in with the Google account that holds the photos.', 'customer-cloud-gallery' ),
							'<a href="https://console.cloud.google.com/" target="_blank" rel="noopener noreferrer">Google Cloud Console</a>'
						),
						$allowed_html
					);
					?>
				</li>
				<li><?php esc_html_e( 'Create a new project (top bar → "Select a project" → "New project"). Name it anything. Skip this step if you already have a project you want to reuse.', 'customer-cloud-gallery' ); ?></li>
				<li>
					<?php
					echo wp_kses(
						sprintf(
							/* translators: %s: name of API library entry */
							__( 'In the left menu go to "APIs & Services" → "Library", search for %s and click "Enable".', 'customer-cloud-gallery' ),
							'<code>Google Drive API</code>'
						),
						$allowed_html
					);
					?>
				</li>
				<li>
					<?php
					echo wp_kses(
						sprintf(
							/* translators: %s: required OAuth scope */
							__( 'Skip this step if OAuth is already configured in this project. Otherwise: "APIs & Services" → "OAuth consent screen", choose "External", enter an app name and your support email. Under "Scopes" add %s. Under "Test users" add your own Google account.', 'customer-cloud-gallery' ),
							'<code>.../auth/drive.readonly</code>'
						),
						$allowed_html
					);
					?>
				</li>
				<li>
					<?php esc_html_e( 'Important: on the "OAuth consent screen" page, click the "Publish App" button at the top to move the app from Testing to "In production". Without this, Google invalidates the OAuth refresh token after 7 days of inactivity and the gallery connection breaks until you reconnect manually. You do NOT need to submit the app for verification — the "unverified app" warning is fine for personal use, but publishing avoids the 7-day expiry.', 'customer-cloud-gallery' ); ?>
				</li>
				<li>
					<?php esc_html_e( '"APIs & Services" → "Credentials" → "Create credentials" → "OAuth client ID". Choose "Web application". Under "Authorized redirect URIs" paste this exact URL:', 'customer-cloud-gallery' ); ?>
					<code class="ccgal-redirect-uri"><?php echo esc_html( $drive_redirect ); ?></code>
				</li>
				<li><?php esc_html_e( 'Save. Google shows you Client ID and Client Secret — copy both.', 'customer-cloud-gallery' ); ?></li>
				<li>
					<?php
					echo wp_kses(
						sprintf(
							/* translators: %s: link to settings tab */
							__( 'Paste them in the %s on this page and click "Save credentials" → then "Connect Google Drive".', 'customer-cloud-gallery' ),
							'<a href="#ccgal-google-drive-section">' . esc_html__( 'Google Drive section below', 'customer-cloud-gallery' ) . '</a>'
						),
						$allowed_html
					);
					?>
				</li>
				<li>
					<?php esc_html_e( 'Heads up: Google will show a "This app isn\'t verified" security warning the first time you connect — that is expected, because the OAuth app you just created is in test mode and only used by you. Click "Advanced" (or "Show advanced") at the bottom of the warning, then click the small link "Go to [your app name] (unsafe)" to continue. After granting access, Google redirects you back here.', 'customer-cloud-gallery' ); ?>
				</li>
			</ol>
		</details>
		<?php
	}

	/**
	 * Render the Dropbox step-by-step setup guide as a collapsed <details> block.
	 * Used both by the first-run welcome panel and by the Settings page Dropbox section.
	 */
	public static function render_dropbox_setup_guide() {
		$dropbox_redirect = class_exists( 'CCGAL_Dropbox_OAuth' ) ? CCGAL_Dropbox_OAuth::get_redirect_uri() : '';
		$allowed_html     = array(
			'a'    => array( 'href' => array(), 'target' => array(), 'rel' => array() ),
			'code' => array(),
		);
		?>
		<details class="ccgal-welcome-guide">
			<summary><?php esc_html_e( 'Dropbox — step-by-step', 'customer-cloud-gallery' ); ?></summary>
			<ol>
				<li>
					<?php
					echo wp_kses(
						sprintf(
							/* translators: %s: Dropbox developer apps URL */
							__( 'Open the %s and sign in with the Dropbox account that holds the photos.', 'customer-cloud-gallery' ),
							'<a href="https://www.dropbox.com/developers/apps" target="_blank" rel="noopener noreferrer">Dropbox App Console</a>'
						),
						$allowed_html
					);
					?>
				</li>
				<li><?php esc_html_e( 'Click "Create app". Choose "Scoped access".', 'customer-cloud-gallery' ); ?></li>
				<li><?php esc_html_e( 'Pick "Full Dropbox" (recommended for client folders) or "App folder" (limited to a single subfolder). Name your app — anything works.', 'customer-cloud-gallery' ); ?></li>
				<li>
					<?php esc_html_e( 'On the "Settings" tab, scroll to "OAuth 2 → Redirect URIs". Paste this URL and click "Add":', 'customer-cloud-gallery' ); ?>
					<code class="ccgal-redirect-uri"><?php echo esc_html( $dropbox_redirect ); ?></code>
				</li>
				<li>
					<?php esc_html_e( 'Switch to the "Permissions" tab, enable both scopes below, and scroll to the bottom of the page to click "Submit" — this last step is easy to miss and the OAuth connection will fail silently without it.', 'customer-cloud-gallery' ); ?>
					<ul>
						<li><code>files.metadata.read</code></li>
						<li><code>files.content.read</code></li>
					</ul>
				</li>
				<li><?php esc_html_e( 'Back on the "Settings" tab, copy "App key" and "App secret" (click "Show" to reveal the secret).', 'customer-cloud-gallery' ); ?></li>
				<li>
					<?php
					echo wp_kses(
						sprintf(
							/* translators: %s: link to settings tab */
							__( 'Paste them in the %s on this page and click "Save credentials" → then "Connect Dropbox".', 'customer-cloud-gallery' ),
							'<a href="#ccgal-dropbox-section">' . esc_html__( 'Dropbox section below', 'customer-cloud-gallery' ) . '</a>'
						),
						$allowed_html
					);
					?>
				</li>
			</ol>
		</details>
		<?php
	}
}
