<?php
/*
Plugin Name: ClearPost - AI Auto Blogging & SEO Agent
Description: Your AI Agent for SEO, in WordPress. An AI content marketer that knows your site, then schedules and generates posts every day.
Plugin URI: https://clearpostplugin.com/
Version: 2.0.68
License: GPLv2 or later
License URI: https://www.gnu.org/licenses/gpl-2.0.html
Author: purposego
Text Domain: clearpost-simple-ai-auto-post
Domain Path: /languages
*/

// Prevent direct file access.
if ( ! defined( 'WPINC' ) ) {
	die;
}

// Define plugin version
define( 'SAIAP_VERSION', '2.0.68' );

// Path to the main plugin file (used by includes/ modules that need to register
// activation/deactivation hooks).
if ( ! defined( 'SAIAP_PLUGIN_FILE' ) ) {
	define( 'SAIAP_PLUGIN_FILE', __FILE__ );
}

// Define premium API URL
if ( ! defined( 'SAIAP_PREMIUM_API_URL' ) ) {
	define( 'SAIAP_PREMIUM_API_URL', 'https://saiap.gopurposego.com' );
}

// Define Stripe checkout URL (Payment Link)
if ( ! defined( 'SAIAP_CHECKOUT_URL' ) ) {
	define( 'SAIAP_CHECKOUT_URL', 'https://buy.stripe.com/7sY6oIfwqgPu1Za7vC3AY06' );
}

/**
 * Get the checkout URL.
 *
 * Routes through the backend redirect endpoint so the Stripe Checkout Session
 * can carry BOTH the encoded domain (client_reference_id, for license
 * attribution) AND the PromoteKit referral (metadata, for affiliate
 * attribution). The static Payment Link is kept as a fallback — the backend
 * itself falls back to it if session creation fails, and this function falls
 * back to it if the backend URL isn't configured.
 *
 * @return string The checkout URL.
 */
function saiap_get_checkout_url() {
	$domain          = wp_parse_url( home_url(), PHP_URL_HOST );
	$encoded_domain  = str_replace( '.', '--', $domain );
	$stored_referral = get_option( 'saiap_promotekit_referral', '' );

	if ( defined( 'SAIAP_PREMIUM_API_URL' ) && SAIAP_PREMIUM_API_URL ) {
		$params = array( 'domain' => $domain );
		if ( ! empty( $stored_referral ) ) {
			$params['referral'] = $stored_referral;
		}
		return trailingslashit( SAIAP_PREMIUM_API_URL ) . 'api/checkout/redirect?' . http_build_query( $params );
	}

	// Fallback: static Payment Link (no affiliate attribution).
	return SAIAP_CHECKOUT_URL . '?client_reference_id=' . rawurlencode( $encoded_domain );
}

// Optionally enable Demo Mode (for internal testing only)
// phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedVariableFound -- Variable is scoped to this file only
$saiap_demo_enabled = ( defined( 'SAIAP_DEMO_MODE' ) && SAIAP_DEMO_MODE );

if ( $saiap_demo_enabled ) {
	// phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedVariableFound -- Variable is scoped to this file only
	$saiap_demo_bootstrap = plugin_dir_path( __FILE__ ) . 'dev/demo-mode/bootstrap.php';
	if ( ! file_exists( $saiap_demo_bootstrap ) ) {
		add_action( 'admin_notices', function() use ( $saiap_demo_bootstrap ) {
			echo '<div class="notice notice-warning"><p><strong>Simple AI Auto Post:</strong> Demo Mode is enabled but demo files were not found at <code>' . esc_html( $saiap_demo_bootstrap ) . '</code>. Make sure you installed the plugin from the Git repo (release ZIPs exclude dev/).</p></div>';
		} );
	} else {
		// Optional: debug console log to confirm load path (kept silent in UI)
		add_action( 'admin_footer', function() use ( $saiap_demo_bootstrap ) {
			echo '<script>console.log("[SAIAP Demo] main plugin requiring bootstrap: ' . esc_js( $saiap_demo_bootstrap ) . '");</script>';
		} );
		require_once $saiap_demo_bootstrap;
	}
}

/**
 * Plugin activation
 */
function saiap_activate() {
	saiap_create_prompt_tables();

	// Set a flag to show the consent notice
	if ( ! get_option( 'saiap_tracking_notice_shown' ) ) {
		set_transient( 'saiap_show_tracking_notice', true, WEEK_IN_SECONDS ); // Show for 1 week
		update_option( 'saiap_tracking_notice_shown', true );
	}

	// Store activation data for later tracking (if user consents)
	if ( ! get_option( 'saiap_activation_data' ) ) {
		update_option(
			'saiap_activation_data',
			array(
				'version' => SAIAP_VERSION,
				'time'    => current_time( 'timestamp' ),
				'is_new'  => get_option( 'saiap_db_version' ) ? 'no' : 'yes',
			)
		);
	}

	// Schedule daily models registry refresh with a small random offset to avoid thundering herd
	if ( ! wp_next_scheduled( 'saiap_refresh_models_registry_event' ) ) {
		$offset = wp_rand( 0, HOUR_IN_SECONDS );
		wp_schedule_event( time() + $offset, 'daily', 'saiap_refresh_models_registry_event' );
	}

	// Set activation redirect transient - will redirect on first admin page load.
	set_transient( 'saiap_activation_redirect', true, HOUR_IN_SECONDS );
}
register_activation_hook( __FILE__, 'saiap_activate' );

/**
 * Handle activation redirect based on user scenario.
 *
 * Redirects user to the appropriate page after plugin activation.
 */
function saiap_maybe_activation_redirect() {
	// Check for activation redirect transient.
	if ( ! get_transient( 'saiap_activation_redirect' ) ) {
		return;
	}

	// Delete transient immediately to ensure redirect only happens once.
	delete_transient( 'saiap_activation_redirect' );

	// Don't redirect during AJAX, bulk activation, or if user is activating multiple plugins.
	// phpcs:ignore WordPress.Security.NonceVerification.Recommended
	if ( wp_doing_ajax() || isset( $_GET['activate-multi'] ) ) {
		return;
	}

	// Always redirect to Dashboard - it shows appropriate content for each scenario:
	// - Fresh users (no_trial_no_keys): Trial welcome section
	// - Users with keys (no_trial_has_keys): Upgrade prompt
	// - Trial/paid users: Metrics and calendar
	wp_safe_redirect( admin_url( 'admin.php?page=saiap&tab=dashboard' ) );
	exit;
}
add_action( 'admin_init', 'saiap_maybe_activation_redirect', 1 );

/**
 * Redirect legacy scheduler tab URLs to dashboard.
 *
 * The Scheduler tab has been consolidated into the Dashboard tab.
 * This ensures old bookmarks and links still work.
 */
function saiap_redirect_scheduler_to_dashboard() {
	// phpcs:ignore WordPress.Security.NonceVerification.Recommended
	if ( isset( $_GET['page'] ) && 'saiap' === $_GET['page'] && isset( $_GET['tab'] ) && 'scheduler' === $_GET['tab'] ) {
		wp_safe_redirect( admin_url( 'admin.php?page=saiap&tab=dashboard' ) );
		exit;
	}
}
add_action( 'admin_init', 'saiap_redirect_scheduler_to_dashboard', 5 );

/**
 * Plugin deactivation
 */
function saiap_deactivate() {
	// Clear the scheduled cron job
	wp_clear_scheduled_hook( 'saiap_generate_scheduled_post' );
	wp_clear_scheduled_hook( 'saiap_refresh_models_registry_event' );
}
register_deactivation_hook( __FILE__, 'saiap_deactivate' );


/**
 * Check for database updates when plugin loads
 */
function saiap_check_for_db_updates() {
	$current_db_version = get_option( 'saiap_db_version', '0' );

	if ( version_compare( $current_db_version, '1.0', '<' ) ) {
		saiap_create_prompt_tables();
		update_option( 'saiap_db_version', '1.0' );
	}
}
add_action( 'plugins_loaded', 'saiap_check_for_db_updates' );

// Make sure this file is being included by a parent file.
if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

/**
 * Helper function to safely get the server host
 *
 * @return string The server host
 */
function saiap_get_server_host() {
	if ( isset( $_SERVER['HTTP_HOST'] ) ) {
		return sanitize_text_field( wp_unslash( $_SERVER['HTTP_HOST'] ) );
	}
	return wp_parse_url( home_url(), PHP_URL_HOST );
}

// Include onboarding functionality
require_once plugin_dir_path( __FILE__ ) . 'includes/onboarding.php';

// Include trial management functionality
require_once plugin_dir_path( __FILE__ ) . 'includes/trial.php';

// Include onboarding wizard for empty sites
require_once plugin_dir_path( __FILE__ ) . 'includes/onboarding-wizard.php';

// Include post generation functionality
require_once plugin_dir_path( __FILE__ ) . 'includes/generate.php';

// Include AI requests functionality
require_once plugin_dir_path( __FILE__ ) . 'includes/ai-requests.php';

// Include prompt history functionality
require_once plugin_dir_path( __FILE__ ) . 'includes/prompt-history.php';

// Include AI settings functionality
require_once plugin_dir_path( __FILE__ ) . 'includes/ai-settings.php';

// Include licensing functionality to give access to features that require a remote server. License not required for use of the free plugin.
require_once plugin_dir_path( __FILE__ ) . 'includes/licensing.php';

// Include site context functionality
require_once plugin_dir_path( __FILE__ ) . 'includes/site-context.php';

// Include analytics functionality
require_once plugin_dir_path( __FILE__ ) . 'includes/analytics.php';

// Include editor chat functionality
require_once plugin_dir_path( __FILE__ ) . 'includes/editor-chat.php';

// Include post scheduler functionality
require_once plugin_dir_path( __FILE__ ) . 'includes/scheduler.php';

// Include remote cron trigger REST endpoint
require_once plugin_dir_path( __FILE__ ) . 'includes/cron-trigger.php';

// Include insert post REST endpoint for backend push generation
require_once plugin_dir_path( __FILE__ ) . 'includes/api-insert-post.php';

// Include SEO meta REST endpoints for agent-driven edits on existing posts.
// Depends on saiap_apply_seo_meta() defined in api-insert-post.php above.
require_once plugin_dir_path( __FILE__ ) . 'includes/api-seo-meta.php';

// Include automatedtaxonomy functionality
require_once plugin_dir_path( __FILE__ ) . 'includes/taxonomy.php';

// Include taxonomy admin REST endpoints (audit + merge) for backend consolidation tool.
require_once plugin_dir_path( __FILE__ ) . 'includes/api-taxonomy-admin.php';

// Include images functionality (image search/select)
require_once plugin_dir_path( __FILE__ ) . 'includes/images.php';

// Include dashboard functionality
require_once plugin_dir_path( __FILE__ ) . 'includes/dashboard.php';

// Include SEO Agent Chat (global AI chat on dashboard).
require_once plugin_dir_path( __FILE__ ) . 'includes/seo-agent-chat.php';

// Include review prompt (sentiment gate + persistent nudge).
require_once plugin_dir_path( __FILE__ ) . 'includes/review-prompt.php';

// Include Trial Setup Stream (live narration during automated setup).
require_once plugin_dir_path( __FILE__ ) . 'includes/setup-stream.php';

// Include global admin banner (shows on ALL admin pages)
require_once plugin_dir_path( __FILE__ ) . 'includes/global-banner.php';

// Include WordPress dashboard widget (admin homepage)
require_once plugin_dir_path( __FILE__ ) . 'includes/dashboard-widget.php';

require_once plugin_dir_path( __FILE__ ) . 'includes/post-puller.php';

// AEO Tools — Custom head code injection (schema, meta tags, analytics).
require_once plugin_dir_path( __FILE__ ) . 'includes/aeo-tools.php';

// Deactivation reporter — POSTs a single best-effort signal when the plugin
// is manually deactivated from wp-admin. See file header for the why.
require_once plugin_dir_path( __FILE__ ) . 'includes/deactivation-hook.php';

// MCP — bundled abilities-api loader + adapter boot, and the ability registrations
// that expose ClearPost as MCP tools at /wp-json/clearpost/mcp.
// mcp-server.php must load first because it boots the adapter and provides
// saiap_mcp_server_supported(); mcp-abilities.php registers tools that the
// adapter exposes.
require_once plugin_dir_path( __FILE__ ) . 'includes/mcp-server.php';
require_once plugin_dir_path( __FILE__ ) . 'includes/mcp-abilities.php';


/**
 * Add custom action links to the plugins page row.
 *
 * @param array $links Existing plugin action links.
 * @return array Modified action links.
 */
function saiap_plugin_action_links( $links ) {
	$scenario = saiap_get_user_scenario();

	// Always add Settings link first.
	$settings_link = sprintf(
		'<a href="%s">%s</a>',
		admin_url( 'admin.php?page=saiap' ),
		__( 'Settings', 'clearpost-simple-ai-auto-post' )
	);

	// Add trial/status link based on scenario.
	$status_link = '';

	switch ( $scenario ) {
		case 'no_trial_no_keys':
		case 'no_trial_has_keys':
			$status_link = sprintf(
				'<a href="%s" style="color: #6366f1; font-weight: 500;">%s</a>',
				admin_url( 'admin.php?page=saiap&tab=dashboard' ),
				__( 'Start Free Trial', 'clearpost-simple-ai-auto-post' )
			);
			break;

		case 'active_trial':
			$days = saiap_get_trial_days_remaining();
			$status_link = sprintf(
				'<span style="color: #22c55e;">%s</span>',
				sprintf(
					/* translators: %d: number of days remaining */
					__( 'Trial: %d days left', 'clearpost-simple-ai-auto-post' ),
					$days
				)
			);
			break;

		case 'expired_trial':
			$status_link = sprintf(
				'<span style="color: #f59e0b; font-weight: 500;">%s</span>',
				__( 'Trial Expired', 'clearpost-simple-ai-auto-post' )
			);
			break;

		case 'paid':
			$status_link = sprintf(
				'<span style="color: #22c55e;">%s</span>',
				__( 'Active', 'clearpost-simple-ai-auto-post' )
			);
			break;
	}

	// Build new links array.
	$new_links = array( 'settings' => $settings_link );
	if ( ! empty( $status_link ) ) {
		$new_links['status'] = $status_link;
	}

	return array_merge( $new_links, $links );
}
add_filter( 'plugin_action_links_' . plugin_basename( __FILE__ ), 'saiap_plugin_action_links' );

/**
 * Register settings
 */
function saiap_register_settings() {
	add_option( 'saiap_ai_prompt', 'Generate a new blog post about the benefits of using AI in daily life.' );
	add_option( 'saiap_post_type', 'post' );
	add_option( 'saiap_license_key', '' );
	add_option( 'saiap_enable_prompt_history', 'yes' );

	add_option( 'saiap_default_provider', 'openai' );

	// OpenAI settings
	add_option( 'saiap_openai_api_key', '' );
	add_option( 'saiap_openai_model', 'gpt-5.4' );

	// Anthropic settings
	add_option( 'saiap_anthropic_api_key', '' );
	add_option( 'saiap_anthropic_model', 'claude-opus-4-5' );

	// Gemini settings
	add_option( 'saiap_gemini_api_key', '' );
	add_option( 'saiap_gemini_model', 'gemini-3-pro-preview' );

	// Get the first ACF field as default
	$default_post_type = 'post';
	$custom_fields     = saiap_get_custom_fields_for_post_type( $default_post_type );

	// Polyfill for array_key_first for PHP < 7.3
	$default_link_field = '';
	if ( ! empty( $custom_fields ) ) {
		if ( function_exists( 'array_key_first' ) ) {
			$default_link_field = array_key_first( $custom_fields );
		} else {
			foreach ( $custom_fields as $key => $value ) {
				$default_link_field = $key;
				break;
			}
		}
	}

	add_option( 'saiap_link_field_name', $default_link_field );
	add_option( 'saiap_context_post_limit', '50' );
	add_option( 'saiap_context_post_age', '365' ); // days

	// Notifications defaults - enabled by default for new installs
	$admin_email_default = get_option( 'admin_email', '' );
	add_option( 'saiap_notify_on_schedule', 'yes' );
	add_option( 'saiap_notify_recipients', $admin_email_default );

	register_setting(
		'saiap_options_group',
		'saiap_ai_prompt',
		array(
			'type'              => 'string',
			'sanitize_callback' => 'sanitize_textarea_field',
			'default'           => 'Generate a new blog post about the benefits of using AI in daily life.',
		)
	);
	register_setting(
		'saiap_options_group',
		'saiap_post_type',
		array(
			'type'              => 'string',
			'sanitize_callback' => 'sanitize_text_field',
			'default'           => 'post',
		)
	);
	register_setting(
		'saiap_options_group',
		'saiap_link_field_name',
		array(
			'type'              => 'string',
			'sanitize_callback' => 'sanitize_text_field',
			'default'           => '',
		)
	);
	// License key NOT required to use the free plugin
	register_setting(
		'saiap_options_group',
		'saiap_license_key',
		array(
			'type'              => 'string',
			'sanitize_callback' => 'sanitize_text_field',
			'default'           => '',
		)
	);

	register_setting(
		'saiap_options_group',
		'saiap_enable_prompt_history',
		array(
			'type'              => 'string',
			'sanitize_callback' => 'sanitize_text_field',
			'default'           => 'yes',
		)
	);
	register_setting(
		'saiap_options_group',
		'saiap_context_post_limit',
		array(
			'type'              => 'integer',
			'sanitize_callback' => 'absint',
			'default'           => 5,
		)
	);
	register_setting(
		'saiap_options_group',
		'saiap_context_post_age',
		array(
			'type'              => 'integer',
			'sanitize_callback' => 'absint',
			'default'           => 365,
		)
	);

	// Register notification settings
	register_setting(
		'saiap_options_group',
		'saiap_notify_on_schedule',
		array(
			'type'              => 'string',
			'sanitize_callback' => 'sanitize_text_field',
			'default'           => 'no',
		)
	);
	register_setting(
		'saiap_options_group',
		'saiap_notify_recipients',
		array(
			'type'              => 'string',
			'sanitize_callback' => 'sanitize_text_field',
			'default'           => $admin_email_default,
		)
	);
	// AI Provider settings
	register_setting(
		'saiap_options_group',
		'saiap_default_provider',
		array(
			'type'              => 'string',
			'sanitize_callback' => 'sanitize_text_field',
			'default'           => 'openai',
		)
	);

	// Register OpenAI settings
	register_setting(
		'saiap_options_group',
		'saiap_openai_api_key',
		array(
			'type'              => 'string',
			'sanitize_callback' => 'sanitize_text_field',
			'default'           => '',
		)
	);
	register_setting(
		'saiap_options_group',
		'saiap_openai_model',
		array(
			'type'              => 'string',
			'sanitize_callback' => 'sanitize_text_field',
			'default'           => 'gpt-5.4',
		)
	);

	// Register Anthropic settings
	register_setting(
		'saiap_options_group',
		'saiap_anthropic_api_key',
		array(
			'type'              => 'string',
			'sanitize_callback' => 'sanitize_text_field',
			'default'           => '',
		)
	);
	register_setting(
		'saiap_options_group',
		'saiap_anthropic_model',
		array(
			'type'              => 'string',
			'sanitize_callback' => 'sanitize_text_field',
			'default'           => 'claude-opus-4-5',
		)
	);

	// Register Gemini settings
	register_setting(
		'saiap_options_group',
		'saiap_gemini_api_key',
		array(
			'type'              => 'string',
			'sanitize_callback' => 'sanitize_text_field',
			'default'           => '',
		)
	);
	register_setting(
		'saiap_options_group',
		'saiap_gemini_model',
		array(
			'type'              => 'string',
			'sanitize_callback' => 'sanitize_text_field',
			'default'           => 'gemini-3-pro-preview',
		)
	);

	// Add a nonce field for form submission
	add_settings_field(
		'saiap_form_nonce',
		'',
		'saiap_render_nonce_field',
		'saiap_options_group'
	);
}
add_action( 'admin_init', 'saiap_register_settings' );

// Trial state management - run once per request to keep state current.
add_action( 'admin_init', 'saiap_maybe_expire_trial' );
add_action( 'admin_init', 'saiap_check_version_update_notice' );

/**
 * Filter posts list to show only ClearPost-generated posts.
 *
 * @param WP_Query $query The query object.
 */
function saiap_filter_generated_posts( $query ) {
	if ( ! is_admin() || ! $query->is_main_query() ) {
		return;
	}

	global $pagenow;
	if ( 'edit.php' !== $pagenow ) {
		return;
	}

	// phpcs:ignore WordPress.Security.NonceVerification.Recommended
	if ( isset( $_GET['saiap_generated'] ) && '1' === $_GET['saiap_generated'] ) {
		$query->set( 'meta_key', '_saiap_generated' );
		$query->set( 'meta_value', '1' );
	}
}
add_action( 'pre_get_posts', 'saiap_filter_generated_posts' );

/**
 * Render nonce field used in multiple forms
 */
function saiap_render_nonce_field() {
	wp_nonce_field( 'saiap_form_action', 'saiap_form_nonce' );
}

/**
 * Enqueue admin scripts and styles
 */
function saiap_enqueue_admin_scripts( $hook ) {
	// Plugin pages
	$plugin_pages = array( 'toplevel_page_saiap' );

	// Only load on plugin settings page
	if ( ! in_array( $hook, $plugin_pages, true ) ) {
		return;
	}

	// Enqueue design system CSS first to establish base styles
	wp_enqueue_style(
		'saiap-design-system',
		plugin_dir_url( __FILE__ ) . 'assets/css/design-system.css',
		array(),
		SAIAP_VERSION
	);

	// Enqueue admin CSS
	$admin_css_version = filemtime( plugin_dir_path( __FILE__ ) . 'assets/css/admin.css' );
	wp_enqueue_style( 'saiap-admin', plugin_dir_url( __FILE__ ) . 'assets/css/admin.css', array( 'saiap-design-system' ), $admin_css_version );

	// Enqueue dashboard CSS
	$dashboard_css_version = filemtime( plugin_dir_path( __FILE__ ) . 'assets/css/dashboard.css' );
	wp_enqueue_style( 'saiap-dashboard', plugin_dir_url( __FILE__ ) . 'assets/css/dashboard.css', array( 'saiap-admin' ), $dashboard_css_version );

	// Enqueue trial CSS (for welcome hero, CTAs, badges, paywalls)
	$trial_css_version = filemtime( plugin_dir_path( __FILE__ ) . 'assets/css/trial.css' );
	wp_enqueue_style( 'saiap-trial', plugin_dir_url( __FILE__ ) . 'assets/css/trial.css', array( 'saiap-admin' ), $trial_css_version );

	// Enqueue dashboard JS
	$dashboard_js_version = filemtime( plugin_dir_path( __FILE__ ) . 'assets/js/dashboard.js' );
	wp_enqueue_script( 'saiap-dashboard-js', plugin_dir_url( __FILE__ ) . 'assets/js/dashboard.js', array( 'jquery' ), $dashboard_js_version, true );

	// Enqueue GSC Recharts bundle
	$gsc_chart_bundle = plugin_dir_path( __FILE__ ) . 'assets/js/dist/gsc-chart.bundle.js';
	if ( file_exists( $gsc_chart_bundle ) ) {
		wp_enqueue_script( 'saiap-gsc-chart', plugin_dir_url( __FILE__ ) . 'assets/js/dist/gsc-chart.bundle.js', array( 'wp-element' ), filemtime( $gsc_chart_bundle ), true );
	}

	// Enqueue admin JS
	$admin_js_version = filemtime( plugin_dir_path( __FILE__ ) . 'assets/js/admin.js' );
	wp_enqueue_script( 'saiap-admin', plugin_dir_url( __FILE__ ) . 'assets/js/admin.js', array( 'jquery' ), $admin_js_version, true );

	// Enqueue marked library for markdown parsing (bundled locally)
	wp_enqueue_script( 'marked', plugin_dir_url( __FILE__ ) . 'assets/js/vendor/marked.min.js', array(), '11.1.1', true );

	// Enqueue site context JS
	$site_context_js_version = file_exists( plugin_dir_path( __FILE__ ) . 'assets/js/site-context.js' ) ?
		filemtime( plugin_dir_path( __FILE__ ) . 'assets/js/site-context.js' ) : SAIAP_VERSION;
	wp_enqueue_script( 'saiap-site-context-js', plugin_dir_url( __FILE__ ) . 'assets/js/site-context.js', array( 'jquery', 'saiap-admin', 'marked' ), $site_context_js_version, true );

	// Enqueue prompt history assets
	$prompt_history_css_version = filemtime( plugin_dir_path( __FILE__ ) . 'assets/css/prompt-history.css' );
	$prompt_history_js_version  = filemtime( plugin_dir_path( __FILE__ ) . 'assets/js/prompt-history.js' );

	// Enqueue scheduler assets
	$scheduler_css_version = filemtime( plugin_dir_path( __FILE__ ) . 'assets/css/scheduler.css' );
	wp_enqueue_style( 'saiap-scheduler', plugin_dir_url( __FILE__ ) . 'assets/css/scheduler.css', array( 'saiap-design-system' ), $scheduler_css_version );
	$scheduler_js_version = filemtime( plugin_dir_path( __FILE__ ) . 'assets/js/scheduler.js' );
	wp_enqueue_script( 'saiap-scheduler-js', plugin_dir_url( __FILE__ ) . 'assets/js/scheduler.js', array( 'jquery' ), $scheduler_js_version, true );

	wp_enqueue_style( 'saiap-prompt-history', plugin_dir_url( __FILE__ ) . 'assets/css/prompt-history.css', array( 'saiap-design-system' ), $prompt_history_css_version );
	wp_enqueue_script( 'saiap-prompt-history-js', plugin_dir_url( __FILE__ ) . 'assets/js/prompt-history.js', array( 'jquery', 'saiap-admin', 'saiap-site-context-js' ), $prompt_history_js_version, true );

	// Enqueue form handler JS
	$form_handler_js_version = filemtime( plugin_dir_path( __FILE__ ) . 'assets/js/form-handler.js' );
	wp_enqueue_script( 'saiap-form-handler', plugin_dir_url( __FILE__ ) . 'assets/js/form-handler.js', array( 'jquery', 'saiap-admin' ), $form_handler_js_version, true );

	// Localize admin script
	wp_localize_script(
		'saiap-admin',
		'saiapAdmin',
		array(
			'ajaxurl'            => admin_url( 'admin-ajax.php' ),
			'adminUrl'           => admin_url(),
			'restNonce'          => wp_create_nonce( 'wp_rest' ),
			'licenseKey'         => get_option( 'saiap_license_key', '' ),
			'promptHistoryNonce' => wp_create_nonce( 'saiap_get_all_prompts' ),
			'customFieldsNonce'  => wp_create_nonce( 'saiap_get_custom_fields' ),
			'contextNonce'       => wp_create_nonce( 'saiap_update_context' ),
			'licenseNonce'       => wp_create_nonce( 'saiap_validate_license' ),
			'formNonce'          => wp_create_nonce( 'saiap_form_action' ),
			'inlineImagesNonce'  => wp_create_nonce( 'saiap_inline_images_status' ),
			'schedulerNonce'     => wp_create_nonce( 'saiap_scheduler_nonce' ),
			'trackingNonce'      => wp_create_nonce( 'saiap_tracking_pref' ),
			'trialNonce'         => wp_create_nonce( 'saiap_trial_nonce' ),
			'reviewPromptNonce'  => wp_create_nonce( 'saiap_review_prompt_nonce' ),
			'showReviewModal'    => function_exists( 'saiap_should_show_review_modal' ) && saiap_should_show_review_modal(),
			'checkoutUrl'        => saiap_get_checkout_url(),
			'planCadenceCap'     => absint( get_option( 'saiap_plan_cadence_cap', 0 ) ),
			'needsWizard'        => saiap_needs_onboarding_wizard(),
			'wizardData'         => get_option( 'saiap_onboarding_wizard_data', array() ),
			'i18n'               => array(
				'licenseActivated'   => __( '✓ License activated successfully!', 'clearpost-simple-ai-auto-post' ),
				'licenseTimeout'     => __( 'License activation timed out. Please refresh the page or contact support.', 'clearpost-simple-ai-auto-post' ),
				'contextSuccess'     => __( 'Site context updated successfully!', 'clearpost-simple-ai-auto-post' ),
				'contextError'       => __( 'Failed to update site context. Please try again.', 'clearpost-simple-ai-auto-post' ),
				'contextUpdated'     => __( 'Site context fields updated successfully!', 'clearpost-simple-ai-auto-post' ),
				'contextUpdateError' => __( 'Failed to update site context fields. Please try again.', 'clearpost-simple-ai-auto-post' ),
				'validationError'    => __( 'Please fix the following errors:', 'clearpost-simple-ai-auto-post' ),
				'loadingContext'     => __( 'Loading site context data...', 'clearpost-simple-ai-auto-post' ),
				'saveChanges'        => __( 'Save Changes', 'clearpost-simple-ai-auto-post' ),
				'cancel'             => __( 'Cancel', 'clearpost-simple-ai-auto-post' ),
				'siteSummary'        => __( 'Site Summary', 'clearpost-simple-ai-auto-post' ),
				'keyTopics'          => __( 'Target Keywords', 'clearpost-simple-ai-auto-post' ),
				'writingStyleGuide'  => __( 'Writing Style Guide', 'clearpost-simple-ai-auto-post' ),
				'futureContentIdeas' => __( 'Future Content Ideas', 'clearpost-simple-ai-auto-post' ),
				'noTopicsFound'      => __( 'No keywords found.', 'clearpost-simple-ai-auto-post' ),
				'noIdeasFound'       => __( 'No future content ideas found.', 'clearpost-simple-ai-auto-post' ),
				'oneTopicPerLine'    => __( 'Enter one keyword per line.', 'clearpost-simple-ai-auto-post' ),
				'oneIdeaPerLine'     => __( 'Enter one idea per line.', 'clearpost-simple-ai-auto-post' ),
				'usePrompt'          => __( 'Use this prompt', 'clearpost-simple-ai-auto-post' ),
				'model'              => __( 'Model', 'clearpost-simple-ai-auto-post' ),
				'posts'              => __( 'Posts', 'clearpost-simple-ai-auto-post' ),
				'noPrompts'          => __( 'No prompts found.', 'clearpost-simple-ai-auto-post' ),
				'loadError'          => __( 'Error loading prompts.', 'clearpost-simple-ai-auto-post' ),
				'usageTracked'       => __( 'Prompt usage tracked', 'clearpost-simple-ai-auto-post' ),
				'usageTrackFailed'   => __( 'Failed to track prompt usage', 'clearpost-simple-ai-auto-post' ),
				'errorEmptyPrompt'   => __( 'Please enter a prompt.', 'clearpost-simple-ai-auto-post' ),
				'errorServer'        => __( 'Server error. Please try again.', 'clearpost-simple-ai-auto-post' ),
				'editPost'           => __( 'Edit Post', 'clearpost-simple-ai-auto-post' ),
				'inlineImagesQueued' => __( 'Inline images are being added in the background. They may take a few seconds to appear in the draft.', 'clearpost-simple-ai-auto-post' ),
				'inlineImagesComplete' => __( 'Inline images have been added to your draft.', 'clearpost-simple-ai-auto-post' ),
				'inlineImagesError'    => __( 'We could not add inline images automatically. Please open the draft to review.', 'clearpost-simple-ai-auto-post' ),
				// Scheduler strings
				'noPromptScheduled'    => __( 'No prompt scheduled.', 'clearpost-simple-ai-auto-post' ),
				'add'                  => __( 'Add', 'clearpost-simple-ai-auto-post' ),
				'edit'                 => __( 'Edit', 'clearpost-simple-ai-auto-post' ),
				'regenerate'           => __( 'Regenerate', 'clearpost-simple-ai-auto-post' ),
				'errorLoadingSchedule' => __( 'Error: Could not load schedule', 'clearpost-simple-ai-auto-post' ),
				'addPrompt'            => __( 'Add New Prompt', 'clearpost-simple-ai-auto-post' ),
				'editPrompt'           => __( 'Edit Prompt', 'clearpost-simple-ai-auto-post' ),
				'savePrompt'           => __( 'Save Prompt', 'clearpost-simple-ai-auto-post' ),
				// Site Overview card strings
				'businessInfo'         => __( 'Site Overview', 'clearpost-simple-ai-auto-post' ),
				'siteName'             => __( 'Site Name', 'clearpost-simple-ai-auto-post' ),
				'niche'                => __( 'Niche', 'clearpost-simple-ai-auto-post' ),
				'description'          => __( 'Description', 'clearpost-simple-ai-auto-post' ),
				'targetAudience'       => __( 'Target Audience', 'clearpost-simple-ai-auto-post' ),
				'seedTopics'           => __( 'Seed Topics', 'clearpost-simple-ai-auto-post' ),
				'locations'            => __( 'Locations', 'clearpost-simple-ai-auto-post' ),
				'competitorUrls'       => __( 'Competitor URLs', 'clearpost-simple-ai-auto-post' ),
			),
		)
	);
}
add_action( 'admin_enqueue_scripts', 'saiap_enqueue_admin_scripts' );

/**
 * Enqueue loader script and styles
 */
function saiap_enqueue_loader( $hook ) {
	// Only load on plugin settings page
	if ( $hook !== 'toplevel_page_saiap' ) {
		return;
	}

	// Enqueue loader CSS
	$loader_css_version = filemtime( plugin_dir_path( __FILE__ ) . 'assets/css/loader.css' );
	wp_enqueue_style( 'saiap-loader', plugin_dir_url( __FILE__ ) . 'assets/css/loader.css', array(), $loader_css_version );

	// Enqueue loader JS
	$loader_js_version = filemtime( plugin_dir_path( __FILE__ ) . 'assets/js/loader.js' );
	wp_enqueue_script( 'saiap-loader', plugin_dir_url( __FILE__ ) . 'assets/js/loader.js', array( 'jquery' ), $loader_js_version, true );
}
add_action( 'admin_enqueue_scripts', 'saiap_enqueue_loader' );

/**
 * Add to admin menu
 */
function saiap_register_options_page() {
	// Custom SVG icon for admin menu (ClearPost sun logo)
	$icon_svg      = file_get_contents( plugin_dir_path( __FILE__ ) . 'assets/images/clearpost-sun-logo-icon-drawn.svg' );
	$icon_svg      = str_replace( 'fill="currentColor"', 'fill="black"', $icon_svg );
	$icon_data_uri = 'data:image/svg+xml;base64,' . base64_encode( $icon_svg );

	add_menu_page(
		'ClearPost AI',
		'ClearPost AI',
		'manage_options',
		'saiap',
		'saiap_options_page',
		$icon_data_uri,
		30 // position in the menu
	);
}
add_action( 'admin_menu', 'saiap_register_options_page' );

/**
 * Render the main plugin page
 */
function saiap_options_page() {
	// Check user capabilities
	if ( ! current_user_can( 'manage_options' ) ) {
		wp_die( esc_html__( 'You do not have sufficient permissions to access this page.', 'clearpost-simple-ai-auto-post' ) );
		return;
	}

	// Get the active tab - Dashboard is the default for ALL users.
	// The Dashboard serves as the command center and shows appropriate content
	// based on user scenario (trial welcome for new users, metrics for active users).
	$scenario    = saiap_get_user_scenario();
	$default_tab = 'dashboard';

    // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Tab navigation in admin doesn't require nonce
	$tab = isset( $_GET['tab'] ) ? sanitize_text_field( wp_unslash( $_GET['tab'] ) ) : $default_tab;

	// Get license information - not required for use of the free plugin, only used if the user wants to upgrade to access premium features that require a remote server
	$license_key = get_option( 'saiap_license_key', '' );

	// Get post types
	$post_types = get_post_types( array( 'public' => true ), 'objects' );

	// Get current post type
	$current_post_type = get_option( 'saiap_post_type', 'post' );

	// Get custom fields for the current post type
	$custom_fields = saiap_get_custom_fields_for_post_type( $current_post_type );

	// Get all AI models
	$models = saiap_get_ai_models();

	?>
	<div class="wrap saiap-admin-page">
		<h1><?php echo esc_html( get_admin_page_title() ); ?></h1>
		
		<nav class="nav-tab-wrapper">
			<a href="?page=saiap&tab=dashboard" class="nav-tab 
			<?php
			if ( $tab === 'dashboard' ) :
				?>
				nav-tab-active<?php endif; ?>">
				<?php esc_html_e( 'Dashboard', 'clearpost-simple-ai-auto-post' ); ?>
			</a>
			<a href="?page=saiap&tab=settings" class="nav-tab 
			<?php
			if ( $tab === 'settings' ) :
				?>
				nav-tab-active<?php endif; ?>">
				<?php esc_html_e( 'Generate', 'clearpost-simple-ai-auto-post' ); ?>
			</a>
			<a href="?page=saiap&tab=ai-settings" class="nav-tab 
			<?php
			if ( $tab === 'ai-settings' ) :
				?>
				nav-tab-active<?php endif; ?>">
				<?php esc_html_e( 'Settings', 'clearpost-simple-ai-auto-post' ); ?>
			</a>
			<a href="?page=saiap&tab=edit-with-ai" class="nav-tab 
			<?php
			if ( $tab === 'edit-with-ai' ) :
				?>
				nav-tab-active<?php endif; ?>">
				<?php esc_html_e( 'Edit with AI', 'clearpost-simple-ai-auto-post' ); ?>
			</a>
			<?php
			// Note: Scheduler tab removed - functionality consolidated into Dashboard tab.
			// Legacy scheduler.php AJAX handlers and cron job remain for backward compatibility.
				?>
			<a href="?page=saiap&tab=site-context" class="nav-tab 
			<?php
			if ( $tab === 'site-context' ) :
				?>
				nav-tab-active<?php endif; ?>">
				<?php esc_html_e( 'Context', 'clearpost-simple-ai-auto-post' ); ?>
			</a>
			<a href="?page=saiap&tab=premium" class="nav-tab 
			<?php
			if ( $tab === 'premium' ) :
				?>
				nav-tab-active<?php endif; ?>">
				<?php esc_html_e( 'Premium', 'clearpost-simple-ai-auto-post' ); ?>
			</a>
		</nav>
		
		<div class="tab-content">
			<?php
			// Trial CTAs are now handled by the Dashboard tab for a unified experience.
			// Only show trial status badge for active trial users on non-Dashboard tabs.
			if ( 'active_trial' === $scenario && 'dashboard' !== $tab ) {
				saiap_render_trial_status_badge();
			}

			if ( $tab === 'dashboard' ) {
				saiap_render_dashboard_tab();
			} elseif ( $tab === 'settings' ) {
				saiap_render_generate_tab( $post_types, $models, $current_post_type, $custom_fields, $license_key );
			} elseif ( $tab === 'site-context' ) {
				saiap_render_site_context_tab();
			} elseif ( $tab === 'ai-settings' ) {
				saiap_render_ai_settings_tab( $models );
			} elseif ( $tab === 'scheduler' ) {
				// Legacy: Redirect scheduler tab to dashboard.
				// The scheduler functionality is now part of the Dashboard SEO calendar.
				saiap_render_dashboard_tab();
			} elseif ( $tab === 'edit-with-ai' ) {
				saiap_render_edit_with_ai_tab();
			} elseif ( $tab === 'premium' ) {
				saiap_render_premium_tab( $license_key );
			}
			?>
		</div>
	</div>
	<?php
}
