<?php if ( ! class_exists( 'WPJ_Load_More_Queries' ) ) {
	class WPJ_Load_More_Queries extends stdClass {
		public function __construct( $args = [] ) {
			$defaults = [
				'pid'               => '',
				'uid'               => '',
				'query_type'        => '',
				'query_status'      => '',
				'query_params'      => '',
				'function_name'     => '',
				'function_params'   => '',
				'posts_per_page'    => wpj_get_option( 'posts_per_page' ) ? wpj_get_option( 'posts_per_page' ) : 12,
				'row_extra_classes' => '',
				'load_type'         => 'button'
			];

			$args = wp_parse_args( $args, $defaults );

			$this->pid               = WPJ_Form::post( 'pid', $args['pid'] );
			$this->uid               = WPJ_Form::post( 'uid', $args['uid'] );
			$this->query_type        = WPJ_Form::post( 'query_type', $args['query_type'] );
			$this->query_status      = WPJ_Form::post( 'query_status', $args['query_status'] );
			$this->query_params      = WPJ_Form::post( 'query_params', $args['query_params'] );
			$this->function_name     = WPJ_Form::post( 'function_name', $args['function_name'] );
			$this->function_params   = WPJ_Form::post( 'function_params', $args['function_params'] );
			$this->posts_per_page    = WPJ_Form::post( 'posts_per_page', $args['posts_per_page'] );
			$this->row_extra_classes = WPJ_Form::post( 'row_extra_classes', $args['row_extra_classes'] );
			$this->load_type         = WPJ_Form::post( 'load_type', $args['load_type'] );

			if ( $this->load_type == 'slider' ) $this->posts_per_page = 36;

			$query_details = $this->get_query( [
				'pid'          => $this->pid,
				'uid'          => $this->uid,
				'query_type'   => $this->query_type,
				'query_status' => $this->query_status,
				'query_params' => $this->query_params
			], 'all' );

			$this->query = $query_details['query'];

			$this->r                = [];
			$this->all_r            = [];
			$this->total_results    = 0;
			$this->number_of_clicks = 0;

			$page_nr = get_query_var( 'paged' );

			if ( ! $page_nr ) $page_nr = 1;

			$this->page_nr = WPJ_Form::post( 'page_nr', $page_nr );

			if ( $this->query && $this->function_name ) {
				$this->limit = $this->posts_per_page * ( $this->page_nr - 1 );

				if ( $this->limit < 0 ) $this->limit = 0;

				if ( $this->query_type == 'messages' && $this->query_status == 'all' && $this->row_extra_classes != 'not-reverse-order' ) {
					$query = explode( 'DESC', $this->query );
					$this->query_limited = $query[0] . ' DESC LIMIT ' . $this->limit . ', ' . $this->posts_per_page . ' ' . $query[1];

				} else {
					$this->query_limited = $this->query . " LIMIT " . $this->limit . ", " . $this->posts_per_page;

				}

				global $wpdb;

				$this->r = $wpdb->get_results( $this->query_limited );

				if ( ! empty( $query_details['primary_key'] ) ) {
					$simplified_query = wpj_replace_string_between( $this->query, 'SELECT', 'FROM', $query_details['primary_key'] );

				} else {
					$simplified_query = $this->query;

				}

				$this->total_results = ( int ) $wpdb->get_var( "SELECT COUNT(*) FROM ({$simplified_query}) AS total_count" );

				$this->number_of_clicks = ceil( ( $this->total_results / $this->posts_per_page ) - 1 );
			}

			add_action( 'wp_ajax_nopriv_show_query_list_ajax', [ $this, 'show_list_ajax' ] );
			add_action( 'wp_ajax_show_query_list_ajax', [ $this, 'show_list_ajax' ] );
		}

		public static function init() {
			$class = __CLASS__;

			new $class( [] );
		}

		public function get_search_results_items() {
			global $wpdb;

			$this->all_r = $wpdb->get_results( $this->query );

			$user_account_items = [];

			if ( $this->all_r ) {
				foreach ( $this->all_r as $key => $row ) {
					if ( isset( $row->job_title ) ) {
						$title = $row->job_title;
						$url   = wpj_get_order_link( $row->id );

					} elseif ( isset( $row->reason ) && isset( $row->oid ) ) {
						$title = '#' . wpj_camouflage_oid( $row->id, $row->datemade ) . ' ' . strip_tags( $row->reason );
						$url   = wpj_get_order_link( $row->oid );

						if ( isset( $row->details ) ) {
							if ( is_numeric( $row->details ) )
								$url = wpj_get_order_link_by_payment_type( 'feature', $row->oid );
							elseif ( $row->details )
								$url = wpj_get_order_link_by_payment_type( 'subscription', $row->oid );
						}

					} elseif ( isset( $row->referral_id ) && isset( $row->reason ) ) {
						if ( isset( $row->total_amount ) ) {
							$title = wpj_get_user_name_by_id( $row->referral_id, 'username' );
							$url   = wpj_get_payment_link() . 'affiliate-reports/?user=' . $title . '#reports';

						} else {
							$rid            = get_user_by( 'id', $row->referral_id );
							$rid_user_login = isset( $rid->user_login ) ? $rid->user_login : '-';

							$title = preg_replace( [ '/Referral/' ], [ $rid_user_login, $rid_user_login ], $row->reason );
							$url   = '#';
						}

					} elseif ( isset( $row->package_id ) ) {
						$title = '#' . wpj_camouflage_oid( $row->id, $row->added_on );
						$url   = wpj_get_order_link_by_payment_type( 'topup', $row->id );

					} elseif ( isset( $row->code ) && isset( $row->name ) ) {
						$title = $row->name . ' ' . $row->code;
						$url   = add_query_arg( ['discount' => $row->code, 'action' => 'edit'], get_permalink( wpj_get_option( 'wpjobster_discounts_page_id' ) ) . 'new-coupon' );

					} else {
						$title = $row->id;
						$url   = wpj_get_order_link( $row->id );

					}

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

			return $user_account_items;
		}

		public function have_rows() {
			if ( $this->r )
				return true;
			else
				return false;
		}

		public function show_list_item( $row ) {
			$function_params = $this->function_params;

			if ( $function_params )
				array_unshift( $function_params, $row ); // add row to params
			else
				$function_params = [$row];

			call_user_func_array( $this->function_name, $function_params );
		}

		public function show_chat_list_item() { $prev_datemade = $initiator = $user = 0; ?>

			<div class="multiple-messages-wrapper">

				<?php foreach ( $this->r as $row ) {

					if ( ( $prev_datemade > 0 && $row->datemade - $prev_datemade >= 30 ) || ( $row->initiator != $initiator || $row->user != $user ) ) { /* 30 seconds */ ?>

						</div><div class="multiple-messages-wrapper">

					<?php }

					$this->show_list_item( $row );

					$prev_datemade = $row->datemade; $initiator = $row->initiator; $user = $row->user;

				} ?>

			</div>

		<?php }

		public function show_list_ajax() {
			if ( $this->r ) {
				if ( $this->function_name == 'wpj_display_chat_message_item' ) {
					$this->show_chat_list_item();

				} else {
					foreach ( $this->r as $row ) {
						$this->show_list_item( $row );
					}

				}
			}

			if ( wpj_is_ajax_call() ) wp_die();
		}

		public function show_list_fnc() {
			if ( $this->r ) {
				if ( $this->load_type == 'icon' && count( $this->r ) == $this->posts_per_page ) { ?>

					<div id="wpjobster-query-load-more-<?php echo $this->load_type; ?>"
						class="load-more-<?php echo $this->load_type; ?> wpj-load-more js-load-more-<?php echo $this->load_type; ?>"
						data-click-nr="1"
						data-clicks="<?php echo $this->number_of_clicks; ?>"
						data-action="show_query_list_ajax"
						data-max="<?php echo $this->posts_per_page; ?>"
						data-pid="<?php echo $this->pid; ?>"
						data-uid="<?php echo $this->uid; ?>"
						data-querytype="<?php echo $this->query_type; ?>"
						data-querystatus="<?php echo $this->query_status; ?>"
						data-queryparams='<?php echo $this->query_params ? json_encode( $this->query_params ) : ''; ?>'
						data-functionname="<?php echo $this->function_name; ?>"
						data-functionparams='<?php echo $this->function_params ? json_encode( $this->function_params ) : ''; ?>'
						data-postsperpage="<?php echo $this->posts_per_page; ?>"
						data-rowextraclasses="<?php echo $this->row_extra_classes; ?>"
						data-loadtype="<?php echo $this->load_type; ?>"
					></div>

				<?php } ?>

				<div class="<?php echo $this->load_type == 'slider' ? 'jobs-carousel js-jobs-carousel owl-carousel owl-theme' : 'row special wpj-load-more-target cf ' . wpj_get_cards_layout_class() . ' ' . $this->row_extra_classes; ?>">

					<?php if ( $this->function_name == 'wpj_display_chat_message_item' ) {
						$this->show_chat_list_item();

					} else {
						foreach ( $this->r as $row ) {
							if ( $this->load_type == 'slider' ) { echo '<div class="item">'; }

								$this->show_list_item( $row );

							if ( $this->load_type == 'slider' ) { echo '</div>'; }
						}

					} ?>

				</div>

				<?php if ( ( $this->load_type == 'button' || $this->load_type == 'icon-down' ) && $this->total_results > $this->posts_per_page ) {
					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'   => $this->page_nr,
								'total'     => ceil( $this->total_results / $this->posts_per_page )
							] ); ?>

						</div>

					<?php } else { ?>

						<div class="div-center">
							<div id="wpjobster-query-load-more-<?php echo $this->load_type; ?>"
								class="load-more-<?php echo $this->load_type; ?> wpj-load-more js-load-more-<?php echo $this->load_type; ?> <?php if ( $this->load_type == 'button' ) echo 'text-button'; ?> <?php if ( wpj_get_option( 'wpjobster_enable_auto-load' ) == "yes" ) { echo 'auto-load'; } ?>"
								data-click-nr="1"
								data-clicks="<?php echo $this->number_of_clicks; ?>"
								data-action="show_query_list_ajax"
								data-max="<?php echo $this->posts_per_page; ?>"
								data-pid="<?php echo $this->pid; ?>"
								data-uid="<?php echo $this->uid; ?>"
								data-querytype="<?php echo $this->query_type; ?>"
								data-querystatus="<?php echo $this->query_status; ?>"
								data-queryparams='<?php echo $this->query_params ? json_encode( $this->query_params ) : ''; ?>'
								data-functionname="<?php echo $this->function_name; ?>"
								data-functionparams='<?php echo $this->function_params ? json_encode( $this->function_params ) : ''; ?>'
								data-postsperpage="<?php echo $this->posts_per_page; ?>"
								data-rowextraclasses="<?php echo $this->row_extra_classes; ?>"
								data-loadtype="<?php echo $this->load_type; ?>"
							>

								<?php if ( $this->load_type == 'button' ) {
									$jobster_design = wpj_get_design_option();

									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 }
				}
			}
		}

		public static function get_query( $args, $return_type = 'query' ) {
			$defaults = [
				'uid'          => false,
				'pid'          => false,
				'query_type'   => false,
				'query_status' => false,
				'query_params' => false
			];

			$args = wp_parse_args( $args, $defaults );

			$uid          = $args['uid'];
			$pid          = $args['pid'];
			$query_type   = $args['query_type'];
			$query_status = $args['query_status'];
			$query_params = $args['query_params'];

			if ( ! $pid ) $pid = get_the_ID();

			if ( ! $uid ) $uid = wpj_get_user_id();

			$query       = false;
			$primary_key = false;

			if ( $query_type == 'jobs' && $query_status == 'all' ) {
				$query = wpj_get_job_search_query( $args );

			} elseif ( $query_type == 'users' && $query_status == 'all' ) {
				$query       = wpj_get_user_search_query( $args );
				$primary_key = '';

			} elseif ( $query_type == 'conversations' && $query_status == 'all' ) {
				$query = wpj_get_conversations_by_type( 'all', 'query' );

			} elseif ( $query_type == 'messages' ) {
				if ( $query_status == 'all' ) {
					if ( $query_params ) {
						$query       = wpj_get_private_messages_by_users( $uid, get_current_user_id(), 'query', false, $query_params );
						$primary_key = 'id, datemade';

					} else {
						$query       = wpj_get_private_messages_by_users( $uid, get_current_user_id(), 'query' );
						$primary_key = 'id, datemade';

					}

				} elseif ( is_numeric( $query_status ) ) {
					$query       = wpj_get_pm_notify( 'DISTINCT *', ['id' => $query_status], 'query' );
					$primary_key = 'id';

				} elseif ( $query_status == 'custom_offer' ) {
					$query       = wpj_get_user_offers_received( $pid, get_current_user_id(), 'query' );
					$primary_key = 'datemade';
				}

			} elseif ( $query_type == 'notifications' && $query_status == 'all' ) {
				$query       = wpj_get_notifications( [ 'limit' => 0, 'uid' => $uid ], 'query' );
				$primary_key = 'chatbox.datemade tm';

			}

			if ( $query_type == 'transactions' && $query_status == 'all' ) {
				$query       = wpj_get_payment_transaction( '*', ['uid' => $uid], 'query', [], 'id DESC', 'datemade, rid' );
				$primary_key = 'id';

			} elseif ( $query_type == 'payments' ) {
				if ( $query_status == 'pending' ) {
					$query       = wpj_get_job_order_post( 'DISTINCT *', ['p.post_author' => $uid, 'p.ID' => 'o.pid', 'o.clearing_period' => 2, 'o.closed' => 0], 'query', [], 'o.id DESC' );
					$primary_key = 'o.id';
				}

			} elseif ( $query_type == 'withdrawals' ) {
				if ( $query_status == 'pending' ) {
					$query       = wpj_get_withdrawal_order( 'DISTINCT *', ['uid'  => $uid, 'done' => 0], 'query', [], 'id DESC' );
					$primary_key = 'id';
				}

			} elseif ( $query_type == 'reviews' ) {
				if ( $query_status == 'to_award' || $query_status == 'to_receive' || $query_status == 'received' ) {
					$query       = wpj_get_order_reviews( $query_status, $uid, 'query' );
					$primary_key = $query_status == 'received' ? '' : 'ratings.id';

				} elseif ( $query_status == 'job_reviews' ) {
					$query = wpj_get_custom_offer_rating( [
						'fields' => 'ratings.*',
						'table' => 'job_ratings',
						'pid' => $pid,
						'extra_conditions' => [
							['posts.post_author', '=', $uid]
						],
						'return' => 'query'
					] );

					$primary_key = '';

				} elseif ( $query_status == 'user_reviews' ) {
					$ratings_table = apply_filters( 'wpj_seller_reviews_database_table_filter', 'job_ratings', $uid );

					if ( $ratings_table == 'job_ratings' )
						$author_column = 'posts.post_author';

					else
						$author_column = 'ratings.uid';

					$query = wpj_get_order_rating(
						'ratings.*',
						[$ratings_table . ' ratings', 'job_orders orders', 'posts posts'],
						['ratings.awarded' => 1, $author_column => $uid],
						'query',
						'',
						'ratings.datemade DESC'
					);

					$primary_key = 'ratings.id';
				}

			} elseif ( $query_type == 'sales' ) {
				if ( $query_status == 'active' ) {
					$query       = wpj_get_sales_orders( $uid, 'active', 'query' );
					$primary_key = 'orders.id';

				} elseif ( $query_status == 'pending-confirmation' ) {
					$query       = wpj_get_sales_orders( $uid, 'pending-confirmation', 'query' );
					$primary_key = 'orders.id';

				} elseif ( $query_status == 'pending-payment' ) {
					$query       = wpj_get_sales_orders( $uid, 'pending-payment', 'query' );
					$primary_key = 'orders.id';

				} elseif ( $query_status == 'delivered' ) {
					$query       = wpj_get_sales_orders( $uid, 'delivered', 'query' );
					$primary_key = 'orders.id';

				} elseif ( $query_status == 'cancelled' ) {
					$query       = wpj_get_sales_orders( $uid, 'cancelled', 'query' );
					$primary_key = 'orders.id';

				} elseif ( $query_status == 'completed' ) {
					$query       = wpj_get_sales_orders( $uid, 'completed', 'query' );
					$primary_key = 'orders.id';
				}

			} elseif ( $query_type == 'shopping' ) {
				if ( $query_status == 'active' ) {
					$query       = wpj_get_shopping_orders( $uid, 'active', 'query' );
					$primary_key = 'id';

				} elseif ( $query_status == 'pending-confirmation' ) {
					$query       = wpj_get_shopping_orders( $uid, 'pending-confirmation', 'query' );
					$primary_key = 'orders.id';

				} elseif ( $query_status == 'pending-payment' ) {
					$query       = wpj_get_shopping_orders( $uid, 'pending-payment', 'query' );
					$primary_key = 'id';

				} elseif ( $query_status == 'pending-review' ) {
					$query       = wpj_get_shopping_orders( $uid, 'pending-review', 'query' );
					$primary_key = 'id';

				} elseif ( $query_status == 'cancelled' ) {
					$query       = wpj_get_shopping_orders( $uid, 'cancelled', 'query' );
					$primary_key = 'id';

				} elseif ( $query_status == 'completed' ) {
					$query       = wpj_get_shopping_orders( $uid, 'completed', 'query' );
					$primary_key = 'id';
				}

			} elseif ( $query_type == 'topup' ) {
				if ( $query_status == 'pending' ) {
					$query       = wpj_get_topup_order( 'DISTINCT *', ['user_id' => $uid, 'payment_status' => 'pending'], 'query' );
					$primary_key = 'id';

				} elseif ( $query_status == 'completed' ) {
					$query       = wpj_get_topup_order( 'DISTINCT *', ['user_id' => $uid, 'payment_status' => 'completed'], 'query' );
					$primary_key = 'id';

				}

			}

			$query       = apply_filters( 'wpj_sql_user_account_query_filter', $query, $query_type, $query_status, $uid );
			$primary_key = apply_filters( 'wpj_sql_user_account_primary_key_filter', $primary_key, $query, $query_type, $query_status, $uid );

			if ( $return_type == 'all' ) {
				return [
					'query'       => $query,
					'primary_key' => $primary_key
				];

			} elseif ( $return_type == 'primary_key' ) {
				return $primary_key;

			} else {
				return $query;

			}
		}

	}

}

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