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

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

		public function __construct() {
			add_action('rest_api_init', array($this, 'register_api_routes'));
			add_action('init', array($this, 'register_custom_order_statuses'));
			add_filter('wc_order_statuses', array($this, 'add_custom_statuses_to_order_list'));
		}

		// Register API Routes
		public function register_api_routes() {
			register_rest_route('asofw/v1', '/create-status', array(
				'methods'             => 'POST',
				'callback'            => array( $this, 'asofw_create_status' ),
				'permission_callback' => array( $this, 'verify_nonce_and_permissions' )
			));

			register_rest_route('asofw/v1', '/statuses', array(
				'methods'             => 'GET',
				'callback'            => array( $this, 'asofw_get_statuses' ),
				'permission_callback' => '__return_true'
			));

			register_rest_route('asofw/v1', '/edit-status/(?P<slug>[a-zA-Z0-9-]+)', array(
				'methods'             => 'PUT',
				'callback'            => array( $this, 'asofw_edit_status' ),
				'permission_callback' => array( $this, 'verify_nonce_and_permissions' ),
				'args' => array(
					'slug' => array(
						'required' => true,
						'validate_callback' => function($param) {
							return is_string($param);
						}
					)
				)
			));

			register_rest_route('asofw/v1', '/delete-status/(?P<slug>[a-zA-Z0-9-]+)', array(
				'methods'             => 'DELETE',
				'callback'            => array( $this, 'asofw_delete_status' ),
				'permission_callback' => array( $this, 'verify_nonce_and_permissions' )
			));
		}

		// Callback for creating a new status
		public function asofw_create_status($request) {
			$nonce = $request->get_header('X-WP-Nonce');
			if (!wp_verify_nonce($nonce, 'wp_rest')) {
				return new WP_Error('rest_forbidden', __('Invalid nonce.', 'advanced-order-status-for-woocommerce'), array('status' => 403));
			}

			$params = $request->get_json_params();
			if (empty($params['statusSlug']) || empty($params['statusName'])) {
				return new WP_Error('missing_parameters', __('Missing required parameters: statusSlug, statusName', 'advanced-order-status-for-woocommerce'), array('status' => 400));
			}

			$slug = sanitize_title($params['statusSlug']);
			$wc_slug = 'wc-' . $slug;
			
			// Check if status already exists
			$existing_statuses = get_option('asofw_custom_statuses', array());
			if (isset($existing_statuses[$slug])) {
				return new WP_Error('status_exists', __('Status already exists', 'advanced-order-status-for-woocommerce'), array('status' => 400));
			}

			$existing_statuses[$slug] = array(
				'statusName' => sanitize_text_field($params['statusName']),
				'dashicon' => isset($params['dashicon']) ? sanitize_text_field($params['dashicon']) : '',
				'statusColor' => isset($params['statusColor']) ? sanitize_hex_color($params['statusColor']) : '#f8dda7'
			);

			update_option('asofw_custom_statuses', $existing_statuses);

			// Clear WooCommerce transients
			if (function_exists('wc_delete_shop_order_transients')) {
				wc_delete_shop_order_transients();
			}

			// Flush rewrite rules to ensure new status works
			flush_rewrite_rules();

			return new WP_REST_Response(array(
				'success' => true,
				'slug' => $slug,
				'wc_slug' => $wc_slug,
				/* translators: %s: Status name */
				'message' => sprintf(__('Status "%s" created successfully', 'advanced-order-status-for-woocommerce'), $params['statusName'])
			), 201);
		}

		// Callback for fetching all custom statuses
		public function asofw_get_statuses() {
			$statuses = get_option('asofw_custom_statuses', []);
			return rest_ensure_response($statuses);
		}

		// Callback for editing a custom status
		public function asofw_edit_status($request) {
			$slug = $request['slug'];
			$params = $request->get_json_params();
			
			if (empty($params['statusName']) || empty($params['dashicon']) || empty($params['statusColor'])) {
				return new WP_Error(
					'missing_parameters', 
					__('Missing required parameters', 'advanced-order-status-for-woocommerce'), 
					array('status' => 400)
				);
			}

			$statuses = get_option('asofw_custom_statuses', array());
			if (isset($statuses[$slug])) {
				$statuses[$slug] = array(
					'statusName' => sanitize_text_field($params['statusName']),
					'dashicon' => sanitize_text_field($params['dashicon']),
					'statusColor' => sanitize_hex_color($params['statusColor'])
				);

				update_option('asofw_custom_statuses', $statuses);
				
				// Clear WooCommerce transients
				if (function_exists('wc_delete_shop_order_transients')) {
					wc_delete_shop_order_transients();
				}

				return rest_ensure_response(array(
					'success' => true,
					'message' => __('Status updated successfully', 'advanced-order-status-for-woocommerce'),
					'status' => $statuses[$slug]
				));
			}

			return new WP_Error(
				'status_not_found', 
				__('Status not found', 'advanced-order-status-for-woocommerce'), 
				array('status' => 404)
			);
		}

		// Callback for deleting a custom status
		public function asofw_delete_status($request) {
			$slug = $request['slug'];
			
			$statuses = get_option('asofw_custom_statuses', array());
			if (isset($statuses[$slug])) {
				unset($statuses[$slug]);
				update_option('asofw_custom_statuses', $statuses);
				
				// Clear WooCommerce transients
				if (function_exists('wc_delete_shop_order_transients')) {
					wc_delete_shop_order_transients();
				}
				
				return rest_ensure_response(array(
					'success' => true,
					'message' => __('Status deleted successfully', 'advanced-order-status-for-woocommerce')
				));
			}

			return new WP_Error(
				'status_not_found', 
				__('Status not found', 'advanced-order-status-for-woocommerce'), 
				array('status' => 404)
			);
		}

		// Verify nonce and permissions for the API
		public function verify_nonce_and_permissions( $request ) {
			$nonce = $request->get_header('X-WP-Nonce'); 
			if ( !$nonce ) {
				return new WP_Error( 
					'rest_missing_nonce', 
					__('You do not have permission to access this resource. Please contact the administrator if you believe this is an error.', 'advanced-order-status-for-woocommerce'), 
					array( 
						'status' => 403, 
						'message' => 'Nonce is missing.' 
					) 
				);
			}
			return true;
		}

		// Register custom order statuses
		public function register_custom_order_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' => $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(
						'%s order with this status',
						'%s orders with this status',
						'advanced-order-status-for-woocommerce'
					)
				));
			}
		}

		// Add custom statuses to WooCommerce order status list
		public function add_custom_statuses_to_order_list($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;
		}
	}

	new AOSFW_API();
}