<?php
/**
 * Order Labels Logic — Handles generation of InPost labels.
 * 
 * @package ParcelSelector
 */

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

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

	public static function init() {
		add_action( 'wp_ajax_parcselect_generate_label', array( __CLASS__, 'ajax_generate_label' ) );
	}

	/**
	 * AJAX handler for legacy label generation endpoint.
	 *
	 * Returns a safe message directing the admin to use the Shipping Label panel.
	 */
	public static function ajax_generate_label() {
		check_ajax_referer( 'parcselect_order_admin_nonce', 'nonce' );

		if ( ! current_user_can( 'manage_woocommerce' ) ) {
			wp_send_json_error( array( 'message' => 'Permission denied.' ), 403 );
		}

		$order_id = isset( $_POST['order_id'] ) ? absint( $_POST['order_id'] ) : 0;
		$order    = wc_get_order( $order_id );

		if ( ! $order ) {
			wp_send_json_error( array( 'message' => 'Order not found.' ), 404 );
		}

		// Cross-install leak guard — purge & ignore meta from another install.
		if ( class_exists( 'Parcselect_Label_Installation' )
			&& ! Parcselect_Label_Installation::owns( $order )
			&& Parcselect_Label_Installation::has_any_label_meta( $order ) ) {
			Parcselect_Label_Installation::purge_order( $order );
		}
		$label_status = $order->get_meta( '_ps_label_status', true );
		if ( 'completed' === $label_status ) {
			$tracking = $order->get_meta( '_ps_label_tracking_number', true );
			wp_send_json_success( array(
				'message'  => __( 'Label already exists.', 'parcel-selector' ),
				'label_id' => $tracking,
			) );
		}

		wp_send_json_error( array(
			'message' => __( 'Use the Shipping Label panel on the order page to create a shipping label.', 'parcel-selector' ),
		) );
	}
}

Parcselect_Order_Labels::init();
}

