<?php

namespace Ilabs\Inpost_International\Settings;

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


use Ilabs\Inpost_International\Helpers\Helper;
use WP_List_Table;
use WP_Query;

/**
 * Manage_Products_Table
 */
class Manage_Products_Table extends WP_List_Table {

	/**
	 * All configured Inpost International shipping methods
	 *
	 * @var $all_inpost_methods;
	 */
	private static $all_inpost_methods = array();

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

	/**
	 * Constructor
	 */
	public function __construct() {
		parent::__construct(
			array(
				'singular' => 'product',
				'plural'   => 'products',
				'ajax'     => false,
			)
		);

		$this->helper             = Helper::init();
		self::$all_inpost_methods = $this->helper->get_inpost_shipping_methods();
	}


	/**
	 * Prepare items
	 *
	 * @return void
	 */
	public function prepare_items() {

		$columns               = $this->get_columns();
		$hidden                = array();
		$sortable              = $this->get_sortable_columns();
		$this->_column_headers = array( $columns, $hidden, $sortable );

		$per_page = 20;

		if ( ! empty( $_REQUEST['nonce'] ) ) {
			check_ajax_referer( 'inpost_international_ajax', 'nonce' );
		}

		if ( isset( $_GET['page'] ) && 'inpost-international-api' === $_GET['page'] && isset( $_GET['tab'] ) && 'products' === $_GET['tab'] ) {
			if ( isset( $_REQUEST['per_page'] ) && is_numeric( $_REQUEST['per_page'] ) ) {
				$per_page = intval( wp_unslash( $_REQUEST['per_page'] ) );
			}
		}

		$current_page = $this->get_pagenum();
		$total_items  = $this->get_total_products();

		$this->set_pagination_args(
			array(
				'total_items' => $total_items,
				'per_page'    => $per_page,
			)
		);

		$this->items = $this->get_products( $per_page, $current_page );
	}

	/**
	 * Get columns
	 *
	 * @return array
	 */
	public function get_columns() {
		$columns = array(
			'cb'                   => '<input type="checkbox" />',
			'title'                => esc_html__( 'Product', 'inpost-international' ),
			'img'                  => esc_html__( 'Img', 'inpost-international' ),
			'sku'                  => esc_html__( 'SKU', 'inpost-international' ),
			'categories'           => esc_html__( 'Categories', 'inpost-international' ),
			'shipping_methods'     => esc_html__( 'Allowed Shipping Methods', 'inpost-international' ),
			'locker'               => esc_html__( 'Locker size', 'inpost-international' ),
			'action_button_result' => esc_html__( 'Status', 'inpost-international' ),
		);
		return $columns;
	}

	/**
	 * Get sortable columns
	 *
	 * @return array[]
	 */
	public function get_sortable_columns() {
		$sortable_columns = array(
			'title' => array( 'title', false ),
			'sku'   => array( 'sku', false ),
		);
		return $sortable_columns;
	}


	/**
	 * Get totalproducts
	 *
	 * @return int
	 */
	private function get_total_products() {

		if ( ! empty( $_REQUEST['nonce'] ) ) {
			check_ajax_referer( 'inpost_international_ajax', 'nonce' );
		}

		$args = array(
			'post_type'      => 'product',
			'post_status'    => 'publish',
			'fields'         => 'ids',
			'posts_per_page' => 1,
			'no_found_rows'  => false,
			'paged'          => 1,
			'orderby'        => 'none',
			'order'          => 'ASC',
		);

		if ( ! empty( $_REQUEST['s'] ) ) {
			$args['s'] = sanitize_text_field( wp_unslash( $_REQUEST['s'] ) );
		}

		if ( ! empty( $_REQUEST['product_cat'] ) ) {

			$args['tax_query'][] = array(
				'taxonomy' => 'product_cat',
				'field'    => 'name',
				'terms'    => sanitize_text_field( wp_unslash( $_REQUEST['product_cat'] ) ),
			);
		}

		if ( ! empty( $_REQUEST['product_type'] ) ) {
			$args['tax_query'][] = array(
				'taxonomy' => 'product_type',
				'field'    => 'slug',
				'terms'    => sanitize_text_field( wp_unslash( $_REQUEST['product_type'] ) ),
			);
		}

		if ( ! empty( $_REQUEST['product_shipping_class'] ) ) {
			$shipping_class_slug = sanitize_text_field( wp_unslash( $_REQUEST['product_shipping_class'] ) );
			$args['tax_query']   = array(
				array(
					'taxonomy' => 'product_shipping_class',
					'field'    => 'slug',
					'terms'    => $shipping_class_slug,
				),
			);
		}

		$query = new WP_Query( $args );

		return $query->found_posts;
	}

	/**
	 * Get products
	 *
	 * @param int $per_page $per_page.
	 * @param int $page_number $page_number.
	 * @return array
	 */
	private function get_products( int $per_page = 20, int $page_number = 1 ) {

		if ( ! empty( $_REQUEST['nonce'] ) ) {
			check_ajax_referer( 'inpost_international_ajax', 'nonce' );
		}

		if ( ! empty( $_REQUEST['product_qty'] ) ) {
			$per_page = sanitize_text_field( wp_unslash( $_REQUEST['product_qty'] ) );
		}

		$orderby = 'date';
		if ( isset( $_REQUEST['orderby'] ) ) {
			$orderby = 'title';
		}

		$args = array(
			'post_type'      => 'product',
			'post_status'    => 'publish',
			'posts_per_page' => $per_page,
			'orderby'        => $orderby,
			'order'          => isset( $_REQUEST['order'] ) ? sanitize_text_field( wp_unslash( $_REQUEST['order'] ) ) : 'DESC',
			'paged'          => $page_number,
		);

		if ( ! empty( $_REQUEST['s'] ) ) {
			$args['s'] = sanitize_text_field( wp_unslash( $_REQUEST['s'] ) );
		}

		if ( ! empty( $_REQUEST['product_cat'] ) ) {

			$args['tax_query'][] = array(
				'taxonomy' => 'product_cat',
				'field'    => 'name',
				'terms'    => sanitize_text_field( wp_unslash( $_REQUEST['product_cat'] ) ),
			);
		}

		if ( ! empty( $_REQUEST['product_type'] ) ) {
			$args['tax_query'][] = array(
				'taxonomy' => 'product_type',
				'field'    => 'slug',
				'terms'    => sanitize_text_field( wp_unslash( $_REQUEST['product_type'] ) ),
			);
		}

		if ( ! empty( $_REQUEST['product_shipping_class'] ) ) {
			$shipping_class_slug = sanitize_text_field( wp_unslash( $_REQUEST['product_shipping_class'] ) );
			$args['tax_query']   = array(
				array(
					'taxonomy' => 'product_shipping_class',
					'field'    => 'slug',
					'terms'    => $shipping_class_slug,
				),
			);
		}

		$product_query = new WP_Query( $args );

		return array_map( 'wc_get_product', $product_query->posts );
	}


	/**
	 * Column content
	 *
	 * @param \WC_Product $item product.
	 * @param $column_name $column_name.
	 * @return bool|string|void
	 */
	public function column_default( $item, $column_name ) {
		switch ( $column_name ) {
			case 'sku':
				return $item->get_sku();
			case 'img':
				return $this->get_product_preview_html( $item->get_id() );
			case 'categories':
				return wp_strip_all_tags( wc_get_product_category_list( $item->get_id() ) );
			case 'shipping_methods':
				return $this->get_product_inpost_shipping_methods( $item->get_id() );
			case 'locker':
				return $this->get_product_inpost_locker_size( $item->get_id() );
			case 'action_button_result':
				return $this->get_action_result_html( $item->get_id() );
			default:
				return '';
		}
	}

	/**
	 * Row checkbox
	 *
	 * @param \WC_Product $item $item.
	 * @return string|void
	 */
	public function column_cb( $item ) {
		return sprintf(
			'<input class="inpost_intl_check_row" type="checkbox" name="product[]" value="%s" />',
			$item->get_id()
		);
	}

	/**
	 * Column title
	 *
	 * @param \WC_Product $item $item.
	 * @return string
	 */
	public function column_title( $item ) {
		$actions = array(
			'edit' => sprintf( '<a href="%s">Edit</a>', get_edit_post_link( $item->get_id() ) ),
			'view' => sprintf( '<a href="%s">View</a>', get_permalink( $item->get_id() ) ),
		);

		return sprintf( '%1$s %2$s', $item->get_name(), $this->row_actions( $actions ) );
	}

	/**
	 * Bulk actions
	 *
	 * @return array
	 */
	public function get_bulk_actions() {
		$actions = array();
		return $actions;
	}

	/**
	 * Process bulk action
	 *
	 * @return void
	 */
	public function process_bulk_action() {
	}




	/**
	 * Product thumbnail
	 *
	 * @param int $product_id $product_id.
	 * @return string
	 */
	public function get_product_preview_html( $product_id ) {
		$product_image = get_the_post_thumbnail( $product_id );
		return $product_image;
	}

	/**
	 * Get Inpost methods based on product configuration
	 *
	 * @param int $product_id $product_id.
	 * @return false|string
	 */
	public function get_product_inpost_shipping_methods( $product_id ) {

		$output = '';

		$product_settings = new Product_Settings();

		$product_config     = $product_settings->get_config_by_product_id( $product_id );
		$all_inpost_methods = self::$all_inpost_methods;

		\ob_start();?>
		<div class="inpost_intl_allowed_methods_<?php echo esc_attr( $product_id ); ?>" data-product-id="<?php echo esc_attr( $product_id ); ?>">
			<ul class="inpost_intl_allowed_methods_<?php echo esc_attr( $product_id ); ?>" data-product-id="<?php echo esc_attr( $product_id ); ?>">
				<?php
				foreach ( $all_inpost_methods as $key => $method ) {
					$value   = 1;
					$checked = 'checked';
					if ( is_array( $product_config ) ) {
						$value   = in_array( $method['method_title_with_id'], $product_config, true ) ? 1 : '';
						$checked = in_array( $method['method_title_with_id'], $product_config, true ) ? 'checked' : '';
					}
					?>
					<li>
						<input type="checkbox"
								data-id="<?php echo esc_attr( $product_id ); ?>"
								data-method="<?php echo esc_attr( $method['method_title_with_id'] ); ?>"
								id="inpost_intl_allowed_methods[<?php echo esc_attr( $product_id ); ?>][<?php echo esc_attr( $method['method_title_with_id'] ); ?>]"
								name="inpost_intl_allowed_methods[<?php echo esc_attr( $product_id ); ?>][<?php echo esc_attr( $method['method_title_with_id'] ); ?>]"
								value="<?php echo esc_attr( $value ); ?>"
								class="checkbox"
							<?php echo esc_attr( $checked ); ?>
						>
						<label for="inpost_intl_allowed_methods[<?php echo esc_attr( $product_id ); ?>][<?php echo esc_attr( $method['method_title_with_id'] ); ?>]">
							<?php echo esc_html( $method['user_title'] ); ?>
						</label>
					</li>
				<?php } ?>
			</ul>
		</div>
		<?php
		$output = \ob_get_contents();
		\ob_end_clean();

		return $output;
	}


	/**
	 * Get Inpost locker size based on product configuration
	 *
	 * @param int $product_id $product_id.
	 * @return false|string
	 */
	public function get_product_inpost_locker_size( $product_id ) {

		$output = '';

		// $meta_key = ATTRIBUTE_PREFIX . '_parcel_dimensions';
		$meta_key = 'inpost_international_parcel_template';

		$options = $this->helper->get_template_options();

		ob_start();

		$saved_value = get_post_meta( $product_id, $meta_key, true );

		$selected_template = ! empty( $saved_value ) ? $saved_value : '';

		woocommerce_wp_select(
			array(
				'id'            => 'inpost_intl_templates_' . $product_id,
				'wrapper_class' => 'inpost_intl_parcel_dimensions_grouped_' . $product_id,
				'label'         => '',
				'options'       => $options,
				'value'         => $selected_template,
			)
		);

		$output = ob_get_contents();
		ob_end_clean();
		return $output;
	}


	/**
	 * Action preloader
	 *
	 * @param int $product_id $product_id.
	 * @return string
	 */
	public function get_action_result_html( $product_id ) {
		return '<span class="inpost_action_result" data-id="' . esc_attr( $product_id ) . '">
		<input type="button" data-product-id="' . esc_attr( $product_id ) . '" class="button button-secondary button-large inpost-intl-update-single-product" value="' . esc_html__( 'Update settings', 'inpost-international' ) . '">
        <span data-action-id="' . esc_attr( $product_id ) . '" class="status inpost-intl-action-status status_hidden" title="OK"></span>
        <img data-id="' . esc_attr( $product_id ) . '" alt="inpost intl pre-loader" class="inpost_action_result_preloader preloader_hidden" src="' . esc_url( inpost_intl_core()->get_plugin_images_url() . '/big-round-preloader.gif' ) . '">
        </span>';
	}


	/**
	 * Render table and filters
	 *
	 * @return void
	 * @throws \Exception Exception.
	 */
	public static function render_custom_product_settings_page() {
		$product_table = new Manage_Products_Table();

		$product_table->prepare_items();
		$current_rel_uri = add_query_arg( null, null );
		?>

		<div class="wrap">
			<h1><?php echo esc_html__( 'Inpost International: manage products settings', 'inpost-international' ); ?></h1>
			<?php

			wp_nonce_field( 'inpost_international_product_settings', 'inpost_international_ajax' );

			$img = inpost_intl_core()->get_plugin_images_url() . '/gabarytABC.jpg';
			?>

			<div class="inpost_intl_row">
				<div class="inpost_intl_row_item item_left" style="padding:5px 5px 5px 5px;" id="inpost-intl-dimensions-wrap">
					<img style="max-height:200px;display:flex;margin-left:auto;margin-right:auto;margin-bottom:20px;" id="inpost-intl-dimensions" src="<?php echo esc_url( $img ); ?>" alt="gabaryt Inpost">
				</div>
				<div class="inpost_intl_row_item item_right">
					<?php
					$current_section_settings = get_option( 'inpost_international_settings_products' );
					$switch_checked           = ! empty( $current_section_settings['allow_all'] ) ? 'checked' : '';
					?>
					<p class="inpost_intl_before_setting_description">
						<?php esc_html_e( 'Enable InPost methods for all products in your shop', 'inpost-international' ); ?>
					</p>
					<label class="inpost-intl-switch">
						<input type="checkbox"
								id="inpost_intl_allow_all"
								class="inpost-intl-switch-checkbox"
								data-id="allow_all"
							<?php echo esc_attr( $switch_checked ); ?>
						>
						<span class="inpost-intl-slider"></span>
					</label>
					<img src="<?php echo esc_url( inpost_intl_core()->get_plugin_images_url() . '/big-round-preloader.gif' ); ?>" id="inpost-intl-allow-all-preloader" alt="inpost intl pre-loader">
					<span class="status allow-all inpost-intl-action-status" title="OK"></span>


					<p class="inpost_intl_before_setting_description">
						<?php esc_html_e( 'By changing these settings you change the settings for all products on the page in a similar way.', 'inpost-international' ); ?>
					</p>
					<div class="inpost_intl_row">
							<span class="inpost_intl_row_item item_left">
								<?php
								$helper                  = new Helper();
								$options                 = $helper->get_template_options();
								$inpost_shipping_methods = self::$all_inpost_methods;

								woocommerce_wp_select(
									array(
										'id'      => 'inpost_intl_templates',
										'label'   => '',
										'options' => $options,
										'value'   => '',
									)
								);
								?>

							<div class="inpost_intl_all_allowed_methods">
							<ul class="inpost_intl_all_allowed_methods_list">
							<?php
							foreach ( $inpost_shipping_methods as $key => $method ) {
								?>
								<li>
									<input type="checkbox"
											data-method="<?php echo esc_attr( $method['method_title_with_id'] ); ?>"
											id="<?php echo esc_attr( $method['method_title_with_id'] ); ?>"
											value=""
											class="checkbox inpost_intl_rule_checkbox"
									>
									<label for="<?php echo esc_attr( $method['method_title_with_id'] ); ?>">
										<?php echo esc_html( $method['user_title'] ); ?>
									</label>
								</li>
							<?php } ?>
							</ul>
							</div>

							</span>

					</div>
					<div class="tablenav top">
						<div class="alignleft actions bulkactions">
							<?php // $product_table->bulk_actions(); ?>
						</div>
						<div class="alignright actions">
							<input type="button" class="button button-primary button-large inpost-intl-update-product-bulk" value="<?php echo esc_html__( 'Update product settings', 'inpost-international' ); ?>">
							<input type="button" class="button button-secondary button-large inpost-intl-update-reload" value="<?php echo esc_html__( 'Re-load page', 'inpost-international' ); ?>">
						</div>
					</div>
				</div>
			</div>

			<div id="inpost_intl_filters" class="inpost_intl_product_filters">
				<?php

				if ( ! empty( $_REQUEST['nonce'] ) ) {
					check_ajax_referer( 'inpost_international_ajax', 'nonce' );
				}

				$current_page = '';
				if ( isset( $_REQUEST['page'] ) ) {
					$current_page = sanitize_text_field( wp_unslash( $_REQUEST['page'] ) );
				}
				?>
				<input type="hidden" name="page" value="<?php echo esc_attr( $current_page ); ?>" />
				<?php
				$product_table->search_box( 'Szukaj produktów', 'search_id' );

				// Add product type dropdown.
				wc_product_dropdown_categories(
					array(
						'show_count'         => 0,
						'hierarchical'       => 1,
						'show_uncategorized' => 0,
						'name'               => 'product_cat',
						'selected'           => isset( $_GET['product_cat'] ) ? sanitize_text_field( wp_unslash( $_GET['product_cat'] ) ) : '',
						'menu_order'         => false,
					)
				);

				// Add product type filter.
				$product_types = wc_get_product_types();
				echo '<select name="product_type" id="dropdown_product_type">';
				echo '<option value="">' . esc_html__( 'Filter by product type', 'inpost-international' ) . '</option>';
				foreach ( $product_types as $value => $label ) {
					echo '<option value="' . esc_attr( $value ) . '"';
					if ( isset( $_GET['product_type'] ) && $value === $_GET['product_type'] ) {
						echo ' selected="selected"';
					}
					echo '>' . esc_html( $label ) . '</option>';
				}
				echo '</select>';

				$product_qtys = array(
					'5'   => '5',
					'10'  => '10',
					'20'  => '20',
					'50'  => '50',
					'100' => '100',
					'200' => '200',
					'500' => '500',
				);

				// Get all shipping classes.
				$shipping_classes = array();
				if ( is_object( WC()->shipping() ) ) {
					$all_shipping_classes = WC()->shipping()->get_shipping_classes();
					foreach ( $all_shipping_classes as $shipping_class ) {
						$shipping_classes[ $shipping_class->slug ] = $shipping_class->name;
					}
				}

				echo '<select name="product_shipping_class" id="dropdown_shipping_classes">';
				echo '<option value="">' . esc_html__( 'Per shipping class', 'inpost-international' ) . '</option>';
				if ( ! empty( $shipping_classes ) && is_array( $shipping_classes ) ) {
					foreach ( $shipping_classes as $value => $label ) {
						echo '<option value="' . esc_attr( $value ) . '"';
						if ( isset( $_GET['product_shipping_class'] ) && $value === $_GET['product_shipping_class'] ) {
							echo ' selected="selected"';
						}
						echo '>' . esc_html( $label ) . '</option>';
					}
				}
				echo '</select>';

				echo '<select name="per_page" id="dropdown_product_qty">';
				echo '<option value="">' . esc_html__( 'Per page', 'inpost-international' ) . '</option>';
				foreach ( $product_qtys as $value => $label ) {
					echo '<option value="' . esc_attr( $value ) . '"';
					if ( isset( $_GET['per_page'] ) && $value === $_GET['per_page'] ) {
						echo ' selected="selected"';
					}
					echo '>' . esc_html( $label ) . '</option>';
				}
				echo '</select>';
				echo '<input type="button" name="filter_action" id="filter_action" class="button" value="Filter">';
				?>

			</div>

			<div class="custom_product_table_settings_wrap">
				<?php
				$product_table->display();
				?>
				<div class="tablenav bottom">
					<div class="alignleft actions bulkactions">
					</div>
					<div class="alignleft actions">
						<input type="button" class="button button-primary button-large inpost-intl-update-product-bulk" value="<?php echo esc_html__( 'Update product settings', 'inpost-international' ); ?>">
						<input type="button" class="button button-secondary button-large inpost-intl-update-reload" value="<?php echo esc_html__( 'Re-load page', 'inpost-international' ); ?>">
					</div>
				</div>
			</div>

		</div>
		<?php
	}




	/**
	 * Displays the table.
	 *
	 *
	 */
	public function display() {
		$singular = $this->_args['singular'];

		$this->display_tablenav( 'top' );

		$this->screen->render_screen_reader_content( 'heading_list' );
		?>
		<table class="inpost-intl wp-list-table <?php echo esc_html( implode( ' ', $this->get_table_classes() ) ); ?>">
			<?php $this->print_table_description(); ?>
			<thead>
			<tr>
				<?php $this->print_column_headers(); ?>
			</tr>
			</thead>

			<tbody id="the-list"
				<?php
				if ( $singular ) {
					echo " data-wp-lists='list:" . esc_html( $singular ) . "'";
				}
				?>
			>
			<?php $this->display_rows_or_placeholder(); ?>
			</tbody>

			<tfoot>
			<tr>
				<?php $this->print_column_headers( false ); ?>
			</tr>
			</tfoot>

		</table>
		<?php
		$this->display_tablenav( 'bottom' );
	}
}
