<?php // phpcs:ignore WordPress.Files.FileName
/**
 * The class that manage the Payout Receiver 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_Receiver_List_Table' ) ) {
	/**
	 * Class YITH_Payouts_Receiver_List_Table
	 */
	class YITH_Payouts_Receiver_List_Table extends WP_List_Table {
		/**
		 * The construct
		 */
		public function __construct() {
			parent::__construct(
				array(
					'singular' => _x( 'Receiver', 'yith-paypal-payouts-for-woocommerce' ),
					// singular name of the listed records.
					'plural'   => _x( 'Receivers', 'yith-paypal-payouts-for-woocommerce' ),
					'screen'   => 'yith-payouts-receiver-list',
				)
			);
		}

		/**
		 * Get columns
		 *
		 * @return array
		 * @since 1.0.0
		 * @author YITH <plugins@yithemes.com>
		 */
		public function get_columns() {
			$columns = array(
				'cb'               => '<input type="checkbox"/>',
				'receiver_info'    => __( 'User', 'yith-paypal-payouts-for-woocommerce' ),
				'receiver_email'   => __( 'PayPal Email', 'yith-paypal-payouts-for-woocommerce' ),
				'receiver_rate'    => __( 'Payout Rate', 'yith-paypal-payouts-for-woocommerce' ),
				'receiver_actions' => '',
			);

			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 'receiver_info':
					$user = get_user_by( 'id', $item['user_id'] );
					if ( $user instanceof WP_User ) {
						$output = $user->display_name . sprintf( '<br><a href="mailto:%1$1s">%1$1s</a>', $user->user_email );
					} else {
						$output = '-';
					}
					break;
				case 'receiver_email':
					$output = $item['paypal_email'];
					break;
				case 'receiver_rate':
					$output = $item['commission_rate'] . '%';
					break;

				case 'receiver_actions':
					$user           = get_user_by( 'id', $item['user_id'] );
					$formatted_name = '';
					if ( $user instanceof WP_User ) {
						$formatted_name = sprintf(
						// translators: 1. user display name; 2. user ID; 3. user email.
							esc_html__( '%1$s (#%2$s &ndash; %3$s)', 'woocommerce' ),
							$user->display_name,
							absint( $user->ID ),
							$user->user_email
						);
					}

					$output = yith_plugin_fw_get_component(
						array(
							'type'   => 'action-button',
							'action' => 'edit',
							'class'  => 'yith-payout-edit-receiver',
							'data'   => array(
								'user' => array_merge( $item, array( 'name' => $formatted_name ) ),
							),
							'title'  => __( 'Edit receiver', 'yith-paypal-payouts-for-woocommerce' ),
						),
						false
					);

					$paypal_email = $item['paypal_email'];
					$delete_url   = wp_nonce_url(
						add_query_arg(
							array(
								'paypal_email'                 => $paypal_email, // phpcs:ignore WordPress.Arrays.MultipleStatementAlignment.DoubleArrowNotAligned
								'yith_payouts_receiver_action' => 'delete_receiver',
							),
							admin_url( 'admin.php' )
						),
						'delete_reciever',
						'yith_payouts_delete_nonce'
					);

					$output .= yith_plugin_fw_get_component(
						array(
							'type'         => 'action-button',
							'action'       => 'delete',
							'icon'         => 'trash',
							'url'          => $delete_url,
							'title'        => __( 'Delete receiver', '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 receiver?', 'yith-paypal-payouts-for-woocommerce' ),
								'confirm-button'      => __( 'Delete', 'yith-paypal-payouts-for-woocommerce' ),
								'confirm-button-type' => 'delete',
							),
						),
						false
					);

					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_receivers_emails[]" value="%s" />',
				$item['paypal_email']
			);
		}

		/**
		 * 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_receivers_emails'] ) ) { // phpcs:ignore WordPress.Security.NonceVerification.Recommended
						$yith_receiver_emails = array_map( 'wc_clean', $_REQUEST['yith_receivers_emails'] ); // phpcs:ignore WordPress.Security.NonceVerification.Recommended,WordPress.Security.ValidatedSanitizedInput.InputNotSanitized, WordPress.Security.ValidatedSanitizedInput.MissingUnslash
						$this->delete( $yith_receiver_emails );
					}
				}
				$url = admin_url( 'admin.php' );
				$url = add_query_arg(
					array(
						'page' => 'yith_wc_paypal_payouts_panel',
						'tab'  => 'payout-receivers',
					),
					$url
				);
				wp_safe_redirect( $url );
				exit;
			}

		}

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

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

			return $actions;
		}

		/**
		 * Customize the display method
		 *
		 * @since 2.0.0
		 */
		public function display() {
			if ( $this->has_items() ) {
				parent::display();
			} else {
				$this->display_rows_or_placeholder();
			}
		}

		/**
		 * Customize the display method
		 *
		 * @since 2.0.0
		 */
		public function display_rows_or_placeholder() {
			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/receiver-empty.svg',
					'message'  => __( 'You have no receiver added yet.', 'yith-paypal-payouts-for-woocommerce' ),
					'cta'      => array(
						'title' => __( 'Add receiver', 'yith-paypal-payouts-for-woocommerce' ),
						'icon'  => 'plus',
						'class' => 'add-receiver',
					),
				);

				yith_plugin_fw_get_component( $component, true );
			}
		}

		/**
		 * Delete the receiver
		 *
		 * @param array $receiver_emails The receiver emails.
		 */
		public function delete( $receiver_emails ) {
			$receivers     = get_option( 'yith_payouts_receiver_list', array() );
			$new_receivers = array();

			foreach ( $receivers as $key => $receiver ) {
				if ( ! in_array( $receiver['paypal_email'], $receiver_emails, true ) ) {
					$new_receivers[] = $receiver;
				}
			}
			update_option( 'yith_payouts_receiver_list', $new_receivers );
		}


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

			$all_items     = get_option( 'yith_payouts_receiver_list', array() );
			$all_items = ! is_array( $all_items ) ? array() : $all_items;
			$total_items   = count( $all_items );
			$current_items = array();
			$item_added    = 0;
			for ( $i = ( $current_page - 1 ) * $per_page; $i < $total_items && $item_added < $per_page; $i ++, $item_added ++ ) {
				$item            = array_merge(
					array(
						'ID' => $i,
					),
					$all_items[ $i ]
				);
				$current_items[] = $item;
			}

			$this->items = $current_items;
			$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.
				)
			);
		}

	}
}
