<?php
/**
 * Settings page template.
 *
 * Body wrapped in a function so all locals are prefixed by scope (avoids
 * Plugin Check NonPrefixedVariable warnings against template-locals like
 * $current_tab and $stats — these only ever exist inside the function now,
 * not in the global namespace that include creates).
 *
 * Called from DOIG_Admin::render_settings_page().
 */

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

if ( ! function_exists( 'doig_render_settings_page' ) ) {

	/**
	 * @param string $current_tab 'settings' | 'logs'
	 * @param array  $stats       { count, size_bytes, size_human } from DOIG_Cache::stats()
	 */
	function doig_render_settings_page( $current_tab, $stats ) {

		// Boot-integrity guard. The template calls four DOIG_Plugin static
		// methods (render_page_header, render_admin_footer, docs_url, brand_url)
		// that landed in 2.0.43-2.0.50. If any are missing, the install is
		// stale (most commonly an old build zip mislabelled as a newer
		// version, or a partial co-existence-guard state where one folder's
		// class-plugin.php loaded ahead of the other folder's settings-page.php).
		// Bail with an actionable admin notice instead of fatal-erroring.
		$required_methods = array( 'render_page_header', 'render_admin_footer', 'docs_url', 'brand_url' );
		$missing = array();
		foreach ( $required_methods as $method ) {
			if ( ! method_exists( 'DOIG_Plugin', $method ) ) {
				$missing[] = $method;
			}
		}
		if ( ! empty( $missing ) ) {
			echo '<div class="wrap"><h1>' . esc_html__( 'PlugUpp Dynamic OG Image Generator', 'dynamic-og-image-generator' ) . '</h1>';
			echo '<div class="notice notice-error"><p><strong>' . esc_html__( 'The plugin installation appears to be incomplete or stale.', 'dynamic-og-image-generator' ) . '</strong></p>';
			echo '<p>' . esc_html__( 'The Settings page expects helper methods that are not present in the loaded plugin code. The most common cause is a plugin folder that was upgraded over an older build, or two builds of this plugin installed alongside each other.', 'dynamic-og-image-generator' ) . '</p>';
			echo '<p>' . esc_html__( 'Try the following:', 'dynamic-og-image-generator' ) . '</p>';
			echo '<ol>';
			echo '<li>' . esc_html__( 'Deactivate any other "PlugUpp Dynamic OG Image Generator" plugin folder (free and premium should not be active at the same time).', 'dynamic-og-image-generator' ) . '</li>';
			echo '<li>' . esc_html__( 'Delete and reinstall the plugin from its source (WordPress.org for the free build; your PlugUpp account for the premium build).', 'dynamic-og-image-generator' ) . '</li>';
			echo '<li>' . esc_html__( 'If the issue persists, contact support with the missing method names below.', 'dynamic-og-image-generator' ) . '</li>';
			echo '</ol>';
			echo '<p><code>Missing: ' . esc_html( implode( ', ', $missing ) ) . '</code></p>';
			echo '</div></div>';
			return;
		}

		// 2.4.0: top-level menu, Settings UI lives at the doig-settings
		// sub-page route. Tab nav stays the same (Settings / Premium /
		// Logs), the parent URL changes.
		$settings_url = admin_url( 'admin.php?page=doig-settings' );
		$logs_url     = admin_url( 'admin.php?page=doig-settings&tab=logs' );
		$premium_url  = admin_url( 'admin.php?page=doig-settings&tab=premium' );
		$is_premium   = DOIG_License::is_premium();
		?>
		<div class="wrap doig-wrap">

			<?php
			$doig_brand_medium = 'logs' === $current_tab
				? 'logs_tab'
				: ( 'premium' === $current_tab ? 'premium_tab' : 'settings_tab' );
			$doig_page_title   = $is_premium
				? __( 'PlugUpp Dynamic OG Image Generator Premium', 'dynamic-og-image-generator' )
				: __( 'PlugUpp Dynamic OG Image Generator', 'dynamic-og-image-generator' );
			DOIG_Plugin::render_page_header( $doig_page_title, $doig_brand_medium );
			?>

			<?php
			// Per-tab deep link into the public documentation. Each tab
			// points at the page that covers what is on screen, so the
			// "Documentation" link is contextual rather than dumping the
			// user on the docs home page. UTM tag on each URL tells us
			// in analytics which tab drives the click.
			switch ( $current_tab ) {
				case 'logs':
					$doig_docs_href = DOIG_Plugin::docs_url( 'troubleshooting', 'logs_tab' );
					break;
				case 'premium':
					$doig_docs_href = DOIG_Plugin::docs_url( 'features/premium-features', 'premium_tab' );
					break;
				case 'settings':
				default:
					$doig_docs_href = DOIG_Plugin::docs_url( 'features/screenshot-settings', 'settings_tab' );
					break;
			}
			?>

			<?php
			// 2.4.0 M1.4: Upgrade banner used to live here, hoisted above
			// the tab nav on Settings + Logs. Relocated to the Dashboard
			// sub-page 2026-06-25 per _standards/docs/CONVENTIONS.md
			// "Banner placement: the primary high-traffic screen, never
			// co-located with the Premium tab". With a Dashboard sub-page
			// now in place (M1.2), the banner belongs there - co-locating
			// it on Settings is redundant with the Premium tab below.
			?>

			<!-- Tab nav: 2.4.0 M1.4 order = Settings -> Premium -> Logs.
			     Premium sits in the middle (more visible slot) ahead of
			     the diagnostic Logs tab. -->
			<nav class="nav-tab-wrapper doig-nav-tab-wrapper">
				<a href="<?php echo esc_url( $settings_url ); ?>"
				   class="nav-tab<?php echo 'settings' === $current_tab ? ' nav-tab-active' : ''; ?>">
					<?php esc_html_e( 'Settings', 'dynamic-og-image-generator' ); ?>
				</a>
				<?php if ( ! $is_premium ) : ?>
				<a href="<?php echo esc_url( $premium_url ); ?>"
				   class="nav-tab doig-nav-tab--premium<?php echo 'premium' === $current_tab ? ' nav-tab-active' : ''; ?>">
					<span class="dashicons dashicons-star-filled" aria-hidden="true"></span>
					<?php esc_html_e( 'Premium', 'dynamic-og-image-generator' ); ?>
				</a>
				<?php endif; ?>
				<a href="<?php echo esc_url( $logs_url ); ?>"
				   class="nav-tab<?php echo 'logs' === $current_tab ? ' nav-tab-active' : ''; ?>">
					<?php esc_html_e( 'Logs', 'dynamic-og-image-generator' ); ?>
				</a>

				<a href="<?php echo esc_url( $doig_docs_href ); ?>"
				   class="doig-docs-link"
				   target="_blank"
				   rel="noopener">
					<span class="dashicons dashicons-book" aria-hidden="true"></span>
					<?php esc_html_e( 'Documentation', 'dynamic-og-image-generator' ); ?>
					<span class="dashicons dashicons-external" aria-hidden="true"></span>
				</a>
			</nav>

			<?php if ( 'settings' === $current_tab ) : ?>

				<?php // Settings errors are rendered by WordPress before the template renders — no explicit call needed here. ?>

				<?php
				// Persistent banner shown whenever DOIG_PROXY_URL is defined in
				// wp-config.php. The override points outbound plugin calls at a
				// non-production proxy (typically a staging server). Surfaced
				// here as a warning so it is impossible to miss when a support
				// agent, developer, or operator is looking at the admin
				// screens - the override is a deliberate test-env signal,
				// never something that should be live on a customer install.
				if ( DOIG_License::is_test_proxy() ) :
				?>
				<div class="notice notice-warning doig-test-env-warning" style="margin:18px 0;">
					<p>
						<strong><?php esc_html_e( 'Test environment', 'dynamic-og-image-generator' ); ?></strong>
						<?php esc_html_e( 'This install is connected to a non-production screenshot service via the DOIG_PROXY_URL constant in wp-config.php. Screenshots, quota counters, and Freemius licence state are operating against staging data, not live PlugUpp infrastructure. Remove the constant to return to production behaviour.', 'dynamic-og-image-generator' ); ?>
						<br>
						<code><?php echo esc_html( DOIG_License::proxy_base_url() ); ?></code>
					</p>
				</div>
				<?php endif; ?>

				<?php
				// Persistent banner shown whenever the WordPress Site Address
				// (the persistent `home` option) is http://. The screenshot
				// service requires https URLs and the proxy will reject every
				// job submitted from an http install.
				//
				// IMPORTANT: this checks get_option('home') rather than
				// home_url() because home_url() lies in admin context. When
				// the admin request is loaded over https, WordPress's
				// home_url() returns https://... regardless of the DB value
				// (it uses set_url_scheme + is_ssl()). The Site Address
				// itself can still be http://, which is what cron sees when
				// it builds the URL to submit to the proxy. The DB value is
				// the canonical truth here.
				$doig_home_option = (string) get_option( 'home', '' );
				if ( 'https' !== wp_parse_url( $doig_home_option, PHP_URL_SCHEME ) ) :
				?>
				<div class="notice notice-error doig-http-warning" style="margin:18px 0;">
					<p>
						<strong><?php esc_html_e( 'Your WordPress site URL is set to http://', 'dynamic-og-image-generator' ); ?></strong>
						<?php esc_html_e( 'The screenshot service requires https:// URLs. Screenshots will fail until you update', 'dynamic-og-image-generator' ); ?>
						<a href="<?php echo esc_url( admin_url( 'options-general.php' ) ); ?>"><?php esc_html_e( 'WordPress Settings → General → Site Address', 'dynamic-og-image-generator' ); ?></a>
						<?php esc_html_e( 'to use https://.', 'dynamic-og-image-generator' ); ?>
					</p>
				</div>
				<?php endif; ?>

				<?php if ( ! DOIG_License::is_connected() ) :
					// Branch between two states:
					//   - Pending activation: user has opted in but not yet clicked
					//     the Freemius confirmation email. Tell them to check
					//     their inbox; the "Refresh" button just reloads this
					//     Settings page so they can come back here once they've
					//     clicked the link in their email.
					//   - Default: standard "Activate now" call-to-action that
					//     opens the Freemius opt-in flow.
					$doig_is_pending = DOIG_License::is_pending_activation();
				?>
				<div class="doig-setup-banner">
					<?php if ( $doig_is_pending ) : ?>
					<span class="dashicons dashicons-email-alt doig-setup-banner__icon" aria-hidden="true"></span>
					<?php else : ?>
					<span class="dashicons dashicons-admin-plugins doig-setup-banner__icon" aria-hidden="true"></span>
					<?php endif; ?>
					<div class="doig-setup-banner__content">
						<?php if ( $doig_is_pending ) : ?>
							<strong><?php esc_html_e( 'Check your email to finish setup', 'dynamic-og-image-generator' ); ?></strong>
							<span><?php esc_html_e( 'We have sent you a confirmation email. Click the link inside it to finish activation, then reload this page.', 'dynamic-og-image-generator' ); ?></span>
						<?php else : ?>
							<strong><?php esc_html_e( 'Complete plugin setup', 'dynamic-og-image-generator' ); ?></strong>
							<span><?php esc_html_e( 'Screenshots cannot be generated until this site is connected. Activation is free, takes only an email address, and requires no payment details.', 'dynamic-og-image-generator' ); ?></span>
						<?php endif; ?>
						<?php if ( ( defined( 'WP_FS__DEV_MODE' ) && WP_FS__DEV_MODE ) || ( defined( 'WP_DEBUG' ) && WP_DEBUG ) ) :
							// Temporary diagnostic - only renders on dev/staging installs
							// (Freemius dev mode flag or WP_DEBUG on), so real customers
							// never see this. Shows the exact Freemius state so we can
							// tell why is_connected() returned false.
							$fs       = function_exists( 'doig_fs' ) ? doig_fs() : null;
							$site     = ( $fs && method_exists( $fs, 'get_site' ) ) ? $fs->get_site() : null;
							$license  = ( $fs && method_exists( $fs, '_get_license' ) ) ? $fs->_get_license() : null;
							$site_sk  = ( is_object( $site ) && ! empty( $site->secret_key ) ) ? 'set (len=' . strlen( $site->secret_key ) . ')' : 'empty';
							$lic_sk   = ( is_object( $license ) && ! empty( $license->secret_key ) ) ? 'set (len=' . strlen( $license->secret_key ) . ')' : 'empty';
							$lic_key  = DOIG_Screenshot::get_licence_key();
						?>
						<?php
							$diag_reason = array();
							if ( defined( 'WP_FS__DEV_MODE' ) && WP_FS__DEV_MODE ) { $diag_reason[] = 'Freemius dev mode'; }
							if ( defined( 'WP_DEBUG' ) && WP_DEBUG )             { $diag_reason[] = 'WP_DEBUG'; }
							$diag_reason_label = implode( ' / ', $diag_reason );
						?>
						<code style="display:block;margin-top:8px;padding:8px;background:#fff;border:1px dashed #c3c4c7;font-size:11px;">
							DOIG diagnostic (visible because <?php echo esc_html( $diag_reason_label ); ?> is on):<br>
							is_registered():         <?php echo $fs && $fs->is_registered() ? 'true' : 'false'; ?><br>
							is_anonymous():          <?php echo $fs && $fs->is_anonymous() ? 'true' : 'false'; ?><br>
							is_pending_activation(): <?php echo $fs && $fs->is_pending_activation() ? 'true' : 'false'; ?><br>
							get_site() returns:      <?php echo is_object( $site ) ? 'object (id=' . esc_html( (string) $site->id ) . ', secret_key=' . esc_html( $site_sk ) . ')' : esc_html( gettype( $site ) ); ?><br>
							_get_license() returns:  <?php echo is_object( $license ) ? 'object (secret_key=' . esc_html( $lic_sk ) . ')' : esc_html( gettype( $license ) ); ?><br>
							get_licence_key():       <?php echo esc_html( '' === $lic_key ? 'empty' : 'set (len=' . strlen( $lic_key ) . ')' ); ?><br>
							activation_url():        <?php echo esc_html( DOIG_License::activation_url() ); ?>
						</code>
						<?php endif; ?>
					</div>
					<?php if ( $doig_is_pending ) : ?>
					<a class="button button-secondary doig-setup-banner__button" href="<?php echo esc_url( $settings_url ); ?>">
						<?php esc_html_e( 'Refresh', 'dynamic-og-image-generator' ); ?>
					</a>
					<?php else : ?>
					<a class="button button-primary doig-setup-banner__button" href="<?php echo esc_url( DOIG_License::activation_url() ); ?>">
						<?php esc_html_e( 'Activate now', 'dynamic-og-image-generator' ); ?>
					</a>
					<?php endif; ?>
				</div>
				<?php endif; ?>

				<?php
				// 2.4.0 M1.4: the 2.1.0-era inline-banner is gone; the
				// 2.4.0 SSAA-pattern banner is hoisted above the tab nav
				// (see top of file) and shown across all tabs except
				// Premium. Single banner, single CTA, no stacking.
				?>

				<form method="post" action="options.php">
					<?php
					settings_fields( 'doig_settings_group' );
					do_settings_sections( 'dynamic-og-image-generator' );
					submit_button();
					?>
				</form>

				<!-- Cache Management -->
				<hr />
				<h2><?php esc_html_e( 'Cache Management', 'dynamic-og-image-generator' ); ?></h2>
				<p>
					<?php
					printf(
						/* translators: 1: number of cached screenshots, 2: disk usage */
						esc_html__( '%1$s screenshot(s) cached, using %2$s of disk space.', 'dynamic-og-image-generator' ),
						'<strong id="doig-cache-count">' . esc_html( $stats['count'] ) . '</strong>',
						'<strong id="doig-cache-size">' . esc_html( $stats['size_human'] ) . '</strong>'
					);
					?>
				</p>
				<div class="doig-cache-action">
					<button type="button" id="doig-clear-cache" class="button button-secondary">
						<?php esc_html_e( 'Clear Entire Cache', 'dynamic-og-image-generator' ); ?>
					</button>
					<p class="description">
						<?php esc_html_e( 'Clears all cached screenshots and resets their status. Your fallback image will show until the scheduled refresh next runs and rebuilds the cache.', 'dynamic-og-image-generator' ); ?>
					</p>
				</div>
				<?php
				// 2.4.0 M1.3: Regenerate All Screenshots button moved to the
				// Dashboard sub-page where it sits with the other operational
				// status surfaces. The JS handler (assets/js/admin.js) still
				// binds to #doig-regenerate-all wherever it appears, so the
				// move is template-only.
				?>
				<p class="description">
					<?php
					printf(
						/* translators: %s: link to Dashboard sub-page */
						esc_html__( 'Need to regenerate every screenshot at once? Use the Regenerate All Screenshots button on the %s.', 'dynamic-og-image-generator' ),
						'<a href="' . esc_url( admin_url( 'admin.php?page=dynamic-og-image-generator' ) ) . '">' . esc_html__( 'Dashboard', 'dynamic-og-image-generator' ) . '</a>'
					);
					?>
				</p>
				<p><span id="doig-cache-result" class="doig-inline-result"></span></p>

				<!-- Viewport note -->
				<hr />
				<h2><?php esc_html_e( 'About Screenshot Dimensions', 'dynamic-og-image-generator' ); ?></h2>
				<p>
					<?php esc_html_e( 'Screenshots are captured at 1200×630 pixels - the Open Graph standard for social media sharing. This ensures your og:image displays correctly when links are shared on Facebook, X (Twitter), LinkedIn and similar platforms.', 'dynamic-og-image-generator' ); ?>
				</p>

			<?php elseif ( 'premium' === $current_tab && ! $is_premium ) :
				// 2.4.0 M1.4: Premium tab refresh to SSAA 1.0.13 pattern.
				// Intro paragraph + top CTA row + 4 feature-group cards
				// (2x2 grid, 1-col on mobile) + licence-expiry
				// reassurance + bottom CTA row. Card copy locked at
				// build time against user-docs/features/premium-features.md
				// (read 2026-06-22). Keep in lock-step on future changes.
				$doig_upgrade_url_tab = doig_fs()->get_upgrade_url();
				$doig_compare_url     = DOIG_Plugin::docs_url( 'features/premium-features', 'premium_tab' );

				$doig_render_premium_cta = function () use ( $doig_upgrade_url_tab, $doig_compare_url ) {
					echo '<p class="doig-premium-cta">';
					if ( '' !== $doig_upgrade_url_tab ) {
						echo '<a class="button button-primary" href="' . esc_url( $doig_upgrade_url_tab ) . '">'
							. esc_html__( 'Upgrade to Premium', 'dynamic-og-image-generator' )
							. '</a>';
					}
					echo '<a href="' . esc_url( $doig_compare_url ) . '" target="_blank" rel="noopener">'
						. esc_html__( 'See the full plan comparison', 'dynamic-og-image-generator' )
						. '</a>';
					echo '</p>';
				};
				?>

				<div class="doig-premium-tab">

					<p class="doig-premium-intro">
						<?php esc_html_e( 'The free plugin captures real browser screenshots of your pages and posts as og:image, with no limits. Premium adds custom-post-type coverage, per-page capture overrides, and Media Library integration. Paid plans are sold and supported by PlugUpp through Freemius.', 'dynamic-og-image-generator' ); ?>
					</p>

					<?php $doig_render_premium_cta(); ?>

					<div class="doig-premium-groups">

						<div class="doig-premium-group">
							<h3><?php esc_html_e( 'Capture more content', 'dynamic-og-image-generator' ); ?></h3>
							<ul>
								<li><?php esc_html_e( 'Custom post types and WooCommerce products', 'dynamic-og-image-generator' ); ?></li>
								<li><?php esc_html_e( 'Per-page overrides for any capture setting via the block editor', 'dynamic-og-image-generator' ); ?></li>
							</ul>
						</div>

						<div class="doig-premium-group">
							<h3><?php esc_html_e( 'Control how captures look', 'dynamic-og-image-generator' ); ?></h3>
							<ul>
								<li><?php esc_html_e( 'Configurable viewport width, capture delay, and retina output', 'dynamic-og-image-generator' ); ?></li>
								<li><?php esc_html_e( 'Country routing for IP-localised captures', 'dynamic-og-image-generator' ); ?></li>
								<li><?php esc_html_e( 'Hide selectors for cookie banners, popups, and chat widgets', 'dynamic-og-image-generator' ); ?></li>
							</ul>
						</div>

						<div class="doig-premium-group">
							<h3><?php esc_html_e( 'Manage your screenshots', 'dynamic-og-image-generator' ); ?></h3>
							<ul>
								<li><?php esc_html_e( 'Save each capture as a Media Library attachment', 'dynamic-og-image-generator' ); ?></li>
								<li><?php esc_html_e( 'Set the capture as the post\'s Featured Image', 'dynamic-og-image-generator' ); ?></li>
								<li><?php esc_html_e( 'Delete the previous capture on regenerate', 'dynamic-og-image-generator' ); ?></li>
							</ul>
						</div>

						<div class="doig-premium-group">
							<h3><?php esc_html_e( 'Cover more sites', 'dynamic-og-image-generator' ); ?></h3>
							<ul>
								<li><?php esc_html_e( 'One licence covers 1, 3, 5 or unlimited sites (Personal, Pro, Business, Agency)', 'dynamic-og-image-generator' ); ?></li>
								<li><?php esc_html_e( 'Higher monthly screenshot allowance (30 / 100 / 300 / 1,000 per month)', 'dynamic-og-image-generator' ); ?></li>
							</ul>
						</div>

					</div>

					<p class="description">
						<?php esc_html_e( 'If a licence expires the plugin keeps working on the free tier - your settings stay and premium features simply switch off until you renew.', 'dynamic-og-image-generator' ); ?>
					</p>

					<?php $doig_render_premium_cta(); ?>

				</div>

			<?php else : // Logs tab - the shared-logging component's canonical surface. ?>

				<?php DOIG_Log_UI::render_tab(); ?>

			<?php endif; ?>

			<?php DOIG_Plugin::render_admin_footer( $doig_brand_medium ); ?>

		</div>
		<?php
	}
}

// Invoke. $current_tab and $stats are provided by the caller (DOIG_Admin::render_settings_page).
doig_render_settings_page( $current_tab, $stats );
