<?php
/**
 * The core analytics class.
 *
 * This class is responsible for creating the analytics dashboard page,
 * enqueuing assets for the dashboard, and handling AJAX requests for data.
 *
 * @package    Ai_Try_N_Buy
 * @subpackage Ai_Try_N_Buy/analytics
 * @author     Edu Brazeal <contact@edubrazeal.com>
 */
class Aitnb_Analytics_Main {

	/**
	 * The ID of this plugin.
	 *
	 * @since    1.0.0
	 * @access   private
	 * @var      string    $plugin_name    The ID of this plugin.
	 */
	private $plugin_name;

	/**
	 * The version of this plugin.
	 *
	 * @since    1.0.0
	 * @access   private
	 * @var      string    $version    The current version of this plugin.
	 */
	private $version;

	/**
	 * Initialize the class and set its properties.
	 *
	 * @since    1.0.0
	 * @param    string    $plugin_name       The name of this plugin.
	 * @param    string    $version    The version of this plugin.
	 */
	public function __construct( $plugin_name, $version ) {
		$this->plugin_name = $plugin_name;
		$this->version     = $version;
	}

	/**
	 * Adds the analytics dashboard page under our new top-level menu.
	 *
	 * @since    1.0.0
	 */
	public function add_dashboard_page() {
			add_submenu_page(
				'aitnb-main',
				__( 'AI Try n Buy Analytics', 'virtual-ai-fit-and-style-assistant' ),
				__( 'Analytics', 'virtual-ai-fit-and-style-assistant' ),
				'manage_options',
				'aitnb-analytics',
				array( $this, 'display_dashboard_page' )
			);
	}

	/**
	 * Renders the view for the dashboard page.
	 *
	 * @since    1.0.0
	 */
	public function display_dashboard_page() {
		require_once plugin_dir_path( __FILE__ ) . 'views/dashboard-view.php';
	}

	/**
	 * Enqueues scripts and styles for the analytics dashboard.
	 *
	 * @since    1.0.0
	 * @param    string    $hook_suffix    The hook suffix for the current admin page.
	 */
	public function enqueue_assets( $hook_suffix ) {
		if ( 'ai-try-n-buy_page_aitnb-analytics' !== $hook_suffix ) {
			return;
		}

		wp_enqueue_script( 'chartjs', plugin_dir_url( __FILE__ ) . 'assets/vendor/chart.umd.min.js', array(), '4.4.1', true );

		wp_enqueue_script(
			$this->plugin_name . '-analytics',
			plugin_dir_url( __FILE__ ) . 'assets/js/analytics-charts.js',
			array( 'jquery', 'chartjs' ),
			$this->version,
			true
		);

			wp_localize_script(
				$this->plugin_name . '-analytics',
				'aitnb_analytics_params',
				array(
					'ajax_url' => admin_url( 'admin-ajax.php' ),
					'nonce'    => wp_create_nonce( 'aitnb_analytics_nonce' ),
					'i18n'     => array(
						'loadingData'         => __( 'Loading analytics data...', 'virtual-ai-fit-and-style-assistant' ),
						'couldNotLoad'        => __( 'Could not load analytics data.', 'virtual-ai-fit-and-style-assistant' ),
						'requestFailed'       => __( 'Request failed.', 'virtual-ai-fit-and-style-assistant' ),
						'permissionDenied'    => __( 'Permission denied. Please ensure you have the necessary capabilities.', 'virtual-ai-fit-and-style-assistant' ),
						'networkError'        => __( 'Network error. Please check your connection.', 'virtual-ai-fit-and-style-assistant' ),
						'securityCheckFailed' => __( 'Security check failed. Please refresh the page and try again.', 'virtual-ai-fit-and-style-assistant' ),
						'statusPrefix'        => __( 'Status: ', 'virtual-ai-fit-and-style-assistant' ),
						'noDataYet'           => __( 'No Data Yet', 'virtual-ai-fit-and-style-assistant' ),
						'eventCount'          => __( 'Event Count', 'virtual-ai-fit-and-style-assistant' ),
						'tryEvents'           => __( 'Try Events', 'virtual-ai-fit-and-style-assistant' ),
						'purchasesFromTries'  => __( 'Purchases from Tries', 'virtual-ai-fit-and-style-assistant' ),
						'noTryOnData'         => __( 'No try-on data available for this period.', 'virtual-ai-fit-and-style-assistant' ),
						'noPurchaseData'      => __( 'No purchase data available for this period.', 'virtual-ai-fit-and-style-assistant' ),
					),
				)
			);
	}

	/**
	 * Registers the AJAX handlers for fetching analytics data.
	 *
	 * @since    1.0.0
	 */
	public function register_ajax_handlers() {
		add_action( 'wp_ajax_aitnb_get_analytics_data', array( $this, 'ajax_get_analytics_data' ) );
	}

	/**
	 * Handles the AJAX request to fetch analytics data from the database.
	 *
	 * @since    1.0.0
	 */
	public function ajax_get_analytics_data() {
		if ( ! check_ajax_referer( 'aitnb_analytics_nonce', 'nonce', false ) ) {
			wp_send_json_error( array( 'message' => __( 'Security check failed. Please refresh the page and try again.', 'virtual-ai-fit-and-style-assistant' ) ) );
			return;
		}

		$has_permission = current_user_can( 'view_woocommerce_reports' ) || current_user_can( 'manage_options' );
		if ( ! $has_permission ) {
			wp_send_json_error( array( 'message' => __( 'You do not have permission to view this data.', 'virtual-ai-fit-and-style-assistant' ) ) );
			return;
		}

		global $wpdb;
		$table_name = $wpdb->prefix . 'aitnb_analytics';
		// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
		$table_exists = $wpdb->get_var( $wpdb->prepare( 'SHOW TABLES LIKE %s', $table_name ) ) === $table_name;
		if ( ! $table_exists ) {
			wp_send_json_error(
				array(
					'message' => __( 'Analytics table not found. Please deactivate and reactivate the plugin to create the required database tables.', 'virtual-ai-fit-and-style-assistant' ),
				)
			);
			return;
		}

		$period = isset( $_POST['period'] ) ? sanitize_text_field( wp_unslash( $_POST['period'] ) ) : 'all_time';
		$transient_key = 'aitnb_analytics_data_' . $period;
		$cached_data = get_transient( $transient_key );

		if ( false !== $cached_data ) {
			wp_send_json_success( $cached_data );
			return;
		}

		require_once plugin_dir_path( __FILE__ ) . 'class-database-manager.php';
		$db_manager = new Aitnb_Database_Manager();

		$conversion_overview    = $db_manager->get_conversion_overview_data( $period );
		$top_tried_products     = $db_manager->get_top_products_data( 'try', $period, 5 );
		$top_purchased_products = $db_manager->get_top_products_data( 'purchase', $period, 5 );

		if ( false === $conversion_overview || false === $top_tried_products || false === $top_purchased_products ) {
			wp_send_json_error(
				array(
					'message' => __( 'Database query failed. Please check your error logs for details.', 'virtual-ai-fit-and-style-assistant' ),
				)
			);
			return;
		}

		$data = array(
			'conversion_overview'    => $conversion_overview,
			'top_tried_products'     => $top_tried_products,
			'top_purchased_products' => $top_purchased_products,
		);

		set_transient( $transient_key, $data, 15 * MINUTE_IN_SECONDS );

		wp_send_json_success( $data );
	}
}