<?php
/**
 * Analytics
 *
 * This file contains all analytics functionality.
 *
 * @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;
}

/**
 * Enqueue the script for the privacy settings
 */
function saiap_enqueue_privacy_settings_script() {
	wp_enqueue_script( 'saiap-admin-js', plugin_dir_url( dirname( __FILE__ ) ) . 'assets/js/admin.js', array( 'jquery' ), '1.0.0', true );
}

/**
 * Enqueue the script for the admin notice
 */
function saiap_enqueue_admin_notice_script() {
	wp_enqueue_script( 'saiap-admin-js', plugin_dir_url( dirname( __FILE__ ) ) . 'assets/js/admin.js', array( 'jquery' ), '1.0.0', true );
}

/**
 * Track analytics events via premium service proxy
 */
function saiap_track_event( $event_name, $event_params = array() ) {
	// Default to NO tracking unless explicitly consented
	if ( get_option( 'saiap_tracking_consent' ) !== 'yes' ) {
		return;
	}

	$premium_service_url = 'https://saiap.gopurposego.com/api/analytics/track';

	$license_key = get_option( 'saiap_license_key', '' );

	$domain = saiap_get_server_host();

	// Simple client ID - site URL hash
	$client_id = md5( get_site_url() );

	// Build payload
	$payload = array(
		'license_key'    => $license_key,
		'domain'         => $domain,
		'client_id'      => $client_id,
		'event_name'     => $event_name,
		'event_params'   => $event_params,
		'plugin_version' => SAIAP_VERSION,
	);

	// Fire and forget to the premium service
	wp_remote_post(
		$premium_service_url,
		array(
			'body'     => wp_json_encode( $payload ),
			'headers'  => array(
				'Content-Type' => 'application/json',
			),
			'timeout'  => 2,
			'blocking' => false,
		)
	);
}

/**
 * Display admin notices for tracking consent.
 *
 * Note: On the plugin page (?page=saiap), tracking consent is handled by
 * the unified onboarding flow (shown after trial start or first API key save).
 * This notice only shows on OTHER admin pages as a fallback.
 */
function saiap_admin_notices() {
	// Only show if user hasn't made a choice yet.
	if ( get_option( 'saiap_tracking_consent', null ) !== null ) {
		return;
	}

	// Don't show this notice on the plugin page - unified onboarding handles it there.
	// phpcs:ignore WordPress.Security.NonceVerification.Recommended
	if ( isset( $_GET['page'] ) && 'saiap' === $_GET['page'] ) {
		return;
	}

	// Only show if the transient is set (first week after install).
	if ( ! get_transient( 'saiap_show_tracking_notice' ) ) {
		return;
	}

	$screen = get_current_screen();
	if ( ! $screen || strpos( $screen->id, 'saiap' ) === false ) {
		return;
	}

	?>
	<div class="notice notice-info" id="saiap-tracking-notice" style="padding: 12px;">
		<h3 style="margin-top: 0;">
			<?php esc_html_e( 'Help improve ClearPost Simple AI Auto Post', 'clearpost-simple-ai-auto-post' ); ?>
		</h3>
		<p>
			<?php esc_html_e( 'We would like to collect anonymous usage data to understand how the plugin is used and improve your experience. This data helps us make the plugin better for everyone.', 'clearpost-simple-ai-auto-post' ); ?>
		</p>
		<p>
			<strong><?php esc_html_e( 'What we collect:', 'clearpost-simple-ai-auto-post' ); ?></strong><br>
			<?php esc_html_e( '• Anonymous usage statistics (features used, settings chosen)', 'clearpost-simple-ai-auto-post' ); ?><br>
			<?php esc_html_e( '• No personal information or content is ever collected', 'clearpost-simple-ai-auto-post' ); ?><br>
			<?php esc_html_e( '• You can change this setting at any time', 'clearpost-simple-ai-auto-post' ); ?>
		</p>
		<p>
			<button class="button button-primary" id="saiap-tracking-allow" style="margin-right: 10px;">
				<?php esc_html_e( 'Allow anonymous tracking', 'clearpost-simple-ai-auto-post' ); ?>
			</button>
			<button class="button button-secondary" id="saiap-tracking-deny">
				<?php esc_html_e( 'Do not track', 'clearpost-simple-ai-auto-post' ); ?>
			</button>
		</p>
	</div>
	<?php
	saiap_enqueue_admin_notice_script();
}
add_action( 'admin_notices', 'saiap_admin_notices' );

/**
 * Check if we should show the tracking consent prompt.
 *
 * This is shown after the user's first commitment action:
 * - Trial path: After starting trial (on Site Context page)
 * - API keys path: After saving first API key (on AI Settings page)
 *
 * @return bool Whether to show the prompt.
 */
function saiap_should_show_tracking_consent_prompt() {
	// Already made a choice? Don't show.
	if ( get_option( 'saiap_tracking_consent', null ) !== null ) {
		return false;
	}

	// Already shown the prompt? Don't show again.
	if ( get_option( 'saiap_tracking_prompt_shown', false ) ) {
		return false;
	}

	return true;
}

/**
 * Render the tracking consent prompt (unified onboarding version).
 *
 * This is a cleaner, more compact prompt shown after the user's first commitment.
 */
function saiap_render_tracking_consent_prompt() {
	if ( ! saiap_should_show_tracking_consent_prompt() ) {
		return;
	}

	// Note: We do NOT mark as shown here. The flag is set in the AJAX handler
	// when the user actually clicks a button, so the prompt reappears on refresh
	// until they make a choice.
	?>
	<div class="notice notice-info saiap-tracking-consent-prompt is-dismissible" id="saiap-tracking-consent-prompt">
		<div class="saiap-tracking-consent-prompt__content">
			<span class="dashicons dashicons-chart-bar saiap-tracking-consent-prompt__icon"></span>
			<div class="saiap-tracking-consent-prompt__text">
				<strong><?php esc_html_e( 'Help improve ClearPost?', 'clearpost-simple-ai-auto-post' ); ?></strong>
				<span><?php esc_html_e( 'Share anonymous usage data to help us make the plugin better. No personal information collected.', 'clearpost-simple-ai-auto-post' ); ?></span>
			</div>
			<div class="saiap-tracking-consent-prompt__actions">
				<button type="button" class="button button-primary" id="saiap-tracking-prompt-allow">
					<?php esc_html_e( 'Yes, I\'ll help', 'clearpost-simple-ai-auto-post' ); ?>
				</button>
				<button type="button" class="button button-secondary" id="saiap-tracking-prompt-deny">
					<?php esc_html_e( 'No thanks', 'clearpost-simple-ai-auto-post' ); ?>
				</button>
			</div>
		</div>
	</div>
	<?php
}

/**
 * AJAX handler for tracking consent prompt responses.
 */
function saiap_ajax_tracking_consent_prompt() {
	check_ajax_referer( 'saiap_admin_nonce', 'nonce' );

	if ( ! current_user_can( 'manage_options' ) ) {
		wp_send_json_error( array( 'message' => 'Unauthorized' ), 403 );
	}

	$consent = isset( $_POST['consent'] ) && 'allow' === $_POST['consent'] ? 'allowed' : 'denied';
	update_option( 'saiap_tracking_consent', $consent );

	// Mark as shown so the prompt doesn't reappear after user makes a choice.
	update_option( 'saiap_tracking_prompt_shown', true );

	wp_send_json_success( array( 'consent' => $consent ) );
}
add_action( 'wp_ajax_saiap_tracking_consent_prompt', 'saiap_ajax_tracking_consent_prompt' );

/**
 * Track post generation
 */
function saiap_track_post_generation( $provider, $model, $post_type, $custom_fields ) {
	saiap_track_event(
		'post_generated',
		array(
			'ai_provider'       => $provider,
			'model'             => $model,
			'post_type'         => $post_type,
			'has_custom_fields' => ! empty( $custom_fields ) ? 'yes' : 'no',
		)
	);
}

/**
 * Track when AI-generated posts are published
 */
function saiap_track_post_published( $new_status, $old_status, $post ) {
	// Only track if transitioning to publish
	if ( $new_status !== 'publish' || $old_status === 'publish' ) {
		return;
	}

	// Check if this post was AI-generated by looking for prompt history
	global $wpdb;
	$prompt_exists = $wpdb->get_var(
		$wpdb->prepare(
			"SELECT COUNT(*) FROM {$wpdb->prefix}saiap_prompt_posts WHERE post_id = %d",
			$post->ID
		)
	);

	if ( $prompt_exists ) {
		// Get the prompt details for additional context
		$prompt_data = $wpdb->get_row(
			$wpdb->prepare(
				"SELECT p.model, p.created_at 
             FROM {$wpdb->prefix}saiap_prompts p
             JOIN {$wpdb->prefix}saiap_prompt_posts pp ON p.id = pp.prompt_id
             WHERE pp.post_id = %d
             ORDER BY p.created_at DESC
             LIMIT 1",
				$post->ID
			)
		);

		// Calculate time from generation to publish
		$time_to_publish = 0;
		if ( $prompt_data && $prompt_data->created_at ) {
			$generated_time  = strtotime( $prompt_data->created_at );
			$published_time  = strtotime( $post->post_date );
			$time_to_publish = round( ( $published_time - $generated_time ) / 60 ); // in minutes
		}

		saiap_track_event(
			'ai_post_published',
			array(
				'post_type'               => $post->post_type,
				'time_to_publish_minutes' => $time_to_publish,
				'model'                   => $prompt_data ? $prompt_data->model : 'unknown',
			)
		);
	}
}
add_action( 'transition_post_status', 'saiap_track_post_published', 10, 3 );

/**
 * Handle tracking preference AJAX
 */
function saiap_set_tracking_preference() {
	check_ajax_referer( 'saiap_tracking_pref', 'nonce' );
	$preference = isset( $_POST['preference'] ) ? sanitize_text_field( wp_unslash( $_POST['preference'] ) ) : '';
	if ( $preference === 'allow' ) {
		update_option( 'saiap_tracking_consent', 'yes' );
		// Send the delayed activation event
		$activation_data = get_option( 'saiap_activation_data' );
		if ( $activation_data ) {
			saiap_track_event(
				'plugin_activated',
				array(
					'version'               => $activation_data['version'],
					'is_new'                => $activation_data['is_new'],
					'consent_delay_minutes' => round( ( current_time( 'timestamp' ) - $activation_data['time'] ) / 60 ),
				)
			);
			// Clear the stored activation data
			delete_option( 'saiap_activation_data' );
		}
	} else {
		update_option( 'saiap_tracking_consent', 'no' );
	}
	// Remove the notice transient
	delete_transient( 'saiap_show_tracking_notice' );

	wp_send_json_success( array( 'preference' => $preference ) );
}
add_action( 'wp_ajax_saiap_set_tracking_preference', 'saiap_set_tracking_preference' );


/**
 * AJAX handler for saving privacy settings
 */
function saiap_save_privacy_settings() {
	// Check nonce
	if ( ! isset( $_POST['saiap_privacy_nonce'] ) || ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['saiap_privacy_nonce'] ) ), 'saiap_save_privacy_action' ) ) {
		wp_send_json_error( 'Security check failed' );
		return;
	}

	// Check user capabilities
	if ( ! current_user_can( 'manage_options' ) ) {
		wp_send_json_error( 'Insufficient permissions' );
		return;
	}

	// Handle tracking preference
	if ( isset( $_POST['saiap_tracking_consent'] ) ) {
		$consent     = sanitize_text_field( wp_unslash( $_POST['saiap_tracking_consent'] ) );
		$old_consent = get_option( 'saiap_tracking_consent' );

		// If changing from no/null to yes, send activation event if we have stored data
		if ( $consent === 'yes' && $old_consent !== 'yes' ) {
			$activation_data = get_option( 'saiap_activation_data' );
			if ( $activation_data ) {
				saiap_track_event(
					'plugin_activated',
					array(
						'version'               => $activation_data['version'],
						'is_new'                => $activation_data['is_new'],
						'consent_delay_minutes' => round( ( current_time( 'timestamp' ) - $activation_data['time'] ) / 60 ),
					)
				);
				delete_option( 'saiap_activation_data' );
			}
		}

		update_option( 'saiap_tracking_consent', $consent );
	}

	wp_send_json_success(
		array(
			'message' => __( 'Privacy settings saved successfully!', 'clearpost-simple-ai-auto-post' ),
		)
	);
}
add_action( 'wp_ajax_saiap_save_privacy_settings', 'saiap_save_privacy_settings' );

/**
 * AJAX handler for tracking upgrade button clicks
 */
function saiap_track_upgrade_click() {
	check_ajax_referer( 'wp_rest', 'nonce' );
	saiap_track_event( 'upgrade_button_clicked' );
	wp_send_json_success( array( 'tracked' => true ) );
}
add_action( 'wp_ajax_saiap_track_upgrade_click', 'saiap_track_upgrade_click' );

/**
 * Render privacy settings
 */
function saiap_render_privacy_settings() {
	?>
	<!-- Privacy Settings Section -->
	<div class="container">
		<div class="col col-12">
			<div class="card">
				<h2 class="spacing-16-row"><?php esc_html_e( 'Privacy Settings', 'clearpost-simple-ai-auto-post' ); ?></h2>
				<p class="body-text spacing-16-row">
					<?php esc_html_e( 'Control how ClearPost Simple AI Auto Post collects anonymous usage data.', 'clearpost-simple-ai-auto-post' ); ?>
				</p>
				
				<form id="saiap-privacy-settings-form" method="post">
					<?php wp_nonce_field( 'saiap_save_privacy_action', 'saiap_privacy_nonce' ); ?>
					
					<div class="spacing-16-row">
						<label class="body-text spacing-8-row"><?php esc_html_e( 'Usage Tracking:', 'clearpost-simple-ai-auto-post' ); ?></label>
						<div class="saiap-radio-group spacing-8-row">
							<label class="saiap-radio-option">
								<input type="radio" 
										name="saiap_tracking_consent" 
										value="yes" 
										<?php checked( get_option( 'saiap_tracking_consent' ), 'yes' ); ?>>
								<span class="body-text"><?php esc_html_e( 'Allow anonymous usage tracking', 'clearpost-simple-ai-auto-post' ); ?></span>
							</label>
							<label class="saiap-radio-option">
								<input type="radio" 
										name="saiap_tracking_consent" 
										value="no" 
										<?php checked( get_option( 'saiap_tracking_consent' ), 'no' ); ?>>
								<span class="body-text"><?php esc_html_e( 'Do not track', 'clearpost-simple-ai-auto-post' ); ?></span>
							</label>
						</div>
						<p class="small-text">
							<?php esc_html_e( 'We collect anonymous data about feature usage to improve the plugin. No personal information is ever collected. You can change this setting at any time.', 'clearpost-simple-ai-auto-post' ); ?>
						</p>
					</div>
					
					<div class="spacing-24 text-align-center">
						<button type="button" id="saiap-save-privacy" class="primary-button" onclick="savePrivacySettings()">
							<?php esc_html_e( 'Save Privacy Settings', 'clearpost-simple-ai-auto-post' ); ?>
						</button>
					</div>
					
					<div id="privacy-settings-message" class="spacing-16" style="display: none;"></div>
				</form>
			</div>
		</div>
	</div>
	<?php
	saiap_enqueue_privacy_settings_script();
}