<?php
/**
 * GSC Settings Page.
 *
 * Tools → Search Console: connect a Google service account, pick the
 * property, set the lookback window, and sync. Shows connection status,
 * last-sync stats, and a sample of top pages.
 *
 * @package Platform\Helm\Modules\GSC
 */

declare( strict_types = 1 );

namespace Platform\Helm\Modules\GSC;

use Platform\Helm\Core\Assets;
use Platform\Helm\Core\Authorization;

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

final class GscSettingsPage {

	public const PAGE_SLUG   = 'platform-helm-gsc';
	public const PARENT_SLUG = 'platform-helm';

	public function __construct(
		private Assets $assets,
		private GscStore $store
	) {}

	public function register_hooks(): void {
		add_action( 'admin_menu', [ $this, 'register_menu' ], 45 );
	}

	public function register_menu(): void {
		if ( ! Authorization::is_master_admin() ) {
			return;
		}
		$hook = add_submenu_page(
			self::PARENT_SLUG,
			__( 'Search Console', 'platform-helm' ),
			__( 'Search Console', 'platform-helm' ),
			'manage_options',
			self::PAGE_SLUG,
			[ $this, 'render' ]
		);
		if ( $hook ) {
			add_action( 'load-' . $hook, [ $this, 'enqueue' ] );
		}
	}

	public function enqueue(): void {
		$this->assets->enqueue_gsc( [
			'ajaxUrl' => admin_url( 'admin-ajax.php' ),
			'nonce'   => wp_create_nonce( GscAjaxController::NONCE_ACTION ),
		] );
	}

	public function render(): void {
		Authorization::require_master_admin();

		$connected = GscCredentials::is_connected();
		$email     = GscCredentials::client_email();
		$property  = GscCredentials::property();
		$range     = GscCredentials::range_days();
		$last      = GscSync::last_sync();
		$rows      = $this->store->count_rows();
		$home      = home_url( '/' );
		$method    = GscCredentials::auth_method();
		$redirect  = GscOAuth::redirect_uri();
		$oauth_err = GscOAuth::last_error();
		// phpcs:ignore WordPress.Security.NonceVerification.Recommended
		$just_connected = isset( $_GET['gsc_connected'] );
		?>
		<div class="wrap ph-gsc">
			<h1><?php esc_html_e( 'Search Console Connector', 'platform-helm' ); ?></h1>
			<p class="ph-gsc-lead">
				<?php esc_html_e( 'Connects this site to Google Search Console, then caches per-post traffic locally so the Content Auditor can use it without hammering Google on every page load.', 'platform-helm' ); ?>
			</p>

			<?php if ( '' !== $oauth_err ) : ?>
				<div class="notice notice-error"><p><?php echo esc_html( $oauth_err ); ?></p></div>
			<?php endif; ?>
			<?php if ( $just_connected && $connected ) : ?>
				<div class="notice notice-success"><p><?php esc_html_e( 'Connected with Google. Pick your property and run the first sync.', 'platform-helm' ); ?></p></div>
			<?php endif; ?>

			<div class="ph-gsc-status <?php echo $connected ? 'is-connected' : 'is-disconnected'; ?>">
				<?php if ( $connected ) : ?>
					<strong><?php esc_html_e( 'Connected', 'platform-helm' ); ?></strong>
					<span>
						<?php
						echo esc_html(
							GscCredentials::METHOD_OAUTH === $method
								? __( 'via Google sign-in (OAuth)', 'platform-helm' )
								: $email
						);
						?>
					</span>
				<?php else : ?>
					<strong><?php esc_html_e( 'Not connected', 'platform-helm' ); ?></strong>
				<?php endif; ?>
			</div>
		<?php // (wrap continues below) ?>

			<?php if ( ! $connected ) : ?>
				<div class="ph-gsc-card">
					<h2><?php esc_html_e( 'Connect with Google (recommended)', 'platform-helm' ); ?></h2>
					<p class="ph-gsc-hint" style="font-size:12px;">
						<?php esc_html_e( 'Authorise with the Google account that owns this Search Console property. Nothing needs to be added inside Search Console — this avoids the current Google bug that blocks new service accounts.', 'platform-helm' ); ?>
					</p>
					<ol class="ph-gsc-steps">
						<li><?php esc_html_e( 'Google Cloud → APIs &amp; Services → enable “Google Search Console API”.', 'platform-helm' ); ?></li>
						<li><?php esc_html_e( 'OAuth consent screen → User type Internal (if you use Google Workspace) or External + Publish, scope: webmasters.readonly.', 'platform-helm' ); ?></li>
						<li><?php esc_html_e( 'Credentials → Create credentials → OAuth client ID → type “Web application”.', 'platform-helm' ); ?></li>
						<li>
							<?php esc_html_e( 'Add this exact Authorised redirect URI:', 'platform-helm' ); ?>
							<code class="ph-gsc-redirect"><?php echo esc_html( $redirect ); ?></code>
						</li>
						<li><?php esc_html_e( 'Paste the Client ID and Client Secret below, then connect.', 'platform-helm' ); ?></li>
					</ol>

					<label class="ph-gsc-label" for="ph-gsc-client-id"><?php esc_html_e( 'OAuth Client ID', 'platform-helm' ); ?></label>
					<input type="text" id="ph-gsc-client-id" class="regular-text" autocomplete="off" placeholder="1234567890-abc.apps.googleusercontent.com" />

					<label class="ph-gsc-label" for="ph-gsc-client-secret"><?php esc_html_e( 'OAuth Client Secret', 'platform-helm' ); ?></label>
					<input type="password" id="ph-gsc-client-secret" class="regular-text" autocomplete="off" placeholder="GOCSPX-…" />

					<div class="ph-gsc-actions">
						<button type="button" class="button button-primary" id="ph-gsc-oauth-connect"><?php esc_html_e( 'Connect with Google', 'platform-helm' ); ?></button>
						<span class="ph-gsc-msg" id="ph-gsc-oauth-msg" aria-live="polite"></span>
					</div>
				</div>

				<details class="ph-gsc-card ph-gsc-advanced">
					<summary><?php esc_html_e( 'Advanced: use a service account instead', 'platform-helm' ); ?></summary>
					<p class="ph-gsc-hint" style="font-size:12px; margin-top:10px;">
						<?php esc_html_e( 'Heads-up: Google currently has an acknowledged bug that rejects new service-account emails in Search Console (“email not found”). Use this only if you have a service account that was already added before the bug, or once Google fixes it.', 'platform-helm' ); ?>
					</p>
					<label class="ph-gsc-label" for="ph-gsc-json"><?php esc_html_e( 'Service-account JSON key', 'platform-helm' ); ?></label>
					<textarea id="ph-gsc-json" class="ph-gsc-textarea" rows="7" placeholder='{ "type": "service_account", "client_email": "...", "private_key": "-----BEGIN PRIVATE KEY-----..." }'></textarea>
					<div class="ph-gsc-actions">
						<button type="button" class="button" id="ph-gsc-connect"><?php esc_html_e( 'Connect service account', 'platform-helm' ); ?></button>
						<span class="ph-gsc-msg" id="ph-gsc-connect-msg" aria-live="polite"></span>
					</div>
				</details>
			<?php else : ?>
				<div class="ph-gsc-card">
					<h2><?php esc_html_e( 'Property &amp; sync', 'platform-helm' ); ?></h2>

					<label class="ph-gsc-label" for="ph-gsc-property"><?php esc_html_e( 'Search Console property', 'platform-helm' ); ?></label>
					<div class="ph-gsc-row">
						<select id="ph-gsc-property" class="ph-gsc-select">
							<?php if ( '' !== $property ) : ?>
								<option value="<?php echo esc_attr( $property ); ?>" selected><?php echo esc_html( $property ); ?></option>
							<?php else : ?>
								<option value=""><?php esc_html_e( '— click “Refresh list” —', 'platform-helm' ); ?></option>
							<?php endif; ?>
						</select>
						<button type="button" class="button" id="ph-gsc-refresh"><?php esc_html_e( 'Refresh list', 'platform-helm' ); ?></button>
					</div>
					<p class="ph-gsc-hint">
						<?php
						echo esc_html( sprintf(
							/* translators: %s: site home URL */
							__( 'Pick the property that matches %s (URL-prefix or Domain).', 'platform-helm' ),
							$home
						) );
						?>
					</p>

					<label class="ph-gsc-label" for="ph-gsc-range"><?php esc_html_e( 'Lookback window (days)', 'platform-helm' ); ?></label>
					<div class="ph-gsc-row">
						<input type="number" id="ph-gsc-range" class="ph-gsc-num" min="7" max="480" step="1" value="<?php echo esc_attr( (string) $range ); ?>" />
						<button type="button" class="button" id="ph-gsc-save-range"><?php esc_html_e( 'Save', 'platform-helm' ); ?></button>
						<span class="ph-gsc-hint"><?php esc_html_e( 'Search Console keeps ~16 months. 90 is a good default.', 'platform-helm' ); ?></span>
					</div>

					<div class="ph-gsc-actions">
						<button type="button" class="button button-primary" id="ph-gsc-sync"><?php esc_html_e( 'Sync now', 'platform-helm' ); ?></button>
						<button type="button" class="button button-link-delete" id="ph-gsc-disconnect"><?php esc_html_e( 'Disconnect', 'platform-helm' ); ?></button>
						<span class="ph-gsc-msg" id="ph-gsc-sync-msg" aria-live="polite"></span>
					</div>
				</div>

				<div class="ph-gsc-card">
					<h2><?php esc_html_e( 'Cache status', 'platform-helm' ); ?></h2>
					<p>
						<?php
						echo esc_html( sprintf(
							/* translators: %d: cached post count */
							_n( '%d post currently has cached metrics.', '%d posts currently have cached metrics.', $rows, 'platform-helm' ),
							$rows
						) );
						?>
						<?php if ( $last ) : ?>
							<br />
							<?php
							echo esc_html( sprintf(
								/* translators: 1: date/time, 2: matched, 3: fetched, 4: skipped */
								__( 'Last sync: %1$s — %2$d posts matched from %3$d pages (%4$d skipped).', 'platform-helm' ),
								wp_date( 'jS M Y g:i a', (int) $last['time'] ),
								(int) $last['matched'],
								(int) $last['fetched'],
								(int) $last['skipped']
							) );
							?>
						<?php endif; ?>
					</p>

					<?php
					$top = $this->store->top_pages( 10 );
					if ( ! empty( $top ) ) :
						?>
						<table class="widefat striped ph-gsc-table">
							<thead>
								<tr>
									<th><?php esc_html_e( 'Post', 'platform-helm' ); ?></th>
									<th><?php esc_html_e( 'Clicks', 'platform-helm' ); ?></th>
									<th><?php esc_html_e( 'Impressions', 'platform-helm' ); ?></th>
									<th><?php esc_html_e( 'Avg. position', 'platform-helm' ); ?></th>
								</tr>
							</thead>
							<tbody>
								<?php foreach ( $top as $r ) : ?>
									<tr>
										<td>
											<a href="<?php echo esc_url( (string) get_edit_post_link( (int) $r['post_id'] ) ); ?>">
												<?php echo esc_html( get_the_title( (int) $r['post_id'] ) ?: (string) $r['url'] ); ?>
											</a>
										</td>
										<td><?php echo esc_html( (string) (int) $r['clicks'] ); ?></td>
										<td><?php echo esc_html( (string) (int) $r['impressions'] ); ?></td>
										<td><?php echo esc_html( number_format( (float) $r['position'], 1 ) ); ?></td>
									</tr>
								<?php endforeach; ?>
							</tbody>
						</table>
					<?php endif; ?>
				</div>
			<?php endif; ?>
		</div>
		<?php
	}
}
