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

	class WPJRequestsNewEdit extends stdClass
	{

		private WPJ_Custom_Fields $custom_field;

		public function __construct() {
			add_action( 'wp_ajax_save_request_post_action', [ $this, 'savePostData' ] );
			add_action( 'wp_ajax_nopriv_save_request_post_action', [ $this, 'savePostData' ] );

			$this->custom_field = new WPJ_Custom_Fields( WPJ_Form::get( 'requestid' ), 'request' );
		}

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

		public function getFieldsContent( $fields = '', $pid = '', $page_content = '' ) {
			if ( ! $pid ) {
				$pid = wpj_get_post_id( $pid );
			}

			if ( $fields['acf_fc_layout'] == 'request_field_separator' ) { // Separator
				$id            = 'field_separator';
				$class         = 'field_separator';
				$label         = 'no';
				$popup         = 'no';
				$field         = 'yes';
				$page_content .= $this->getContentFromBuffer( 'separator', ['label' => $fields['label']] );

			} elseif ( strpos( $fields['acf_fc_layout'], 'custom_field' ) !== false ) { // Custom Fields
				$class         = 'cf';
				$rcf           = $this->custom_field->getFieldsContent( $fields );
				$popup         = $rcf['popup'];
				$label         = $rcf['label'];
				$page_content .= $rcf['content'];

			} else { // Request Fields
				$page_content .= $this->getContentFromBuffer( str_replace( 'request_', '', $fields['acf_fc_layout'] ),
					['placeholder' => isset( $fields['placeholder'] ) ? $fields['placeholder'] : '']
				);

			}

			// Hidden Fields
			if ( ! in_array( $fields['acf_fc_layout'],
				[
					'request_field_separator',
					'request_title',
					'request_description',
					'request_category',
					'request_subcategory',
					'request_tags',
					'request_autoclose'
				]
			) ) {
				$parent_class = $class = 'hidden';
			}

			$return_arr = [
				'id'           => $id ?? '',
				'class'        => $class ?? '',
				'parent_class' => $parent_class ?? '',
				'label'        => $label ?? '',
				'popup'        => $popup ?? '',
				'field'        => $field ?? '',
				'instr'        => $fields['instructions'] ?? '',
				'f_rej_name'   => str_replace( 'request_', '', $fields['acf_fc_layout'] ),
				'content'      => $page_content
			];

			return apply_filters( 'wpj_post_new_request_fields_content_filter', $return_arr, $pid, $fields );
		}

		public function validatePostData() {
			$required_fields = apply_filters( 'wpj_request_required_fields_filter', [
				'request_title',
				'request_description',
				'request_category'
			] );

			if ( $required_fields ) {
				$requirements_met = true;

				foreach ( $required_fields as $key => $field ) {
					if (
						( empty( $_POST[$field] ) && strlen( $_POST[$field] ) == 0 )
						|| ( is_array( $_POST[$field] ) && ! wpj_multidimensional_array_has_all_values( $_POST[$field] ) )
					) {
						$requirements_met = false; continue;
					}
				}
			}

			if ( ( $required_fields && $requirements_met ) || ! $required_fields ) {
				return true;
			}

			return false;
		}

		public function savePostData( $pid = '', $action_type = '', $status = '' ) {

			if ( isset( $_POST['aoer_form_submitted'] ) && ! is_demo_user() ) {

				$uid = get_current_user_id();

				$pid  = WPJ_Form::post( 'requestid', $pid );
				$post = get_post( $pid );

				$action_type = WPJ_Form::post( 'action_type', $action_type );

				if ( ! $action_type ) $action_type = 'new-request';

				$status = WPJ_Form::post( 'status', $status );

				if ( isset( $post->post_author ) && $uid == $post->post_author ) {

					if ( isset( $_POST['post_new_or_edit_request_field'] ) && wp_verify_nonce( $_POST['post_new_or_edit_request_field'], 'post_new_or_edit_request_action' ) ) {

						if ( $action_type == 'new-request' || ( $action_type == 'edit-request' && $status == 'publish' ) ) {

							// Vars
							$request_title       = WPJ_Form::post( 'request_title', mb_substr( trim( WPJ_Form::post( 'request_description' ) ), 0, 65 ) . '...' );
							$request_description = WPJ_Form::post( 'request_description' );
							$request_tag         = WPJ_Form::post( 'request_tags' );
							$request_category    = WPJ_Form::post( 'request_category' );
							$request_subcategory = WPJ_Form::post( 'subcat' );
							$request_attachment  = WPJ_Form::post( 'request_attachments' );

							// Tags
							wp_set_post_tags( $pid, trim( strip_tags( htmlspecialchars( $request_tag ) ) ) );

							// Categories
							wp_set_post_terms( $pid, $this->getCategoriesToBeSaved( $request_category, $request_subcategory ), 'request_cat' );

							// Attachments
							if ( $request_attachment != '' ) {
								if ( $action_type == 'edit-request' )
									wpj_save_attachments( $request_attachment, $pid, 'request_attachments', 'edit' );

								else
									wpj_save_attachments( $request_attachment, $pid, 'request_attachments', 'new' );
							}

							// Autoclose
							update_post_meta( $pid, 'request_autoclose', WPJ_Form::post( 'request_autoclose' ) );

							// Let's meet
							update_post_meta( $pid, 'request_lets_meet', WPJ_Form::post( 'request_lets_meet' ) );

							// Custom fields
							$this->custom_field->saveFieldsContent();

							// Other fields
							$skiped_fields = [
								'request_title',
								'request_description',
								'request_tags',
								'request_category',
								'subcat',
								'request_attachments',
								'request_autoclose',
								'request_lets_meet'
							];

							if ( $_POST ) {
								foreach ( $_POST AS $key => $val ) {
									if ( ! in_array( $key, $skiped_fields ) ) {
										if ( is_string( $val ) ) update_post_meta( $pid, $key, trim( htmlspecialchars( wpj_validate_input_content( $val ) ) ) );
										elseif ( is_array( $val ) ) update_post_meta( $pid, $key, array_values( array_filter( $val ) ) );
										else update_post_meta( $pid, $key, $val );
									}
								}
							}

							do_action( 'wpj_before_create_or_update_request_post', $uid, $pid );

							// Create the post
							$request_post                 = [];
							$request_post['ID']           = $pid;
							$request_post['post_title']   = $request_title;
							$request_post['post_content'] = $request_description;

							wp_update_post( $request_post );

							if ( $status == 'publish' && $this->validatePostData() ) {
								$redirect = wpj_get_option( 'wpjobster_post_new_request_redirection_page' );
								$url      = $redirect > 1 ? get_permalink( $redirect ) : get_permalink( wpj_get_option( 'wpjobster_my_requests_page_id' ) );

								wp_publish_post( $pid );

								$admin_approve_request = wpj_get_option( 'wpjobster_admin_approve_request' );

								if ( $admin_approve_request == 'yes' ) {

									update_post_meta( $pid, 'under_review', '1' );

									$request_post['post_status'] = 'draft';

									wp_update_post( $request_post );

									$url .= 'in-review';
									$url = add_query_arg( 'submitted', $pid, $url );

								} else {

									update_post_meta( $pid, 'under_review', '0' );
									update_post_meta( $pid, 'active', '1' );

									$post = get_post( $pid );

									if ( isset( $post->post_title ) && $post->post_title != 'Auto Draft'
										&& isset( $post->post_content ) && $post->post_content != 'Auto Draft' ) {
										$request_post['post_status'] = 'publish';

										do_action( 'wpj_after_request_published', $uid, $pid );

									} else {
										$request_post['post_status'] = 'draft';

									}

									wp_update_post( $request_post );

									$url = add_query_arg( 'submitted', $pid, $url );

								}

								// Send e-mails
								if ( $admin_approve_request == 'yes' ) {
									wpj_notify_user_translated( 'request_admin_new', 'admin', [
										'##username##'     => wpj_get_user_display_type( get_post_field( 'post_author', $pid ) ),
										'##request_name##' => $request_title,
										'##request_link##' => admin_url( 'post.php?post=' . $pid . '&action=edit' )
									] );

									wpj_notify_user_translated( 'request_new', get_post_field( 'post_author', $pid ), [ '##request_name##' => $request_title ] );

								} else {
									wpj_notify_user_translated( 'request_admin_acc', 'admin', [
										'##username##'     => wpj_get_user_display_type( get_post_field( 'post_author', $pid ) ),
										'##request_name##' => $request_title,
										'##request_link##' => admin_url( 'post.php?post=' . $pid . '&action=edit' )
									] );

									if ( ! is_admin() ) {
										wpj_notify_user_translated( 'request_acc', get_post_field( 'post_author', $pid ), [
											'##username##'     => wpj_get_user_display_type( get_post_field( 'post_author', $pid ) ),
											'##request_name##' => $request_title,
											'##request_link##' => get_post_permalink( $pid )
										] );
									}

								}

								echo $url = apply_filters( 'wpj_post_new_request_redirect_url_filter', $url, $pid );

							} else _e( 'Complete all required fields.', 'wpjobster' );

						} else _e( 'No action type defined.', 'wpjobster' );

					} else _e( 'Sorry, your nonce did not verify.', 'wpjobster' );

				} else _e( 'You are not allowed to edit this request because you are not the author.', 'wpjobster' );

			} else _e( 'Something went wrong. Please try again', 'wpjobster' );

			if ( wpj_is_ajax_call() ) wp_die();
		}

		public function getContentFromBuffer( $method_name = '', $params = [] ) {
			ob_start();

			$field_content_class = new WPJRequestsNewEditFieldsContent();

			if ( $params )
				call_user_func_array( [ $field_content_class, $method_name ], $params );
			else
				call_user_func( [ $field_content_class, $method_name ] );

			return ob_get_clean();
		}

		public function getPostCategories() {
			$category_value    = [];
			$subcategory_value = [];

			$meta_category = wp_get_post_terms( WPJ_Form::get( 'requestid' ), 'request_cat' );

			if ( is_array( $meta_category ) ) {
				if ( $meta_category ) {
					foreach ( $meta_category as $key => $value ) {
						if ( $value->parent == 0 ) {
							$category_value[] = str_replace( '-req', '', $value->slug );

						} else {
							$subcategory_value[] = str_replace( '-req', '', $value->slug );

							$term_details = get_term_by( 'id', $value->parent, 'request_cat' );
							$current_term = str_replace( '-req', '', $term_details->slug );

							if ( ! in_array( $current_term, $category_value ) ) {
								$category_value[] = $current_term;
							}
						}
					}

					$category_value = array_unique( $category_value );
				}

			} elseif ( $meta_category ) {
				if ( $meta_category[0]->parent == 0 ) {
					$category_value = str_replace( '-req', '', $meta_category[0]->slug );

				} else {
					$subcategory_value = str_replace( '-req', '', $meta_category[0]->slug );
					$subcategory_value = strtolower( $subcategory_value );

					$term_details   = get_term_by( 'id', $meta_category[0]->parent, 'request_cat' );
					$category_value = str_replace( '-req', '', $term_details->slug );

				}

				$category_value = strtolower( $category_value );

			}

			if ( ! empty( $_GET['category'] ) ) {
				$url_category = $_GET['category'];

				$term = get_term_by( 'slug', $url_category, 'request_cat' );

				if ( $term && $term->parent != '0' ) {
					$term_parent = get_term_by( 'term_id', $term->parent, 'request_cat' );

					$category_value    = str_replace( '-req', '', $term_parent->slug );
					$subcategory_value = str_replace( '-req', '', $term->slug );
				
				} elseif ( $term ) {
					$category_value = str_replace( '-req', '', $term->slug );

				}
			}

			$post_category_value    = apply_filters( 'wpj_post_request_category_filter', WPJ_Form::post( 'request_category', $category_value ) );
			$post_subcategory_value = apply_filters( 'wpj_post_request_subcategory_filter', WPJ_Form::post( 'subcat', $subcategory_value ) );

			return [
				'category'    => $post_category_value,
				'subcategory' => $post_subcategory_value
			];
		}

		public function getCategoriesToBeSaved( $request_category = '', $request_subcategory = '' ) {
			if ( ! is_array( $request_category ) ) {
				$request_category = [ $request_category ];
			}

			if ( ! is_array( $request_subcategory ) ) {
				$request_subcategory = [ $request_subcategory ];
			}

			$post_categories = array_merge( $request_category, $request_subcategory );

			$request_category_arr = [];

			if ( $post_categories ) {
				foreach ( $post_categories as $key => $request_category_value ) {
					$job_term = get_term_by( 'slug', $request_category_value , 'job_cat' );

					if ( $job_term ) {
						$request_term = get_term_by( 'slug', $request_category_value . '-req' , 'request_cat' );

						if ( $request_term ) {
							$request_category_arr[] = $request_term->term_id;

						} else {
							if ( $job_term->parent ) {
								$job_category     = get_term_by( 'id', $job_term->parent, 'job_cat' );
								$request_category = get_term_by( 'slug', $job_category->slug . '-req', 'request_cat' );

							} else {
								$job_category     = '';
								$request_category = get_term_by( 'slug', $request_category_value . '-req', 'request_cat' );
								$include_category = true;

							}

							if ( ! $request_category ) {
								if ( $job_category ) {
									$new_category = array (
										'cat_name'             => $job_category->name,
										'category_description' => '',
										'category_nicename'    => $job_category->slug . '-req',
										'category-slug'        => $job_category->slug . '-req',
										'taxonomy'             => 'request_cat'
									);

								} else {
									$new_category = [
										'cat_name'             => $job_term->name,
										'category_description' => '',
										'category_nicename'    => $job_term->slug . '-req',
										'category-slug'        => $job_term->slug . '-req',
										'taxonomy'             => 'request_cat'
									];

								}

								require_once( ABSPATH . 'wp-load.php' );
								require_once( ABSPATH . 'wp-admin/includes/taxonomy.php' );

								$request_category_id = wp_insert_category( $new_category );

							} else {
								$request_category_id = $request_category->term_id;

							}

							if ( isset( $include_category ) ) {
								$request_category_arr[] = $request_category_id;
							}

							if ( $job_term->parent ) {
								$new_subcategory = [
									'cat_name'             => $job_term->name,
									'category_description' => '',
									'category_nicename'    => $job_term->slug . '-req',
									'category-slug'        => $job_term->slug . '-req',
									'category_parent'      => $request_category_id,
									'taxonomy'             => 'request_cat'
								];

								require_once( ABSPATH . 'wp-load.php' );
								require_once( ABSPATH . 'wp-admin/includes/taxonomy.php' );

								$request_subcategory_id = wp_insert_category( $new_subcategory );
								$request_category_arr[] = $request_subcategory_id;
							}
						}
					}
				}
			}

			return $request_category_arr;
		}

		public static function saveAnonymousDraft() {
			if ( isset( $_COOKIE['wpj_request_id'] ) && is_user_logged_in() ) {
				$pid = $_COOKIE['wpj_request_id'];
				$uid = get_current_user_id();

				$request_post                 = [];
				$request_post['ID']           = $pid;
				$request_post['post_author']  = $uid;

				wp_update_post( $request_post );
				wp_publish_post( $pid );

				$admin_approve_request = wpj_get_option( 'wpjobster_admin_approve_request' );

				if ( $admin_approve_request == 'yes' ) {
					update_post_meta( $pid, 'under_review', '1' );

					$request_post['post_status'] = 'draft';
					wp_update_post( $request_post );

					$tab = 'in-review';

				} else {
					update_post_meta( $pid, 'under_review', '0' );
					update_post_meta( $pid, 'active', '1' );

					$post = get_post( $pid );

					if (
						isset( $post->post_title ) && $post->post_title != 'Auto Draft'
						&& isset( $post->post_content ) && $post->post_content != 'Auto Draft'
					) {
						$request_post['post_status'] = 'publish';

						$tab = 'active';

						do_action( 'wpj_after_request_published', $uid, $pid );

					} else {
						$request_post['post_status'] = 'draft';

						$tab = 'in-review';

					}

					wp_update_post( $request_post );

				}

				// Send e-mails
				if (
					isset( $post->post_title ) && $post->post_title != 'Auto Draft'
					&& isset( $post->post_content ) && $post->post_content != 'Auto Draft'
				) {
					if ( $admin_approve_request == 'yes' ) {
						wpj_notify_user_translated( 'request_admin_new', 'admin', [
							'##username##'     => wpj_get_user_display_type( $uid ), '##request_name##' => get_the_title( $pid ),
							'##request_link##' => admin_url( 'post.php?post=' . $pid . '&action=edit' )
						] );

						wpj_notify_user_translated( 'request_new', $uid, [ '##request_name##' => get_the_title( $pid ) ] );

					} else {
						wpj_notify_user_translated( 'request_admin_acc', 'admin', [
							'##username##'     => wpj_get_user_display_type( $uid ),
							'##request_name##' => get_the_title( $pid ),
							'##request_link##' => admin_url( 'post.php?post=' . $pid . '&action=edit' )
						] );

						if ( ! is_admin() ) {
							wpj_notify_user_translated( 'request_acc', get_post_field( 'post_author', $pid ), [
								'##username##'     => wpj_get_user_display_type( $uid ),
								'##request_name##' => get_the_title( $pid ),
								'##request_link##' => get_post_permalink( $pid )
							] );
						}
					}

				}

				setcookie( 'wpj_request_id', '', time() - 3600, '/' );

				$redirect = wpj_get_option( 'wpjobster_post_new_request_redirection_page' );
				$url      = $redirect > 1 ? get_permalink( $redirect ) : get_permalink( wpj_get_option( 'wpjobster_my_requests_page_id' ) );

				wp_redirect( add_query_arg( 'submitted', $pid, $url . $tab ) );
				exit;
			}
		}
	}
}

add_action( 'admin_init', ['WPJRequestsNewEdit', 'init'] );
add_action( 'init', ['WPJRequestsNewEdit', 'saveAnonymousDraft'] );