<?php

namespace Prodigy\Includes;

use Prodigy\Includes\Frontend\Pages\Prodigy_Shop_Page;
use Prodigy\includes\helpers\Prodigy_Elementor;
use Prodigy\includes\helpers\Prodigy_Elementor_Layouts;
use Prodigy\Includes\Helpers\Prodigy_Formatting;
use Prodigy\Includes\Helpers\Prodigy_Parameters;
use Prodigy\Includes\Helpers\Prodigy_Url_Helper;
use Prodigy\Includes\Support\Addons\Elementor\Widgets\Archive\Prodigy_Products;

defined( 'ABSPATH' ) || exit;

/**
 * Class Prodigy_Pagination
 */
class Prodigy_Pagination {

	/**
	 * @param int $number
	 * @param int $number_per_page
	 *
	 * @return false|float
	 */
	public static function calculate_count_pages( int $number, int $number_per_page ) {
		if ( ! empty( $number_per_page ) ) {
			return ceil( $number / $number_per_page );
		}

		return 1;
	}

	/**
	 * @return int|mixed
	 */
	public static function get_per_page_by_options() {
		$customizer_shop_options = get_option( 'prodigy_shop_settings' );
		$per_page                = $customizer_shop_options['prodigy_shop_products_number_items_per_page'] ?? null;
		if ( Prodigy_Elementor_Layouts::is_using_archive_elementor_templates() || Prodigy_Elementor_Layouts::is_elementor_live_preview() ) {
			if ( wp_doing_ajax() && ! Prodigy_Elementor_Layouts::is_elementor_action() ) {
				$widget_id = Prodigy_Parameters::get_parameter( $_GET, 'products_widget_id', 'sanitize_key' );
				if ( $widget_id === null ) {
					return $per_page ?? Prodigy_Shop_Page::NUMBER_ITEMS_PER_PAGE;
				}
				if ( Prodigy_Elementor::is_elementor_enabled() ) {
					$elementor_products_archive_widget_options = Prodigy_Elementor::get_widget_options( ( new Prodigy_Products() )->get_name(), $widget_id );
					$per_page                                  = $elementor_products_archive_widget_options['content_archive_products_content_items_number'];
				}
			}
		}

		return $per_page ?? Prodigy_Shop_Page::NUMBER_ITEMS_PER_PAGE;
	}

	/**
	 * @param array $data
	 * @param int   $pages_number
	 * @param int   $range
	 *
	 * @return void
	 */
	public static function prodigy_pagination( array $data, int $pages_number = 1, int $range = 4 ) {
		if ( ! empty( $pages_number ) ) {
			$showitems = ( $range * 2 ) + 1;
			if ( isset( $pages_number, $data['page_number'] ) && 1 != $pages_number ) {
				if ( (int) $data['page_number'] > 2 && (int) $data['page_number'] > $range + 1 && $showitems < $pages_number ) {
					$first = self::get_url_for_page( 1 );
					echo wp_kses(
						sprintf(
							'<a aria-label="%1$s" class="prodigy-pagination__nav" href="%2$s">&laquo;</a>',
							__( 'First', 'prodigy-commerce' ),
							esc_attr( $first )
						),
						Prodigy_Formatting::get_allowed_html()
					);
				}

				if ( $data['page_number'] > 1 && $showitems < $pages_number ) {
					$prev = self::get_url_for_page( (int) $data['page_number'] - 1 );
					echo wp_kses(
						sprintf(
							'<a aria-label="%1$s" class="prodigy-pagination__nav prodigy-pagination__nav-prev" href="%2$s">&lsaquo;</a>',
							__( 'Previous', 'prodigy-commerce' ),
							esc_attr( $prev )
						),
						Prodigy_Formatting::get_allowed_html()
					);
				}

				$max_range = (int) $data['page_number'] + $range + 1;
				$min_range = (int) $data['page_number'] - $range - 1;
				for ( $i = 1; $i <= $pages_number; $i++ ) {
					if ( 1 !== $pages_number && ( ! ( $i >= $max_range || $i <= $min_range ) || $pages_number <= $showitems ) ) {
						$url = self::get_url_for_page( $i );
						/* translators: %d: page number */
						$aria_label = sprintf( __( 'Go to page %d', 'prodigy-commerce' ), $i );
						if ( (int) $data['page_number'] === $i ) {
							echo wp_kses(
								sprintf(
									'<span class="prodigy-pagination__item prodigy-pagination__item--active" aria-current="%1$s">%1$s</span>',
									esc_html( $i )
								),
								Prodigy_Formatting::get_allowed_html()
							);
						} else {
							echo wp_kses(
								sprintf(
									'<a class="prodigy-pagination__item" href="%1$s" aria-label="%2$s">%3$s</a>',
									esc_url( $url ),
									esc_attr( $aria_label ),
									esc_html( $i )
								),
								Prodigy_Formatting::get_allowed_html()
							);
						}
					}
				}

				if ( $data['page_number'] < $pages_number && $showitems < $pages_number ) {
					$next = self::get_url_for_page( (int) $data['page_number'] + 1 );
					echo wp_kses(
						sprintf(
							'<a aria-label="%1$s" class="prodigy-pagination__nav prodigy-pagination__nav-next" href="%2$s">&rsaquo;</a>',
							__( 'Next', 'prodigy-commerce' ),
							esc_attr( $next )
						),
						Prodigy_Formatting::get_allowed_html()
					);
				}

				if ( $data['page_number'] < $pages_number - 1 && (int) $data['page_number'] + $range - 1 < $pages_number && $showitems < $pages_number ) {
					$last = self::get_url_for_page( $data['pages'] );
					echo wp_kses(
						sprintf(
							'<a aria-label="%1$s" class="prodigy-pagination__nav" href="%2$s">&raquo;</a>',
							__( 'Last', 'prodigy-commerce' ),
							esc_attr( $last )
						),
						Prodigy_Formatting::get_allowed_html()
					);
				}

				echo "</div>\n";
			}
		}
	}

	/**
	 * Get current page number.
	 *
	 * @param array $query
	 *
	 * @return int
	 */
	public static function get_current_page( array $query ): int {
		$page = 1;
		if ( isset( $query['pg'] ) ) {
			parse_str( $query['pg'], $array );
			foreach ( $array as $key => $param ) {
				if ( $key === 'pg' ) {
					$page = $param;
				}
			}
		}

		return (int) $page;
	}

	/**
	 * @param int $page
	 *
	 * @return string
	 */
	private static function get_url_for_page( int $page ): string {
		$sort        = Prodigy_Parameters::get_parameter( $_GET, 'sort' );
		$current_url = Prodigy_Url_Helper::prodigy_get_request_uri();

		if ( wp_doing_ajax() ) {
			$url      = Prodigy_Parameters::get_parameter( $_GET, 'current_url', 'sanitize_url' );
			$referrer = Prodigy_Parameters::get_parameter( $_SERVER, 'HTTP_REFERER', 'sanitize_url' );

			if ( is_admin() ) {
				$current_url = $referrer ?: $url;
			}
		}

		if ( $page <= 1 ) {
			return remove_query_arg( array( 'pg' ), $current_url );
		}

		$args = array( 'pg' => $page );

		if ( $sort ) {
			$args['sort'] = $sort;
		}

		$query = add_query_arg( $args, wp_parse_url( $current_url, PHP_URL_QUERY ) );
		if ( ! empty( $query ) && strpos( $query, '?' ) !== 0 ) {
			return '?' . $query;
		}

		return $query;
	}
}
