<?php // phpcs:ignore WordPress.Files.FileName
/**
 * The class that manage the Payout List table
 *
 * @package YITH\PayPalPayouts\Classes
 */

if ( ! defined( 'ABSPATH' ) ) {

	exit;
}

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

if ( ! class_exists( 'YITH_PayOuts_List_Table' ) ) {
	/**
	 * Class YITH_PayOuts_List_Table
	 */
	class YITH_PayOuts_List_Table extends WP_List_Table {

		/**
		 * Get columns
		 *
		 * @return array
		 * @since 1.0.0
		 * @author YITH <plugins@yithemes.com>
		 */
		public function get_columns() {
			$columns = array(
				'cb'              => '<input type="checkbox"/>',
				'payout_batch_id' => __( 'Payout Batch ID', 'yith-paypal-payouts-for-woocommerce' ),
				'payout_mode'     => __( 'Payout Mode', 'yith-paypal-payouts-for-woocommerce' ),
				'last_edit'       => __( 'Creation Date', 'yith-paypal-payouts-for-woocommerce' ),
				'payout_status'   => __( 'Payout Batch Status', 'yith-paypal-payouts-for-woocommerce' ),
				'payout_detail'   => '',
			);

			return $columns;
		}

		/**
		 * Show the column content
		 *
		 * @param object $item The item.
		 * @param string $column_name The column name.
		 */
		public function column_default( $item, $column_name ) {

			$output = '';
			switch ( $column_name ) {

				case 'payout_batch_id':
					$output = empty( $item['payout_batch_id'] ) ? __( 'N/A', 'yith-paypal-payouts-for-woocommerce' ) : $item['payout_batch_id'];
					break;
				case 'payout_status':
					$status         = YITH_Payouts::get_payouts_status();
					$current_status = strtolower( $item['payout_status'] );
					$output         = isset( $status[ $current_status ] ) ? $status[ $current_status ] : $item['payout_status'];
					$output         = sprintf( '<span class="payouts-status %1$s">%2$s</span>', $current_status, $output );
					break;
				case 'payout_mode':
					$payment_mode = YITH_PayOuts::get_payout_payment_mode();
					$output       = isset( $payment_mode[ $item['payout_mode'] ] ) ? $payment_mode[ $item['payout_mode'] ] : $item['payout_mode'];
					break;

				case 'payout_detail':
					$query_args = array(
						'page'                => 'yith_wc_paypal_payouts_panel',
						'tab'                 => 'payout-list',
						'show_payout_details' => $item['sender_batch_id'],
					);

					if ( isset( $_GET['payment_mode'] ) ) { // phpcs:ignore WordPress.Security.NonceVerification.Recommended, WordPress.Security.ValidatedSanitizedInput.InputNotSanitized

						$query_args['payment_mode'] = wp_unslash( $_GET['payment_mode'] ); // phpcs:ignore WordPress.Security.NonceVerification.Recommended, WordPress.Security.ValidatedSanitizedInput.InputNotSanitized
					}

					$url = esc_url( add_query_arg( $query_args, admin_url( 'admin.php' ) ) );

					$output = yith_plugin_fw_get_component(
						array(
							'type'   => 'action-button',
							'action' => 'view',
							'icon'   => 'eye',
							'url'    => $url,
							'title'  => __( 'View payout', 'yith-paypal-payouts-for-woocommerce' ),
						),
						false
					);

					$delete_url = wp_nonce_url(
						add_query_arg(
							array(
								'yith_payouts_action' => 'delete_payout',
								'payout_id'           => $item['ID'],
							)
						),
						'delete_payouts',
						'yith_payouts_delete_nonce'
					);

					$output .= yith_plugin_fw_get_component(
						array(
							'type'         => 'action-button',
							'action'       => 'delete',
							'icon'         => 'trash',
							'url'          => $delete_url,
							'title'        => __( 'Delete payout', 'yith-paypal-payouts-for-woocommerce' ),
							'confirm_data' => array(
								'title'               => __( 'Confirm Delete', 'yith-paypal-payouts-for-woocommerce' ),
								'message'             => __( 'Are you sure you want to delete this payout?', 'yith-paypal-payouts-for-woocommerce' ),
								'confirm-button'      => __( 'Delete', 'yith-paypal-payouts-for-woocommerce' ),
								'confirm-button-type' => 'delete',
							),
						),
						false
					);

					if ( empty( $item['payout_batch_id'] ) ) {
						$pay_url = wp_nonce_url(
							add_query_arg(
								array(
									'yith_payouts_action' => 'pay_payouts',
									'sender_batch_id'     => $item['sender_batch_id'],
								)
							),
							'pay_payouts',
							'yith_payouts_pay_nonce'
						);

						$output .= yith_plugin_fw_get_component(
							array(
								'type'         => 'action-button',
								'title'        => __( 'Pay', 'yith-paypal-payouts-for-woocommerce' ),
								'action'       => 'pay',
								'icon'         => 'credit-card',
								'url'          => $pay_url,
								'confirm_data' => array(
									'title'   => __( 'Pay a Payout', 'yith-paypal-payouts-for-woocommerce' ),
									'message' => __( 'Do you want to try to pay this payout?', 'yith-paypal-payouts-for-woocommerce' ),
								),
							),
							false
						);
					} elseif ( 'success' !== $item['payout_status'] ) {

						$url = add_query_arg(
							array(
								'yith_payouts_action' => 'update_status',
								'batch_id'            => $item['payout_batch_id'],
							)
						);
						$url = wp_nonce_url( $url, 'payouts_update_status', 'yith_payouts_update_status_nonce' );

						$output .= yith_plugin_fw_get_component(
							array(
								'type'  => 'action-button',
								'title' => __( 'Check status', 'yith-paypal-payouts-for-woocommerce' ),
								'class' => 'yith_payouts_check_status',
								'url'   => $url,
								'icon'  => 'reset',
							),
							false
						);

					}
					break;
				case 'last_edit':
					if ( '0000-00-00 00:00:00' !== $item[ $column_name ] ) {
						$output = $this->get_formatted_date( $item[ $column_name ] );
					} else {
						$output = __( 'N\A', 'yith-paypal-payouts-for-woocommerce' );
					}
					break;
			}

			return $output;
		}

		/**
		 * Show the cb column
		 *
		 * @param object $item The item.
		 *
		 * @return string
		 * @since 1.0.0
		 */
		public function column_cb( $item ) {
			return sprintf(
				'<input type="checkbox" name="yith_payouts_ids[]" value="%s" />',
				$item['ID']
			);
		}

		/**
		 * Process the bulk action
		 *
		 * @since 2.0.0
		 */
		public function process_bulk_actions() {

			if ( isset( $_REQUEST['action'] ) ) { // phpcs:ignore WordPress.Security.NonceVerification.Recommended
				if ( 'delete' === sanitize_text_field( wp_unslash( $_REQUEST['action'] ) ) ) { // phpcs:ignore WordPress.Security.NonceVerification.Recommended
					if ( isset( $_REQUEST['yith_payouts_ids'] ) ) { // phpcs:ignore WordPress.Security.NonceVerification.Recommended
						$yith_receiver_ids = array_map( 'intval', $_REQUEST['yith_payouts_ids'] ); // phpcs:ignore WordPress.Security.NonceVerification.Recommended,WordPress.Security.ValidatedSanitizedInput.InputNotSanitized, WordPress.Security.ValidatedSanitizedInput.MissingUnslash
						$this->delete( $yith_receiver_ids );
					}
				}
			}

		}

		/**
		 * Return bulk actions
		 *
		 * @return array|false|string
		 * @since 1.0.0
		 */
		public function get_bulk_actions() {

			$actions = array(
				'delete' => __( 'Delete', 'yith-paypal-payouts-for-woocommerce' ),
			);

			return $actions;
		}


		/**
		 * Delete the payout
		 *
		 * @param array $payout_ids The payout ids.
		 */
		public function delete( $payout_ids ) {

			foreach ( $payout_ids as $key => $payout_id ) {
				YITH_Payouts::delete_payout( $payout_id );
			}
		}

		/**
		 * Extra controls to be displayed between bulk actions and pagination
		 *
		 * @param string $which The position.
		 *
		 * @since 1.0.0
		 * @access protected
		 *
		 */
		protected function extra_tablenav( $which ) {
			if ( 'top' === $which ) {
				if ( ! empty( $_REQUEST['payout_status'] ) ) { // phpcs:ignore WordPress.Security.NonceVerification.Recommended, WordPress.Security.ValidatedSanitizedInput.InputNotSanitized
					echo '<input type="hidden" name="payout_status" value="' . esc_attr( wp_unslash( $_REQUEST['payout_status'] ) ) . '" />'; // phpcs:ignore WordPress.Security.NonceVerification.Recommended, WordPress.Security.ValidatedSanitizedInput.InputNotSanitized
				}

				$this->payout_payment_mode_dropdown();
			}
		}

		/**
		 * Show the dropdown to filter payment mode
		 *
		 * @since 1.0.0
		 */
		public function payout_payment_mode_dropdown() {

			$payment_mode          = YITH_PayOuts::get_payout_payment_mode();
			$payment_mode_selected = isset( $_REQUEST['payment_mode'] ) ? wp_unslash( $_REQUEST['payment_mode'] ) : 'all'; // phpcs:ignore WordPress.Security.NonceVerification.Recommended, WordPress.Security.ValidatedSanitizedInput.InputNotSanitized

			?>
			<div class="alignleft actions">
				<label for="filter-by-payment-mode" class="screen-reader-text"><?php esc_html_e( 'Payment Mode', 'yith-paypal-payouts-for-woocommerce' ); ?></label>
				<select name="payment_mode" id="filter-by-payment-mode">
					<option value="all" <?php selected( 'all', $payment_mode_selected ); ?> ><?php esc_html_e( 'All payment modes', 'yith-paypal-payouts-for-woocommerce' ); ?></option>
					<?php foreach ( $payment_mode as $value => $name ) : ?>
						<option value="<?php echo esc_attr( $value ); ?>" <?php selected( $value, $payment_mode_selected ); ?> ><?php echo esc_html( $name ); ?></option>
					<?php endforeach; ?>
				</select>
				<?php if ( ! empty( $_REQUEST['payout_status'] ) ) { // phpcs:ignore WordPress.Security.NonceVerification.Recommended, WordPress.Security.ValidatedSanitizedInput.InputNotSanitized ?>
					<input type="hidden" name="payout_status" value="<?php echo esc_attr( wp_unslash( $_REQUEST['payout_status'] ) ); // phpcs:ignore WordPress.Security.NonceVerification.Recommended, WordPress.Security.ValidatedSanitizedInput.InputNotSanitized ?>"/>
					<?php
				}
				?>
				<input type="submit" name="filter_action" id="post-query-submit" class="button" value="Filter">
			</div>
			<?php
		}


		/**
		 * Prepare items to display
		 *
		 * @since 1.0.0
		 */
		public function prepare_items() {
			$this->process_bulk_actions();
			$per_page              = 15;
			$columns               = $this->get_columns();
			$hidden                = array();
			$sortable              = $this->get_sortable_columns();
			$this->_column_headers = array( $columns, $hidden, $sortable );

			$current_page = $this->get_pagenum();
			$s            = isset( $_REQUEST['s'] ) ? wp_unslash( $_REQUEST['s'] ) : ''; // phpcs:ignore WordPress.Security.NonceVerification.Recommended, WordPress.Security.ValidatedSanitizedInput.InputNotSanitized
			$payout_mode  = isset( $_REQUEST['payment_mode'] ) ? wp_unslash( $_REQUEST['payment_mode'] ) : 'all'; // phpcs:ignore WordPress.Security.NonceVerification.Recommended, WordPress.Security.ValidatedSanitizedInput.InputNotSanitized
			$query_args   = array(
				'number'        => $per_page,
				'paged'         => $current_page,
				'order'         => 'DESC',
				'orderby'       => 'ID',
				's'             => $s,
				'payout_status' => $this->get_current_view(),
				'payout_mode'   => $payout_mode,
				'fields'        => array(
					'ID',
					'payout_batch_id',
					'sender_batch_id',
					'payout_status',
					'payout_mode',
					'last_edit',
					'last_edit_gmt',
				),
			);

			$this->items = YITH_Payouts()->get_payouts( $query_args );

			/**
			 * The total items
			 *
			 * @var int $total_items
			 */
			$total_items = YITH_Payouts()->get_payouts(
				array(
					'fields'        => 'count',
					'payout_status' => $this->get_current_view(),
					'payment_mode'  => $payout_mode,
					's'             => $s,
				)
			);

			$this->set_pagination_args(
				array(
					'total_items' => $total_items,                  // WE have to calculate the total number of items.
					'per_page'    => $per_page,                     // WE have to determine how many items to show on a page.
					'total_pages' => ceil( $total_items / $per_page ),   // WE have to calculate the total number of pages.
				)
			);
		}

		/**
		 * Get all views for payouts
		 *
		 * @return array
		 * @since 1.0.0
		 */
		protected function get_views() {

			$views = array( 'all' => __( 'All', 'yith-paypal-payouts-for-woocommerce' ) );

			$payout_status = YITH_PayOuts::get_payouts_status();

			$views = array_merge( $views, $payout_status );

			$current_view = $this->get_current_view();
			foreach ( $views as $view_id => $view ) {

				$class_current_view = $view_id === $current_view ? 'current' : '';

				$args = array(
					'payout_status' => $view_id,
					'fields'        => 'count',
					's'             => isset( $_GET['s'] ) ? wp_unslash( $_GET['s'] ) : '', // phpcs:ignore WordPress.Security.NonceVerification.Recommended, WordPress.Security.ValidatedSanitizedInput.InputNotSanitized
				);

				$count = YITH_PayOuts()->get_payouts( $args );

				if ( $count > 0 ) {
					$link = esc_url( add_query_arg( array( 'payout_status' => $view_id ) ) );

					$views[ $view_id ] = sprintf( "<a href='%s' class='%s'>%s <span class='count'>(%d)</span></a>", $link, $class_current_view, $view, $count );
				} else {
					unset( $views[ $view_id ] );
				}
			}

			return $views;
		}

		/**
		 * Get current view
		 *
		 * @return string
		 * @since 1.0.0
		 */
		public function get_current_view() {

			return isset( $_GET['payout_status'] ) ? wp_unslash( $_GET['payout_status'] ) : 'all'; // phpcs:ignore WordPress.Security.NonceVerification.Recommended, WordPress.Security.ValidatedSanitizedInput.InputNotSanitized
		}


		/**
		 * Show the search box
		 *
		 * @param string $text The text to search.
		 * @param string $input_id The input id.
		 *
		 * @since 1.0.0
		 */
		public function search_box( $text, $input_id ) {

			$input_id = $input_id . '-search-input';
			?>
			<p class="search-box">
				<label class="screen-reader-text" for="<?php echo esc_attr( $input_id ); ?>"><?php echo esc_html( $text ); ?>
					:</label>
				<input type="search" id="<?php echo esc_attr( $input_id ); ?>" name="s" value="<?php _admin_search_query(); ?>"/>
				<input type="hidden" name="page" value="yith_wc_paypal_payouts_panel"/>
				<input type="hidden" name="tab" value="payout-list"/>
				<?php submit_button( $text, '', '', false, array( 'id' => 'search-submit' ) ); ?>
			</p>
			<?php
		}

		/**
		 * Get all item ids
		 *
		 * @param string $sender_batch_id The sender batch id.
		 *
		 * @return array
		 * @since 1.0.0
		 */
		public function get_sender_item_ids( $sender_batch_id ) {

			$args = array(
				'sender_batch_id' => $sender_batch_id,
				'fields'          => array( 'sender_item_id' ),
			);

			$results = YITH_Payout_Items()->get_payout_items( $args );

			$ids = array();
			if ( count( $results ) > 0 ) {

				foreach ( $results as $result ) {

					if ( ! empty( $result['sender_item_id'] ) ) {

						$ids[] = $result['sender_item_id'];
					}
				}
			}

			return $ids;
		}

		/**
		 * Return the formatted date
		 *
		 * @param string $date The date.
		 *
		 * @return string
		 * @throws Exception The exception.
		 * @since 2.0.0
		 */
		public function get_formatted_date( $date ) {

			$wc_date   = new WC_DateTime( $date );
			$show_date = $wc_date->date_i18n( apply_filters( 'woocommerce_admin_order_date_format', __( 'M j, Y', 'woocommerce' ) ) );

			return sprintf(
				'<time datetime="%1$s" title="%2$s">%3$s</time>',
				esc_attr( $wc_date->date( 'c' ) ),
				esc_html( $wc_date->date_i18n( get_option( 'date_format' ) . ' ' . get_option( 'time_format' ) ) ),
				esc_html( $show_date )
			);
		}

		/**
		 * Customize the display method
		 *
		 * @since 2.0.0
		 */
		public function display() {
			if ( $this->has_items() || isset( $_REQUEST['payment_mode'] ) && 'all' !== sanitize_text_field( wp_unslash( $_REQUEST['payment_mode'] ) ) ) { // phpcs:ignore WordPress.Security.NonceVerification.Recommended
				parent::display();
			} else {
				$this->display_rows_or_placeholder();
			}
		}

		/**
		 * Customize the display method
		 *
		 * @since 2.0.0
		 */
		public function display_rows_or_placeholder() {
			if ( isset( $_REQUEST['payment_mode'] ) && 'all' !== sanitize_text_field( wp_unslash( $_REQUEST['payment_mode'] ) ) ) { // phpcs:ignore WordPress.Security.NonceVerification.Recommended
				parent::display_rows_or_placeholder();
			} else {
				if ( $this->has_items() ) {
					$this->display_rows();
				} else {
					echo '<style>.page-title-action{display:none!important;}</style>';
					$component = array(
						'type'     => 'list-table-blank-state',
						'icon_url' => YITH_PAYOUTS_ASSETS_URL . '/icons/payout-empty.svg',
						'message'  => __( 'You have no payouts yet.', 'yith-paypal-payouts-for-woocommerce' ),
						'cta'      => array(
							'title' => __( 'Add payouts', 'yith-paypal-payouts-for-woocommerce' ),
							'icon'  => 'plus',
							'class' => 'add-payouts',
						),
					);

					yith_plugin_fw_get_component( $component, true );
				}
			}
		}
	}
}
