<?php
/**
 * Chat metrics trait.
 *
 * @package Niwa_AI
 */

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

trait Niwa_AI_Chat_Metrics {

	public function get_metrics_tool_payload( $period = 'yesterday' ) {
		$snapshot = $this->get_metrics_snapshot( $period );

		$payload = array(
			'period'             => isset( $snapshot['period'] ) ? (string) $snapshot['period'] : 'yesterday',
			'period_label'       => isset( $snapshot['period_label'] ) ? (string) $snapshot['period_label'] : 'yesterday',
			'report_date'        => isset( $snapshot['report_date'] ) ? (string) $snapshot['report_date'] : '',
			'host'               => isset( $snapshot['host'] ) ? (string) $snapshot['host'] : '',
			'site_profile'       => isset( $snapshot['site_profile'] ) && is_array( $snapshot['site_profile'] ) ? $snapshot['site_profile'] : array(),
			'traffic_analytics'  => $this->prune_metrics_block( isset( $snapshot['traffic_analytics'] ) ? $snapshot['traffic_analytics'] : array() ),
			'attention_capture'  => $this->prune_metrics_block( isset( $snapshot['attention_capture'] ) ? $snapshot['attention_capture'] : array() ),
			'leads'              => $this->prune_metrics_block( isset( $snapshot['leads'] ) ? $snapshot['leads'] : array() ),
			'external_analytics' => $this->prune_metrics_block( isset( $snapshot['external_analytics'] ) ? $snapshot['external_analytics'] : array() ),
			'highlights'         => isset( $snapshot['highlights'] ) ? array_values( $snapshot['highlights'] ) : array(),
			'noteworthy'         => ! empty( $snapshot['noteworthy'] ),
		);

		if ( isset( $snapshot['woocommerce'] ) ) {
			$payload['woocommerce'] = $this->prune_metrics_block( $snapshot['woocommerce'] );
		}
		if ( isset( $snapshot['conversion_busters'] ) ) {
			$payload['conversion_busters'] = $this->prune_metrics_block( $snapshot['conversion_busters'] );
		}

		return $payload;
	}

	private function get_metrics_snapshot( $period ) {
		$range = $this->build_metrics_period_range( $period );

		$site_profile = $this->get_site_operating_profile();
		$snapshot     = array(
			'host'               => wp_parse_url( home_url( '/' ), PHP_URL_HOST ),
			'site_name'          => get_bloginfo( 'name' ),
			'site_profile'       => $site_profile,
			'period'             => isset( $range['period'] ) ? (string) $range['period'] : 'yesterday',
			'period_label'       => isset( $range['label'] ) ? (string) $range['label'] : 'yesterday',
			'report_date'        => isset( $range['report_date'] ) ? (string) $range['report_date'] : '',
			'date_range'         => array(
				'start_local' => isset( $range['start_local'] ) ? $range['start_local']->format( 'Y-m-d H:i:s' ) : '',
				'end_local'   => isset( $range['end_local'] ) ? $range['end_local']->format( 'Y-m-d H:i:s' ) : '',
			),
			'traffic_analytics'  => $this->collect_traffic_analytics_metrics( $range ),
			'attention_capture'  => $this->collect_attention_capture_metrics( $range ),
			'leads'              => $this->collect_lead_metrics( $range ),
			'external_analytics' => $this->collect_external_metrics( $range ),
		);
		if ( ! empty( $site_profile['transactions_available'] ) ) {
			$snapshot['woocommerce']        = $this->collect_woocommerce_metrics( $range );
			$snapshot['conversion_busters'] = $this->collect_conversion_busters_metrics( $range );
		}

		$snapshot['highlights'] = $this->extract_metrics_highlights( $snapshot );
		$snapshot['noteworthy'] = ! empty( $snapshot['highlights'] );

		return $snapshot;
	}

	private function build_metrics_period_range( $period ) {
		$period = trim( strtolower( (string) $period ) );
		if ( ! in_array( $period, array( 'today', 'yesterday', 'last_7_days', 'last_30_days' ), true ) ) {
			$period = 'yesterday';
		}

		$tz    = wp_timezone();
		$now   = new DateTimeImmutable( 'now', $tz );
		$today = $now->setTime( 0, 0, 0 );

		if ( 'today' === $period ) {
			$start       = $today;
			$end         = $now;
			$label       = 'today';
			$report_date = $today->format( 'Y-m-d' );
		} elseif ( 'last_7_days' === $period ) {
			$start       = $today->modify( '-6 days' );
			$end         = $now;
			$label       = 'last 7 days';
			$report_date = $today->format( 'Y-m-d' );
		} elseif ( 'last_30_days' === $period ) {
			$start       = $today->modify( '-29 days' );
			$end         = $now;
			$label       = 'last 30 days';
			$report_date = $today->format( 'Y-m-d' );
		} else {
			$start       = $today->modify( '-1 day' );
			$end         = $start->setTime( 23, 59, 59 );
			$label       = 'yesterday';
			$report_date = $start->format( 'Y-m-d' );
		}

		return array(
			'period'      => $period,
			'label'       => $label,
			'report_date' => $report_date,
			'start_local' => $start,
			'end_local'   => $end,
			'start_mysql' => $start->format( 'Y-m-d H:i:s' ),
			'end_mysql'   => $end->format( 'Y-m-d H:i:s' ),
		);
	}

	private function collect_traffic_analytics_metrics( $range ) {
		if ( ! class_exists( 'Niwa_AI_Traffic_Repository' ) ) {
			return array(
				'available' => false,
				'source'    => 'niwa_traffic_analysis',
			);
		}

		try {
			$repository = new Niwa_AI_Traffic_Repository();
			return $repository->get_snapshot( $range );
		} catch ( \Throwable $e ) {
			return array(
				'available' => false,
				'source'    => 'niwa_traffic_analysis',
				'error'     => $e->getMessage(),
			);
		}
	}

	private function collect_woocommerce_metrics( $range ) {
		$site_profile = $this->get_site_operating_profile();
		if ( empty( $site_profile['transactions_available'] ) || ! function_exists( 'wc_get_orders' ) ) {
			return array(
				'available' => false,
				'source'    => 'woocommerce',
			);
		}

		$orders = wc_get_orders(
			array(
				'status'       => array( 'wc-processing', 'wc-completed', 'wc-on-hold' ),
				'limit'        => -1,
				'return'       => 'objects',
				'date_created' => $range['start_mysql'] . '...' . $range['end_mysql'],
			)
		);

		if ( ! is_array( $orders ) ) {
			$orders = array();
		}

		$order_count     = 0;
		$revenue         = 0.0;
		$items_sold      = 0;
		$customer_emails = array();

		foreach ( $orders as $order ) {
			if ( ! is_object( $order ) || ! method_exists( $order, 'get_total' ) ) {
				continue;
			}

			$order_count++;
			$revenue += floatval( $order->get_total() );

			foreach ( $order->get_items() as $item ) {
				if ( is_object( $item ) && method_exists( $item, 'get_quantity' ) ) {
					$items_sold += intval( $item->get_quantity() );
				}
			}

			if ( method_exists( $order, 'get_billing_email' ) ) {
				$email = trim( strtolower( (string) $order->get_billing_email() ) );
				if ( '' !== $email ) {
					$customer_emails[ $email ] = true;
				}
			}
		}

		return array(
			'available'       => true,
			'source'          => 'woocommerce',
			'orders'          => $order_count,
			'revenue'         => round( $revenue, 2 ),
			'items_sold'      => $items_sold,
			'customers'       => count( $customer_emails ),
			'avg_order_value' => $order_count > 0 ? round( $revenue / $order_count, 2 ) : 0.0,
		);
	}

	private function collect_conversion_busters_metrics( $range ) {
		global $wpdb;

		$table = $wpdb->prefix . Niwa_AI_Conversion_Busters::ANALYTICS_TABLE;
		if ( $table !== $wpdb->get_var( $wpdb->prepare( 'SHOW TABLES LIKE %s', $table ) ) ) {
			return array(
				'available' => false,
				'source'    => 'conversion_busters',
			);
		}

		$row = $wpdb->get_row(
			$wpdb->prepare(
				"SELECT
                    SUM(CASE WHEN created_at BETWEEN %s AND %s THEN 1 ELSE 0 END) AS offers_created,
                    COUNT(DISTINCT CASE WHEN created_at BETWEEN %s AND %s THEN user_session ELSE NULL END) AS reached_sessions,
                    SUM(CASE WHEN status = 'used' AND used_at BETWEEN %s AND %s THEN 1 ELSE 0 END) AS conversions,
                    COALESCE(SUM(CASE WHEN status = 'used' AND used_at BETWEEN %s AND %s THEN order_total ELSE 0 END), 0) AS recovered_revenue,
                    COALESCE(SUM(CASE WHEN status = 'used' AND used_at BETWEEN %s AND %s THEN discount_amount ELSE 0 END), 0) AS discount_total
                 FROM {$table}
                 WHERE ( created_at BETWEEN %s AND %s )
                    OR ( used_at BETWEEN %s AND %s )",
				$range['start_mysql'],
				$range['end_mysql'],
				$range['start_mysql'],
				$range['end_mysql'],
				$range['start_mysql'],
				$range['end_mysql'],
				$range['start_mysql'],
				$range['end_mysql'],
				$range['start_mysql'],
				$range['end_mysql'],
				$range['start_mysql'],
				$range['end_mysql'],
				$range['start_mysql'],
				$range['end_mysql']
			),
			ARRAY_A
		);

		$offers_created = isset( $row['offers_created'] ) ? intval( $row['offers_created'] ) : 0;
		$conversions    = isset( $row['conversions'] ) ? intval( $row['conversions'] ) : 0;

		return array(
			'available'         => true,
			'source'            => 'conversion_busters',
			'offers_created'    => $offers_created,
			'reached_sessions'  => isset( $row['reached_sessions'] ) ? intval( $row['reached_sessions'] ) : 0,
			'conversions'       => $conversions,
			'recovered_revenue' => isset( $row['recovered_revenue'] ) ? round( floatval( $row['recovered_revenue'] ), 2 ) : 0.0,
			'discount_total'    => isset( $row['discount_total'] ) ? round( floatval( $row['discount_total'] ), 2 ) : 0.0,
			'conversion_rate'   => $offers_created > 0 ? round( ( $conversions / $offers_created ) * 100, 1 ) : 0.0,
		);
	}

	private function collect_attention_capture_metrics( $range ) {
		global $wpdb;

		$table = $wpdb->prefix . Niwa_AI_Attention_Capture::ANALYTICS_TABLE;
		if ( $table !== $wpdb->get_var( $wpdb->prepare( 'SHOW TABLES LIKE %s', $table ) ) ) {
			return array(
				'available' => false,
				'source'    => 'attention_capture',
			);
		}

		$row = $wpdb->get_row(
			$wpdb->prepare(
				"SELECT
                    COUNT(*) AS total_events,
                    SUM(CASE WHEN event_type = 'bubble_shown' THEN 1 ELSE 0 END) AS bubble_shown,
                    SUM(CASE WHEN event_type = 'bubble_clicked' THEN 1 ELSE 0 END) AS bubble_clicked,
                    SUM(CASE WHEN event_type = 'action_button_clicked' THEN 1 ELSE 0 END) AS action_clicked,
                    SUM(CASE WHEN event_type = 'cb_mini_started' THEN 1 ELSE 0 END) AS cb_mini_started,
                    SUM(CASE WHEN event_type = 'launcher_click' THEN 1 ELSE 0 END) AS launcher_click,
                    COUNT(DISTINCT CASE WHEN event_type IN ('bubble_clicked', 'action_button_clicked', 'cb_mini_started', 'launcher_click') THEN user_session ELSE NULL END) AS engaged_sessions
                 FROM {$table}
                 WHERE created_at BETWEEN %s AND %s",
				$range['start_mysql'],
				$range['end_mysql']
			),
			ARRAY_A
		);

		$top_pages = $wpdb->get_results(
			$wpdb->prepare(
				"SELECT
                    page_path,
                    COUNT(*) AS total_events,
                    SUM(CASE WHEN event_type = 'bubble_shown' THEN 1 ELSE 0 END) AS bubble_shown,
                    SUM(CASE WHEN event_type IN ('bubble_clicked', 'action_button_clicked', 'cb_mini_started', 'launcher_click') THEN 1 ELSE 0 END) AS engaged_events
                 FROM {$table}
                 WHERE created_at BETWEEN %s AND %s
                 GROUP BY page_path
                 ORDER BY engaged_events DESC, total_events DESC
                 LIMIT 3",
				$range['start_mysql'],
				$range['end_mysql']
			),
			ARRAY_A
		);

		$bubble_shown   = isset( $row['bubble_shown'] ) ? intval( $row['bubble_shown'] ) : 0;
		$bubble_clicked = isset( $row['bubble_clicked'] ) ? intval( $row['bubble_clicked'] ) : 0;

		return array(
			'available'         => true,
			'source'            => 'attention_capture',
			'total_events'      => isset( $row['total_events'] ) ? intval( $row['total_events'] ) : 0,
			'bubble_shown'      => $bubble_shown,
			'bubble_clicked'    => $bubble_clicked,
			'action_clicked'    => isset( $row['action_clicked'] ) ? intval( $row['action_clicked'] ) : 0,
			'cb_mini_started'   => isset( $row['cb_mini_started'] ) ? intval( $row['cb_mini_started'] ) : 0,
			'launcher_click'    => isset( $row['launcher_click'] ) ? intval( $row['launcher_click'] ) : 0,
			'engaged_sessions'  => isset( $row['engaged_sessions'] ) ? intval( $row['engaged_sessions'] ) : 0,
			'click_rate'        => $bubble_shown > 0 ? round( ( $bubble_clicked / $bubble_shown ) * 100, 1 ) : 0.0,
			'top_engaged_pages' => is_array( $top_pages ) ? array_values( $top_pages ) : array(),
		);
	}

	private function collect_lead_metrics( $range ) {
		global $wpdb;

		$table = $wpdb->prefix . Niwa_AI_Contact_Service::TABLE_NAME;
		if ( $table !== $wpdb->get_var( $wpdb->prepare( 'SHOW TABLES LIKE %s', $table ) ) ) {
			return array(
				'available' => false,
				'source'    => 'niwa_leads',
			);
		}

		$row = $wpdb->get_row(
			$wpdb->prepare(
				"SELECT
                    COUNT(*) AS leads,
                    SUM(CASE WHEN name IS NOT NULL AND name <> '' THEN 1 ELSE 0 END) AS named_leads,
                    SUM(CASE WHEN phone IS NOT NULL AND phone <> '' THEN 1 ELSE 0 END) AS phone_leads
                 FROM {$table}
                 WHERE created_at BETWEEN %s AND %s",
				$range['start_mysql'],
				$range['end_mysql']
			),
			ARRAY_A
		);

		return array(
			'available'   => true,
			'source'      => 'niwa_leads',
			'leads'       => isset( $row['leads'] ) ? intval( $row['leads'] ) : 0,
			'named_leads' => isset( $row['named_leads'] ) ? intval( $row['named_leads'] ) : 0,
			'phone_leads' => isset( $row['phone_leads'] ) ? intval( $row['phone_leads'] ) : 0,
		);
	}

	private function collect_external_metrics( $range ) {
		$payload   = apply_filters( 'niwa_ai_admin_autonomy_external_metrics', array(), $range );
		$providers = $this->normalize_external_metrics( $payload );

		return array(
			'available'        => ! empty( $providers ),
			'source'           => 'external',
			'providers'        => $providers,
			'detected_plugins' => $this->detect_analytics_plugins(),
		);
	}

	private function normalize_external_metrics( $payload ) {
		if ( empty( $payload ) ) {
			return array();
		}

		$items = array();
		if ( $this->looks_like_external_metrics_provider( $payload ) ) {
			$items[] = $payload;
		} elseif ( is_array( $payload ) ) {
			foreach ( $payload as $provider ) {
				if ( $this->looks_like_external_metrics_provider( $provider ) ) {
					$items[] = $provider;
				}
			}
		}

		$providers = array();
		foreach ( $items as $provider ) {
			$normalized = array(
				'source'    => isset( $provider['source'] ) ? sanitize_key( $provider['source'] ) : 'external',
				'label'     => isset( $provider['label'] ) ? sanitize_text_field( $provider['label'] ) : 'External analytics',
				'visits'    => isset( $provider['visits'] ) ? intval( $provider['visits'] ) : 0,
				'users'     => isset( $provider['users'] ) ? intval( $provider['users'] ) : 0,
				'pageviews' => isset( $provider['pageviews'] ) ? intval( $provider['pageviews'] ) : 0,
				'top_pages' => array(),
			);

			if ( ! empty( $provider['top_pages'] ) && is_array( $provider['top_pages'] ) ) {
				foreach ( array_slice( $provider['top_pages'], 0, 5 ) as $page ) {
					if ( ! is_array( $page ) ) {
						continue;
					}
					$normalized['top_pages'][] = array(
						'title' => isset( $page['title'] ) ? sanitize_text_field( $page['title'] ) : '',
						'path'  => isset( $page['path'] ) ? sanitize_text_field( $page['path'] ) : '',
						'views' => isset( $page['views'] ) ? intval( $page['views'] ) : 0,
					);
				}
			}

			if ( $normalized['visits'] > 0 || $normalized['users'] > 0 || $normalized['pageviews'] > 0 || ! empty( $normalized['top_pages'] ) ) {
				$providers[] = $normalized;
			}
		}

		return $providers;
	}

	private function detect_analytics_plugins() {
		$active = get_option( 'active_plugins', array() );
		if ( ! is_array( $active ) ) {
			$active = array();
		}

		$known = array(
			'google-site-kit/google-site-kit.php'                => 'Google Site Kit',
			'google-analytics-for-wordpress/googleanalytics.php' => 'MonsterInsights',
			'ga-google-analytics/ga-google-analytics.php'        => 'GA Google Analytics',
			'independent-analytics/independent-analytics.php'    => 'Independent Analytics',
			'exactmetrics/exactmetrics.php'                      => 'ExactMetrics',
		);

		$detected = array();
		foreach ( $known as $plugin_file => $label ) {
			if ( in_array( $plugin_file, $active, true ) ) {
				$detected[] = $label;
			}
		}

		return $detected;
	}

	private function extract_metrics_highlights( $snapshot ) {
		$highlights = array();
		$woo        = isset( $snapshot['woocommerce'] ) && is_array( $snapshot['woocommerce'] ) ? $snapshot['woocommerce'] : array();
		$traffic    = isset( $snapshot['traffic_analytics'] ) && is_array( $snapshot['traffic_analytics'] ) ? $snapshot['traffic_analytics'] : array();
		$cb         = isset( $snapshot['conversion_busters'] ) && is_array( $snapshot['conversion_busters'] ) ? $snapshot['conversion_busters'] : array();
		$ac         = isset( $snapshot['attention_capture'] ) && is_array( $snapshot['attention_capture'] ) ? $snapshot['attention_capture'] : array();
		$leads      = isset( $snapshot['leads'] ) && is_array( $snapshot['leads'] ) ? $snapshot['leads'] : array();
		$analytics  = isset( $snapshot['external_analytics']['providers'][0] ) && is_array( $snapshot['external_analytics']['providers'][0] )
			? $snapshot['external_analytics']['providers'][0]
			: array();

		if ( ! empty( $woo['available'] ) && intval( $woo['orders'] ) > 0 ) {
			$highlights[] = sprintf(
				'%d WooCommerce porudzbina u vrednosti %s.',
				intval( $woo['orders'] ),
				$this->format_money( isset( $woo['revenue'] ) ? $woo['revenue'] : 0 )
			);
		}

		if ( ! empty( $analytics ) && intval( $analytics['visits'] ) >= 20 ) {
			$line = sprintf( '%d poseta sajtu.', intval( $analytics['visits'] ) );
			if ( ! empty( $analytics['top_pages'] ) ) {
				$page_names = array();
				foreach ( array_slice( $analytics['top_pages'], 0, 3 ) as $page ) {
					if ( ! empty( $page['title'] ) ) {
						$page_names[] = (string) $page['title'];
					} elseif ( ! empty( $page['path'] ) ) {
						$page_names[] = (string) $page['path'];
					}
				}
				if ( ! empty( $page_names ) ) {
					$line .= ' Najposecenije: ' . implode( ', ', $page_names ) . '.';
				}
			}
			$highlights[] = $line;
		}

		if ( ! empty( $traffic['available'] ) && ! empty( $traffic['summary'] ) && is_array( $traffic['summary'] ) ) {
			$summary = $traffic['summary'];
			if ( intval( $summary['sessions'] ?? 0 ) >= 10 || intval( $summary['conversions'] ?? 0 ) > 0 ) {
				$line = sprintf(
					'Traffic Analysis: %d sesija, %d pageview-a, %d konverzija, %s prihoda.',
					intval( $summary['sessions'] ?? 0 ),
					intval( $summary['pageviews'] ?? 0 ),
					intval( $summary['conversions'] ?? 0 ),
					$this->format_money( $summary['revenue'] ?? 0 )
				);
				if ( ! empty( $traffic['top_campaigns'][0]['label'] ) ) {
					$line .= ' Top kampanja: ' . (string) $traffic['top_campaigns'][0]['label'] . '.';
				} elseif ( ! empty( $traffic['top_channels'][0]['label'] ) ) {
					$line .= ' Top kanal: ' . (string) $traffic['top_channels'][0]['label'] . '.';
				}
				$highlights[] = $line;
			}
		}

		if ( ! empty( $cb['available'] ) && intval( $cb['conversions'] ) > 0 ) {
			$highlights[] = sprintf(
				'Conversion Busters je pomogao %d kupovine i povratio %s.',
				intval( $cb['conversions'] ),
				$this->format_money( isset( $cb['recovered_revenue'] ) ? $cb['recovered_revenue'] : 0 )
			);
		} elseif ( ! empty( $cb['available'] ) && intval( $cb['offers_created'] ) >= 3 ) {
			$highlights[] = sprintf(
				'Conversion Busters je aktivirao %d ponuda kroz %d sesija.',
				intval( $cb['offers_created'] ),
				intval( isset( $cb['reached_sessions'] ) ? $cb['reached_sessions'] : 0 )
			);
		}

		if ( ! empty( $ac['available'] ) && intval( $ac['engaged_sessions'] ) >= 3 ) {
			$highlights[] = sprintf(
				'Attention Capture je uvukao %d sesija u interakciju, uz %d bubble klikova i %d CB Mini startova.',
				intval( $ac['engaged_sessions'] ),
				intval( isset( $ac['bubble_clicked'] ) ? $ac['bubble_clicked'] : 0 ),
				intval( isset( $ac['cb_mini_started'] ) ? $ac['cb_mini_started'] : 0 )
			);
		}

		if ( ! empty( $leads['available'] ) && intval( $leads['leads'] ) > 0 ) {
			$highlights[] = sprintf( 'Niwa AI je uhvatio %d novih leadova.', intval( $leads['leads'] ) );
		}

		return array_values( array_unique( array_filter( $highlights ) ) );
	}

	private function collect_weekly_bestsellers() {
		$site_profile = $this->get_site_operating_profile();
		if ( empty( $site_profile['transactions_available'] ) || ! function_exists( 'wc_get_orders' ) ) {
			return array();
		}

		$week_ago = gmdate( 'Y-m-d', strtotime( '-7 days' ) );
		$orders   = wc_get_orders( array(
			'date_created' => '>=' . $week_ago,
			'status'       => array( 'wc-completed', 'wc-processing' ),
			'limit'        => 200,
		) );

		if ( ! is_array( $orders ) || empty( $orders ) ) {
			return array();
		}

		$product_sales = array();
		foreach ( $orders as $order ) {
			if ( ! is_object( $order ) || ! method_exists( $order, 'get_items' ) ) {
				continue;
			}

			foreach ( $order->get_items() as $item ) {
				if ( ! is_object( $item ) || ! method_exists( $item, 'get_product_id' ) ) {
					continue;
				}

				$pid = intval( $item->get_product_id() );
				if ( $pid <= 0 ) {
					continue;
				}

				if ( ! isset( $product_sales[ $pid ] ) ) {
					$product_sales[ $pid ] = array(
						'product_id' => $pid,
						'name'       => method_exists( $item, 'get_name' ) ? (string) $item->get_name() : '',
						'qty'        => 0,
						'revenue'    => 0.0,
					);
				}

				$product_sales[ $pid ]['qty']     += method_exists( $item, 'get_quantity' ) ? intval( $item->get_quantity() ) : 0;
				$product_sales[ $pid ]['revenue'] += method_exists( $item, 'get_total' ) ? floatval( $item->get_total() ) : 0.0;
			}
		}

		usort( $product_sales, function ( $a, $b ) {
			return $b['revenue'] <=> $a['revenue'];
		} );

		return array_slice( $product_sales, 0, 15 );
	}

	private function collect_product_catalog_summary() {
		$site_profile = $this->get_site_operating_profile();
		if ( empty( $site_profile['catalog_available'] ) || ! function_exists( 'wc_get_products' ) ) {
			return array();
		}

		$total     = wp_count_posts( 'product' );
		$published = isset( $total->publish ) ? intval( $total->publish ) : 0;
		$draft     = isset( $total->draft ) ? intval( $total->draft ) : 0;

		$categories = get_terms( array(
			'taxonomy'   => 'product_cat',
			'hide_empty' => true,
			'fields'     => 'names',
		) );

		$summary = array(
			'published'    => $published,
			'draft'        => $draft,
			'categories'   => is_array( $categories ) ? array_slice( $categories, 0, 20 ) : array(),
		);

		if ( ! empty( $site_profile['transactions_available'] ) ) {
			$stock_counts           = $this->get_effective_catalog_stock_counts();
			$summary['out_of_stock'] = intval( $stock_counts['out_of_stock'] );
			$summary['low_stock']    = intval( $stock_counts['low_stock'] );
		}

		return $summary;
	}

	private function get_effective_catalog_stock_counts() {
		$counts = array(
			'out_of_stock' => 0,
			'low_stock'    => 0,
		);

		if ( ! function_exists( 'wc_get_product' ) || ! function_exists( 'get_posts' ) ) {
			return $counts;
		}

		$product_ids = get_posts(
			array(
				'post_type'      => 'product',
				'post_status'    => 'publish',
				'fields'         => 'ids',
				'posts_per_page' => -1,
				'no_found_rows'  => true,
			)
		);

		foreach ( (array) $product_ids as $product_id ) {
			$product = wc_get_product( intval( $product_id ) );
			if ( ! $product || ! method_exists( $product, 'is_type' ) ) {
				continue;
			}

			$status = $this->get_effective_catalog_product_stock_status( $product );
			if ( 'outofstock' === $status ) {
				$counts['out_of_stock']++;
				continue;
			}

			if ( $this->is_effective_catalog_product_low_stock( $product ) ) {
				$counts['low_stock']++;
			}
		}

		return $counts;
	}

	private function get_effective_catalog_product_stock_status( $product ) {
		if ( $product && method_exists( $product, 'is_type' ) && $product->is_type( 'variable' ) && method_exists( $product, 'get_children' ) ) {
			foreach ( (array) $product->get_children() as $variation_id ) {
				$variation = wc_get_product( intval( $variation_id ) );
				if ( ! $variation || ! method_exists( $variation, 'is_type' ) || ! $variation->is_type( 'variation' ) ) {
					continue;
				}
				if ( method_exists( $variation, 'get_status' ) && ! in_array( (string) $variation->get_status(), array( 'publish', 'private' ), true ) ) {
					continue;
				}
				if ( method_exists( $variation, 'is_in_stock' ) && $variation->is_in_stock() ) {
					return 'instock';
				}
				if ( method_exists( $variation, 'get_stock_status' ) && 'outofstock' !== (string) $variation->get_stock_status() ) {
					return (string) $variation->get_stock_status();
				}
			}

			return 'outofstock';
		}

		return $product && method_exists( $product, 'get_stock_status' ) ? (string) $product->get_stock_status() : 'instock';
	}

	private function is_effective_catalog_product_low_stock( $product ) {
		if ( $product && method_exists( $product, 'is_type' ) && $product->is_type( 'variable' ) && method_exists( $product, 'get_children' ) ) {
			foreach ( (array) $product->get_children() as $variation_id ) {
				$variation = wc_get_product( intval( $variation_id ) );
				if ( ! $variation || ! method_exists( $variation, 'is_type' ) || ! $variation->is_type( 'variation' ) ) {
					continue;
				}
				if ( method_exists( $variation, 'get_status' ) && ! in_array( (string) $variation->get_status(), array( 'publish', 'private' ), true ) ) {
					continue;
				}
				if ( method_exists( $variation, 'get_manage_stock' ) && $variation->get_manage_stock() && method_exists( $variation, 'get_stock_quantity' ) ) {
					$qty = $variation->get_stock_quantity();
					if ( null !== $qty && intval( $qty ) > 0 && intval( $qty ) <= 5 ) {
						return true;
					}
				}
			}

			return false;
		}

		if ( $product && method_exists( $product, 'get_manage_stock' ) && $product->get_manage_stock() && method_exists( $product, 'get_stock_quantity' ) ) {
			$qty = $product->get_stock_quantity();
			return null !== $qty && intval( $qty ) > 0 && intval( $qty ) <= 5;
		}

		return false;
	}

	private function collect_existing_blog_posts() {
		$posts = get_posts( array(
			'post_type'      => 'post',
			'post_status'    => array( 'publish', 'draft' ),
			'posts_per_page' => 10,
			'orderby'        => 'date',
			'order'          => 'DESC',
		) );

		if ( ! is_array( $posts ) || empty( $posts ) ) {
			return array();
		}

		$out = array();
		foreach ( $posts as $post ) {
			$cats = wp_get_post_categories( $post->ID, array( 'fields' => 'names' ) );
			$out[] = array(
				'id'         => $post->ID,
				'title'      => $post->post_title,
				'status'     => $post->post_status,
				'date'       => $post->post_date,
				'categories' => is_array( $cats ) ? $cats : array(),
			);
		}

		return $out;
	}

	private function collect_recent_customer_questions() {
		try {
			$qlog = new Niwa_AI_Frontend_Question_Log();
			$questions = $qlog->get_recent_days( 7, 50 );
			if ( ! is_array( $questions ) || empty( $questions ) ) {
				return array( 'note' => 'Nema logiranih pitanja kupaca u poslednjih 7 dana.' );
			}

			return array(
				'count_7d'  => count( $questions ),
				'total'     => $qlog->count_all(),
				'questions' => $questions,
			);
		} catch ( \Throwable $e ) {
			return array( 'note' => 'Greska pri citanju pitanja: ' . $e->getMessage() );
		}
	}

	private function prune_metrics_block( $block ) {
		if ( empty( $block ) || ! is_array( $block ) ) {
			return array();
		}

		$out = array();
		foreach ( $block as $key => $value ) {
			if ( in_array( $key, array( 'source', 'available', 'summary', 'providers', 'top_pages', 'top_channels', 'top_campaigns', 'top_engaged_pages', 'detected_plugins', 'attribution' ), true ) ) {
				if ( ! empty( $value ) ) {
					$out[ $key ] = $value;
				}
				continue;
			}

			if ( is_numeric( $value ) && floatval( $value ) > 0 ) {
				$out[ $key ] = $value;
			}
		}

		if ( isset( $block['available'] ) ) {
			$out['available'] = ! empty( $block['available'] );
		}
		if ( isset( $block['source'] ) ) {
			$out['source'] = $block['source'];
		}

		return $out;
	}

	private function looks_like_external_metrics_provider( $provider ) {
		return is_array( $provider ) && (
			array_key_exists( 'visits', $provider ) ||
			array_key_exists( 'users', $provider ) ||
			array_key_exists( 'pageviews', $provider ) ||
			array_key_exists( 'top_pages', $provider )
		);
	}

	private function format_money( $amount ) {
		$amount = floatval( $amount );
		if ( function_exists( 'wc_price' ) && class_exists( 'WooCommerce' ) ) {
			return wp_strip_all_tags( html_entity_decode( wc_price( $amount ), ENT_QUOTES, get_bloginfo( 'charset' ) ) );
		}

		return number_format_i18n( $amount, 2 );
	}

	private function format_internal_timestamp( $timestamp ) {
		$timestamp = intval( $timestamp );
		if ( $timestamp <= 0 ) {
			return '-';
		}

		return wp_date( 'Y-m-d H:i:s', $timestamp );
	}
}
