<?php
/**
 * WP Ultimo Integration for SimplyConf
 * 
 * Ensures that when a new site is created via WP Ultimo,
 * a default event is automatically created for the user.
 * 
 * @package SimplyConf
 * @since 1.0.0
 */

// Exit if accessed directly
if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

/**
 * Hook into WP Ultimo site creation
 * 
 * WP Ultimo fires this action after a new site is created and activated.
 * We use it to create a default event for the new site.
 */
add_action( 'wu_site_post_create', 'simplyconf_create_event_for_new_ultimo_site', 10, 2 );

/**
 * Create default event when WP Ultimo creates a new site
 *
 * @param int   $site_id The ID of the newly created site
 * @param array $site_data Additional site data from WP Ultimo
 */
function simplyconf_create_event_for_new_ultimo_site( $site_id, $site_data ) {
	// Switch to the new site context
	switch_to_blog( $site_id );
	
	// Check if SimplyConf is active on this site
	if ( ! function_exists( 'simplyconf_create_default_event' ) ) {
		restore_current_blog();
		return;
	}
	
	// Create the default event
	simplyconf_create_default_event();
	
	if ( defined( 'WP_DEBUG' ) && WP_DEBUG ) {
		error_log( sprintf(
			'SimplyConf: Created default event for new SimplyConf site #%d',
			$site_id
		) );
	}
	
	// Switch back to the main site
	restore_current_blog();
}

/**
 * Alternative hook for older WP Ultimo versions
 * 
 * Some versions of WP Ultimo use different hook names.
 * This ensures compatibility.
 */
add_action( 'wpultimo_registration_completed', 'simplyconf_create_event_on_ultimo_registration', 10, 3 );

/**
 * Create event when registration is completed (alternative hook)
 *
 * @param int    $user_id User ID
 * @param object $subscription Subscription object
 * @param int    $site_id Site ID
 */
function simplyconf_create_event_on_ultimo_registration( $user_id, $subscription, $site_id ) {
	if ( empty( $site_id ) ) {
		return;
	}
	
	// Switch to the new site
	switch_to_blog( $site_id );
	
	// Check if SimplyConf is active
	if ( function_exists( 'simplyconf_create_default_event' ) ) {
		simplyconf_create_default_event();
	}
	
	// Switch back
	restore_current_blog();
}

/**
 * Ensure event exists when user first accesses dashboard
 * 
 * This is a safety net in case the hooks above don't fire.
 * Checks on admin_init if we're in SaaS mode and creates event if missing.
 */
add_action( 'admin_init', 'simplyconf_ensure_event_exists_saas', 5 );

function simplyconf_ensure_event_exists_saas() {
	// Only run in SaaS mode
	if ( ! defined( 'SIMPLYCONF_SAAS_MODE' ) || ! SIMPLYCONF_SAAS_MODE ) {
		return;
	}
	
	// Only run once per site (use transient to prevent repeated checks)
	$checked = get_transient( 'simplyconf_event_check_done' );
	if ( $checked ) {
		return;
	}
	
	// Check if we have any events
	global $wpdb;
	$events_table = SimplyConf_DB::get_table( 'events' );
	$event_count  = $wpdb->get_var( "SELECT COUNT(*) FROM $events_table" );
	
	// If no events exist, create one
	if ( $event_count == 0 ) {
		if ( function_exists( 'simplyconf_create_default_event' ) ) {
			simplyconf_create_default_event();
			
			if ( defined( 'WP_DEBUG' ) && WP_DEBUG ) {
				error_log( sprintf(
					'SimplyConf: Auto-created event for SaaS site (blog_id: %d)',
					get_current_blog_id()
				) );
			}
		}
	}
	
	// Set transient to prevent repeated checks (expires in 1 week)
	set_transient( 'simplyconf_event_check_done', true, WEEK_IN_SECONDS );
}

/**
 * Customize default event name for SaaS users
 * 
 * Makes the default event more personalized for WP Ultimo users
 */
add_filter( 'simplyconf_default_event_data', 'simplyconf_customize_saas_event_data' );

function simplyconf_customize_saas_event_data( $event_data ) {
	// Only customize in SaaS mode
	if ( ! defined( 'SIMPLYCONF_SAAS_MODE' ) || ! SIMPLYCONF_SAAS_MODE ) {
		return $event_data;
	}
	
	// Get current user info
	$current_user = wp_get_current_user();
	$site_name = get_bloginfo( 'name' );
	
	// Customize the event name
	if ( ! empty( $site_name ) && $site_name !== 'WordPress' ) {
		$event_data['name'] = $site_name . ' Conference';
	} else {
		$event_data['name'] = $current_user->display_name . "'s Conference";
	}
	
	// Update description
	$event_data['description'] = sprintf(
		'Welcome to SimplyConf! This is your first event. Start by adding tracks, configuring submission settings, and inviting reviewers.',
		$current_user->display_name
	);
	
	return $event_data;
}

/**
 * Sync feature flags when WP Ultimo plan changes
 * Hook into plan change event specifically
 */
add_action( 'wu_membership_plan_changed', 'simplyconf_sync_features_on_plan_change', 10, 3 );
function simplyconf_sync_features_on_plan_change( $membership, $old_plan_id, $new_plan_id ) {
	if ( ! class_exists( 'SimplyConf_Feature_Manager' ) ) {
		return;
	}
	
	// Get site ID from membership
	$site_id = $membership->get_site_id();
	if ( ! $site_id ) {
		return;
	}
	
	$manager = SimplyConf_Feature_Manager::instance();
	$manager->sync_saas_features( $site_id );
	
	if ( defined( 'WP_DEBUG' ) && WP_DEBUG ) {
		error_log( sprintf(
			'SimplyConf: Synced features for site #%d (plan changed from %d to %d)',
			$site_id,
			$old_plan_id,
			$new_plan_id
		) );
	}
}

/**
 * Sync feature flags when membership status changes to active
 * This handles new signups and reactivations
 */
add_action( 'wu_membership_status_changed', 'simplyconf_sync_features_on_status_change', 10, 3 );
function simplyconf_sync_features_on_status_change( $membership, $old_status, $new_status ) {
	if ( ! class_exists( 'SimplyConf_Feature_Manager' ) ) {
		return;
	}
	
	// Only sync when becoming active
	if ( $new_status !== 'active' ) {
		return;
	}
	
	$site_id = $membership->get_site_id();
	if ( ! $site_id ) {
		return;
	}
	
	$manager = SimplyConf_Feature_Manager::instance();
	$manager->sync_saas_features( $site_id );
	
	if ( defined( 'WP_DEBUG' ) && WP_DEBUG ) {
		error_log( sprintf(
			'SimplyConf: Synced features for site #%d (status changed to active)',
			$site_id
		) );
	}
}

/**
 * Sync feature flags when new site is created
 * 
 * @param object $site Site object
 */
add_action( 'wu_site_created', 'simplyconf_sync_features_on_site_creation', 10, 1 );
function simplyconf_sync_features_on_site_creation( $site ) {
	if ( ! class_exists( 'SimplyConf_Feature_Manager' ) ) {
		return;
	}
	
	$manager = SimplyConf_Feature_Manager::instance();
	$manager->sync_saas_features( $site->get_id() );
	
	if ( defined( 'WP_DEBUG' ) && WP_DEBUG ) {
		error_log( sprintf(
			'SimplyConf: Synced features for new site #%d',
			$site->get_id()
		) );
	}
}

/**
 * Revoke features when subscription expires
 * 
 * @param int $site_id Site ID
 */
add_action( 'wu_subscription_expired', 'simplyconf_revoke_features_on_expiry', 10, 1 );
function simplyconf_revoke_features_on_expiry( $site_id ) {
	if ( ! class_exists( 'SimplyConf_Feature_Manager' ) ) {
		return;
	}
	
	$manager = SimplyConf_Feature_Manager::instance();
	$all_features = SimplyConf_Feature_Registry::get_all_features();
	
	foreach ( $all_features as $slug => $data ) {
		$manager->revoke_feature( $site_id, $slug );
	}
	
	if ( defined( 'WP_DEBUG' ) && WP_DEBUG ) {
		error_log( sprintf(
			'SimplyConf: Revoked all features for site #%d (subscription expired)',
			$site_id
		) );
	}
}

/**
 * Sync features when subscription is activated/reactivated
 * 
 * @param int $site_id Site ID
 */
add_action( 'wu_subscription_activated', 'simplyconf_sync_features_on_activation', 10, 1 );
function simplyconf_sync_features_on_activation( $site_id ) {
	if ( ! class_exists( 'SimplyConf_Feature_Manager' ) ) {
		return;
	}
	
	$manager = SimplyConf_Feature_Manager::instance();
	$manager->sync_saas_features( $site_id );
	
	if ( defined( 'WP_DEBUG' ) && WP_DEBUG ) {
		error_log( sprintf(
			'SimplyConf: Synced features for site #%d (subscription activated)',
			$site_id
		) );
	}
}
