<?php
/**
 * Admin Dashboard Class
 *
 * Handles WordPress admin menu and dashboard pages
 *
 * @package SHOPEXPLORER\Inc
 * @since 1.0.0
 */

namespace SHOPEXPLORER\Inc;

use SHOPEXPLORER\Admin\SHOPEX_SettingsManager;
use SHOPEXPLORER\GoogleSheets\SHOPEX_SHOPEX_GoogleSheetsAuth;

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

/**
 * Admin Dashboard class
 *
 * @since 1.0.0
 */
class SHOPEX_AdminDashboard {


	/**
	 * Settings manager instance
	 *
	 * @var SHOPEX_SettingsManager
	 */
	private $settings_manager;

	/**
	 * Constructor
	 *
	 * @since 1.0.0
	 */
	public function __construct() {
		$this->settings_manager = new SHOPEX_SettingsManager();

		add_action( 'admin_menu', [ $this, 'add_admin_menu' ] );
		add_action( 'admin_enqueue_scripts', [ $this, 'enqueue_admin_assets' ] );
	}

	/**
	 * Add admin menu pages
	 *
	 * @since 1.0.0
	 */
	public function add_admin_menu() {
		$icon = 'data:image/svg+xml;base64,' . base64_encode( $this->get_menu_icon() );

		// Main menu page
		add_menu_page(
			__( 'Shop Explorer', 'shop-explorer' ),
			__( 'Shop Explorer', 'shop-explorer' ),
			'manage_woocommerce',
			'shop-explorer',
			[ $this, 'render_dashboard_page' ],
			$icon,
			56 // Position after WooCommerce
		);

		// Add submenu pages
		if ( current_user_can( 'manage_woocommerce' ) ) {
			global $submenu;

			$submenu['shop-explorer'][] = [
				__( '📊 Dashboard', 'shop-explorer' ),
				'manage_woocommerce',
				'admin.php?page=shop-explorer#/',
			];

			$submenu['shop-explorer'][] = [
				__( '📦 Orders', 'shop-explorer' ),
				'manage_woocommerce',
				'admin.php?page=shop-explorer#/orders',
			];

			$submenu['shop-explorer'][] = [
				__( '🛍️ Products', 'shop-explorer' ),
				'manage_woocommerce',
				'admin.php?page=shop-explorer#/products',
			];

			$submenu['shop-explorer'][] = [
				__( '👥 Customers', 'shop-explorer' ),
				'manage_woocommerce',
				'admin.php?page=shop-explorer#/customers',
			];

			$submenu['shop-explorer'][] = [
				__( '📈 WooAnalytics', 'shop-explorer' ),
				'manage_woocommerce',
				'admin.php?page=shop-explorer#/woo-analytics',
			];

			$submenu['shop-explorer'][] = [
				__( '⚙️ Settings', 'shop-explorer' ),
				'manage_woocommerce',
				'admin.php?page=shop-explorer#/settings',
			];

		}
	}

	/**
	 * Render dashboard page
	 *
	 * @since 1.0.0
	 */
	public function render_dashboard_page() {
		// Check user permissions
		if ( ! current_user_can( 'manage_woocommerce' ) ) {
			wp_die( esc_html__( 'You do not have sufficient permissions to access this page.', 'shop-explorer' ) );
		}

		// Remove admin notices on our page
		remove_all_actions( 'admin_notices' );
		remove_all_actions( 'all_admin_notices' );

		echo '<div id="shopexplore_dashboard"></div>';
	}

	/**
	 * Enqueue admin assets
	 */
	public function enqueue_admin_assets( $hook ) {
		// Only enqueue on Shop Explorer admin page
		if ( $hook !== 'toplevel_page_shop-explorer' ) {
			return;
		}

		// Remove admin notices on our pages
		remove_all_actions( 'admin_notices' );
		remove_all_actions( 'all_admin_notices' );

		// Enqueue WordPress media scripts for media library functionality
		wp_enqueue_media();

		// Enqueue WordPress editor for rich text editing
		wp_enqueue_editor();

		// Check if build files exist
		$build_js_file = SHOPEX_PATH . 'build/index.bundle.js';

		if ( ! file_exists( $build_js_file ) ) {
			// Show admin notice if build file doesn't exist
			add_action( 'admin_notices', function () {
				echo '<div class="notice notice-error"><p>';
				esc_html_e( 'Shop Explorer: React build files not found. Please run "npm run build" to compile the assets.', 'shop-explorer' );
				echo '</p></div>';
			});
			return;
		}

		// Enqueue React dependencies
		wp_enqueue_script( 'wp-element' );
		wp_enqueue_script( 'wp-util' );

		// Try to find and enqueue CSS file
		$possible_css_files = [
			'build/index.bundle.css',
			'build/index.css',
			'build/style-index.css',
		];

		foreach ( $possible_css_files as $css_file ) {
			if ( file_exists( SHOPEX_PATH . $css_file ) ) {
				wp_enqueue_style(
					'shop-explorer-app-styles',
					SHOPEX_URL . $css_file,
					[],
					SHOPEX_VERSION
				);
				break;
			}
		}

		// Enqueue additional WordPress media dependencies
		wp_enqueue_script( 'media-models' );
		wp_enqueue_script( 'media-views' );
		wp_enqueue_script( 'media-editor' );

		// Enqueue main React app
		wp_enqueue_script(
			'shop-explorer-app',
			SHOPEX_URL . 'build/index.bundle.js',
			[ 'jquery', 'wp-element', 'wp-util', 'wp-ajax-response', 'media-models', 'media-views', 'media-editor' ],
			SHOPEX_VERSION,
			true
		);

		// Get current settings for React
		$current_settings = [
			'databaseMode' => $this->settings_manager->get_setting( 'database_mode_enabled' ),
			'googleSheetsMode' => $this->settings_manager->get_setting( 'google_sheets_mode_enabled' ),
			'multivendorMode' => $this->settings_manager->get_setting( 'multivendor_enabled' ),
			'autoSync' => $this->settings_manager->get_setting( 'auto_sync_enabled' ),
			'syncInterval' => $this->settings_manager->get_setting( 'sync_interval' ),
			'sheetsConfig' => $this->settings_manager->get_setting( 'sheets_config' ),
			'orderFieldMappings' => $this->settings_manager->get_setting( 'order_field_mappings' ),
			'productFieldMappings' => $this->settings_manager->get_setting( 'product_field_mappings' ),
		];

		// Get Google Sheets status
		$sheets_auth = $this->get_sheets_auth();
		$google_sheets_status = [
			'available' => class_exists( 'Google_Client' ) && $sheets_auth !== null,
			'connected' => $sheets_auth ? $sheets_auth->is_authenticated() : false,
			'authUrl' => $sheets_auth ? $sheets_auth->get_auth_url() : null,
		];

		// Get current user data (same format as Enqueue.php)
		$current_user = wp_get_current_user();
		$user_data = [
			'id' => $current_user->ID,
			'name' => $current_user->display_name,
			'email' => $current_user->user_email,
			'login' => $current_user->user_login,
			'roles' => $current_user->roles,
			'capabilities' => [
				'manage_woocommerce' => current_user_can( 'manage_woocommerce' ),
				'manage_options' => current_user_can( 'manage_options' ),
				'edit_shop_orders' => current_user_can( 'edit_shop_orders' ),
				'edit_products' => current_user_can( 'edit_products' ),
			],
		];

		// Get database instance and pro status
		$shopex_db_instance = new \SHOPEXPLORER\Database\DatabaseManager();
		$is_pro_active = $shopex_db_instance->is_pro_active();

		// Localize script for React - create both shopExplorerData and shopLocalizer for compatibility
		$localization_data = [
			'apiUrl' => home_url( '/wp-json/shop-explorer/v1' ),
			'nonce' => wp_create_nonce( 'wp_rest' ),
			'ajaxUrl' => admin_url( 'admin-ajax.php' ),
			'ajaxNonces' => [
				'uploadImage' => wp_create_nonce( 'shopex_upload_image' ),
				'createCategory' => wp_create_nonce( 'shopex_create_category' ),
				'createTag' => wp_create_nonce( 'shopex_create_tag' ),
				'createBrand' => wp_create_nonce( 'shopex_create_brand' ),
			],
			'adminUrl' => admin_url(),
			'currentUser' => $user_data,
			'settings' => $current_settings,
			'googleSheets' => $google_sheets_status,
			'logoutUrl' => wp_logout_url(),
			'isPro' => $is_pro_active,
			'notice_settings' => $this->get_notice_settings(),
			'mediaLibrary' => [
				'enabled' => true,
				'uploadUrl' => admin_url( 'async-upload.php' ),
			],
			'nonces' => [
				'wp_rest' => wp_create_nonce( 'wp_rest' ),
				'upload_image' => wp_create_nonce( 'shopex_upload_image' ),
				'media_nonce' => wp_create_nonce( 'shopex_media_nonce' ),
				'create_category' => wp_create_nonce( 'shopex_create_category' ),
				'create_tag' => wp_create_nonce( 'shopex_create_tag' ),
				'create_brand' => wp_create_nonce( 'shopex_create_brand' ),
			],
		];

		// Create shopExplorerData for Layout.jsx and other new components
		wp_localize_script( 'shop-explorer-app', 'shopExplorerData', $localization_data );
		
		// Also create shopLocalizer for backward compatibility with existing components like WooAnalytics
		wp_localize_script( 'shop-explorer-app', 'shopLocalizer', $localization_data );
	}


	/**
	 * Get Google Sheets auth instance (lazy loading)
	 *
	 * @return SHOPEX_SHOPEX_GoogleSheetsAuth|null
	 */
	private function get_sheets_auth() {
		if ( class_exists( 'Google_Client' ) && class_exists( 'SHOPEXPLORER\\GoogleSheets\\SHOPEX_SHOPEX_GoogleSheetsAuth' ) ) {
			return new SHOPEX_SHOPEX_GoogleSheetsAuth();
		}
		return null;
	}

	/**
	 * Get notice settings for React app
	 *
	 * @return array
	 */
	private function get_notice_settings() {
		// Get WooCommerce settings
		$woo_settings = get_option( 'wpnts_schedules_interval_woocommerce_settings', [] );
		if ( is_string( $woo_settings ) ) {
			$woo_settings = json_decode( $woo_settings, true );
		}
		if ( ! is_array( $woo_settings ) ) {
			$woo_settings = [];
		}

		return [
			'wpnts_schedules_interval_woocommerce_settings' => $woo_settings
		];
	}

	/**
	 * Get menu icon SVG
	 *
	 * @return string
	 */
	private function get_menu_icon() {
		return '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="white">
			<path d="M7 18c-1.1 0-1.99.9-1.99 2S5.9 22 7 22s2-.9 2-2-.9-2-2-2zM1 2v2h2l3.6 7.59-1.35 2.45c-.16.28-.25.61-.25.96 0 1.1.9 2 2 2h12v-2H7.42c-.14 0-.25-.11-.25-.25l.03-.12.9-1.63h7.45c.75 0 1.41-.41 1.75-1.03l3.58-6.49c.08-.14.12-.31.12-.48 0-.55-.45-1-1-1H5.21l-.94-2H1zm16 16c-1.1 0-1.99.9-1.99 2s.89 2 1.99 2 2-.9 2-2-.9-2-2-2z"/>
		</svg>';
	}
}
