<?php
// Prevent direct access
if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

// Real opt-in connect: send the same fields Freemius collected to Supabase.
lean_csns_fs()->add_action( 'after_account_connection', function ( $fs_user, $fs_install ) {
	lean_csns_send_diagnostic_data( array(
		'site_uid'       => md5( 'fs_install_' . $fs_install->id ),
		'site_url'       => $fs_install->url,
		'site_title'     => $fs_install->title,
		'plugin_version' => $fs_install->version,
		'wp_version'     => $fs_install->platform_version,
		'php_version'    => $fs_install->programming_language_version,
		'language'       => $fs_install->language,
		'first_name'     => $fs_user->first,
		'last_name'      => $fs_user->last,
	) );
}, 10, 2 );

add_action( 'admin_init', function () {
	static $notified = false;
	if ( $notified || ! function_exists( 'lean_csns_fs' ) ) {
		return;
	}

	$already_flagged = get_option( 'lean_csns_freemius_skip_seen' );
	if ( lean_csns_fs()->is_anonymous() && ! $already_flagged ) {
		update_option( 'lean_csns_freemius_skip_seen', 1 );
		$notified = true;
	}
}, 20 );

lean_csns_fs()->add_action( 'before_admin_menu_init', function () {
	if ( empty( $_GET['pending_activation'] ) || ! fs_request_is_action( lean_csns_fs()->get_unique_affix() . '_activate_new' ) ) {
		return;
	}
	$wp_user = wp_get_current_user();
	lean_csns_send_diagnostic_data( array(
		'site_uid'       => md5( 'site_' . home_url() ),
		'site_url'       => home_url(),
		'site_title'     => get_bloginfo( 'name' ),
		'wp_version'     => get_bloginfo( 'version' ),
		'php_version'    => phpversion(),
		'language'       => get_locale(),
		'first_name'     => $wp_user->first_name,
		'last_name'      => $wp_user->last_name,
	) );
} );

if ( ! function_exists( 'lean_csns_send_diagnostic_data' ) ) {
	function lean_csns_send_diagnostic_data( array $fields ) {
		$fields = wp_parse_args( $fields, array(
			'plugin_slug'     => 'lean-cart-share-and-save',
			'plugin_version'  => defined( 'LEAN_CSNS_VERSION' ) ? LEAN_CSNS_VERSION : null,
			'additional_data' => array(), // NOT NULL column, empty array = "nothing collected"
		) );

		wp_remote_post( 'https://qqcwdsrfytuefaoitiqn.supabase.co/rest/v1/diagnostic_data', array(
			'headers'  => array(
				'Content-Type'  => 'application/json',
				'apikey'        => 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6InFxY3dkc3JmeXR1ZWZhb2l0aXFuIiwicm9sZSI6ImFub24iLCJpYXQiOjE3NjE5ODAxNDAsImV4cCI6MjA3NzU1NjE0MH0.aiJyKVXWdhnsnV2oHAX0940_TZ6YTd5d3P_w6GXV0m4',
				'Authorization' => 'Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6InFxY3dkc3JmeXR1ZWZhb2l0aXFuIiwicm9sZSI6ImFub24iLCJpYXQiOjE3NjE5ODAxNDAsImV4cCI6MjA3NzU1NjE0MH0.aiJyKVXWdhnsnV2oHAX0940_TZ6YTd5d3P_w6GXV0m4',
				'Prefer'        => 'return=minimal',
			),
			'body'     => wp_json_encode( $fields ),
			'timeout'  => 5,
			'blocking' => false, // fire-and-forget, don't slow down the redirect
		) );
	}
}
