<?php namespace MeowCrew\CancellationOffers\SurveyAnswers\SurveyAnswersPage;

use Exception;
use MeowCrew\CancellationOffers\Core\ServiceContainerTrait;
use MeowCrew\CancellationOffers\Offer\CPT\CancellationOffersCPT;
use MeowCrew\CancellationOffers\SurveyAnswers\SurveyAnswer;
use MeowCrew\CancellationOffers\SurveyAnswers\SurveyAnswersPage\Actions\SurveyAnswersListAction;
use MeowCrew\CancellationOffers\SurveyAnswers\SurveyAnswersPage\Columns\ActionsColumn;
use MeowCrew\CancellationOffers\SurveyAnswers\SurveyAnswersPage\Columns\AnswerColumn;
use MeowCrew\CancellationOffers\SurveyAnswers\SurveyAnswersPage\Columns\CbColumn;
use MeowCrew\CancellationOffers\SurveyAnswers\SurveyAnswersPage\Columns\RetentionOfferColumn;
use MeowCrew\CancellationOffers\SurveyAnswers\SurveyAnswersPage\Columns\DateCreatedColumn;
use MeowCrew\CancellationOffers\SurveyAnswers\SurveyAnswersPage\Columns\IsDiscountOfferAccepted;
use MeowCrew\CancellationOffers\SurveyAnswers\SurveyAnswersPage\Columns\OfferColumn;
use MeowCrew\CancellationOffers\SurveyAnswers\SurveyAnswersPage\Columns\SubscriptionColumn;
use MeowCrew\CancellationOffers\SurveyAnswers\SurveyAnswersPage\Columns\UserColumn;
use MeowCrew\CancellationOffers\SurveyAnswers\SurveyAnswersRepository;
use WP_List_Table;
use wpdb;

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

class SurveyAnswersWPListTable extends WP_List_Table {
	
	use ServiceContainerTrait;
	
	public $answersCount;
	
	/**
	 * List actions
	 *
	 * @var SurveyAnswersListAction[]
	 */
	private $lineActions;
	
	private $tableColumns;
	
	private $perPage;
	
	/**
	 * Initialize the log table list.
	 */
	public function __construct( $lineActions ) {
		$this->lineActions = $lineActions;
		$this->initTableColumns();
		
		parent::__construct( array(
			'singular' => __( 'Survey Answer', 'cancellation-surveys-offers-woocommerce-subscriptions' ),
			'plural'   => __( 'Survey Answer', 'cancellation-surveys-offers-woocommerce-subscriptions' ),
			'ajax'     => false,
			'screen'   => null,
		) );
		
		$this->perPage = 10;
	}
	
	protected function extra_tablenav( $which ) {
		if ( 'top' === $which ) {
			?>
			<div class="alignleft actions">
				<select name="offer_id" id="offer_id">
					<option value="">
						<?php
							esc_attr_e( 'All Survey & Offers',
								'cancellation-surveys-offers-woocommerce-subscriptions' );
						?>
					</option>
					<?php
						$offers = CancellationOffersCPT::getOffers();
						
					foreach ( $offers as $offer ) {
						$selected = isset( $_GET['offer_id'] ) && absint( $_GET['offer_id'] ) === $offer->getId();
							
						?>
							<option value="<?php echo esc_attr( $offer->getId() ); ?>" <?php selected( $selected ); ?>>
							<?php echo esc_html( get_the_title( $offer->getId() ) ); ?>
							</option>
							<?php
					}
					?>
				</select>

				<select name="retain_status" id="retain_status">
					<option value="">
						<?php
							esc_attr_e( 'Any Retain Status', 'cancellation-surveys-offers-woocommerce-subscriptions' );
						?>
					</option>
					<option value="retained" <?php selected( isset( $_GET['retain_status'] ) && 'retained' === $_GET['retain_status'] ); ?>>
						<?php esc_attr_e( 'Retained', 'cancellation-surveys-offers-woocommerce-subscriptions' ); ?>
					</option>
					<option value="cancelled" <?php selected( isset( $_GET['retain_status'] ) && 'cancelled' === $_GET['retain_status'] ); ?>>
						<?php esc_attr_e( 'Cancelled', 'cancellation-surveys-offers-woocommerce-subscriptions' ); ?>
					</option>
				</select>

				<input type="submit" name="filter_action" id="post-query-submit" class="button"
					   value="
					   <?php
						   esc_attr_e( 'Filter', 'cancellation-surveys-offers-woocommerce-subscriptions' );
						?>
						   ">
			</div>
			<?php
		}
	}
	
	protected function initTableColumns() {
		/**
		 * Columns of survey answers list table
		 *
		 * @since 1.0.0
		 */
		$columns = apply_filters( 'cancellation_offers/survey_answers/columns', array(
			new CbColumn(),
			new AnswerColumn(),
			new UserColumn(),
			new SubscriptionColumn(),
			new OfferColumn(),
			
			new IsDiscountOfferAccepted(),
			new RetentionOfferColumn(),
			new DateCreatedColumn(),
			new ActionsColumn( $this->lineActions ),
		) );
		
		foreach ( $columns as $column ) {
			$this->tableColumns[ $column->getSlug() ] = $column;
		}
	}
	
	public function no_items() {
		esc_attr_e( 'No survey answers yet.', 'cancellation-surveys-offers-woocommerce-subscriptions' );
	}
	
	public function single_row( $item ) {
		
		$class = ! $item->isSeen() ? 'cos-new-survey-answer-row' : '';
		
		echo '<tr class="' . esc_attr( $class ) . '">';
		$this->single_row_columns( $item );
		echo '</tr>';
	}
	
	
	/**
	 * Handles output for the default column.
	 *
	 * @param  SurveyAnswer  $item
	 * @param  string  $column_name  Identifier for the custom column.
	 */
	public function column_default( $item, $column_name ) {
		/**
		 * Fires for each custom column in the Feedbacks list Table in the administrative screen.
		 *
		 * @param  string  $column_name  Identifier for the custom column.
		 * @param  SurveyAnswer  $survey_answer
		 *
		 * @since 1.0.0
		 *
		 */
		do_action( 'cancellation_offers/admin/survey_answers_list/render_column', $column_name, $item );
	}
	
	/**
	 * Get list columns.
	 *
	 * @return array
	 */
	public function get_columns(): array {
		
		$columns['cb'] = '<input type="checkbox" />';
		
		foreach ( $this->tableColumns as $column ) {
			$columns[ $column->getSlug() ] = $column->getName();
		}
		
		return $columns;
	}
	
	/**
	 * Column cb.
	 *
	 * @param  SurveyAnswer  $item
	 *
	 * @return string
	 */
	public function column_cb( $item ): string {
		return sprintf( '<input type="checkbox" name="survey_answers[]" value="%1$s" />', esc_attr( $item->getId() ) );
	}
	
	/**
	 * Get bulk actions.
	 *
	 * @return array
	 */
	protected function get_bulk_actions(): array {
		return array(
			'delete' => __( 'Delete', 'cancellation-surveys-offers-woocommerce-subscriptions' ),
		);
	}
	
	/**
	 * Get a list of sortable columns.
	 *
	 * @return array
	 */
	protected function get_sortable_columns(): array {
		return array();
	}
	
	protected function calculateFeedbacksCounts() {
		$this->answersCount = SurveyAnswersRepository::getAllSurveyAnswersCount();
	}
	
	public function process_bulk_action() {
		
		$action = $this->current_action();
		
		if ( $action ) {
			
			$nonce = isset( $_REQUEST['_wpnonce'] ) ? sanitize_text_field( $_REQUEST['_wpnonce'] ) : null;
			
			if ( ! wp_verify_nonce( $nonce, 'bulk-' . $this->_args['plural'] ) ) {
				$this->getContainer()->getAdminNotifier()->flash( __( 'Security check failed. Please try again.',
					'cancellation-surveys-offers-woocommerce-subscriptions' ) );
				
				return wp_safe_redirect( wp_get_referer() );
			}
			
			switch ( $action ) {
				case 'delete':
					$surveyAnswers = ! empty( $_GET['survey_answers'] ) ? array_map( 'intval',
						(array) $_GET['survey_answers'] ) : array();
					if ( ! empty( $surveyAnswers ) ) {
						SurveyAnswersRepository::bulkDelete( $surveyAnswers );
						
						$this->getContainer()->getAdminNotifier()->flash( __( 'Survey Answers have been deleted successfully',
							'cancellation-surveys-offers-woocommerce-subscriptions' ) );
					}
					break;
				
				default:
					break;
			}
			
			return wp_safe_redirect( wp_get_referer() );
		}
	}
	
	/**
	 * Prepare table list items.
	 *
	 * @global wpdb $wpdb
	 */
	public function prepare_items() {
		
		$this->calculateFeedbacksCounts();
		$this->process_bulk_action();
		$this->items = array();
		
		$offerId      = isset( $_GET['offer_id'] ) ? absint( $_GET['offer_id'] ) : null;
		$retainStatus = isset( $_GET['retain_status'] ) ? sanitize_text_field( $_GET['retain_status'] ) : null;
		
		$totalItems = SurveyAnswersRepository::getAllSurveyAnswersCount( $offerId, $retainStatus );
		
		$this->set_pagination_args( array(
			'total_items' => $totalItems,
			'per_page'    => $this->perPage,
			'total_pages' => ceil( $totalItems / $this->perPage ),
		) );
		
		$this->prepare_column_headers();
		
		$offset = $this->getOffset();
		
		try {
			global $wpdb;
			
			$where = '';
			
			if ( $offerId ) {
				$where .= $wpdb->prepare( ' AND offer_id = %d', $offerId );
			}
			
			if ( $retainStatus ) {
				$where .= $wpdb->prepare( ' AND is_discount_offer_accepted = %d',
					'retained' === $retainStatus ? 1 : 0 );
			}
			
			$this->items = SurveyAnswersRepository::get( $offset, $this->perPage, $where );
			
		} catch ( Exception $e ) {
			$this->items = array();
		}
		
		$ids = array_map( function ( $item ) {
			return $item->getId();
		}, $this->items );
		
		add_action( 'shutdown', function () use ( $ids ) {
			SurveyAnswersRepository::markAllAsSeen( $ids );
		} );
	}
	
	/**
	 * Get prepared OFFSET clause for items query
	 *
	 * @return int
	 */
	protected function getOffset(): int {
		
		$current_page = $this->get_pagenum();
		
		if ( 1 < $current_page ) {
			$offset = $this->perPage * ( $current_page - 1 );
		} else {
			$offset = 0;
		}
		
		return (int) $offset;
	}
	
	/**
	 * Set _column_headers property for table list
	 */
	protected function prepare_column_headers() {
		$this->_column_headers = array(
			$this->get_columns(),
			array(),
			$this->get_sortable_columns(),
		);
	}
}
