<?php

namespace Inspire_Labs\Alsendo_Connect;

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

/**
 * Orders_Bulk_Actions
 */
class Order_Bulk_Actions {


	/**
	 * @var Helper
	 */
	private $helper;

	/**
	 * Constructor
	 */
	public function __construct() {
		$this->hooks();
		$this->helper = new Helper();
	}

	/**
	 * Hooks
	 *
	 * @return void
	 */
	public function hooks() {
		add_filter( 'bulk_actions-edit-shop_order', array( $this, 'register_bulk_action' ) );
		add_filter( 'bulk_actions-woocommerce_page_wc-orders', array( $this, 'register_bulk_action' ) );
		add_action( 'admin_enqueue_scripts', array( $this, 'enqueue_admin_scripts' ), 75 );
		add_filter( 'manage_woocommerce_page_wc-orders_columns', array( $this, 'manage_edit_shop_order_columns' ), 11 );
		add_filter( 'manage_edit-shop_order_columns', array( $this, 'manage_edit_shop_order_columns' ), 11 );

		add_action( 'wp_ajax_easypack_bulk_create_shipments', array( $this, 'bulk_create_parcels_callback' ) );

		add_action( 'manage_shop_order_posts_custom_column', array( $this, 'manage_shop_order_posts_custom_column' ), 11, 2 );
		add_action( 'manage_woocommerce_page_wc-orders_custom_column', array( $this, 'manage_shop_order_posts_custom_column' ), 11, 2 );
	}


	/**
	 * Register custom actions
	 *
	 * @param array $bulk_actions $bulk_actions.
	 *
	 * @return array
	 */
	public function register_bulk_action( $bulk_actions ) {

		$api_type = alsendo_connect()->get_main_settings_api();
		if ( 'zaslat' === $api_type ) {
			return $bulk_actions;
		}

		$bulk_actions['alsendo_cnt_bulk_create_shipments'] = esc_html__( 'Alsendo Connect create shipments', 'alsendo-connect' );

		$bulk_actions['alsendo_cnt_bulk_create_labels']    = esc_html__( 'Alsendo Connect get labels', 'alsendo-connect' );
		$bulk_actions['alsendo_cnt_bulk_cancel_shipments'] = esc_html__( 'Alsendo Connect cancel shipments', 'alsendo-connect' );

		return $bulk_actions;
	}


	/**
	 * Manage columns
	 *
	 * @param array $columns .
	 *
	 * @return array
	 */
	public function manage_edit_shop_order_columns( $columns ) {

		$api_type = alsendo_connect()->get_main_settings_api();
		if ( 'zaslat' === $api_type ) {
			return $columns;
		}

		if ( isset( $columns['alsendo_connect_shipping_statuses'] ) ) {
			return $columns;
		}

		$ret = array();

		$col_added = false;

		foreach ( $columns as $key => $column ) {
			if ( ! $col_added && in_array( $key, array( 'order_actions', 'wc_actions' ), true ) ) {
				$ret['alsendo_connect_shipping_statuses'] = esc_html__( 'Alsendo status 📦', 'alsendo-connect' );
				$col_added                                = true;
			}
			$ret[ $key ] = $column;
		}

		if ( ! $col_added ) {
			$ret['alsendo_connect_shipping_statuses'] = esc_html__( 'Alsendo status 📦', 'alsendo-connect' );
		}

		return $ret;
	}



	/**
	 * Manage columns
	 *
	 * @param string $column $column.
	 * @param mixed  $post_id   $post_id.
	 *
	 * @return void
	 */
	public function manage_shop_order_posts_custom_column( $column, $post_id ) {
		if ( 'alsendo_connect_shipping_statuses' !== $column ) {
			return;
		}

		$parcel_status          = '';
		$tracking_url           = '';
		$shipping_method_title  = '';
		$is_alsendo_order       = false;
		$alsendo_order_created  = false;
		$alsendo_api_carrier_id = '';

		$order = wc_get_order( $post_id );

		if ( ! $order || is_wp_error( $order ) ) {
			return;
		}

		$order_id = $order->get_id();

		$order_meta = alsendo_connect()->get_order_meta_data( $order_id );
		if ( ! empty( $order_meta ) ) {
			$is_alsendo_order = true;
			if ( ! empty( $order_meta['package_send'] ) ) {
				$alsendo_order_created = ! empty( $order_meta['alsendo_order'] ) ? true : false;
			}
		}

		if ( ! $is_alsendo_order ) {
			return;
		}

		$api_type         = alsendo_connect()->get_main_settings_api();
		$shipping_country = $order->get_shipping_country();
		$country_notice   = '';
		if ( 'RO' !== $shipping_country ) {
			$country_notice = $shipping_country . ': ';
		}

		foreach ( $order->get_shipping_methods() as $shipping_method ) {
			$shipping_method_title = $shipping_method->get_method_title();
		}

		$alsendo_api_carrier_id = $this->helper->get_linked_carrier_id( $order_id );

		/*$print_label_icon = sprintf(
			'<a style="padding:2px;" class="alsendo_connect_order_list_create button-secondary btn-shipment-action" data-order-id="%s" data-carrier-id="%s" title="Alsendo Connect create shipment"><img class="alsendo_connect_order_list_create" alt="Alsendo Connect create shipment" src="%s" data-order-id="%s" data-carrier-id="%s"></a>',
			esc_attr( $order_id ),
			esc_attr( $alsendo_api_carrier_id ),
			esc_url( alsendo_connect()->get_plugin_img_url() . '/alsendo-triangle.jpg' ),
			esc_attr( $order_id ),
			esc_attr( $alsendo_api_carrier_id )
		);*/

		$animation = alsendo_connect()->get_plugin_img_url() . '/animation-round-small.gif';

		$preloader = sprintf(
			'<span data-id="%s" class="alsendo_connect_order_list_preloader"><img class="alsendo_connect_preloader" src="%s" alt="preloader"/></span><span data-id="%s" class="alsendo_connect_order_list_status_error"></span>',
			esc_attr( $order_id ),
			esc_url( $animation ),
			esc_attr( $order_id ),
		);

		//$package_template_data = $this->helper->get_package_template_data();
		$package_template_selector = $this->helper->get_package_template_selector();

		$parcel_status = '<div data-carrier-id="' . esc_attr( $alsendo_api_carrier_id ) . '" class="alsendo-connect-inside-td">'
						/*. $print_label_icon . ' '*/
						. esc_html__( 'Not created yet', 'alsendo-connect' )
						. ' ('
						. $country_notice . '<span data-method-id="' . esc_attr( $order_id ) . '" class="alsendo-method-name">' . $shipping_method_title . '</span>'
						. ')'
						//. $package_template_data
						. $package_template_selector
						. $preloader
						. '</div>';

		if ( $alsendo_order_created ) {

			if ( 'apaczka' === $api_type ) {
				if ( ! empty( $order_meta['alsendo_order']['waybill_number'] ) ) {
					$package_number = $order_meta['alsendo_order']['waybill_number'];

					$tracking_url = ! empty( $order_meta['alsendo_order']['tracking_url'] ) ? $order_meta['alsendo_order']['tracking_url'] : '';

					$uuid = '';

					if ( ! empty( $order_meta['alsendo_order']['id'] ) ) {
						$uuid = $order_meta['alsendo_order']['id'];
					}

					$print_label_icon = sprintf(
						'<a style="padding:2px;" class="alsendo_connect_order_list_label btn-clone button-secondary btn-shipment-action" data-order-id="%s" data-uuid="%s" title="Get Alsendo Connect label"><span class="alsendo_connect_order_list_label dashicons dashicons-admin-page" data-order-id="%s" data-uuid="%s"></span></a>',
						esc_attr( $order_id ),
						esc_attr( $uuid ),
						esc_attr( $order_id ),
						esc_attr( $uuid ),
					);

					$link_to_tracking = sprintf(
						'<a data-carrier-id="%s" data-tracking-id="%s" data-order-id="%s" data-uuid="%s" class="alsendo_connect_order_list_tracking_number" href="%s">%s</a>',
						esc_attr( $alsendo_api_carrier_id ),
						esc_attr( $package_number ),
						esc_attr( $order_id ),
						esc_attr( $uuid ),
						esc_url( $tracking_url ),
						esc_attr( $package_number )
					);

					$parcel_status = '<div class="alsendo-connect-status-inside-td">'
									. $country_notice . $shipping_method_title
									. '<br>'
									. $print_label_icon . ' ' . $link_to_tracking
									. $preloader
									. '</div>';
				}
			}

			if ( 'ecolet' === $api_type ) {
				if ( ! empty( $order_meta['alsendo_order']['ecolet_awb_id'] ) ) {
					$package_number = $order_meta['alsendo_order']['ecolet_awb_id'];
					$ecolet         = new Ecolet();
					$tracking_url   = $ecolet->get_tracking_url( $package_number );

					$uuid = '';

					if ( ! empty( $order_meta['alsendo_order']['id'] ) ) {
						$uuid = $order_meta['alsendo_order']['id'];
					}

					$print_label_icon = sprintf(
						'<a style="padding:2px;" class="alsendo_connect_order_list_label btn-clone button-secondary btn-shipment-action" data-order-id="%s" data-uuid="%s" title="Get Alsendo Connect label"><span class="alsendo_connect_order_list_label dashicons dashicons-admin-page" data-order-id="%s" data-uuid="%s"></span></a>',
						esc_attr( $order_id ),
						esc_attr( $uuid ),
						esc_attr( $order_id ),
						esc_attr( $uuid ),
					);

					$link_to_tracking = sprintf(
						'<a data-tracking-id="%s" data-order-id="%s" data-uuid="%s" class="alsendo_connect_order_list_tracking_number" href="%s">%s</a>',
						esc_attr( $package_number ),
						esc_attr( $order_id ),
						esc_attr( $uuid ),
						esc_url( $tracking_url ),
						esc_attr( $package_number )
					);

					$parcel_status = '<div class="alsendo-connect-status-inside-td">'
									. $country_notice . $shipping_method_title
									. '<br>'
									. $print_label_icon . ' ' . $country_notice . ' ' . $link_to_tracking
									. $preloader
									. '</div>';
				}
			}
		}

		//echo wp_kses_post( $parcel_status );
		$allowed_html = array(
			'td'     => array(
				'class'        => array(),
				'data-colname' => array(),
			),
			'div'    => array(
				'data-carrier-id' => array(),
				'class'           => array(),
			),
			'span'   => array(
				'data-method-id'   => array(),
				'class'            => array(),
				'data-id'          => array(),
				'data-order-id'    => array(),
				'data-uuid'        => array(),
				'data-tracking-id' => array(),
			),
			'select' => array(
				'class' => array(),
				'id'    => array(),
			),
			'option' => array(
				'value'    => array(),
				'selected' => array(),
			),
			'img'    => array(
				'class' => array(),
				'src'   => array(),
				'alt'   => array(),
			),
			'br'     => array(),
			'a'      => array(
				'style'            => array(),
				'class'            => array(),
				'data-order-id'    => array(),
				'data-uuid'        => array(),
				'title'            => array(),
				'href'             => array(),
				'data-carrier-id'  => array(),
				'data-tracking-id' => array(),
			),
		);

		echo wp_kses( $parcel_status, $allowed_html );
	}



	/**
	 * Enqueue admin scripts
	 *
	 * @return void
	 * @throws \Exception Exception
	 */
	public function enqueue_admin_scripts() {

		if ( isset( $_GET['action'] ) && 'edit' === $_GET['action'] ) {
			return;
		}

		$current_screen = get_current_screen();
		// only on order's list page.
		if ( ( is_a( $current_screen, 'WP_Screen' ) && 'edit-shop_order' === $current_screen->id )
			|| 'woocommerce_page_wc-orders' === $current_screen->id ) {

			$current_plugin_version     = alsendo_connect()->get_plugin_version();
			$api_type                   = alsendo_connect()->get_main_settings_api();
			$order_bulk_actions_js_path = '';
			$order_bulk_actions_js_src  = null;
			$order_bulk_actions_js_ver  = '';
			$tracking_url               = '';

			$order_list_bulk_css_path = alsendo_connect()->get_plugin_dir() . 'assets/css/order-bulk-actions.css';
			$order_list_bulk_css_ver  = file_exists( $order_list_bulk_css_path ) ? filemtime( $order_list_bulk_css_path ) : $current_plugin_version;
			wp_enqueue_style(
				alsendo_connect()->get_plugin_prefix() . '_order_bulk_actions_css',
				alsendo_connect()->get_plugin_css_url() . '/order-bulk-actions.css',
				array(),
				$order_list_bulk_css_ver
			);

			if ( 'ecolet' === $api_type ) {
				$order_bulk_actions_js_path = alsendo_connect()->get_plugin_dir() . 'assets/js/order-bulk-actions-ecolet.js';
				$order_bulk_actions_js_ver  = file_exists( $order_bulk_actions_js_path ) ? filemtime( $order_bulk_actions_js_path ) : $current_plugin_version;
				$order_bulk_actions_js_src  = alsendo_connect()->get_plugin_js_url() . '/order-bulk-actions-ecolet.js';

				$ecolet       = new Ecolet();
				$tracking_url = $ecolet->get_tracking_url();
			}

			if ( 'apaczka' === $api_type ) {
				$order_bulk_actions_js_path = alsendo_connect()->get_plugin_dir() . 'assets/js/order-bulk-actions-apaczka.js';
				$order_bulk_actions_js_ver  = file_exists( $order_bulk_actions_js_path ) ? filemtime( $order_bulk_actions_js_path ) : $current_plugin_version;
				$order_bulk_actions_js_src  = alsendo_connect()->get_plugin_js_url() . '/order-bulk-actions-apaczka.js';
			}

			if ( ! $order_bulk_actions_js_src ) {
				return;
			}

			wp_enqueue_script(
				alsendo_connect()->get_plugin_prefix() . '_order_bulk_actions',
				$order_bulk_actions_js_src,
				array( 'jquery' ),
				$order_bulk_actions_js_ver,
				array( 'in_footer' => true )
			);
			wp_localize_script(
				alsendo_connect()->get_plugin_prefix() . '_order_bulk_actions',
				'alsendo_connect_orders_bulk',
				array(
					'ajaxurl'              => admin_url( 'admin-ajax.php' ),
					//'logo_src'   => alsendo_connect()->get_plugin_img_url() . '/white.png',
					'nonce'                => wp_create_nonce( 'alsendo_connect_order_metabox' ),
					'log_path'             => alsendo_connect()->get_woocommerce_logs_section_url(),
					'img_path'             => alsendo_connect()->get_plugin_img_url(),
					'tracking_url'         => esc_url( $tracking_url ),
					'jszip_path'           => alsendo_connect()->get_plugin_js_url() . '/jszip.min.js',
					'animation'            => alsendo_connect()->get_plugin_img_url() . '/animation-round-small.gif',
					'hpos'                 => 'yes' === get_option( 'woocommerce_custom_orders_table_enabled' ),
					'admin_url'            => get_admin_url( null, '', 'admin' ),
					'notice_text'          => esc_html__( 'Notice', 'alsendo-connect' ),
					'already_created_text' => esc_html__( 'Already created', 'alsendo-connect' ),
					'api_method_text'      => esc_html__( 'API method: ', 'alsendo-connect' ),
					'cancelled_text'       => esc_html__( 'Cancelled', 'alsendo-connect' ),
				)
			);

			add_action( 'admin_footer', array( $this, 'package_status_modal' ), 100 );

		}
	}



	/**
	 * Renders the HTML for the Alsendo Connect package status modal.
	 *
	 * This function outputs the HTML structure for a modal dialog that displays
	 * package status information for Alsendo Connect shipments. The modal
	 * includes the Alsendo Connect logo, tracking number display, and a placeholder for
	 * status text.
	 *
	 * @since 1.0.0
	 *
	 * @uses alsendo_connect()->get_plugin_images_url() To get the URL for plugin images.
	 * @uses esc_attr() To escape the image URL for safe output in an HTML attribute.
	 * @uses esc_html__() To translate and escape text for output.
	 *
	 * @return void Outputs HTML directly.
	 */
	public function package_status_modal() {

		$img = alsendo_connect()->get_plugin_img_url() . '/alsendo-logo.jpg';
		?>

		<div id="alsendo_connect_status_modal" class="alsendo_connect_status_modal">
			<div class="modalCover"></div>
			<div class="modalContext">
				<!-- Close button X -->
				<div class="alsendo_connect_status_modal_close">
					<span class="alsendo_connect_status_modal_close close-x">×</span>
				</div>
				<div class="alsendo_connect_status_modal_close"></div>
				<div class="alsendo_connect_status_modal_text_wrapper">
					<img id="alsendo_connect_logo" src="<?php echo esc_attr( $img ); ?>">
				</div>
				<div class="alsendo_connect_status_modal_title">
					<h2 class="alsendo_connect_status_modal_sub_title"></h2>
					<h3><span class="alsendo_connect_status_modal_tracking"></span></h3>
				</div>
				<div class="alsendo_connect_status_modal_text">
				</div>
				<div class="alsendo_connect_status_modal_action">
					<button class="alsendo_connect_status_modal_close_button">Ok</button>
				</div>
			</div>
		</div>

		<?php
	}
}
