<?php if ( ! class_exists( 'WPJ_Load_More_Posts' ) ) {

	class WPJ_Load_More_Posts extends stdClass {

		public function __construct() {
			$this->post_type             = '';
			$this->page                  = '';
			$this->posts_per_page        = wpj_get_option( 'posts_per_page' ) ? wpj_get_option( 'posts_per_page' ) : 12;
			$this->post_status           = '';
			$this->orderby               = '';
			$this->order                 = '';
			$this->author                = '';
			$this->meta_query            = '';
			$this->meta_key              = '';
			$this->force_no_custom_order = '';
			$this->tax_query             = '';
			$this->year                  = '';
			$this->monthnum              = '';
			$this->tag                   = '';
			$this->term                  = '';
			$this->taxonomy              = '';
			$this->s                     = '';
			$this->container_class       = '';
			$this->load_type             = 'button';
			$this->params                = '';
			$this->current_page          = '';
			$this->post__in              = '';
			$this->post__not_in          = '';
			$this->search_args           = '';
			$this->function_name         = '';
			$this->category_name         = '';

			$this->arguments = func_get_args();

			if ( ! empty( $this->arguments ) ) {
				foreach ( $this->arguments[0] as $key => $property ) {
					$this->{$key} = $property;
				}
			}

			$this->args = [
				'post_type'             => $this->post_type,
				'posts_per_page'        => $this->load_type == 'slider' ? -1 : $this->posts_per_page,
				'post_status'           => $this->post_status ? $this->post_status : 'publish',
				'orderby'               => $this->orderby,
				'order'                 => $this->order,
				'author'                => $this->author,
				'meta_query'            => $this->meta_query,
				'meta_key'              => $this->meta_key,
				'force_no_custom_order' => $this->force_no_custom_order,
				'tax_query'             => $this->tax_query,
				'year'                  => $this->year,
				'monthnum'              => $this->monthnum,
				'tag'                   => $this->tag,
				'term'                  => $this->term,
				'taxonomy'              => $this->taxonomy,
				's'                     => $this->s,
				'container_class'       => $this->container_class,
				'load_type'             => $this->load_type,
				'params'                => $this->params,
				'current_page'          => $this->current_page,
				'post__in'              => $this->post__in,
				'post__not_in'          => $this->post__not_in,
				'search_args'           => $this->search_args,
				'function_name'         => $this->function_name,
				'category_name'         => $this->category_name
			];

			$this->filters = new WPJ_Search_SQL_Filters( $this->args, $this->search_args, $this->post_type );

			$this->first_posts = false;

			add_action( 'wp_ajax_nopriv_show_list_ajax', [ $this, 'show_list_ajax' ] );
			add_action( 'wp_ajax_show_list_ajax',  [ $this, 'show_list_ajax' ] );
		}

		public static function init() {
			$arguments = isset( $_POST['args_encoded'] ) ? $_POST['args_encoded'] : '';

			$arg = [];

			if ( ! empty( $arguments[0] ) && is_array( $arguments[0] ) ) {
				foreach ( $arguments[0] as $key => $property ) {
					$arg[$key] = $property;
				}
			}

			$class = __CLASS__;
			new $class( $arg );
		}

		public function get_first_posts() {
			if ( $this->first_posts === false ) {
				$page_nr = get_query_var( 'paged' );
				if ( ! $page_nr ) $page_nr = 1;

				$args = $this->args + [ 'paged' => $page_nr ];

				$this->filters->add_search_filters();
				$the_query = new WP_Query( $args );
				$this->filters->remove_search_filters();

				$this->first_posts = $the_query;
			}

			return $this->first_posts;
		}

		public function get_search_results_items() {
			$args = $this->args;
			$args['posts_per_page'] = -1;

			$this->filters->add_search_filters();
			$the_query = new WP_Query( $args );
			$this->filters->remove_search_filters();

			$user_account_items = [];
			if ( $the_query->have_posts() ) {
				foreach ( $the_query->posts as $key => $row ) {
					if ( $this->function_name == 'wpj_display_proposal_list_items' ) {
						$custom_offer_row = wpj_get_pm_notify( 'id, initiator, user', ['custom_offer' => $row->ID], 'row' );

						if ( $custom_offer_row ) {
							if ( $custom_offer_row->initiator == get_current_user_id() ) $user_id = $custom_offer_row->user;
							else $user_id = $custom_offer_row->initiator;

							$url = wpj_get_pm_link( $user_id, $custom_offer_row->id );
						}

						if ( empty( $url ) ) $url = wpj_get_pm_link();

					} else {
						$url = get_permalink( $row->ID );

					}

					$user_account_items[$key] = [
						'post_id' => $row->ID,
						'title'   => addslashes( $row->post_title ),
						'url'     => $url
					];
				}
			}

			return $user_account_items;
		}

		public function have_rows() {
			$the_query = $this->get_first_posts();
			return $the_query->have_posts();
		}

		public function show_list_item() {
			if ( ! is_array( $this->params ) ) $this->params = [$this->params];
			call_user_func_array( $this->function_name, $this->params );
		}

		public function show_list_ajax() {
			$page_nr = get_query_var( 'paged' );
			if ( ! $page_nr ) $page_nr = 2;

			$page_nr = WPJ_Form::post( 'page_nr', $page_nr );
			$args    = $this->args + [ 'paged' => $page_nr ];

			$this->filters->add_search_filters();
			$the_query = new WP_Query( $args );
			$this->filters->remove_search_filters();

			if ( $the_query->have_posts() ) {
				while ( $the_query->have_posts() ) {
					$the_query->the_post();
					$this->show_list_item();
				}

				wp_reset_query();
			}

			if ( wpj_is_ajax_call() ) { wp_die(); }
		}

		public function show_list_fnc() {
			$the_query = $this->get_first_posts();

			if ( $the_query->have_posts() ) {

				$class = $this->load_type == 'slider' ? 'jobs-carousel js-jobs-carousel owl-carousel owl-theme' : 'row wpj-load-more-target' . ' ' . wpj_get_cards_layout_class() . ' ' . $this->container_class;
				$id    = $this->load_type != 'slider' ? 'job_listings' : '';

				if ( is_page( wpj_get_option( 'wpjobster_user_profile_page_id' ) ) ) $page_type = 'data-querytype="user_profile"';
				elseif ( is_front_page() ) $page_type = 'data-querytype="homepage"';
				else $page_type = ''; ?>

				<div id="<?php echo $id; ?>" class="<?php echo $class; ?>">

					<?php while ( $the_query->have_posts() ) {
						if ( $this->load_type == 'slider' ) { echo '<div class="item">'; }
							$the_query->the_post();
							$this->show_list_item();
						if ( $this->load_type == 'slider' ) { echo '</div>'; }
					}

					wp_reset_query(); ?>

				</div>

				<?php if ( $the_query->max_num_pages > 1 ) {

					if ( wpj_get_option( 'wpj_posts_load_type' ) == 'pagination' ) { ?>

						<div class="pagination-wrapper js-pagination-wrapper">

							<?php echo paginate_links( [
								'base'      => is_front_page() ? get_bloginfo( 'url' ) . '/' . get_post_field( 'post_name', get_post() ) . '%_%' : str_replace( 999999999, '%#%', esc_url( get_pagenum_link( 999999999 ) ) ),
								'prev_text' => __( 'Previous Page', 'wpjobster' ),
								'next_text' => __( 'Next Page', 'wpjobster' ),
								'format'    => '/page/%#%',
								'current'   => max( 1, get_query_var( 'paged' ) ),
								'total'     => $the_query->max_num_pages
							] ); ?>

						</div>

					<?php } else {

						$jobster_design = wpj_get_design_option(); ?>

						<div class="div-center">

							<div id="wpjobster-post-load-more-button"
								class="load-more-button text-button js-load-more-button wpj-load-more z-index-bigger<?php if ( wpj_get_option( 'wpjobster_enable_auto-load' ) == "yes" ) { echo ' auto-load'; } ?>" <?php echo $page_type; ?>
								data-clicks="<?php echo $the_query->found_posts > 0 && $this->posts_per_page > 0 ? ceil( ( intval( $the_query->found_posts ) / intval( $this->posts_per_page ) ) - 1 ) : 0; ?>"
								data-click-nr="1"
								data-action="show_list_ajax"
								data-max="<?php echo $the_query->max_num_pages; ?>"
								data-functionname="<?php echo $this->function_name; ?>"
								data-class-args='<?php echo json_encode( $this->arguments ); ?>'
								data-postsperpage="<?php echo $this->posts_per_page; ?>"
							>

								<?php if ( ! empty( $jobster_design['user_account_load_more_button_image']['url'] ) ) { ?>

									<img alt="" src="<?php echo $jobster_design['user_account_load_more_button_image']['url']; ?>" class="div-center" />

								<?php } else {

									_e( "Load more", "wpjobster" );

								} ?>

							</div>

						</div>

					<?php }

				}
			}
		}
	}
}

add_action( 'init', [ 'WPJ_Load_More_Posts', 'init' ] );