<?php

if ( ! class_exists( 'ES_Dashboard_Controller' ) ) {

	/**
	 * Class to handle dashboard operation
	 * 
	 * @class ES_Dashboard_Controller
	 */
	class ES_Dashboard_Controller {

		public static $instance;
		public static $api_instance = null;

		public function __construct() {
			$this->init();
		}

		public static function get_instance() {
			if ( ! isset( self::$instance ) ) {
				self::$instance = new self();
			}

			return self::$instance;
		}

		public function init() {
			$this->register_hooks();
		}

		public function register_hooks() {
		}

		public static function get_subscribers_stats( $data = array() ) {
		
			if ( is_string( $data ) ) {
				$decoded_data = json_decode( $data, true );
				if ( $decoded_data ) {
					$data = $decoded_data;
				}
			} 
		
			$page           = '';
			$days           = '';
			$list_id        = '';
			$override_cache = false; 
		
			if ( isset( $data['page'] ) || isset( $data['days'] ) || isset( $data['list_id'] ) ) {
				$page           = isset( $data['page'] ) ? $data['page'] : 'dashboard';
				$days           = isset( $data['days'] ) ? $data['days'] : '';
				$list_id        = isset( $data['list_id'] ) ? $data['list_id'] : '';
				$override_cache = isset( $data['override_cache'] ) ? $data['override_cache'] : false; 
			} 
		
			if ( empty( $days ) || ! is_numeric( $days ) ) {
				$days = 7;
			} else {
				$days = intval( $days );
				if ( $days < 1 || $days > 365 ) {
					$days = 7;
				}
			} 

			if ( $list_id === 'all' ) {
				$list_id = 0;
			} elseif ( ! empty( $list_id ) && ! is_numeric( $list_id ) ) {
				$list_id = '';
			} elseif ( ! empty( $list_id ) ) {
				$list_id = intval( $list_id );
			}
			// If $list_id is empty, leave it as empty string (default behavior)
 
			$reports_args = array(
			'list_id' => $list_id,
			'days'    => $days,
			);
		
			// Get enhanced audience insights data
			$enhanced_data = ES_Reports_Data::get_audience_insights_data( $reports_args );
		
			// Default to 'dashboard' page if not set
			if ( empty( $page ) ) {
				$page = 'dashboard';
			}
		
			// Get basic dashboard reports data and merge with enhanced data
			$reports_data = ES_Reports_Data::get_dashboard_reports_data( $page, $override_cache, $reports_args );
		
			return array_merge( $reports_data, $enhanced_data );
		}		
	
		public static function get_dashboard_data( $args ) {
			$dashboard_kpi = ES_Reports_Data::get_dashboard_reports_data( 'dashboard', false, $args );
			
			$campaign_args = array(
				'status'          => array(
					IG_ES_CAMPAIGN_STATUS_IN_ACTIVE,
					
					IG_ES_CAMPAIGN_STATUS_ACTIVE,
				),
				'order_by_column' => 'ID',
				'limit'           => '5',
				'order'           => 'DESC',
			);
			$campaigns = ES()->campaigns_db->get_campaigns( $campaign_args );
			
			$audience_activity = self::get_audience_activities();
		
			$forms_args = array(
				'order_by_column' => 'ID',
				'limit'           => '5',
				'order'           => 'DESC',
			);
			$forms = ES()->forms_db->get_forms( $forms_args );

			if ( ! empty( $forms ) && is_array( $forms ) ) {
				$form_ids = array_column( $forms, 'id' );
				$form_ids = array_filter( $form_ids, 'is_numeric' );
			
				if ( ! empty( $form_ids ) ) {
					$all_list_ids = array();
				
					foreach ( $forms as $form ) {
						$settings = ! empty( $form['settings'] ) ? ig_es_maybe_unserialize( $form['settings'] ) : array();
						if ( ! empty( $settings['lists'] ) ) {
							$list_ids = is_array( $settings['lists'] ) ? $settings['lists'] : array( intval( $settings['lists'] ) );
							$all_list_ids = array_merge( $all_list_ids, $list_ids );
						}
					}
					$all_list_ids = array_unique( $all_list_ids );
				
					$subscriber_counts = ES()->contacts_db->get_subscriber_counts_by_form_ids( $form_ids );
					$list_names_map = ! empty( $all_list_ids ) ? ES()->lists_db->get_list_name_by_ids( $all_list_ids ) : array();
				
					foreach ( $forms as &$form ) {
						$form_id = intval( $form['id'] );
						$form['subscriber_count'] = isset( $subscriber_counts[ $form_id ] ) ? $subscriber_counts[ $form_id ] : 0;
					
						$settings = ! empty( $form['settings'] ) ? ig_es_maybe_unserialize( $form['settings'] ) : array();
						$list_ids = ! empty( $settings['lists'] ) ? ( is_array( $settings['lists'] ) ? $settings['lists'] : array( intval( $settings['lists'] ) ) ) : array();
					
						$list_names = array();
						foreach ( $list_ids as $list_id ) {
							if ( isset( $list_names_map[ $list_id ] ) ) {
								$list_names[] = $list_names_map[ $list_id ];
							}
						}
						$form['list_names'] = implode( ', ', $list_names );
					}
				}
			}

			$lists = ES()->lists_db->get_lists( array( 'order_by' => 'id', 'order' => 'DESC', 'limit' => 2 ) );
			$workflows_count = ES()->workflows_db->get_workflows_count();

			
			$onboarding_tasks_status = array(
				'sendFirstCampaign' => ! empty( $campaigns ) ? 'yes' : 'no',
				'importContacts' => ! empty( $dashboard_kpi['total_subscribers'] ) && $dashboard_kpi['total_subscribers'] > 0 ? 'yes' : 'no',
				'createSubscriptionFormDone' => ! empty( $forms ) ? 'yes' : 'no',
				'createWorkflowDone' => $workflows_count > 0 ? 'yes' : 'no'
			);
			
			$icegram_plugins = self::get_icegram_plugins_info();
			
			$plan = ES()->get_plan();
			return array(	
				'campaigns'         => $campaigns,
				'audience_activity' => $audience_activity,
				'forms'             => $forms,
				'lists'             => $lists,
				'dashboard_kpi'     => $dashboard_kpi,
				'plan'              => $plan,
				'icegram_plugins'   => $icegram_plugins,
				'onboarding_tasks_status' => $onboarding_tasks_status
			);
		}
		
		public static function create_dashboard_workflow( $data = array() ) {		
			// Get data from request if not passed directly
			if ( empty( $data ) ) {
				$data = ig_es_get_request_data( 'data', array(), false );
			}
			
			if ( is_string( $data ) ) {
				$decoded = json_decode( $data, true );
				if ( $decoded ) {
					$data = $decoded;
				}
			}
			
			$workflow_type = isset( $data['workflow_type'] ) ? sanitize_text_field( $data['workflow_type'] ) : '';
			
			
			if ('abandoned-cart-email' === $workflow_type  ||  'abandoned-cart' === $workflow_type ) {
				$is_pro = ES()->is_pro();
				$plan = ES()->get_plan();
				
				if ( ! $is_pro ) {
					return array(
						'success' => false,
						'message' => __( 'Abandoned cart email workflow requires a Pro plan. Please upgrade to access this feature.', 'email-subscribers' ),
						'action' => 'redirect_to_pricing',
						'requires_upgrade' => true,
						'current_plan' => $plan,
						'pricing_url' => admin_url( 'admin.php?page=es_pricing' ),
						'workflow_type' => $workflow_type
					);
				}
			}
			
			$workflow_gallery_map = array(
				'welcome-email' => 'welcome-email',
				'confirmation-email' => 'confirmation-email',
				'unsubscribe-email' => 'unsubscribe-email',
				'abandoned-cart-email' => 'abandoned-cart-basic-email',
				'abandoned-cart' => 'abandoned-cart-basic-email',
			);
			
			if ( empty( $workflow_type ) || ! isset( $workflow_gallery_map[ $workflow_type ] ) ) {
				return array(
					'success' => false,
					'message' => __( 'Invalid workflow type.', 'email-subscribers' )
				);
			}
			
			$gallery_item_name = $workflow_gallery_map[ $workflow_type ];
			
			// Create workflow
			$args = array( 'item_name' => $gallery_item_name );
			$workflow_id = ES_Workflows_Controller::create_workflow_from_gallery_item( $args );
			
			if ( ! $workflow_id ) {
				return array(
					'success' => false,
					'message' => __( 'Failed to create workflow. Please try again.', 'email-subscribers' )
				);
			}
			
			$workflow_id = intval( $workflow_id );
			
			$workflow_from_db = ES()->workflows_db->get_workflow( $workflow_id );
			
			if ( ! $workflow_from_db ) {
				return array(
					'success' => false,
					'message' => __( 'Workflow was not created properly.', 'email-subscribers' )
				);
			}
			
			// Ensure we have the correct ID from database
			$db_workflow_id = isset( $workflow_from_db['id'] ) ? intval( $workflow_from_db['id'] ) : $workflow_id;
			if ( $db_workflow_id !== $workflow_id ) {
				$workflow_id = $db_workflow_id;
			}
			
			$edit_url = admin_url( "admin.php?page=es_workflows&action=edit&id={$workflow_id}" );
			
			// Get workflow display name
			$workflow_names = array(
				'welcome-email' => __( 'Welcome Email', 'email-subscribers' ),
				'confirmation-email' => __( 'Confirmation Email', 'email-subscribers' ),
				'unsubscribe-email' => __( 'Unsubscribe Email', 'email-subscribers' ),
				'abandoned-cart-email' => __( 'Abandoned Cart Email', 'email-subscribers' ),
				'abandoned-cart' => __( 'Abandoned Cart Email', 'email-subscribers' ),
			);
			$workflow_display_name = isset( $workflow_names[ $workflow_type ] ) ? $workflow_names[ $workflow_type ] : __( 'Workflow', 'email-subscribers' );
			
			// Return success response
			$success_response = array(
				'success' => true,
				'workflow_id' => intval( $workflow_id ),
				'edit_url' => $edit_url,
				/* translators: %s: workflow display name */
				'message' => sprintf( __( '%s workflow created successfully!', 'email-subscribers' ), $workflow_display_name )
			);
			return $success_response;
		}
		
		public static function get_icegram_plugins_info() {
			global $ig_es_tracker;
			
			// Get the admin URL base
			$admin_url_base = admin_url();
			
			$icegram_plugins = array(
				'icegram-mailer/icegram-mailer.php' => array(
					'name' => __( 'Icegram Mailer', 'email-subscribers' ),
					'description' => __( 'Use our built-in service, Mailer, for stress-free email delivery. No SMTP, no tech setup required. Send emails that actually reach inboxes.', 'email-subscribers' ),
					'plugin_url' => 'https://wordpress.org/plugins/icegram-mailer/',
					'install_url' => $admin_url_base . 'plugin-install.php?s=icegram%2520mailer&tab=search&type=term',
					'activate_url' => wp_nonce_url( $admin_url_base . 'plugins.php?action=activate&plugin=icegram-mailer/icegram-mailer.php', 'activate-plugin_icegram-mailer/icegram-mailer.php' ),
				),
				'icegram/icegram.php' => array(
					'name' => __( 'Icegram Engage', 'email-subscribers' ),
					'description' => __( 'The best WP popup plugin that creates a popup. Customize popup, target popups to show offers, email signups, social buttons, etc and increase conversions on your website.', 'email-subscribers' ),
					'plugin_url' => 'https://wordpress.org/plugins/icegram/',
					'install_url' => $admin_url_base . 'plugin-install.php?s=icegram&tab=search&type=term',
					'activate_url' => wp_nonce_url( $admin_url_base . 'plugins.php?action=activate&plugin=icegram/icegram.php', 'activate-plugin_icegram/icegram.php' ),
				),
				'icegram-rainmaker/icegram-rainmaker.php' => array(
					'name' => __( 'Icegram Collect', 'email-subscribers' ),
					'description' => __( 'Get readymade contact forms, email subscription forms and custom forms for your website. Choose from beautiful templates and get started within seconds', 'email-subscribers' ),
					'plugin_url' => 'https://wordpress.org/plugins/icegram-rainmaker/',
					'install_url' => $admin_url_base . 'plugin-install.php?s=rainmaker&tab=search&type=term',
					'activate_url' => wp_nonce_url( $admin_url_base . 'plugins.php?action=activate&plugin=icegram-rainmaker/icegram-rainmaker.php', 'activate-plugin_icegram-rainmaker/icegram-rainmaker.php' ),
				),
			);
			
			$active_plugins = $ig_es_tracker::get_active_plugins();
			$all_plugins = $ig_es_tracker::get_plugins( 'all', true );
			
			$plugins_info = array();
			
			foreach ( $icegram_plugins as $plugin_slug => $plugin_data ) {
				$is_installed = $ig_es_tracker::is_plugin_installed( $plugin_slug );
				$is_active = $ig_es_tracker::is_plugin_activated( $plugin_slug );
				
				$plugins_info[] = array(
					'slug' => $plugin_slug,
					'name' => $plugin_data['name'],
					'description' => $plugin_data['description'],
					'plugin_url' => $plugin_data['plugin_url'],
					'is_installed' => $is_installed,
					'is_active' => $is_active,
					'install_url' => $plugin_data['install_url'],
					'activate_url' => $plugin_data['activate_url'],
					'status_text' => $is_active ? __( 'Active', 'email-subscribers' ) : ( $is_installed ? __( 'Installed', 'email-subscribers' ) : __( 'Not Installed', 'email-subscribers' ) ),
					'action_text' => $is_active ? __( 'Active', 'email-subscribers' ) : ( $is_installed ? __( 'Activate', 'email-subscribers' ) : __( 'Install', 'email-subscribers' ) ),
					'action_url' => $is_active ? '' : ( $is_installed ? $plugin_data['activate_url'] : $plugin_data['install_url'] ),
				);
			}
			
			return $plugins_info;
		}
		
		/**
	 * Get audience activity feed with recent subscribe/unsubscribe actions
	 *
	 * @return array Recent activities with caching
	 * @since 4.0.0
	 */
		public static function get_audience_activities() {
			$cache_key = 'es_audience_activities';
			$cached = ES_Cache::get_transient( $cache_key );
			if ( false !== $cached ) {
				return $cached;
			}
		
			$recent_activities_args = array(
			'limit'    => 5,
			'order_by' => 'id',
			'order'    => 'DESC',
			'type' => array(
				IG_CONTACT_SUBSCRIBE,
				IG_CONTACT_UNSUBSCRIBE
			)
			);
			$recent_actions    = ES()->actions_db->get_actions( $recent_activities_args );
			$recent_activities = self::prepare_activities_from_actions( $recent_actions );
		
			if ( ! empty( $recent_activities ) ) {
				ES_Cache::set_transient( $cache_key, $recent_activities, 5 / 60 ); // 5 minutes
			}
			return $recent_activities;
		}

		/**
	 * Prepare activity feed from raw action records
	 *
	 * @param array $actions Raw action records from database
	 * @return array Formatted activities for display
	 * @since 4.0.0
	 */
		public static function prepare_activities_from_actions( $actions ) {
			$activities = array();
			if ( $actions ) {
				$contact_ids      = array_column( $actions, 'contact_id' );
				$contact_ids      = array_filter( $contact_ids, array( 'ES_Common', 'is_positive_number' ) );
				$contacts_details = array();
				if ( ! empty( $contact_ids ) ) {
					$contact_ids      = array_map( 'intval', $contact_ids );
					$contacts_details = ES()->contacts_db->get_details_by_ids( $contact_ids );
				}
				$list_ids   = array_column( $actions, 'list_id' );
				$list_ids   = array_filter( $list_ids, array( 'ES_Common', 'is_positive_number' ) );
				$lists_name = array();
				if ( ! empty( $list_ids ) ) {
					$list_ids   = array_map( 'intval', $list_ids );
					$lists_name = ES()->lists_db->get_list_name_by_ids( $list_ids );
				}
			
				foreach ( $actions as $action ) {
					$action_type   = $action['type'];
					$contact_id    = $action['contact_id'];
					$contact_email = ! empty( $contacts_details[ $contact_id ]['email'] ) ? $contacts_details[ $contact_id ]['email'] : '';
					if ( empty( $contact_email ) ) {
						continue;
					}
					$contact_first_name = ! empty( $contacts_details[ $contact_id ]['first_name'] ) ? $contacts_details[ $contact_id ]['first_name'] : '';
					if ( ! empty( $contact_first_name ) ) {
						$contact_info_text = $contact_first_name;
						if ( !  empty( $contacts_details[ $contact_id ]['last_name'] ) ) {
							$contact_info_text .= ' ' . $contacts_details[ $contact_id ]['last_name'];
						}
					} else {
						$contact_info_text = $contact_email;
					}
					
				$contact_url = esc_url( admin_url( 'admin.php?page=es_dashboard#/audience' ) );
				$contact_info_text = '<a href="' . $contact_url . '" class="text-indigo-600" target="_blank">' . esc_html( $contact_info_text ) . '</a>';
				$action_verb       = ES()->actions->get_action_verb( $action_type );
				$action_created_at = $action['created_at'];
				$activity_time     = human_time_diff( $action_created_at, time() ) . ' ' . __( 'ago', 'email-subscribers' );
				
				$list_id         = ! empty( $action['list_id'] ) ? $action['list_id'] : 0;
				$list_name       = ! empty( $lists_name[ $list_id ] ) ? $lists_name[ $list_id ] : '';
				$list_url = esc_url( add_query_arg( array( 'page' => 'es_lists', 'action' => 'edit', 'list' => $list_id ), admin_url( 'admin.php' ) ) );
				$action_obj_name = '<a href="' . $list_url . '" target="_blank">' . esc_html( $list_name ) . '</a> ' . esc_html__( 'list', 'email-subscribers' );
					$activity_text = $contact_info_text . ' ' . $action_verb . ' ' . $action_obj_name;
					$activities[]  = array(
						'time' => $activity_time,
						'text' => $activity_text,
					);
				}
			}

			return $activities;
		}

		/**
	 * Get campaign performance KPIs (open rate, click rate, sent count)
	 *
	 * @param int $campaign_id Campaign ID
	 * @return array Campaign statistics
	 * @since 4.0.0
	 */
		public static function get_recent_campaigns_kpis( $campaign_id ) {
			$args = array(
				'campaign_id' => $campaign_id,
				'types' => array(
					IG_MESSAGE_SENT,
					IG_MESSAGE_OPEN,
					IG_LINK_CLICK
				)
			);
			$actions_count       = ES()->actions_db->get_actions_count( $args );
			$total_email_sent    = isset( $actions_count['sent'] ) ? intval( $actions_count['sent'] ) : 0;
			$total_email_opened  = isset( $actions_count['opened'] ) ? intval( $actions_count['opened'] ) : 0;
			$total_email_clicked = isset( $actions_count['clicked'] ) ? intval( $actions_count['clicked'] ) : 0;
			$open_rate  = ! empty( $total_email_sent ) ? number_format_i18n( ( ( $total_email_opened * 100 ) / $total_email_sent ), 2 ) : 0 ;
			$click_rate = ! empty( $total_email_sent ) ? number_format_i18n( ( ( $total_email_clicked * 100 ) / $total_email_sent ), 2 ) : 0;
		
			$campaign = array(
			'open_rate'  => $open_rate,
			'click_rate' => $click_rate,
			'total_email_sent' => $total_email_sent
			);

			return $campaign;
		}

	/**
	 * Save onboarding step to WordPress options
	 *
	 * @param array $data
	 * @return array
	 */
		public static function save_onboarding_step( $data = array() ) {
			if ( is_string( $data ) ) {
				$decoded_data = json_decode( $data, true );
				if ( $decoded_data ) {
					$data = $decoded_data;
				}
			}

			$step_name = isset( $data['step_name'] ) ? sanitize_text_field( $data['step_name'] ) : '';
			$value = isset( $data['value'] ) ? sanitize_text_field( $data['value'] ) : 'no';

			if ( empty( $step_name ) ) {
				return array(
					'success' => false,
					'message' => 'Step name is required'
				);
			}

			// Define valid step names
			$valid_steps = array(
				'sendFirstCampaign',
				'importContacts', 
				'createSubscriptionForm',
				'createWorkflow'
			);

			if ( ! in_array( $step_name, $valid_steps ) ) {
				return array(
					'success' => false,
					'message' => 'Invalid step name'
				);
			}

			$option_name = 'ig_es_onboarding_' . $step_name;
			$updated = update_option( $option_name, $value, false );

			return array(
				'success' => true,
				'message' => 'Onboarding step saved successfully',
				'data' => array(
					'step' => $step_name,
					'value' => $value
				)
			);
		}

		/**
	 * Get onboarding steps status - reuses data from dashboard to avoid duplicate queries
	 *
	 * @param array|null $campaigns Optional campaigns array from dashboard
	 * @param array|null $forms Optional forms array from dashboard  
	 * @param int|null $workflows_count Optional workflows count
	 * @return array Onboarding steps data
	 */
		public static function get_onboarding_steps( $campaigns = null, $forms = null, $workflows_count = null ) {
			if ( is_null( $campaigns ) ) {
				$campaign_args = array(
				'status'          => array(
					IG_ES_CAMPAIGN_STATUS_IN_ACTIVE,
					IG_ES_CAMPAIGN_STATUS_ACTIVE,
				),
				'order_by_column' => 'ID',
				'limit'           => '1',
				'order'           => 'DESC',
				);
				$campaigns = ES()->campaigns_db->get_campaigns( $campaign_args );
			}

			if ( is_null( $forms ) ) {
				$forms_args = array(
				'order_by_column' => 'ID',
				'limit'           => '1',
				'order'           => 'DESC',
				);
				$forms = ES()->forms_db->get_forms( $forms_args );
			}

			if ( is_null( $workflows_count ) ) {
				$workflows_count = ES()->workflows_db->get_workflows_count();
			}
		
			$imported_contacts_count = ES()->contacts_db->get_contacts_count_by_source( 'import' );

			return array(
			'sendFirstCampaign' => ! empty( $campaigns ),
			'importContacts' => $imported_contacts_count > 0,
			'createSubscriptionForm' => ! empty( $forms ),
			'createWorkflow' => $workflows_count > 0
			);
		}



		public static function get_audience_growth_stats( $data = array() ) {
	
			if ( is_string( $data ) ) {
				$decoded_data = json_decode( $data, true );
				if ( $decoded_data ) {
					$data = $decoded_data;
				}
			}
			
			$days = isset( $data['days'] ) ? intval( $data['days'] ) : 30;
			
			try { 
				
				$end_date = current_time( 'Y-m-d' );
				$start_date = date( 'Y-m-d', strtotime( "-{$days} days" ) );

				$contacts_db = ES()->contacts_db;
				
				$current_total = $contacts_db->get_total_contacts();
				$total_before_period = $contacts_db->get_total_subscribed_contacts_before_days( $days );
				
				$new_contacts = $current_total - $total_before_period;
				
				$subscribed_args = array(
					'days' => $days
				);
				$subscribed = ES_Reports_Data::get_total_subscribed_contacts( $subscribed_args );
				
				$non_subscribed = $new_contacts - $subscribed;
				$non_subscribed = $non_subscribed > 0 ? $non_subscribed : 0;

				$growth_stats = array(
					'new_contacts' => intval( $new_contacts ),
					'non_subscribed' => $non_subscribed > 0 ? $non_subscribed : 0,
					'subscribed' => intval( $subscribed ),
					'start_date' => $start_date,
					'end_date' => $end_date
				);
				
				return $growth_stats;
				
			} catch ( Exception $e ) {
				return array(
					'success' => false,
					'message' => 'Failed to fetch audience growth statistics: ' . $e->getMessage()
				);
			}
		}

		/**
		 * Get contact/audience dashboard batch data in a single request
		 * Used by Audience page - combines lists, stats, growth, health, and country data
		 * 
		 * @param array $data Request data containing 'days', 'list_id', 'growth_days' parameters
		 * @return array Batched audience data
		 * 
		 * @since 5.9.15
		 */
		public static function get_contact_dashboard_batch_data( $data = array() ) {
			if ( is_string( $data ) ) {
				$decoded_data = json_decode( $data, true );
				if ( $decoded_data ) {
					$data = $decoded_data;
				}
			}
			
			$days = isset( $data['days'] ) ? intval( $data['days'] ) : 7;
			$list_id = isset( $data['list_id'] ) ? $data['list_id'] : 'all';
			$growth_days = isset( $data['growth_days'] ) ? intval( $data['growth_days'] ) : 30;
			
			if ( $days < 1 || $days > 365 ) {
				$days = 7;
			}
			
			// 1. Get subscriber stats (audience insights)
			$subscribers_stats = self::get_subscribers_stats( array(
				'list_id' => $list_id,
				'days'    => $days,
			) );
			
			
			// 3. Get country stats
			$country_stats = ES_Lists_Controller::get_country_stats( array(
				'list_id' => $list_id,
				'days'    => $days,
			) );
			
			// 4. Get audience growth stats
			$audience_growth = self::get_audience_growth_stats( array(
				'days' => $growth_days,
			) );
			
			// 5. Get audience health stats
			$audience_health = ES_Contacts_Controller::get_audience_health_stats();
			
			return array(
				'country_stats'     => ! empty( $country_stats ) ? $country_stats : array(),
				'audience_growth'   => $audience_growth,
				'audience_health'   => $audience_health,
				'subscribers_stats' => $subscribers_stats,
			);
		}
		
		/**
		 * Get main dashboard batch data (campaigns, forms, onboarding)
		 * Used by Main Dashboard page
		 * 
		 * @param array $data Request data containing 'days' parameter
		 * @return array Combined dashboard and onboarding data
		 * 
		 * @since 5.9.15
		 */
		public static function get_main_dashboard_batch_data( $data = array() ) {
			if ( is_string( $data ) ) {
				$decoded_data = json_decode( $data, true );
				if ( $decoded_data ) {
					$data = $decoded_data;
				}
			}
			
			$days = isset( $data['days'] ) ? intval( $data['days'] ) : 7;
			
			if ( $days < 1 || $days > 365 ) {
				$days = 7;
			}
			
			$dashboard_data = self::get_dashboard_data( array( 'days' => $days ) );
			
			$onboarding_steps = self::get_onboarding_steps(
				! empty( $dashboard_data['campaigns'] ) && is_array( $dashboard_data['campaigns'] ) ? $dashboard_data['campaigns'] : null,
				! empty( $dashboard_data['forms'] ) && is_array( $dashboard_data['forms'] ) ? $dashboard_data['forms'] : null,
				null
			);
			
			return array(
				'dashboard'   => $dashboard_data,
				'onboarding'  => $onboarding_steps
			);
		}
	}

}

ES_Dashboard_Controller::get_instance();
