<?php

namespace Ilabs\Inpost_International\Backend;

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


use Ilabs\Inpost_International\Helpers\Helper;

/**
 * Orders_Bulk_Actions
 */
class Orders_Bulk_Actions {


	/**
	 * Helper instance for utility functions.
	 *
	 * @since 1.0.0
	 * @var Helper An instance of the Helper class that provides utility methods.
	 */
	private $helper;


	/**
	 * Constructor
	 */
	public function __construct() {
		$this->helper = Helper::init();
		$this->hooks();
	}
	/**
	 * 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 ) {
		$bulk_actions['inpost_intl_bulk_create_shipments'] = esc_html__( 'InPost INT create shipments', 'inpost-international' );

		$bulk_actions['inpost_intl_bulk_create_labels'] = esc_html__( 'InPost INT get labels', 'inpost-international' );

		return $bulk_actions;
	}


	/**
	 * Manage columns
	 *
	 * @param array $columns .
	 *
	 * @return array
	 */
	public function manage_edit_shop_order_columns( $columns ) {
		if ( isset( $columns['easypack_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['easypack_shipping_statuses'] = esc_html__( 'Inpost status', 'inpost-international' );
				$col_added                         = true;
			}
			$ret[ $key ] = $column;
		}

		if ( ! $col_added ) {
			$ret['easypack_shipping_statuses'] = esc_html__( 'Inpost status', 'inpost-international' );
		}

		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 ( 'easypack_shipping_statuses' !== $column ) {
			return;
		}

		$inpost_status = '';

		$order = wc_get_order( $post_id );

		if ( $order && ! is_wp_error( $order ) ) {

			$order_id     = $order->get_id();
			$tracking_url = $this->helper->get_tracking_url();

			foreach ( $order->get_shipping_methods() as $shipping_method ) {
				// if order was made via Flexible Shipping.

				$shipping_instance_id = $shipping_method->get_instance_id();
				$fs_method_name       = $this->helper->get_method_linked_to_fs_by_instance_id( $shipping_instance_id );

				if ( 0 === strpos( $shipping_method->get_method_id(), 'inpost_international_' )
					|| 0 === strpos( $fs_method_name, 'inpost_international_' )
				) {

					$created         = false;
					$tracking_number = '';
					$status          = $order->get_shipping_country();

					$package_data = $this->helper->get_package_meta( $order_id );
					if ( ! empty( $package_data['api_response']['trackingNumber'] ) ) {
						$tracking_number = $package_data['api_response']['trackingNumber'];
					}

					if ( ! empty( $package_data['api_response']['status'] ) ) {
						$created = $package_data['api_response']['status'];
					}

					if ( ! empty( $tracking_number ) ) {
						$uuid = '';

						if ( ! empty( $package_data['api_response']['uuid'] ) ) {
							$uuid = $package_data['api_response']['uuid'];
						}

						$full_tracking_link = $tracking_url . $tracking_number;

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

						$link_to_tracking = sprintf(
							'<a data-tracking-id="%1s" data-order-id="%2s" data-uuid="%3s" class="inpost_intl_order_list_tracking_number" href="%4s">%5s</a>',
							esc_attr( $tracking_number ),
							esc_attr( $order_id ),
							esc_attr( $uuid ),
							esc_url( $full_tracking_link ),
							esc_attr( $tracking_number )
						);

						$animation_2 = inpost_intl_core()->get_plugin_images_url() . '/animation-round-small.gif';

						$preloader = sprintf(
							'<span data-id="%1s" class="inpost_intl_order_list_preloader"><img class="inpost_intl_preloader" src="%2s" alt="inpost international preloader"/></span><span data-id="%3s" class="inpost_intl_order_list_status_error"></span>',
							esc_attr( $order_id ),
							esc_url( $animation_2 ),
							esc_attr( $order_id ),
						);

						$shipping_method_name = $shipping_method->get_method_title();

						$inpost_status = '<div class="inpost-status-inside-td">'
										// . $print_label_icon . ' ' . $status . ': ' . $shipping_method_name . ' ' . $link_to_tracking
										. $print_label_icon . ' ' . $status . ' ' . $link_to_tracking
										. $preloader
										. '</div>';

					} else {
						$inpost_status = '<div class="inpost-status-inside-td">'
										. esc_html__( 'Not created yet', 'inpost-international' )
										. ' ('
										. ' ' . $status . ': ' . $shipping_method->get_method_title()
										. ')'
										. '<span data-id="' . esc_attr( $order_id ) . '" class="inpost_intl_order_list_status_error"></span></div>';
					}
				}
			}
		}

		echo wp_kses_post( $inpost_status );
	}


	/**
	 * 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 = inpost_intl_core()->get_plugin_version();

			$helper                     = new Helper();
			$order_bulk_actions_js_path = inpost_intl_core()->get_plugin_dir() . 'assets/js/order-bulk-actions.js';
			$order_bulk_actions_js_ver  = file_exists( $order_bulk_actions_js_path ) ? filemtime( $order_bulk_actions_js_path ) : $current_plugin_version;
			wp_enqueue_script(
				inpost_intl_core()->get_plugin_prefix() . '_order_bulk_actions_js',
				inpost_intl_core()->get_plugin_js_url() . '/order-bulk-actions.js',
				array( 'jquery' ),
				$order_bulk_actions_js_ver,
				array( 'in_footer' => true )
			);
			wp_localize_script(
				inpost_intl_core()->get_plugin_prefix() . '_order_bulk_actions_js',
				'inpost_intl_orders_bulk',
				array(
					'ajaxurl'    => admin_url( 'admin-ajax.php' ),
					'logo_src'   => inpost_intl_core()->get_plugin_images_url() . '/white.png',
					'nonce'      => wp_create_nonce( 'inpost_international_ajax' ),
					'log_path'   => $helper->get_woocommerce_logs_section_url(),
					'img_path'   => inpost_intl_core()->get_plugin_images_url(),
					'jszip_path' => inpost_intl_core()->get_plugin_js_url() . '/jszip.min.js',
					'animation'  => inpost_intl_core()->get_plugin_images_url() . '/animation-round-small.gif',
					'hpos'  => 'yes' === get_option( 'woocommerce_custom_orders_table_enabled' ),
				)
			);

			$order_list_bulk_css_path = inpost_intl_core()->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(
				inpost_intl_core()->get_plugin_prefix() . '_order_bulk_actions_css',
				inpost_intl_core()->get_plugin_css_url() . '/order-bulk-actions.css',
				array(),
				$order_list_bulk_css_ver
			);

			add_action( 'admin_footer', array( $helper, 'package_status_modal' ), 100 );
		}
	}
}
