<?php

namespace WPKIN_SHOP_MANAGER;

if ( ! defined( 'ABSPATH' ) ) {
	wp_die( esc_html__( 'You can\'t access this page', 'shop-manager' ) );
}

/**
 * Assets Handler Class
 *
 * @since 1.0.0
 */
class Assets {

	/**
	 * Assets class constructor
	 *
	 * @since 1.0.0
	 */
	public function __construct() {
		add_action( 'wp_enqueue_scripts', [ $this, 'wpkin_frontend_enqueue_scripts' ] );
		add_action( 'admin_enqueue_scripts', [ $this, 'wpkin_admin_enqueue_scripts' ] );
	}

	/**
	 * Method frontend_enqueue_scripts.
	 *
	 * @since 1.0.0
	 */
	public function wpkin_frontend_enqueue_scripts() {
		if ( ! is_page( 'sm-dashboard' ) ) {
			return;
		}

		// Enqueue WordPress media scripts
		wp_enqueue_media();

		// Add these scripts to ensure the media modal works properly
		wp_enqueue_script( 'jquery-ui-core' );
		wp_enqueue_script( 'jquery-ui-dialog' );
		wp_enqueue_script( 'jquery-ui-draggable' );
		wp_enqueue_script( 'jquery-ui-resizable' );

		// Enqueue WordPress editor
		if ( function_exists( 'wp_enqueue_editor' ) ) {
			wp_enqueue_editor();
		}

		// Enqueue your main styles and scripts
		wp_enqueue_style( 'wpkin-sm-public-style', WPKIN_SM_URL . '/build/public.bundle.css', [], filemtime( WPKIN_SM_PATH . 'build/public.bundle.css' ), false );
		wp_enqueue_script( 'wpkin-sm-public-scripts', WPKIN_SM_URL . '/build/public.bundle.js', [ 'wp-i18n', 'wp-element', 'jquery', 'wp-api' ], filemtime( WPKIN_SM_PATH . 'build/public.bundle.js' ), true );

		// Get payment methods
		$payment_gateways = WC()->payment_gateways->payment_gateways();
		$available_gateways = [];

		foreach ( $payment_gateways as $gateway ) {
			if ( $gateway->enabled === 'yes' ) {
				$available_gateways[] = [
					'id' => $gateway->id,
					'title' => $gateway->title,
					'description' => $gateway->description,
					'icon' => $gateway->icon,
					'method_title' => $gateway->method_title,
				];
			}
		}

		// Order Statuses
		$settings = get_option( 'wpkin_sm_admin_settings', [] );

		// Get current user avatar
		$current_user = wp_get_current_user();
		$user_data = [
			'id'              => $current_user->ID,
			'name'            => ucfirst( $current_user->display_name ),
			'role'            => ! empty( $current_user->roles ) ? ( wp_roles()->roles[ $current_user->roles[0] ]['name'] ?? $current_user->roles[0] ) : '',
			'avatar'          => $current_user->ID ? get_avatar_url( $current_user->ID ) : '',
			'oxi_sm_role'     => \WPKIN_SHOP_MANAGER\Modules\EmployeeManager::is_employee_role( $current_user->roles[0] ?? '' ) ? ( $current_user->roles[0] ?? '' ) : '',
			'oxi_permissions' => \WPKIN_SHOP_MANAGER\Modules\EmployeeManager::get_user_oxi_permissions( $current_user ),
		];

		$wpkin_admin_settings = get_option( 'wpkin_sm_admin_settings', true );

		$custom_statuses       = isset( $settings['orders']['custom_statuses'] ) && $settings['orders']['custom_statuses'] ? $settings['orders']['custom_statuses'] : [];
		$default_status_styles = isset( $settings['orders']['default_status_styles'] ) && $settings['orders']['default_status_styles'] ? $settings['orders']['default_status_styles'] : [];

		$status_styles = $custom_statuses + $default_status_styles;

		wp_localize_script(
			'wpkin-sm-public-scripts',
			'wpkinSM',
			[
				'version'           => WPKIN_SM_VERSION,
				'root'              => get_site_url(),
				'rest_url'          => esc_url_raw( rest_url() ),
				'nonce'             => wp_create_nonce( 'wp_rest' ),
				'currency'          => function_exists( 'get_woocommerce_currency_symbol' ) ? get_woocommerce_currency_symbol() : '$',
				'payment_methods'   => $available_gateways,
				'versioncontrol'    => \WPKIN_SHOP_MANAGER\Helper::wpkin_plugins_version_control(),
				'order_statuses'    => $settings['orders']['order_statuses'],
				'status_styles'     => $status_styles,
				'user'              => $user_data,
				'dashboard_url'     => admin_url( 'admin.php?page=shop-manager-settings' ),
				'sm_dashboard_path' => wp_parse_url( get_permalink( get_option( 'wpkin_page_id' ) ), PHP_URL_PATH ) ?? '/sm-dashboard',
				'logout_url'        => wp_logout_url( get_permalink( get_option( 'wpkin_page_id' ) ) ?: home_url( '/sm-dashboard' ) ),
				'ajaxUrl'         => admin_url( 'admin-ajax.php' ),
				'mediaUploadUrl'  => admin_url( 'media-upload.php' ),
				'wpkin_sm_settings' => [
					'module_settings'         => isset( $wpkin_admin_settings['module_settings'] ) ? $wpkin_admin_settings['module_settings'] : [],
					'order_settings_statuses' => isset( $wpkin_admin_settings['orders']['order_statuses'] ) ? $wpkin_admin_settings['orders']['order_statuses'] : [],
					'filter_settings'         => isset( $wpkin_admin_settings['orders']['filter_settings'] ) ? $wpkin_admin_settings['orders']['filter_settings'] : [],
					'products'                => $wpkin_admin_settings['products'] ?? [],
				],
				'appearance' => [
					'preset'        => $wpkin_admin_settings['appearance']['preset']        ?? 'compact',
					'colorScheme'   => $wpkin_admin_settings['appearance']['colorScheme']   ?? 'ocean',
					'darkMode'      => $wpkin_admin_settings['appearance']['darkMode']      ?? null,
					'preferredDark' => $wpkin_admin_settings['appearance']['preferredDark'] ?? $wpkin_admin_settings['appearance']['darkMode'] ?? 'slate',
				],
			]
		);

		// Add script to initialize WordPress editor
		wp_add_inline_script(
            'wpkin-sm-public-scripts', '
				window.initWPEditors = function() {
				if (typeof wp !== "undefined" && wp.editor && wp.editor.initialize) {
					// Remove any existing editors first to prevent conflicts
					if (window.tinyMCE) {
					const descEditor = window.tinyMCE.get("product_description");
					const shortDescEditor = window.tinyMCE.get("product_short_description");
					
					if (descEditor) {
						window.tinyMCE.remove(descEditor);
					}
					
					if (shortDescEditor) {
						window.tinyMCE.remove(shortDescEditor);
					}
					}
					
					// Initialize the editors with proper settings
					wp.editor.initialize("product_description", {
					tinymce: {
						wpautop: true,
                        plugins: "charmap colorpicker compat3x directionality fullscreen hr image lists media paste tabfocus textcolor WordPress wpautoresize wpdialogs wpeditimage wpemoji wpgallery wplink wptextpattern wpview",
						toolbar1: "formatselect bold italic bullist numlist blockquote alignleft aligncenter alignright link wp_more fullscreen wp_adv",
						toolbar2: "strikethrough hr forecolor pastetext removeformat charmap outdent indent undo redo wp_help",
						setup: function(editor) {
						// Fix for media button
						editor.on("init", function() {
							const mediaButtons = document.querySelectorAll(\'.mce-btn[aria-label="Add Media"]\');
							mediaButtons.forEach(button => {
							button.addEventListener("click", function(e) {
								e.preventDefault();
								e.stopPropagation();
								
								// Create a media frame
								const mediaFrame = wp.media({
								title: "Insert Media",
								button: {
									text: "Insert into editor",
								},
								multiple: true
								});
								
								// When media is selected, insert it into the editor
								mediaFrame.on("select", function() {
								const attachments = mediaFrame.state().get("selection").toJSON();
								attachments.forEach(attachment => {
									if (attachment.type === "image") {
									editor.insertContent("<img src=\"" + attachment.url + "\" alt=\"" + (attachment.alt || "") + "\" />");
									} else {
									editor.insertContent("<a href=\"" + attachment.url + "\">" + attachment.title + "</a>");
									}
								});
								});
								
								// Open the media frame
								mediaFrame.open();
							});
							});
						});
						}
					},
					quicktags: true,
					mediaButtons: true
					});
					
					wp.editor.initialize("product_short_description", {
					tinymce: {
						wpautop: true,
                        plugins: "charmap colorpicker compat3x directionality fullscreen hr image lists media paste tabfocus textcolor WordPress wpautoresize wpdialogs wpeditimage wpemoji wpgallery wplink wptextpattern wpview",
						toolbar1: "formatselect bold italic bullist numlist blockquote alignleft aligncenter alignright link fullscreen",
						toolbar2: "",
						setup: function(editor) {
						// Fix for media button
						editor.on("init", function() {
							const mediaButtons = document.querySelectorAll(\'.mce-btn[aria-label="Add Media"]\');
							mediaButtons.forEach(button => {
							button.addEventListener("click", function(e) {
								e.preventDefault();
								e.stopPropagation();
								
								// Create a media frame
								const mediaFrame = wp.media({
								title: "Insert Media",
								button: {
									text: "Insert into editor",
								},
								multiple: true
								});
								
								// When media is selected, insert it into the editor
								mediaFrame.on("select", function() {
								const attachments = mediaFrame.state().get("selection").toJSON();
								attachments.forEach(attachment => {
									if (attachment.type === "image") {
									editor.insertContent("<img src=\"" + attachment.url + "\" alt=\"" + (attachment.alt || "") + "\" />");
									} else {
									editor.insertContent("<a href=\"" + attachment.url + "\">" + attachment.title + "</a>");
									}
								});
								});
								
								// Open the media frame
								mediaFrame.open();
							});
							});
						});
						}
					},
					quicktags: true,
					mediaButtons: true
					});
				}
				};

				// Initialize editors when document is ready
				jQuery(document).ready(function() {
				if (document.getElementById("product_description") && document.getElementById("product_short_description")) {
					setTimeout(function() {
					initWPEditors();
					}, 1000); // Increased timeout to ensure DOM is fully ready
				}
				});
			'
        );
	}


	/**
	 * Method admin_translation_text.
	 */
	public function wpkin_admin_translation_text() {
		return [
			// Header
			'settings'     => __( 'Settings', 'shop-manager' ),
			'dashboard'    => __( 'Dashboard', 'shop-manager' ),
			'save_changes' => __( 'Save Changes', 'shop-manager' ),
			// Admin Sidebar Menu
			'orders'       => __( 'Orders', 'shop-manager' ),
			'employee_management' => __( 'Employee', 'shop-manager' ),
			'carrier'      => __( 'Carrier', 'shop-manager' ),
			'appearance'   => __( 'Appearance', 'shop-manager' ),
			'addons'       => __( 'Addons', 'shop-manager' ),
			'modules'      => __( 'Modules', 'shop-manager' ),
			'tools'        => __( 'Tools', 'shop-manager' ),
		];
	}

	/**
	 * Method admin_enqueue_scripts.
	 *
	 * @since 1.0.0
	 */
	public function wpkin_admin_enqueue_scripts() {

		$current_screen = get_current_screen()->id;

		if ( 'toplevel_page_shop-manager-settings' === $current_screen ) {
			wp_enqueue_style( 'wpkin-sm-admin-style', WPKIN_SM_URL . '/build/admin.bundle.css', [], filemtime( WPKIN_SM_PATH . 'build/admin.bundle.css' ), false );
			wp_enqueue_script( 'wpkin-sm-admin-scripts', WPKIN_SM_URL . '/build/admin.bundle.js', [ 'wp-i18n', 'wp-element' ], filemtime( WPKIN_SM_PATH . 'build/admin.bundle.js' ), true );

			$wpkin_admin_settings = get_option( 'wpkin_sm_admin_settings', true );

			wp_localize_script(
				'wpkin-sm-admin-scripts',
				'wpkinSM',
				[
					'root'              => esc_url_raw( rest_url() ),
					'nonce'             => wp_create_nonce( 'wp_rest' ),
					'admin_texts'       => $this->wpkin_admin_translation_text(),
					'versioncontrol'     => \WPKIN_SHOP_MANAGER\Helper::wpkin_plugins_version_control(),
					'wpkin_sm_settings' => [
						'module_settings'         => isset( $wpkin_admin_settings['module_settings'] ) ? $wpkin_admin_settings['module_settings'] : [],
						'order_settings_statuses' => isset( $wpkin_admin_settings['orders']['order_statuses'] ) ? $wpkin_admin_settings['orders']['order_statuses'] : [],
						'custom_statuses'         => isset( $wpkin_admin_settings['orders']['custom_statuses'] ) ? $wpkin_admin_settings['orders']['custom_statuses'] : [],
						'default_status_styles'   => isset( $wpkin_admin_settings['orders']['default_status_styles'] ) ? $wpkin_admin_settings['orders']['default_status_styles'] : [],
						'filter_settings'         => isset( $wpkin_admin_settings['orders']['filter_settings'] ) ? $wpkin_admin_settings['orders']['filter_settings'] : [],
						'ai_settings'             => [
							'provider'    => $wpkin_admin_settings['ai_settings']['provider']    ?? 'claude',
							'model'       => $wpkin_admin_settings['ai_settings']['model']       ?? 'claude-sonnet-4-6',
							'max_tokens'  => $wpkin_admin_settings['ai_settings']['max_tokens']  ?? 1024,
							'temperature' => $wpkin_admin_settings['ai_settings']['temperature'] ?? 0.7,
							'api_key_set' => ! empty( $wpkin_admin_settings['ai_settings']['api_key_encrypted'] ),
						],
						'products'                => $wpkin_admin_settings['products'] ?? [],
						'customer_tagging'        => $wpkin_admin_settings['customer_tagging'] ?? [],
						'invoice_settings'        => $wpkin_admin_settings['invoice_settings'] ?? [],
						'employee_management'     => $wpkin_admin_settings['employee_management'] ?? [],
						'chatbot_settings'        => $wpkin_admin_settings['chatbot_settings'] ?? [
							'enabled'              => true,
							'max_messages_per_day' => 50,
							'system_prompt_extra'  => '',
							'show_tool_calls'      => false,
						],
					],
					'appearance' => [
						'preset'        => $wpkin_admin_settings['appearance']['preset']        ?? 'compact',
						'colorScheme'   => $wpkin_admin_settings['appearance']['colorScheme']   ?? 'ocean',
						'darkMode'      => $wpkin_admin_settings['appearance']['darkMode']      ?? null,
						'preferredDark' => $wpkin_admin_settings['appearance']['preferredDark'] ?? $wpkin_admin_settings['appearance']['darkMode'] ?? 'slate',
					],
					'wp_roles' => array_map(
						fn( $role_key, $role_data ) => [ 'value' => $role_key, 'label' => $role_data['name'] ],
						array_keys( wp_roles()->roles ),
						array_values( wp_roles()->roles )
					),
					'currency'      => function_exists( 'get_woocommerce_currency_symbol' ) ? get_woocommerce_currency_symbol() : '$',
					'frontend_url'  => esc_url( home_url( '/sm-dashboard/' ) ),
				]
			);
		}
	}
}
