<?php
namespace TotalTheme\Pagination;

defined( 'ABSPATH' ) || exit;

/**
 * Standard Pagination.
 *
 * @package TotalTheme
 * @subpackage Author
 * @version 5.5
 */
class Standard {

	/**
	 * The current query.
	 */
	protected $query;

	/**
	 * The pagination args.
	 */
	protected $args;

	/**
	 * Constructor.
	 */
	public function __construct( $query = null )  {
		if ( $query ) {
			$this->query = $query;
		} else {
			global $wp_query;
			$this->query = $wp_query;
		}
	}

	/**
	 * Renders the pagination.
	 */
	public function render()  {
		echo '<div class="wpex-pagination wpex-clear wpex-mt-30 wpex-clr' . $this->get_alignment() . '">' . paginate_links( $this->get_args() ) . '</div>';
	}

	/**
	 * Returns pagination args.
	 */
	protected function get_args()  {
		if ( ! is_null( $this->args ) ) {
			return $this->args;
		}

		$arrow_icon = sanitize_html_class( get_theme_mod( 'pagination_arrow' ) ?: 'angle' );

		if ( is_rtl() ) {
			$prev_arrow = $arrow_icon . '-right';
			$next_arrow = $arrow_icon . '-left';
		} else {
			$prev_arrow = $arrow_icon . '-left';
			$next_arrow = $arrow_icon . '-right';
		}

		// Set vars.
		$total = (int) $this->query->max_num_pages;
		$big   = 999999999;

		// Display pagination.
		if ( empty( $total ) || 1 === $total ) {
			return;
		}

		// Get current page.
		if ( $current_page = get_query_var( 'paged' ) ) {
			$current_page = $current_page;
		} elseif ( $current_page = get_query_var( 'page' ) ) {
			$current_page = $current_page;
		} else {
			$current_page = 1;
		}

		// Get permalink structure.
		if ( get_option( 'permalink_structure' ) ) {
			if ( is_page() ) {
				$format = 'page/%#%/';
			} else {
				$format = '/%#%/';
			}
		} else {
			$format = '&paged=%#%';
		}

		$args = [
			'base'               => str_replace( $big, '%#%', html_entity_decode( get_pagenum_link( $big ) ) ),
			'format'             => $format,
			'current'            => max( 1, $current_page ),
			'total'              => $total,
			'mid_size'           => 3,
			'type'               => 'list',
			'prev_text'          => wpex_get_theme_icon_html( $prev_arrow ) . '<span class="screen-reader-text">' . esc_html__( 'Previous', 'total' ) . '</span>',
			'next_text'          => wpex_get_theme_icon_html( $next_arrow ) . '<span class="screen-reader-text">' . esc_html__( 'Next', 'total' ) . '</span>',
			'before_page_number' => '<span class="screen-reader-text">' . esc_html__( 'Page', 'total' ) . ' </span>',
		];

		/**
		 * Filters the standard pagination args.
		 *
		 * @param array $args
		 */
		$this->args = (array) apply_filters( 'wpex_pagination_args', $args );

		return $this->args;
	}

	/**
	 * Returns pagination alignment.
	 */
	protected function get_alignment() {
		return ( $align = get_theme_mod( 'pagination_align' ) ) ? ' text' . sanitize_html_class( $align ) : '';
	}

}