<?php
/**
 * Plugin Name: WooCommerce Analytics Dashboard
 * Description: A React-powered analytics dashboard for WooCommerce with an integrated AI store assistant.
 * Version: 1.0.0
 * Author: Visionsharp
 * Text Domain: woo-analytics-dashboard
 * Requires at least: 6.0
 * Requires PHP: 8.0
 * WC requires at least: 8.0
 * WC tested up to: 9.5
 */

defined( 'ABSPATH' ) || exit;

define( 'WAD_VERSION', '1.0.0' );
define( 'WAD_PLUGIN_DIR', plugin_dir_path( __FILE__ ) );
define( 'WAD_PLUGIN_URL', plugin_dir_url( __FILE__ ) );
define( 'WAD_PLUGIN_FILE', __FILE__ );

/**
 * Declare HPOS (High-Performance Order Storage) compatibility.
 */
add_action( 'before_woocommerce_init', function () {
	if ( class_exists( \Automattic\WooCommerce\Utilities\FeaturesUtil::class ) ) {
		\Automattic\WooCommerce\Utilities\FeaturesUtil::declare_compatibility(
			'custom_order_tables',
			__FILE__,
			true
		);
	}
} );

/**
 * Bootstrap the plugin after all plugins have loaded.
 * Ensures WooCommerce is present before loading any classes.
 */
add_action( 'plugins_loaded', function () {
	if ( ! class_exists( 'WooCommerce' ) ) {
		add_action( 'admin_notices', function () {
			echo '<div class="notice notice-error"><p>'
				. esc_html__( 'WooCommerce Analytics Dashboard requires WooCommerce to be installed and active.', 'woo-analytics-dashboard' )
				. '</p></div>';
		} );
		return;
	}

	require_once WAD_PLUGIN_DIR . 'includes/class-data.php';
	require_once WAD_PLUGIN_DIR . 'includes/class-query-engine.php';
	require_once WAD_PLUGIN_DIR . 'includes/class-ai.php';
	require_once WAD_PLUGIN_DIR . 'includes/class-rest.php';
	require_once WAD_PLUGIN_DIR . 'includes/class-admin.php';
	require_once WAD_PLUGIN_DIR . 'includes/class-settings.php';
	require_once WAD_PLUGIN_DIR . 'includes/class-seeder.php';

	WAD_Admin::init();
	WAD_REST::init();
	WAD_Settings::init();
} );

/**
 * Bust cached transients when orders or products change.
 */
add_action( 'woocommerce_new_order', 'wad_bust_cache' );
add_action( 'woocommerce_order_status_changed', 'wad_bust_cache' );
add_action( 'woocommerce_update_product', 'wad_bust_cache' );

function wad_bust_cache() {
	foreach ( [ '7d', '1m', '3m', '6m', '1y' ] as $range ) {
		delete_transient( 'wad_overview_' . $range );
		delete_transient( 'wad_revenue_chart_' . $range );
	}
	foreach ( [ 6, 10, 20 ] as $limit ) {
		delete_transient( 'wad_recent_orders_' . $limit );
	}
	delete_transient( 'wad_ai_store_context' );
	delete_transient( 'wad_query_catalog_v1' );
}
