<?php
/**
 * Licensing and Premium Features
 *
 * This file contains all license key saving and Premium tab rendering.
 *
 * @package Simple_Ai_Auto_Post
 * @since 1.0.0
 */

// If this file is called directly, abort.
if ( ! defined( 'WPINC' ) ) {
	die;
}

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

/**
 * Save license key from form submission and auto-trigger setup if needed.
 *
 * When a valid license key is entered:
 * - If trial was started via website with wizard data → auto-trigger setup with that data
 * - If trial was started via plugin → use existing plugin wizard data or prompt for it
 * - License key entry is the universal trigger for automated setup
 */
function saiap_save_license() {
	// Check user capabilities.
	if ( ! current_user_can( 'manage_options' ) ) {
		wp_send_json_error( 'Insufficient permissions' );
		return;
	}

	// Verify nonce from POST request.
	if ( ! isset( $_POST['saiap_license_form_nonce'] ) || ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['saiap_license_form_nonce'] ) ), 'saiap_save_license_action' ) ) {
		wp_send_json_error( 'Invalid nonce verification' );
		return;
	}

	// Get existing license key to detect if this is a new activation.
	$previous_license_key = get_option( 'saiap_license_key', '' );

	// Sanitize and save the new license key.
	$license_key = isset( $_POST['saiap_license_key'] ) ? sanitize_text_field( wp_unslash( $_POST['saiap_license_key'] ) ) : '';
	update_option( 'saiap_license_key', $license_key );

	// Validate using premium access validation (includes trial info with source and wizard_data).
	$validation_result = saiap_validate_premium_access();

	// Handle WP_Error.
	if ( is_wp_error( $validation_result ) ) {
		wp_send_json_error(
			array(
				'message'    => $validation_result->get_error_message(),
				'error_code' => $validation_result->get_error_code(),
			)
		);
		return;
	}

	// Check if validation was successful.
	$is_valid = isset( $validation_result['isValid'] ) && $validation_result['isValid'];

	// If valid AND this is a new license key activation, trigger automated setup.
	$is_new_activation   = empty( $previous_license_key ) && ! empty( $license_key );
	$setup_already_run   = ! empty( get_option( 'saiap_setup_triggered_at', 0 ) );
	$should_trigger_setup = $is_valid && $is_new_activation && ! $setup_already_run;

	// Track license activation with time from signup (for web-started trials).
	if ( $is_valid && $is_new_activation ) {
		$source     = get_option( 'saiap_trial_source', 'plugin' );
		$started_at = isset( $validation_result['trial']['started_at'] ) ? $validation_result['trial']['started_at'] : null;

		$time_to_activation_minutes = null;
		if ( $started_at ) {
			$signup_time    = strtotime( $started_at );
			$activation_time = time();
			if ( $signup_time > 0 ) {
				$time_to_activation_minutes = round( ( $activation_time - $signup_time ) / 60 );
			}
		}

		saiap_track_event(
			'license_activated',
			array(
				'source'                     => $source,
				'time_to_activation_minutes' => $time_to_activation_minutes,
			)
		);
	}

	$context_loaded  = false;
	$setup_triggered = false;
	$needs_wizard    = false;

	if ( $should_trigger_setup ) {
		// First, try to load pre-generated context from website checkout flow.
		$context_loaded = saiap_load_pregenerated_context();

		if ( ! $context_loaded ) {
			// No pre-generated context, fall back to triggering setup.
			$source          = get_option( 'saiap_trial_source', 'plugin' );
			$web_wizard_data = get_option( 'saiap_web_wizard_data', null );
			$plugin_wizard_data = get_option( 'saiap_onboarding_wizard_data', null );

			if ( 'website' === $source && ! empty( $web_wizard_data ) ) {
				// Web-started trial with wizard data: auto-trigger setup.
				saiap_trigger_automated_setup( $web_wizard_data );
				update_option( 'saiap_setup_triggered_at', time() );
				$setup_triggered = true;
			} elseif ( ! empty( $plugin_wizard_data ) ) {
				// Plugin-started trial with existing wizard data: auto-trigger setup.
				saiap_trigger_automated_setup( $plugin_wizard_data );
				update_option( 'saiap_setup_triggered_at', time() );
				$setup_triggered = true;
			} elseif ( ! saiap_is_site_empty() ) {
				// Site has content: auto-trigger setup without wizard data.
				saiap_trigger_automated_setup();
				update_option( 'saiap_setup_triggered_at', time() );
				$setup_triggered = true;
			} else {
				// Empty site with no wizard data: need to show wizard.
				$needs_wizard = true;
			}
		} else {
			// Pre-generated context was loaded, mark setup as done.
			update_option( 'saiap_setup_triggered_at', time() );
		}
	}

	wp_send_json_success(
		array(
			'message'         => 'License key settings updated.',
			'validation'      => $validation_result,
			'context_loaded'  => $context_loaded,
			'setup_triggered' => $setup_triggered,
			'needs_wizard'    => $needs_wizard,
		)
	);
}
add_action( 'wp_ajax_saiap_save_license', 'saiap_save_license' );

/**
 * Check for and load pre-generated site context from checkout flow
 *
 * Called after license validation to see if the user went through the website
 * checkout flow which pre-generates site context during Stripe checkout.
 *
 * @return bool True if context was loaded, false otherwise
 */
function saiap_load_pregenerated_context() {
	// Don't overwrite existing context.
	$existing_context = get_option( 'saiap_context_last_updated', 0 );
	if ( $existing_context > 0 ) {
		return false;
	}

	$domain = saiap_get_server_host();

	// Call the activation status endpoint.
	$response = wp_remote_get(
		SAIAP_PREMIUM_API_URL . '/api/activation-status/domain?' . http_build_query( array( 'domain' => $domain ) ),
		array(
			'headers' => array( 'Content-Type' => 'application/json' ),
			'timeout' => 15,
		)
	);

	if ( is_wp_error( $response ) ) {
		// Network error - silently fail, user can generate context manually.
		return false;
	}

	$status_code = wp_remote_retrieve_response_code( $response );
	if ( 404 === $status_code ) {
		// No pre-generated context exists for this domain.
		return false;
	}

	if ( 200 !== $status_code ) {
		// Other error - silently fail.
		return false;
	}

	$data = json_decode( wp_remote_retrieve_body( $response ), true );

	$status = isset( $data['status'] ) ? $data['status'] : '';
	if ( empty( $data ) || 'complete' !== $status ) {
		// Context not ready or failed.
		return false;
	}

	// Store the pre-generated site context.
	if ( ! empty( $data['siteContext'] ) ) {
		update_option( 'saiap_site_context', $data['siteContext'] );
		update_option( 'saiap_context_last_updated', time() );
		update_option( 'saiap_context_auto_loaded', true );

		// Also cache it for display.
		update_option( 'saiap_context_cache', $data['siteContext'] );

		// Mark premium onboarding step 1 as complete.
		if ( function_exists( 'saiap_premium_onboarding_mark_step_complete' ) ) {
			saiap_premium_onboarding_mark_step_complete( 1 );
		}

		return true;
	}

	return false;
}

/**
 * Validate license key helper function
 * 
 * @param string $license_key Optional license key to validate. If not provided, uses stored key.
 * @return array Validation result with 'isValid' boolean and other data - not stored, only used for immediate feedback to the user
 */
function saiap_validate_license_key( $license_key = '' ) {
	if ( empty( $license_key ) ) {
		$license_key = get_option( 'saiap_license_key' );
	}
	
	if ( empty( $license_key ) ) {
		return array( 'isValid' => false, 'error' => 'No license key provided' );
	}

	// Make request to premium API just to validate the license key, doesn't store the result
	$response = wp_remote_post(
		SAIAP_PREMIUM_API_URL . '/api/validate',
		array(
			'headers' => array( 'Content-Type' => 'application/json' ),
			'body'    => wp_json_encode(
				array(
					'license_key' => $license_key,
					'domain'      => saiap_get_server_host(),
				)
			),
			'timeout' => 15,
		)
	);

	if ( is_wp_error( $response ) ) {
		return array( 'isValid' => false, 'error' => $response->get_error_message() );
	}

	$result = json_decode( wp_remote_retrieve_body( $response ), true );
	return $result ?: array( 'isValid' => false, 'error' => 'Invalid response from validation service' );
}

/**
 * AJAX endpoint for manual license validation, only used for immediate feedback to the user on license key save and not stored
 */
function saiap_ajax_validate_license() {
	check_ajax_referer( 'saiap_validate_license', 'nonce' );

	if ( ! current_user_can( 'manage_options' ) ) {
		wp_send_json_error( 'Unauthorized' );
	}

	// Check if domain is set in POST data
	if ( ! isset( $_POST['domain'] ) ) {
		wp_send_json_error( 'Domain parameter is required' );
		return;
	}

	$result = saiap_validate_license_key();
	
	if ( $result['isValid'] ) {
		wp_send_json_success( $result );
	} else {
		wp_send_json_error( $result['error'] ?? 'License validation failed' );
	}
}
add_action( 'wp_ajax_saiap_validate_license', 'saiap_ajax_validate_license' );

/**
 * Render the premium tab content
 *
 * @param string $license_key The current license key
 */
function saiap_render_premium_tab( $license_key ) {
	// Track page view
	saiap_track_event(
		'premium_page_viewed',
		array(
			'has_license' => ! empty( $license_key ) ? 'yes' : 'no',
		)
	);

	$scenario = saiap_get_user_scenario();

	// Show trial CTA for eligible users.
	if ( in_array( $scenario, array( 'no_trial_no_keys', 'no_trial_has_keys' ), true ) ) {
		?>
		<div class="saiap-premium-trial-section">
			<div class="saiap-premium-trial-section__content">
				<h2><?php esc_html_e( 'Try ClearPost Premium Free for 7 Days', 'clearpost-simple-ai-auto-post' ); ?></h2>
				<p><?php esc_html_e( 'Experience the full power of automated SEO-driven publishing. No credit card required.', 'clearpost-simple-ai-auto-post' ); ?></p>
				<button type="button" class="button button-primary button-hero saiap-start-trial-btn">
					<?php esc_html_e( 'Start Free Trial', 'clearpost-simple-ai-auto-post' ); ?>
				</button>
			</div>
		</div>
		<hr class="saiap-divider" />
		<p class="saiap-premium-or-text"><?php esc_html_e( 'Already have a license key?', 'clearpost-simple-ai-auto-post' ); ?></p>
		<?php
	} elseif ( 'active_trial' === $scenario ) {
		$days_remaining = saiap_get_trial_days_remaining();
		$total_days     = saiap_get_trial_total_days();
		$current_day    = max( 1, $total_days - $days_remaining + 1 );
		?>
		<div class="saiap-premium-trial-active">
			<div class="saiap-premium-trial-active__content">
				<span class="saiap-premium-trial-active__badge">
					<?php
					printf(
						/* translators: %1$d: current day, %2$d: total days */
						esc_html__( 'Trial: Day %1$d of %2$d', 'clearpost-simple-ai-auto-post' ),
						absint( $current_day ),
						absint( $total_days )
					);
					?>
				</span>
				<h3><?php esc_html_e( 'Enjoying ClearPost? Subscribe to continue after your trial ends.', 'clearpost-simple-ai-auto-post' ); ?></h3>
				<a href="<?php echo esc_url( saiap_get_checkout_url() ); ?>" class="button button-primary" target="_blank">
					<?php esc_html_e( 'Subscribe Now', 'clearpost-simple-ai-auto-post' ); ?>
				</a>
			</div>
		</div>
		<hr class="saiap-divider" />
		<?php
	}

	?>
	<?php if ( empty( $license_key ) ) : ?>
	<div class="container">
		<div class="card">
			<h3 class="spacing-16-row"><?php esc_html_e( 'Grow organic traffic on autopilot', 'clearpost-simple-ai-auto-post' ); ?></h3>
			
			<div class="row">
				<div class="col col-6">
					<p class="body-text spacing-16-row">
					<?php
						esc_html_e( 'Finally get found on Google. Get recommended by ChatGPT. Get the content engine that runs while you sleep.', 'clearpost-simple-ai-auto-post' );
					?>
					</p>
					<ul>
						<li class="body-text spacing-8-row"><?php esc_html_e( '✓ Relax while your AI content engine pumps out content that drives organic traffic to your site.', 'clearpost-simple-ai-auto-post' ); ?></li>
						<li class="body-text spacing-8-row"><?php esc_html_e( '✓ Context + SEO AI Agent deeply analyzes your site, target audience, and objectives to produce a context architecture that ensures your new posts naturally rank and sound like you.', 'clearpost-simple-ai-auto-post' ); ?></li>
						<li class="body-text spacing-8-row"><?php esc_html_e( '✓ ClearPost autonomously schedules and generates articles every day, then pings you to review and publish.', 'clearpost-simple-ai-auto-post' ); ?></li>
						<li class="body-text spacing-8-row"><?php esc_html_e( '✓ AI Chat-to-Edit: Just chat with the AI and watch it edit your posts in real time.', 'clearpost-simple-ai-auto-post' ); ?></li>						
						<li class="body-text spacing-8-row"><?php esc_html_e( '✓ Auto Google Image Search: Our AI does a Google Image search for you, and suggests images for every post.', 'clearpost-simple-ai-auto-post' ); ?></li>
						<li class="body-text spacing-8-row"><?php esc_html_e( '✓ AI that lives in your site: ClearPost is WordPress-native, and always learning and getting smarter - so your content gets better and better over time.', 'clearpost-simple-ai-auto-post' ); ?></li>
						<li class="body-text spacing-8-row"><?php esc_html_e( '✓ Premium support', 'clearpost-simple-ai-auto-post' ); ?></li>
					</ul>
				</div>
				<div class="col col-6">
					<div style="background: var(--surface-secondary); padding: 16px; border-left: 4px solid var(--primary-color);">
						<h4><?php esc_html_e( 'What\'s blocking you now:', 'clearpost-simple-ai-auto-post' ); ?></h4>
						<ul style="margin: 8px 0 16px 20px;">
							<li class="small-text"><?php esc_html_e( 'Drafts stay unfinished because you\'re running the whole site.', 'clearpost-simple-ai-auto-post' ); ?></li>
							<li class="small-text"><?php esc_html_e( 'A couple of posts a month can\'t outrank sites that publish daily.', 'clearpost-simple-ai-auto-post' ); ?></li>
							<li class="small-text"><?php esc_html_e( 'Freelancers cost more than the revenue you\'re trying to earn.', 'clearpost-simple-ai-auto-post' ); ?></li>
						</ul>
						
						<p class="small-text" style="margin: 16px 0 8px 0;">
							<?php esc_html_e( 'Imagine the impact on your business when you start publishing great content every single day.', 'clearpost-simple-ai-auto-post' ); ?>
						</p>
						
						<h4><?php esc_html_e( 'Picture your analytics one month from now:', 'clearpost-simple-ai-auto-post' ); ?></h4>
						<ul style="margin: 8px 0 16px 20px;">
							<li class="small-text"><?php esc_html_e( 'A fresh article goes live every single day.', 'clearpost-simple-ai-auto-post' ); ?></li>
							<li class="small-text"><?php esc_html_e( 'Search impressions climb, clicks follow, conversions roll in.', 'clearpost-simple-ai-auto-post' ); ?></li>
							<li class="small-text"><?php esc_html_e( 'Competitors wonder how you suddenly outpace their content teams.', 'clearpost-simple-ai-auto-post' ); ?></li>
						</ul>
						
						<p class="small-text" style="margin: 0; font-weight: 600;">
							<?php esc_html_e( 'That starts now.', 'clearpost-simple-ai-auto-post' ); ?>
						</p>
					</div>
								
					<div class="spacing-24">
						<a href="https://clearpostplugin.com/" target="_blank" class="primary-button" style="display: inline-block; text-decoration: none;">
							<?php esc_html_e( 'Grow organic traffic on autopilot', 'clearpost-simple-ai-auto-post' ); ?>
						</a>
					</div>
				</div>
			</div>

		</div>
	</div>
	<?php endif; ?>
	<div class="container">
		<div class="card">
			<div class="col col-6">
				<h3 class="spacing-16-row"><?php esc_html_e( 'License Management', 'clearpost-simple-ai-auto-post' ); ?></h3>
				
				<form id="saiap-license-form" method="post">
					<?php saiap_render_nonce_field(); ?>
					<?php wp_nonce_field( 'saiap_save_license_action', 'saiap_license_form_nonce' ); ?>
					
					<div class="spacing-16-row">
						<label for="saiap-license-key" class="body-text"><?php esc_html_e( 'License Key:', 'clearpost-simple-ai-auto-post' ); ?></label>
						<input type="text" id="saiap-license-key" name="license_key" class="regular-text" value="<?php echo esc_attr( $license_key ); ?>" 
						<?php
						if ( !empty( $license_key ) ) {
							echo 'readonly';}
						?>
						>
					</div>
					
					<div class="spacing-16-row">
						<?php if ( !empty( $license_key ) ) : ?>
							<p class="small-text" style="color: var(--success-color);">
								<?php esc_html_e( 'License key saved.', 'clearpost-simple-ai-auto-post' ); ?>
							</p>
						<?php else : ?>
							<p class="small-text" style="color: var(--text-secondary);">
								<?php esc_html_e( 'Enter your license key to activate premium features.', 'clearpost-simple-ai-auto-post' ); ?>
							</p>
						<?php endif; ?>
					</div>
					
					<div class="spacing-24">
						<?php if ( !empty( $license_key ) ) : ?>
							<button type="submit" name="saiap_clear_license" class="secondary-button" id="saiap-clear-license">
								<?php esc_html_e( 'Clear License Key', 'clearpost-simple-ai-auto-post' ); ?>
							</button>
						<?php else : ?>
							<button type="submit" name="saiap_activate_license" class="primary-button" id="saiap-activate-license">
								<?php esc_html_e( 'Save License Key', 'clearpost-simple-ai-auto-post' ); ?>
							</button>
						<?php endif; ?>
					</div>
				</form>
				
				<?php if ( !empty( $license_key ) ) : ?>
					<div class="spacing-16" style="background: var(--surface-secondary); padding: 16px; border-left: 4px solid var(--text-secondary);">
						<p class="small-text" style="margin: 0;">
							<?php esc_html_e( 'To cancel your subscription, please email ', 'clearpost-simple-ai-auto-post' ); ?>
							<a href="mailto:support@clearpostplugin.com">support@clearpostplugin.com</a>
						</p>
					</div>
				<?php endif; ?>
			</div>
		</div>
	</div>
	<?php
}

/**
 * Generate content using premium API
 *
 * @param array  $request_data The request data including model, messages, etc.
 * @param string $provider The AI provider (openai, anthropic, or gemini)
 * @return array Generated content response from premium API
 * @throws Exception If the API request fails or returns an error
 */
function saiap_generate_premium_content( $request_data, $provider = 'openai' ) {
	$license_key = get_option( 'saiap_license_key' );
	$domain      = saiap_get_server_host();

	$response = wp_remote_post(
		SAIAP_PREMIUM_API_URL . '/api/generate',
		array(
			'headers' => array(
				'Content-Type' => 'application/json',
			),
			'body'    => wp_json_encode(
				array_merge(
					$request_data,
					array(
						'license_key' => $license_key,
						'domain'      => $domain,
						'provider'    => $provider,
					)
				)
			),
			'timeout' => 360,
		)
	);

	if ( is_wp_error( $response ) ) {
		throw new Exception( esc_html( $response->get_error_message() ) );
	}

	$body = wp_remote_retrieve_body( $response );
	$data = json_decode( $body, true );

	if ( ! $data || isset( $data['error'] ) ) {
		throw new Exception( isset( $data['error'] ) ? esc_html( $data['error'] ) : 'Invalid response from premium API' );
	}

	if ( function_exists( 'saiap_premium_onboarding_mark_step_complete' ) ) {
		saiap_premium_onboarding_mark_step_complete( 2 );
	}

	return $data;
}
