<?php // phpcs:ignore WordPress.Files.FileName
/**
 * 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_PayOut_Items_List_Table' ) ) {
	/**
	 * Class YITH_PayOut_Items_List_Table
	 */
	class YITH_PayOut_Items_List_Table extends WP_List_Table {
		/**
		 * YITH_PayOut_Items_List_Table constructor.
		 *
		 * @param array $args The args.
		 */
		public function __construct( $args = array() ) {
			parent::__construct( $args );

			add_action( 'admin_footer', array( $this, 'payout_item_preview_template' ) );

			add_filter( 'yith_paypal_payout_instant_items_html', array( $this, 'get_instant_items_html' ), 10, 4 );
			add_filter( 'yith_paypal_payout_affiliate_items_html', array( $this, 'get_affiliate_items_html' ), 10, 2 );
			add_filter( 'yith_paypal_payout_commission_items_html', array( $this, 'get_commission_items_html' ), 10, 2 );

		}

		/**
		 * Get columns
		 *
		 * @return array
		 * @since 1.0.0
		 * @author YITH <plugins@yithemes.com>
		 */
		public function get_columns() {
			$columns = array(
				'receiver'           => __( 'Receiver', 'yith-paypal-payouts-for-woocommerce' ),
				'transaction_id'     => __( 'Transaction ID', 'yith-paypal-payouts-for-woocommerce' ),
				'amount'             => __( 'Amount', 'yith-paypal-payouts-for-woocommerce' ),
				'fee'                => __( 'Fee', 'yith-paypal-payout-for-woocommerce' ),
				'transaction_status' => __( 'Transaction Status', 'yith-paypal-payouts-for-woocommerce' ),
				'details'            => '',
			);

			return $columns;
		}

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

			$output = '';
			switch ( $column_name ) {
				case 'amount':
				case 'fee':
					$currency = $item['currency'];
					$output   = wc_price( $item[ $column_name ], array( 'currency' => $currency ) );
					break;
				case 'transaction_status':
					$status = YITH_Payout_Items()->get_transaction_status();
					$output = ! empty( $status[ $item['transaction_status'] ] ) ? $status[ $item['transaction_status'] ] : $item['transaction_status'];
					$output = sprintf( '<span class="payouts-status %1$s">%2$s</span>', $item['transaction_status'], $output );

					break;
				case 'transaction_id':
					$output = ! empty( $item[ $column_name ] ) ? $item[ $column_name ] : 'N/A';
					break;
				case 'details':
					$args   = array(
						'fields'          => array(
							'payout_mode',
						),
						'sender_batch_id' => $item['sender_batch_id'],
					);
					$payout = YITH_Payouts()->get_payouts( $args );
					$payout = $payout[0];
					$output = '';
					if ( 'csv' !== $payout['payout_mode'] ) {
						$output = yith_plugin_fw_get_component(
							array(
								'type'   => 'action-button',
								'action' => 'view',
								'icon'   => 'eye',
								'data'   => array(
									'ID' => $item['ID'],
								),
								'title'  => __( 'View details', 'yith-paypal-payouts-for-woocommerce' ),
								'class'  => 'payout-item-preview',
							),
							false
						);
					}
					if ( '' !== $item['payout_item_id'] && 'success' !== $item['transaction_status'] ) {
						$url = add_query_arg(
							array(
								'yith_payouts_action' => 'update_item_status',
								'payout_item_id'      => $item['payout_item_id'],
							)
						);
						$url = wp_nonce_url( $url, 'payouts_item_update_status', 'yith_payouts_update_item_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;
				default:
					$output = ! empty( $item[ $column_name ] ) ? $item[ $column_name ] : 'N/A';
					break;
			}

			echo wp_kses_post( $output );
		}


		/**
		 * Prepare items to display
		 *
		 * @since 1.0.0
		 */
		public function prepare_items() {
			$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();

			$query_args = array(
				'number'          => $per_page,
				'sender_batch_id' => wp_unslash( $_GET['show_payout_details'] ), // phpcs:ignore WordPress.Security.NonceVerification.Recommended, WordPress.Security.ValidatedSanitizedInput
				'paged'           => $current_page,
				'fields'          => array(
					'ID',
					'receiver',
					'transaction_id',
					'transaction_status',
					'amount',
					'fee',
					'currency',
					'payout_item_id',
					'sender_batch_id',
				),
			);

			$this->items = YITH_Payout_Items()->get_payout_items( $query_args );

			$total_items = YITH_Payout_Items()->get_payout_items(
				array(
					'fields'          => 'count',
					'payout_batch_id' => wp_unslash( $_GET['show_payout_details'] ), // phpcs:ignore WordPress.Security.NonceVerification.Recommended, WordPress.Security.ValidatedSanitizedInput
				)
			);

			$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( (int) $total_items / $per_page ),   // WE have to calculate the total number of pages.
				)
			);
		}


		/**
		 * Get payout item details
		 *
		 * @param int $payout_item_id The payout item id.
		 *
		 * @return array
		 * @since 1.0.1
		 */
		public static function payout_item_preview_get_payout_item_details( $payout_item_id ) {

			if ( ! $payout_item_id ) {
				return array();
			}

			$args = array(
				'fields' => array(
					'ID',
					'sender_batch_id',
					'transaction_id',
					'transaction_status',
					'amount',
				),
				'ID'     => $payout_item_id,
			);

			$payout_item = YITH_Payout_Items()->get_payout_items( $args );
			$payout_item = 1 === count( $payout_item ) ? $payout_item[0] : array();

			$status              = YITH_Payout_Items()->get_transaction_status();
			$current_status      = strtolower( $payout_item['transaction_status'] );
			$payout_item_details = array(
				'transaction_id'          => ! empty( $payout_item['transaction_id'] ) ? $payout_item['transaction_id'] : 'N/A',
				'transaction_status_name' => isset( $status[ $current_status ] ) ? $status[ $current_status ] : $current_status,
				'transaction_status'      => $payout_item['transaction_status'],
				'item_html'               => self::get_payout_item_preview_item_html( $payout_item ),
			);

			return $payout_item_details;

		}

		/**
		 * Render the payout item details
		 *
		 * @param array $payout_item the item.
		 *
		 * @return string
		 */
		public static function get_payout_item_preview_item_html( $payout_item ) {

			$sender_batch_id = $payout_item['sender_batch_id'];
			$args            = array(
				'fields'          => array(
					'payout_mode',
					'order_id',
				),
				'sender_batch_id' => $sender_batch_id,
			);
			$payout          = YITH_Payouts()->get_payouts( $args );
			$payout          = $payout[0];

			$items = apply_filters( 'yith_paypal_payout_' . str_replace( '-', '_', $payout['payout_mode'] ) . '_items_html', '', $sender_batch_id, $payout, $payout_item ); // phpcs:ignore

			$columns = apply_filters(
				'yith_payouts_items_columns',
				array(
					'order' => __( 'Order', 'yith-paypal-payouts-for-woocommerce' ),
					'total' => __( 'Total', 'yith-paypal-payouts-for-woocommerce' ),
				),
				$payout['payout_mode']
			);

			ob_start();
			?>
			<div class="wc-order-preview-table-wrapper">
				<table cellspacing="0" class="wc-order-preview-table">
					<thead>
					<tr>
						<?php foreach ( $columns as $column => $label ) : ?>
							<th class="wc-order-preview-table__column--<?php echo esc_attr( $column ); ?>"><?php echo esc_html( $label ); ?></th>
						<?php endforeach; ?>
					</tr>
					</thead>
					<tbody>
					<?php
					if ( ! empty( $items ) ) :
						echo $items; //phpcs:ignore WordPress.Security.EscapeOutput
						?>
					<?php else : ?>
						<tr class="wc-order-preview-table__item wc-order-preview-table__item--no-row">
							<td colspan="2" class="wc-order-preview-table__column--no-row">
								<?php echo apply_filters( 'yith_payouts_not_item_row', esc_html__( 'No commission found for this transaction ID.', 'yith-paypal-payouts-for-woocommerce' ), $payout['payout_mode'] ); // phpcs:ignore WordPress.Security.EscapeOutput ?></td>
						</tr>
					<?php endif; ?>

					</tbody>
				</table>
			</div>
			<?php

			$template = ob_get_contents();
			ob_end_clean();

			return $template;
		}


		/**
		 * Get order detail for batch id
		 *
		 * @param array  $items The items.
		 * @param array  $sender_batch_id The sender id.
		 * @param string $payout The single payout.
		 * @param array  $payout_item The payout item.
		 *
		 * @return string
		 * @since 1.0.1
		 */
		public function get_instant_items_html( $items, $sender_batch_id, $payout, $payout_item ) {

			if ( ! empty( $payout['order_id'] ) ) {
				$order_id        = $payout['order_id'];
				$order           = wc_get_order( $order_id );
				$formatted_total = $order->get_formatted_order_total();
				$total           = $order->get_total();
				$url             = $order->get_edit_order_url();
				$customer        = $order->get_user();

				if ( $customer ) {

					$customer_name = $customer->user_firstname . ' ' . $customer->last_name;
				} else {
					$customer_name = 'Guest';
				}
				$url  = '<a href="' . $url . '">#' . $order->get_order_number() . ' ' . $customer_name . '</a>';
				$html = '<tr class="wc-order-preview-table__item wc-order-preview-table__item--' . $order_id . '">
								<td class="wc-order-preview-table__column--order_commission">' . $url . '</td>
								<td class="wc-order-preview-table__column--total">' . $formatted_total . '</td>
								</tr>';

				$query_args           = array(
					'fields'          => array(
						'receiver',
						'amount',
						'fee',
					),
					'sender_batch_id' => $payout_item['sender_batch_id'],
				);
				$receiver_commissions = YITH_Payout_Items()->get_payout_items( $query_args );
				if ( count( $receiver_commissions ) > 0 ) {

					$currency  = $order->get_currency();
					$total_fee = 0;
					foreach ( $receiver_commissions as $receiver_commission ) {

						$amount = $receiver_commission['amount'];
						$fee    = isset( $receiver_commission['fee'] ) ? $receiver_commission['fee'] : 0;

						$total_fee += $fee;
						$total     -= $amount - $fee;

						$formatted_amount = '-' . wc_price( $amount, array( 'currency', $currency ) );

						$html .= '<tr class="wc-order-preview-table__item wc-order-preview-table__item--receiver-commission">
												<td class="wc-order-preview-table__column--order_commission">' . __( 'Receiver Commission', 'yith-paypal-payouts-for-woocommerce' ) . '
													<p><small>' . $receiver_commission['receiver'] . '</small></p>
												</td>
												<td class="wc-order-preview-table__column--total">' . $formatted_amount . '</td>
											</tr>';
					}

					$new_formatted_fee = '-' . wc_price( $total_fee, array( 'currency', $currency ) );

					$html .= '<tr class="wc-order-preview-table__item wc-order-preview-table__item--net-total">
								<td class="wc-order-preview-table__column--order_commission"><strong>' . __( 'Fee', 'yith-paypal-payouts-for-woocommerce' ) . '</strong></td>
								<td class="wc-order-preview-table__column--total">' . $new_formatted_fee . '</td>
								</tr>';

					$new_formatted_total = wc_price( $total, array( 'currency', $currency ) );

					$html .= '<tr class="wc-order-preview-table__item wc-order-preview-table__item--net-total">
								<td class="wc-order-preview-table__column--order_commission"><strong>' . __( 'Net Total', 'yith-paypal-payouts-for-woocommerce' ) . '</strong></td>
								<td class="wc-order-preview-table__column--total">' . $new_formatted_total . '</td>
								</tr>';
				}
			}

			return $html;
		}

		/**
		 * Return the affiliates items detail
		 *
		 * @param string $html The default output.
		 * @param string $sender_batch_id The sender id.
		 *
		 * @return string
		 */
		public function get_affiliate_items_html( $html, $sender_batch_id ) {
			$args = array(
				'sender_batch_id' => $sender_batch_id,
				'fields'          => array( 'sender_item_id', 'amount', 'fee' ),
			);

			$affiliate_query_args = array(
				'page'    => 'yith_wcaf_panel',
				'tab'     => 'commissions',
				'sub_tab' => 'commissions-payments',
			);

			$results = YITH_Payout_Items()->get_payout_items( $args );
			$html    = '';
			if ( count( $results ) > 0 ) {
				$total     = 0;
				$total_fee = 0;
				$href_text = _x( 'Affiliate Payment', 'Affiliate Payment for : list payment ids', 'yith-paypal-payouts-for-woocommerce' );
				foreach ( $results as $result ) {

					$affiliate_id    = str_replace( 'affiliate_payment_', '', $result['sender_item_id'] );
					$affiliate_total = $result['amount'];
					$fee             = isset( $result['fee'] ) ? $result['fee'] : 0;

					$total_fee += $fee;
					$total     += $affiliate_total;

					$affiliate_formatted_total          = wc_price( $affiliate_total );
					$affiliate_query_args['payment_id'] = $affiliate_id;
					$url                                = esc_url( add_query_arg( $affiliate_query_args, admin_url( 'admin.php' ) ) );
					$url                                = sprintf( '<a href="%s" target="_blank">%s</a>', $url, '#' . $affiliate_id );

					$html .= '<tr class="wc-order-preview-table__item wc-order-preview-table__item--receiver-commission">
												<td class="wc-order-preview-table__column--order_commission">' . $href_text . ' ' . $url . '

												</td>
												<td class="wc-order-preview-table__column--total">' . $affiliate_formatted_total . '</td>
											</tr>';

				}

				$new_formatted_fee = wc_price( $total_fee );

				$html .= '<tr class="wc-order-preview-table__item wc-order-preview-table__item--net-total">
								<td class="wc-order-preview-table__column--order_commission"><strong>' . __( 'Fee', 'yith-paypal-payouts-for-woocommerce' ) . '</strong></td>
								<td class="wc-order-preview-table__column--total">' . $new_formatted_fee . '</td>
								</tr>';

				$new_formatted_total = wc_price( $total + $total_fee );

				$html .= '<tr class="wc-order-preview-table__item wc-order-preview-table__item--net-total">
								<td class="wc-order-preview-table__column--order_commission"><strong>' . __( 'Total Transaction', 'yith-paypal-payouts-for-woocommerce' ) . '</strong></td>
								<td class="wc-order-preview-table__column--total">' . $new_formatted_total . '</td>
								</tr>';
			} else {
				$html = '<tr class="wc-order-preview-table__item wc-order-preview-table__item--no-row">
							<td colspan="2" class="wc-order-preview-table__column--no-row">' . __( 'No affiliate payments found for this transaction ID.', 'yith-paypal-payouts-for-woocommerce' ) . '</td>
						</tr>';
			}

			return $html;
		}

		/**
		 * Get the commission details for a batch payment
		 *
		 * @param string $html The default output.
		 * @param string $sender_batch_id The sender id.
		 *
		 * @return string
		 * @since 1.0.1
		 */
		public function get_commission_items_html( $html, $sender_batch_id ) {

			$query_args    = array(
				'fields'          => array(
					'fee',
				),
				'sender_batch_id' => $sender_batch_id,
			);
			$receiver_fees = YITH_Payout_Items()->get_payout_items( $query_args );

			$row_fees_html = '';
			$total_fee     = 0;
			if ( count( $receiver_fees ) > 0 ) {

				foreach ( $receiver_fees as $receiver_fee ) {

					$fee = isset( $receiver_fee['fee'] ) ? $receiver_fee['fee'] : 0;

					$total_fee += $fee;
				}
				$new_formatted_total = wc_price( $total_fee );
				$row_fees_html       = '<tr class="wc-order-preview-table__item wc-order-preview-table__item--net-total">
								<td class="wc-order-preview-table__column--order_commission"><strong>' . __( 'Total Fee', 'yith-paypal-payouts-for-woocommerce' ) . '</strong></td>
								<td class="wc-order-preview-table__column--total">' . $new_formatted_total . '</td>
								</tr>';
			}

			$payment_id     = str_replace( 'commission_', '', $sender_batch_id );
			$commission_ids = array();

			if ( function_exists( 'YITH_Vendors' ) ) {
				$paid_ids       = YITH_Vendors()->payments->get_commissions_by_payment_id( $payment_id, 'paid' );
				$processing_ids = YITH_Vendors()->payments->get_commissions_by_payment_id( $payment_id, 'processing' );
				$unpaid_ids     = YITH_Vendors()->payments->get_commissions_by_payment_id( $payment_id, 'unpaid' );

				$commission_ids = array_merge( $paid_ids, $processing_ids, $unpaid_ids );
			}

			if ( count( $commission_ids ) > 0 ) {

				$total               = 0;
				$commission_function = function_exists( 'yith_wcmv_get_commission' ) ? 'yith_wcmv_get_commission' : 'YITH_Commission';
				foreach ( $commission_ids as $commission_id ) {
					$commission       = $commission_function( $commission_id );
					$commission_total = $commission->get_amount( 'display' );

					$total += $commission->get_amount();

					$order = $commission->get_order();

					$order_url = $order->get_edit_order_url();
					$customer  = $order->get_user();

					if ( $customer ) {
						$customer_name = $customer->user_firstname . ' ' . $customer->last_name;
					} else {
						$customer_name = 'Guest';
					}
					$order_url          = '<a href="' . $order_url . '">#' . $order->get_order_number() . ' ' . $customer_name . '</a>';
					$args_query['view'] = $commission_id;

					$url = $commission->get_view_url( 'admin' );

					$link = sprintf( '<a href="%s" target="_blank">%s %s</a>', $url, _x( 'Commission', 'Commission for order #123', 'yith-paypal-payouts-for-woocommerce' ), '#' . $commission_id );
					$text = $link . ' ' . _x( 'for order', 'Commission for order #123', 'yith-paypal-payout-for-woocommerce' ) . ' ' . $order_url;

					$html .= '<tr class="wc-order-preview-table__item wc-order-preview-table__item--' . $commission_id . '">
								<td class="wc-order-preview-table__column--order_commission">' . $text . '</td>
								<td class="wc-order-preview-table__column--total">' . $commission_total . '</td>
								</tr>';
				}

				$html .= $row_fees_html;

				$new_formatted_total = wc_price( $total + $total_fee );

				$html .= '<tr class="wc-order-preview-table__item wc-order-preview-table__item--net-total">
								<td class="wc-order-preview-table__column--order_commission"><strong>' . __( 'Total Transaction', 'yith-paypal-payouts-for-woocommerce' ) . '</strong></td>
								<td class="wc-order-preview-table__column--total">' . $new_formatted_total . '</td>
								</tr>';
			}

			return $html;
		}

		/**
		 * The payout item template
		 *
		 * @since 1.0.0
		 */
		public function payout_item_preview_template() {
			?>
			<script type="text/template" id="tmpl-yith-payouts-modal-view-payout-item">
				<div class="wc-backbone-modal wc-payout-item-preview wc-order-preview">
					<div class="wc-backbone-modal-content">
						<section class="wc-backbone-modal-main" role="main">
							<header class="wc-backbone-modal-header">
								<span class="order-status payouts-status {{ data.transaction_status }}">{{ data.transaction_status_name }}
								</span>
								<?php /* translators: %s: order ID */ ?>
								<h1><?php echo esc_html( sprintf( __( 'Transaction ID #%s', 'woocommerce' ), '{{ data.transaction_id }}' ) ); ?></h1>
							</header>
							<article>
								{{{data.item_html }}}
							</article>
						</section>
					</div>
				</div>
			</script>
			<?php

		}

		/**
		 * Not show the table nav
		 *
		 * @param string $which The which string.
		 *
		 * @return string
		 * @since
		 */
		public function display_tablenav( $which ) {
			return '';
		}

	}

}
