<?php

namespace GPLoker\Inc;
class AutoPageBreak {
	private $page_break = '<!--nextpage-->';
	private $page_break_at_paragraph = 3;
	private $before_prefix_text;
	private $after_prefix_text;

	public function __construct() {

		if ( $this->autoPageBreakIsEnabled() ) {

			$this->page_break_at_paragraph = Option::get( 'page_break_at_paragraph', $this->page_break_at_paragraph );
			$this->before_prefix_text      = Option::get( 'page_break_name', 'Halaman' );
			$this->after_prefix_text       = Option::get( 'page_break_show_all', 'Lihat Semua' );

			add_action( 'the_posts', [ $this, 'autoPageBreak' ], 10, 2 );
			add_filter( 'the_content', [ $this, 'pageBreakPagination' ] );
			add_filter( 'wp_link_pages_args', [ $this, 'paginationArgs' ] );
			add_action( 'wp_head', [ $this, 'pageBreakPaginationStyle' ] );
		}
	}

	public function autoPageBreak( $posts, $query ) {
		if ( $query->is_main_query() && $query->is_single() ) {
			foreach ( $posts as $post ) {
				$post->post_content = $this->setPageBreak( $post->post_content, $this->page_break_at_paragraph );
			}
		}

		return $posts;
	}

	public function pageBreakPagination( $content ) {
		global $multipage, $post;

		if ( ! empty( $_GET['show'] ) && $_GET['show'] == 'all' ) {
			return $post->post_content;
		}

		if (
			$multipage &&
			$this->autoPageBreakIsEnabled() &&
			! str_contains( $content, '<div class="gploker-auto-page-break-pagination">' )
		) {
			$content .= wp_link_pages( $this->paginationArgs() );
		}

		return $content;
	}

	public function pageBreakPaginationStyle() {
		?>
		<style>
            .gploker-auto-page-break-pagination {
                display: flex;
                flex-wrap: wrap;
            }
		</style>
		<?php
	}

	public function paginationArgs() {
		global $post;

		$before = '<div class="gploker-auto-page-break-pagination"><div class="pagination"><span class="prefix">' . $this->before_prefix_text . ': </span>';

		$link_show_all = add_query_arg( [
			'show' => 'all'
		], get_permalink( $post ) );

		$after = '</div><div class="gploker-show-all-page-content"><a href="' . $link_show_all . '">' . $this->after_prefix_text . '</a></div>';

		return [
			'before'           => $before,
			'after'            => $after,
			'link_before'      => '<span class="page-number">',
			'link_after'       => '</span>',
			'next_or_number'   => 'number',
			'separator'        => ' ',
			'aria_current'     => 'page',
			'nextpagelink'     => __( 'Next page' ),
			'previouspagelink' => __( 'Previous page' ),
			'pagelink'         => '%',
			'echo'             => false
		];
	}

	protected function setPageBreak( $post_content, $break_at_paragraph = 0 ) {
		if ( empty( $break_at_paragraph ) ) {
			return $post_content;
		}

		if ( str_contains( $post_content, $this->page_break ) ) {
			return $post_content;
		}

		$_content = '';
		$n        = 0;
		$blocks   = parse_blocks( $post_content );

		if ( $blocks ) {
			foreach ( $blocks as $block ) {
				if ( ! empty( $block['blockName'] ) && $block['blockName'] == 'core/paragraph' ) {
					$n ++;
				}

				$_content .= render_block( $block );
				if ( $n == $break_at_paragraph ) {
					$_content .= $this->page_break;
					$n        = 0;
				}

			}
		} else {
			$paragraphs = explode( '</p>', $post_content );
			foreach ( $paragraphs as $paragraph ) {
				if ( empty( $this->cleanWPBlocks( $paragraph ) ) ) {
					continue;
				}

				$_content .= $paragraph . '</p>';
				if ( $n == $break_at_paragraph ) {
					$_content .= $this->page_break;
					$n        = 0;
				}

				$n ++;
			}
		}

		return $_content;
	}

	protected function autoPageBreakIsEnabled() {
		return Option::get( 'use_auto_page_break', true );
	}

	private function cleanWPBlocks( $content ) {
		// Define the regex pattern to match WordPress block comments
		$pattern = '/<!--\s*\/?wp:[a-z0-9\-]+\s*-->/i';

		// Use preg_replace() to remove the matched block comments
		$clean = preg_replace( $pattern, '', $content );

		return trim( $clean );
	}
}

new AutoPageBreak();