<?php
/**
 * Settings page view, two tabs: Settings (preview lengths) and Logs.
 * The Logs tab replicates the canonical PlugUpp layout (DOIG reference):
 * one toolbar row (level + Save + Clear Log + Download Log), an info line,
 * and a dark terminal-style viewer showing the newest entries first.
 *
 * Forms post to options.php; SSAA_Settings::sanitise() preserves fields
 * absent from the posting form, so the Logs tab saving only log_level can
 * never reset the others.
 *
 * @package search-social-appearance-audit
 */

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

function ssaa_render_settings_page() {
	// The Premium tab and its surfaces only exist on the free / unlicensed build.
	$ssaa_show_premium = ! SSAA_License::is_premium();

	// phpcs:ignore WordPress.Security.NonceVerification.Recommended -- read-only view state.
	$tab        = isset( $_GET['tab'] ) ? sanitize_key( wp_unslash( $_GET['tab'] ) ) : 'settings';
	$valid_tabs = $ssaa_show_premium ? array( 'settings', 'premium', 'logs' ) : array( 'settings', 'logs' );
	$tab        = in_array( $tab, $valid_tabs, true ) ? $tab : 'settings';
	$base       = admin_url( 'admin.php?page=ssaa-settings' );

	$ssaa_tab_medium = 'logs' === $tab ? 'logs_tab' : ( 'premium' === $tab ? 'premium_tab' : 'settings_tab' );

	echo '<div class="wrap ssaa-wrap">';
	SSAA_Plugin::render_page_header( __( 'PlugUpp Search & Social Appearance Audit', 'search-social-appearance-audit' ), $ssaa_tab_medium );

	// The upgrade banner lives on the Dashboard (the high-traffic screen), not
	// here - this page already carries the Premium tab, so a banner alongside it
	// would be redundant. See _standards CONVENTIONS upsell rules.

	$tabs = array( 'settings' => __( 'Settings', 'search-social-appearance-audit' ) );
	if ( $ssaa_show_premium ) {
		$tabs['premium'] = __( 'Premium', 'search-social-appearance-audit' );
	}
	$tabs['logs'] = __( 'Logs', 'search-social-appearance-audit' );

	echo '<nav class="nav-tab-wrapper ssaa-nav-tab-wrapper">';
	foreach ( $tabs as $key => $label ) {
		$class = 'nav-tab' . ( $tab === $key ? ' nav-tab-active' : '' );
		$url   = ( 'settings' === $key ) ? $base : add_query_arg( 'tab', $key, $base );
		// The Premium tab is accented (blue star + blue label) so it stands out
		// in the nav now the upgrade banner has moved to the Dashboard.
		if ( 'premium' === $key ) {
			$class .= ' ssaa-nav-tab-premium';
			echo '<a class="' . esc_attr( $class ) . '" href="' . esc_url( $url ) . '">'
				. '<span class="dashicons dashicons-star-filled ssaa-nav-tab-premium-icon" aria-hidden="true"></span>'
				. esc_html( $label ) . '</a>';
			continue;
		}
		echo '<a class="' . esc_attr( $class ) . '" href="' . esc_url( $url ) . '">' . esc_html( $label ) . '</a>';
	}
	SSAA_Plugin::render_docs_link( $ssaa_tab_medium );
	echo '</nav>';

	if ( 'logs' === $tab ) {
		ssaa_render_logs_tab();
	} elseif ( 'premium' === $tab ) {
		ssaa_render_premium_tab();
	} else {
		ssaa_render_settings_tab();
	}

	SSAA_Plugin::render_admin_footer();
	echo '</div>';
}

function ssaa_render_settings_tab() {
	$search_len = (int) SSAA_Settings::get( 'search_desc_length', 160 );
	$social_len = (int) SSAA_Settings::get( 'social_desc_length', 110 );
	$types      = (array) SSAA_Settings::get( 'scan_post_types', array( 'post', 'page' ) );

	echo '<form method="post" action="options.php">';
	settings_fields( 'ssaa_settings_group' );

	echo '<table class="form-table" role="presentation">';

	// Content types (built-ins; add-on files append their own type rows
	// via the ssaa_settings_fields extension point below).
	echo '<tr><th scope="row">' . esc_html__( 'Content types', 'search-social-appearance-audit' ) . '</th><td>';
	$builtins = array(
		'post' => __( 'Posts', 'search-social-appearance-audit' ),
		'page' => __( 'Pages', 'search-social-appearance-audit' ),
	);
	foreach ( $builtins as $type => $label ) {
		echo '<label class="ssaa-type-option"><input type="checkbox" name="' . esc_attr( SSAA_OPTION_KEY ) . '[scan_post_types][]" value="' . esc_attr( $type ) . '"';
		checked( in_array( $type, $types, true ), true );
		echo ' /> ' . esc_html( $label ) . '</label>';
	}
	echo '<p class="description">' . esc_html__( 'Which content types are audited. At least one stays enabled. Turning a type off removes its stored results; they return after the next scan if re-enabled.', 'search-social-appearance-audit' ) . '</p>';
	// Contextual upgrade nudge: prose only, free build only, one per section.
	if ( ! SSAA_License::is_premium() ) {
		echo '<p class="description ssaa-premium-hint">' . esc_html__( 'Premium also audits custom post types and WooCommerce products, and can check drafts and scheduled posts before they go live.', 'search-social-appearance-audit' ) . '</p>';
	}
	echo '</td></tr>';

	// Archive pages (free): part of the "what gets audited" scope group.
	echo '<tr><th scope="row">' . esc_html__( 'Archive pages', 'search-social-appearance-audit' ) . '</th><td>';
	echo '<input type="hidden" name="' . esc_attr( SSAA_OPTION_KEY ) . '[scan_archives]" value="0" />';
	echo '<label><input type="checkbox" name="' . esc_attr( SSAA_OPTION_KEY ) . '[scan_archives]" value="1"';
	checked( (bool) SSAA_Settings::get( 'scan_archives', 1 ), true );
	echo ' /> ' . esc_html__( 'Audit archive pages', 'search-social-appearance-audit' ) . '</label>';
	echo '<p class="description">' . esc_html__( 'Also audits the blog home, category, tag and date archive pages - they have their own titles, descriptions and social tags, and they rank in search and get shared like any other page. Turning this off removes their stored results; they return after the next scan if re-enabled.', 'search-social-appearance-audit' ) . '</p>';
	echo '</td></tr>';

	/**
	 * Extension point for "what gets audited" rows, placed immediately after
	 * Content types so the scope settings stay grouped. Premium adds Custom
	 * post types (priority 10) then Unpublished content (priority 20) here.
	 */
	do_action( 'ssaa_settings_fields_scope' );

	echo '<tr><th scope="row"><label for="ssaa-search-desc-length">' . esc_html__( 'Meta description preview length', 'search-social-appearance-audit' ) . '</label></th><td>';
	echo '<input type="number" min="50" max="400" id="ssaa-search-desc-length" name="' . esc_attr( SSAA_OPTION_KEY ) . '[search_desc_length]" value="' . esc_attr( (string) $search_len ) . '" class="small-text" /> ';
	echo esc_html__( 'characters', 'search-social-appearance-audit' );
	echo '<p class="description">' . esc_html__( 'Where the Search Appearance tab truncates meta descriptions. Google truncates result snippets at roughly 160 characters (it is technically pixel-based, around 920px on desktop), so the default of 160 approximates what searchers actually see.', 'search-social-appearance-audit' ) . '</p>';
	echo '</td></tr>';

	echo '<tr><th scope="row"><label for="ssaa-social-desc-length">' . esc_html__( 'Social description preview length', 'search-social-appearance-audit' ) . '</label></th><td>';
	echo '<input type="number" min="50" max="400" id="ssaa-social-desc-length" name="' . esc_attr( SSAA_OPTION_KEY ) . '[social_desc_length]" value="' . esc_attr( (string) $social_len ) . '" class="small-text" /> ';
	echo esc_html__( 'characters', 'search-social-appearance-audit' );
	echo '<p class="description">' . esc_html__( 'Where the Social Appearance tab truncates OG descriptions. Platforms vary - Facebook shows roughly 110 characters in feed, LinkedIn around 200 - so the default of 110 approximates the most common visible length.', 'search-social-appearance-audit' ) . '</p>';
	echo '</td></tr>';

	/**
	 * Extension point: add-on files append their own settings rows
	 * (<tr> elements) inside this form table.
	 */
	do_action( 'ssaa_settings_fields' );

	echo '</table>';

	submit_button();
	echo '</form>';
}

/**
 * Premium tab: a prose feature comparison with one CTA top and bottom.
 *
 * Marketing surface only. It DESCRIBES paid features in prose; it renders no
 * locked inputs, no mock UI, and carries no implementation traces (constants,
 * defaults, wire-format names). Shown only on the free build - the caller
 * gates the whole tab on ! is_premium(). Keep the feature wording in lock-step
 * with user-docs/features/premium-features.md and the Freemius dashboard.
 */
function ssaa_render_premium_tab() {
	$upgrade_url = SSAA_License::upgrade_url();
	$compare_url = SSAA_Plugin::docs_url( 'features/premium-features', 'premium_tab' );

	$cta = function () use ( $upgrade_url, $compare_url ) {
		echo '<p class="ssaa-premium-cta">';
		if ( '' !== $upgrade_url ) {
			echo '<a class="button button-primary" href="' . esc_url( $upgrade_url ) . '">'
				. esc_html__( 'Upgrade to Premium', 'search-social-appearance-audit' ) . '</a> ';
		}
		echo '<a href="' . esc_url( $compare_url ) . '" target="_blank" rel="noopener">'
			. esc_html__( 'See the full plan comparison', 'search-social-appearance-audit' ) . '</a>';
		echo '</p>';
	};

	echo '<div class="ssaa-premium-tab">';

	echo '<p class="ssaa-premium-intro">' . esc_html__( 'The free plugin audits your pages and posts, with no limits. Premium adds automation, deeper analysis and more content types. Paid plans are sold and supported by PlugUpp through Freemius. All paid plans share the same features and differ only by how many sites the licence covers.', 'search-social-appearance-audit' ) . '</p>';

	$cta();

	$groups = array(
		array(
			'title' => __( 'Audit more content', 'search-social-appearance-audit' ),
			'items' => array(
				__( 'Custom post types and WooCommerce products', 'search-social-appearance-audit' ),
				__( 'Pre-publish auditing of drafts, scheduled and pending content', 'search-social-appearance-audit' ),
			),
		),
		array(
			'title' => __( 'Automate scanning and reporting', 'search-social-appearance-audit' ),
			'items' => array(
				__( 'Scheduled scans that run on their own', 'search-social-appearance-audit' ),
				__( 'Changes since last scan: what was newly flagged, fixed or edited', 'search-social-appearance-audit' ),
				__( 'Email reports showing the per-page changes since the last scan', 'search-social-appearance-audit' ),
				__( 'Enhanced scan: fallback-image prediction and weak social-image detection', 'search-social-appearance-audit' ),
			),
		),
		array(
			'title' => __( 'Work through results faster', 'search-social-appearance-audit' ),
			'items' => array(
				__( 'Filter by severity and issue type', 'search-social-appearance-audit' ),
				__( 'Export results to CSV', 'search-social-appearance-audit' ),
				__( 'Flag content by author', 'search-social-appearance-audit' ),
			),
		),
		array(
			'title' => __( 'Cover more sites', 'search-social-appearance-audit' ),
			'items' => array(
				__( 'Licences for 1, 3, 5 or unlimited sites (Personal, Pro, Business, Agency)', 'search-social-appearance-audit' ),
			),
		),
	);

	echo '<div class="ssaa-premium-groups">';
	foreach ( $groups as $group ) {
		echo '<div class="ssaa-premium-group">';
		echo '<h3>' . esc_html( $group['title'] ) . '</h3>';
		echo '<ul>';
		foreach ( $group['items'] as $item ) {
			echo '<li>' . esc_html( $item ) . '</li>';
		}
		echo '</ul>';
		echo '</div>';
	}
	echo '</div>';

	echo '<p class="description">' . esc_html__( 'If a licence expires the plugin keeps working on the free tier - your results stay and premium features simply switch off until you renew.', 'search-social-appearance-audit' ) . '</p>';

	$cta();

	echo '</div>';
}

function ssaa_render_logs_tab() {
	// The engine's canonical Log UI (engine 0.1.6) owns the whole tab.
	SSAA_Log_UI::render_tab();
}

ssaa_render_settings_page();
