<?php
defined('ABSPATH') || exit;

if ( ! class_exists( 'AOSFW_Register' ) ) {
	class AOSFW_Register {

		public function __construct() {
			add_action('admin_menu', array($this, 'aosfw_create_menu'));
			add_action('admin_enqueue_scripts', array($this, 'aosfw_scripts'));
			add_action('init', array($this, 'load_custom_statuses'));
			add_action('admin_head', array($this, 'add_custom_status_icons'));

			add_filter('bulk_actions-edit-shop_order', array($this, 'add_custom_status_bulk_actions'));
			add_filter('bulk_actions-woocommerce_page_wc-orders', array($this, 'add_custom_status_bulk_actions'));

			add_filter('handle_bulk_actions-edit-shop_order', array($this, 'process_custom_status_bulk_actions'), 10, 3);
			add_filter('handle_bulk_actions-woocommerce_page_wc-orders', array($this, 'process_custom_status_bulk_actions'), 10, 3);
			//add_action('admin_notices', array($this, 'custom_status_admin_notice'));
		}
		
		public function add_custom_status_icons() {
			$custom_statuses = get_option('asofw_custom_statuses', array());

			if (empty($custom_statuses)) {
				return;
			}

			echo '<style>';
			foreach ($custom_statuses as $slug => $status_data) {
				$bg_color = $status_data['statusColor'] ?? '#080604';
				$text_color = '#080604'; // Fixed text color

				echo '.order-status.status-' . esc_attr(str_replace('wc-', '', $slug)) . ' {'; 
				echo '  background: ' . esc_attr($bg_color) . ';';
				echo '  color: ' . esc_attr($text_color) . ';';
				echo '}';

				if (!empty($status_data['dashicon'])) {
					$icon = $status_data['dashicon'];
					if (strpos($icon, '\\') !== 0 && strpos($icon, 'f') === 0) {
						$icon = '\\' . $icon;
					}

					echo '.order-status.status-' . esc_attr(str_replace('wc-', '', $slug)) . '::before {'; 
					echo '  font-family: dashicons;'; 
					echo '  content: "' . esc_attr($icon) . '";';
					echo '  margin-right: 4px;';
					echo '  vertical-align: middle;';
					echo '}';
				}
			}
			echo '</style>';
		}

		public function add_custom_status_bulk_actions($bulk_actions) {
			$custom_statuses = get_option('asofw_custom_statuses', array());
			
			foreach ($custom_statuses as $slug => $status_data) {
				// Remove 'wc-' prefix if it exists
				$action_slug = str_replace('wc-', '', $slug);
				/* translators: %s: Status name */
				$bulk_actions['mark_' . $action_slug] = sprintf(
					/* translators: %s: Status name */
					esc_html__('Change status to %s', 'advanced-order-status-for-woocommerce'),
					esc_html($status_data['statusName'])
				);
			}
			
			return $bulk_actions;
		}

		public function process_custom_status_bulk_actions($redirect_to, $action, $post_ids) {
			$custom_statuses = get_option('asofw_custom_statuses', array());
			
			foreach ($custom_statuses as $slug => $status_data) {
				$action_slug = str_replace('wc-', '', $slug);
				if ('mark_' . $action_slug === $action) {
					$changed = 0;
					
					foreach ($post_ids as $post_id) {
						$order = wc_get_order($post_id);
						if ($order) {
							$order->update_status(
								$action_slug,
								__('Status changed via bulk action', 'advanced-order-status-for-woocommerce'),
								true
							);
							$changed++;
						}
					}
					
					$redirect_to = add_query_arg(array(
						'changed' => $changed,
						'ids' => join(',', $post_ids),
						'custom_status_updated' => true
					), $redirect_to);
					
					break;
				}
			}
			
			return $redirect_to;
		}

		// public function custom_status_admin_notice() {
		// 	$data = $_REQUEST;
		// 	if (!empty($data['custom_status_updated']) && !empty($data['changed'])) {
		// 		$count = intval($data['changed']);
				
		// 		$message = wp_kses(
					
		// 			sprintf(
		// 				/* translators: %d: Number of orders updated */
		// 				_n(
		// 					'%d order status updated.',
		// 					'%d order statuses updated.',
		// 					$count,
		// 					'advanced-order-status-for-woocommerce'
		// 				),
		// 				esc_html($count)
		// 			),
		// 			array('p' => array())
		// 		);
				
		// 		printf(
		// 			'<div class="updated notice"><p>%s</p></div>',
		// 			wp_kses_post($message)
		// 		);
		// 	}
		// }

		public function load_custom_statuses() {
			$custom_statuses = get_option('asofw_custom_statuses', array());
			foreach ($custom_statuses as $slug => $status_data) {
				$wc_slug = 'wc-' . $slug;
				
				register_post_status($wc_slug, array(
					'label' => esc_html($status_data['statusName']),
					'public' => true,
					'exclude_from_search' => false,
					'show_in_admin_all_list' => true,
					'show_in_admin_status_list' => true,
					/* translators: %s: number of orders */
					'label_count' => _n_noop(
						'Order (%s)',
						'Orders (%s)',
						'advanced-order-status-for-woocommerce'
					)
				));
			}
		}

		public function add_custom_statuses_to_wc($order_statuses) {
			$custom_statuses = get_option('asofw_custom_statuses', array());
			foreach ($custom_statuses as $slug => $status_data) {
				$wc_slug = 'wc-' . $slug;
				$order_statuses[$wc_slug] = $status_data['statusName'];
			}
			return $order_statuses;
		}

		public function aosfw_create_menu() {
			add_submenu_page(
				'woocommerce',                      
				__('Advanced Order Status', 'advanced-order-status-for-woocommerce'),
				__('Advanced Order Status', 'advanced-order-status-for-woocommerce'),
				'manage_woocommerce',               
				'advanced-order-status-for-woocommerce',              
				array( $this, 'aosfw_menu_page_callback' ), 
				35
			);
		}

		public function aosfw_menu_page_callback() {
			wp_enqueue_script( 'aosfw-script' );
			echo '<div id="aosfw-admin"></div>';
		}

		public function aosfw_scripts() {
			wp_register_script('aosfw-script', AOSFW_URL . 'build/index.bundle.js', array( 'wp-element' ), '1.0.0', true);
			wp_localize_script('aosfw-script', 'AOSFW_APP', array(
				'root' => esc_url_raw(rest_url()),
				'nonce' => wp_create_nonce('wp_rest'),
			));
		}
	}

	new AOSFW_Register();
}
