<?php // phpcs:ignore WordPress.Files.FileName.InvalidClassFileName
/**
 * General admin table handling
 *
 * @author  YITH
 * @package YITH\Cost of Goods
 * @version 1.0.0
 */

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

if ( ! class_exists( 'WP_List_Table' ) ) {
	require_once ABSPATH . 'wp-admin/includes/class-wp-list-table.php';
}

if ( ! class_exists( 'YITH_COG_Abstract_Admin_Table' ) ) {
	/**
	 * Wraps general method used in admin panel
	 *
	 * @since 1.0.0
	 */
	abstract class YITH_COG_Abstract_Admin_Table extends WP_List_Table {

		/**
		 * The current list of items.
		 *
		 * @var int $items
		 */
		public $items;

		/**
		 * The current list of items without pagination.
		 *
		 * @var int $items
		 */
		public $total_items;

		/**
		 * The max number of items.
		 *
		 * @var int $max_items
		 */
		public $max_items;

		/**
		 * Visible columns; if this param is empty, screen option will be used instead.
		 *
		 * @var array $visible_columns
		 */
		protected $visible_columns;

		/**
		 * Number of items per page; if this param is empty, screen option will be used instead
		 *
		 * @var int $items_per_page
		 */
		protected $items_per_page;

		/**
		 * Array that contains tablenavs to show.
		 *
		 * @var array
		 */
		protected $tablenav_to_show = array( 'top' );

		/**
		 * Class constructor method
		 *
		 * @param array $args Arguments for the parent constructor.
		 *
		 * @since 1.0.0
		 */
		public function __construct( $args ) {
			// Set parent defaults.
			parent::__construct();
		}

		/**
		 * Returns hidden columns for current table
		 *
		 * @return mixed Array of hidden columns
		 * @since 1.0.0
		 */
		public function get_hidden_columns() {

			if ( $this->visible_columns ) {
				return array_diff( array_keys( $this->get_columns() ), $this->visible_columns );
			}

			return get_hidden_columns( $this->screen );
		}

		/**
		 * Allow to set visible columns
		 *
		 * @param array $columns Columns to show.
		 */
		public function set_visible_columns( $columns ) {
			$this->visible_columns = array_intersect( $columns, array_keys( $this->get_columns() ) );
		}

		/**
		 * Whether the table has items to display or not
		 *
		 * @return bool
		 */
		public function has_items() {
			return $this->items && count( $this->items ) > 0;
		}

		/**
		 * Gets the number of items to display on a single page.
		 *
		 * @param string $option  Option to read to retrieve items per page.
		 * @param int    $default Default value.
		 * @return int
		 */
		protected function get_items_per_page( $option, $default = 20 ) {
			if ( $this->items_per_page ) {
				return $this->items_per_page;
			}

			return parent::get_items_per_page( $option, $default );
		}

		/**
		 * Checks whether passed tablenav should be shown or not
		 * If no param is passed, will return true if at least one of the tablenav is shown
		 *
		 * @param string $which Tablenav position.
		 * @return bool Whether to show it or not.
		 */
		public function should_show_tablenav( $which = false ) {
			if ( ! $which ) {
				return ! empty( $this->tablenav_to_show );
			}

			return in_array( $which, $this->tablenav_to_show, true );
		}

		/**
		 * Hides tablenav for current table (before display)
		 *
		 * @param string $which Tablenav position.
		 */
		public function show_tablenav( $which = '' ) {
			if ( ! empty( $which ) ) {
				$this->tablenav_to_show[] = $which;
			} else {
				$this->tablenav_to_show = array(
					'top',
				);
			}
		}

		/**
		 * Displays the table or empty state.
		 */
		public function display() {

			?>
			<div class="table-container yith-cog-report-table">
				<?php
				if ( ! $this->has_items() ) {
					$this->display_empty_state();
				} else {
					parent::display();
				}

				?>
			</div>
			<?php
		}

		/**
		 * Generates the table navigation above or below the table
		 *
		 * @param string $which Position for current tablenav.
		 */
		protected function display_tablenav( $which ) {
			if ( ! $this->should_show_tablenav( $which ) ) {
				return;
			}

			parent::display_tablenav( $which );
		}

		/**
		 * Displays empty state for the table.
		 */
		protected function display_empty_state() {

			$message = __( 'You have to set a cost for your products first!', 'yith-cost-of-goods-for-woocommerce' );

			if ( isset( $_REQUEST['filter_action'] ) ) { // phpcs:ignore

				$message = __( 'No items found', 'yith-cost-of-goods-for-woocommerce' );
			}

			if ( isset( $_REQUEST['sub_tab'] ) && 'report-sales' === $_REQUEST['sub_tab'] && ! isset( $_REQUEST['filter_action'] ) ) { // phpcs:ignore

				$message = __( 'There are no costs linked to your current sales, set a cost on your products and click on the next button to apply it to your orders.', 'yith-cost-of-goods-for-woocommerce' );
			}

			$component = array(
				'type'     => 'list-table-blank-state',
				'icon_url' => YITH_COG_URL . 'assets/images/empty-state-cog.svg',
				'message'  => $message,
			);

			yith_plugin_fw_get_component( $component, true );

			if ( isset( $_REQUEST['sub_tab'] ) && 'report-sales' === $_REQUEST['sub_tab'] && ! isset( $_REQUEST['filter_action'] ) ) { // phpcs:ignore

				?>
				<div class="apply-cost-empty-state">
					<a class="apply_cost button action primary" id="yith_cog_apply_cost" ><?php echo esc_html__( 'Apply Costs', 'yith-cost-of-goods-for-woocommerce' ); ?></a>
				</div>
				<?php
			}
		}

		/**
		 * Prints a select that allows filter by category in the report table.
		 *
		 * @return void
		 */
		protected function print_category_filter() {

			$value = isset( $_POST['_category_id'] ) && ! empty( $_POST['_category_id'] ) ? $_POST['_category_id'] : ''; // phpcs:ignore

			yith_plugin_fw_get_field(
				array(
					'type'     => 'ajax-terms',
					'class'    => 'yith-term-search',
					'value'    => $value,
					'name'     => '_category_id',
					'multiple' => true,
					'data'     => array(
						'taxonomy'    => 'product_cat',
						'placeholder' => _x( 'Search product categories', '[ADMIN] Category filter placeholder', 'yith-cost-of-goods-for-woocommerce' ),
					),
				),
				true
			);
		}

		/**
		 * Prints a select that allows filter items by product id.
		 *
		 * @return void
		 */
		protected function print_product_filter() {
			$value = isset( $_POST['_product_id'] ) && ! empty( $_POST['_product_id'] ) ? $_POST['_product_id'] : ''; // phpcs:ignore
			yith_plugin_fw_get_field(
				array(
					'id'    => 'yith-cog-search-products',
					'name'  => '_product_id',
					'value' => $value,
					'type'  => 'ajax-products',
					'data'  => array(
						'action'   => 'woocommerce_json_search_products_and_variations',
						'security' => wp_create_nonce( 'search-products' ),
					),
				),
				true
			);
		}

		/**
		 * Prints a field that allows to order the table
		 *
		 * @param array $options array of options to be used in the select input.
		 * @return void
		 */
		protected function print_select_orderby( $options ) {

			$value   = isset( $_POST['cog_orderby'] ) && ! empty( $_POST['cog_orderby'] ) ? $_POST['cog_orderby'] : ''; // phpcs:ignore

			$default = array(
				'placeholder' => _x( 'Sort by:', '[ADMIN] Label of the order by select input', 'yith-cost-of-goods-for-woocommerce' ),
			);
			$options = ! ! $options ? array_merge( $default, $options ) : array();

			$field = array(
				'id'                => 'yith-cog-orderby-select',
				'class'             => 'wc-enhanced-select',
				'type'              => 'select',
				'value'             => $value,
				'name'              => 'cog_orderby',
				'custom_attributes' => array(
					'style' => 'width: 100%',
				),
				'options'           => $options,
			);

			yith_plugin_fw_get_field( $field, true );
		}

		/**
		 * Prints a field that allows filter items from date
		 *
		 * @return void
		 */
		protected function print_from_datepicker() {

			$default_from  = apply_filters( 'yith_cog_default_from_datepicker', date ( 'd-m-Y', strtotime("first day of this month") ) );

			$value = isset( $_POST['yith-cog-from-datepicker'] ) && ! empty( $_POST['yith-cog-from-datepicker'] ) ? $_POST['yith-cog-from-datepicker'] : $default_from; // phpcs:ignore

			$value = $_GET['yith-cog-from-datepicker'] ?? $value;

			$field = array(
				'id'                => 'yith-cog-from-datepicker',
				'type'              => 'datepicker',
				'value'             => $value,
				'name'              => 'yith-cog-from-datepicker',
				'data'              => array(
					'date-format' => 'dd-mm-yy',
				),
				'custom_attributes' => array(
					'placeholder' => _x( 'From:', '[ADMIN] Filter datepicker input placeholder', 'yith-cost-of-goods-for-woocommerce' ),
				),
			);

			yith_plugin_fw_get_field( $field, true );
		}

		/**
		 * Prints a field that allows filter items to date
		 *
		 * @return void
		 */
		protected function print_to_datepicker() {

			$default_to  = date ( 'd-m-Y', strtotime("today") );

			$value = isset( $_POST['yith-cog-to-datepicker'] ) && ! empty( $_POST['yith-cog-to-datepicker'] ) ? $_POST['yith-cog-to-datepicker'] : $default_to; // phpcs:ignore

			$value = $_GET['yith-cog-to-datepicker'] ?? $value;

			$field = array(
				'id'                => 'yith-cog-to-datepicker',
				'type'              => 'datepicker',
				'value'             => $value,
				'name'              => 'yith-cog-to-datepicker',
				'data'              => array(
					'date-format' => 'dd-mm-yy',
				),
				'custom_attributes' => array(
					'placeholder' => _x( 'To:', '[ADMIN] Filter datepicker input placeholder', 'yith-cost-of-goods-for-woocommerce' ),
				),
			);

			yith_plugin_fw_get_field( $field, true );
		}

		/**
		 * Prints filter button that removes any filter currently applied
		 *
		 * @return void
		 */
		protected function print_filter_button() {
			submit_button(
				_x( 'Filter', '[ADMIN] Filter button label', 'yith-cost-of-goods-for-woocommerce' ),
				'button',
				'filter_action',
				false,
				array(
					'id' => 'post-query-submit',
				)
			);
		}

		/**
		 * Prints reset button that removes any filter currently applied
		 *
		 * @return void
		 */
		protected function print_reset_button() {
			if ( ! isset( $_REQUEST['filter_action'] ) ) { // phpcs:ignore WordPress.Security.NonceVerification.Recommended
				return;
			}

			echo sprintf(
				'<a href="#" class="button button-secondary action reset-button">%s</a>',
				esc_html_x( 'Reset', '[ADMIN] Reset button label', 'yith-cost-of-goods-for-woocommerce' )
			);
		}

		/**
		 * Print the total section of the table.
		 *
		 * @param array $args Values to be printed.
		 * @return void.
		 */
		protected function print_totals_section( $args ) {
			$args = ! ! $args ? $args : array();

			if ( empty( $args ) ) {
				return;
			}
			?>
				<div class="yith-cog-tablenav-totals-report">
					<?php
					foreach ( $args as $key => $item ) {
						?>
							<span class="yith-cog-totals-block">
								<div class="yith-cog-totals-block-title"><?php echo esc_html( $item['label'] ); ?></div>
								<p class="yith-cog-totals-block-value"><?php echo wp_kses_post( $item['value'] ); ?></p>
								<?php

								switch ( $key ) {
									case 'cost':
										$include_fees     = 'yes' === get_option( 'yith_cog_include_fees_as_cost', false ) ? '<span>' . _x( 'Including order fees', '[ADMIN] tooltip of the totals section in the sales report table', 'yith-cost-of-goods-for-woocommerce' ) . '</span><br>' : '';
										$include_shipping = 'yes' === get_option( 'yith_cog_include_shipping_as_cost', false ) ? '<span>' . _x( 'Including shipping costs', '[ADMIN] tooltip of the totals section in the sales report table', 'yith-cost-of-goods-for-woocommerce' ) . '</span>' : '';

										if ( 'yes' === get_option( 'yith_cog_include_fees_as_cost', false ) || 'yes' === get_option( 'yith_cog_include_shipping_as_cost', false ) ) {
											?>
										<div class="yith-cog-sales-report-tooltip">
											<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20" fill="currentColor" class="w-5 h-5">
												<path fill-rule="evenodd" d="M18 10a8 8 0 11-16 0 8 8 0 0116 0zM8.94 6.94a.75.75 0 11-1.061-1.061 3 3 0 112.871 5.026v.345a.75.75 0 01-1.5 0v-.5c0-.72.57-1.172 1.081-1.287A1.5 1.5 0 108.94 6.94zM10 15a1 1 0 100-2 1 1 0 000 2z" clip-rule="evenodd" />
											</svg>
											<span class="yith-cog-sales-report-tooltip-text">
												<?php
													echo wp_kses_post( $include_fees . $include_shipping );
												?>
											</span>
										</div>
											<?php

										}
										break;
									case 'margin':
										$include_shipping = get_option( 'yith_cog_include_shipping_as_margin', false );

										if ( 'yes' === $include_shipping ) {
											?>
										<div class="yith-cog-sales-report-tooltip">
											<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20" fill="currentColor" class="w-5 h-5">
												<path fill-rule="evenodd" d="M18 10a8 8 0 11-16 0 8 8 0 0116 0zM8.94 6.94a.75.75 0 11-1.061-1.061 3 3 0 112.871 5.026v.345a.75.75 0 01-1.5 0v-.5c0-.72.57-1.172 1.081-1.287A1.5 1.5 0 108.94 6.94zM10 15a1 1 0 100-2 1 1 0 000 2z" clip-rule="evenodd" />
											</svg>
											<span class="yith-cog-sales-report-tooltip-text"><?php echo esc_html_x( 'Including shipping costs', '[ADMIN] tooltip of the totals section in the sales report table', 'yith-cost-of-goods-for-woocommerce' ); ?></span>
										</div>
											<?php

										}
										break;
								}

								?>
							</span>
						<?php
					}
					?>
				</div>
			<?php
		}
	}
}
