<?php if ( ! empty( $_POST ) ) {
	$absolute_path = __FILE__;
	$path_to_file  = explode( 'wp-content', $absolute_path );
	$path_to_wp    = $path_to_file[0];

	require_once ( $path_to_wp . '/wp-load.php' );
	require_once ( ABSPATH . 'wp-admin/includes/file.php' );
	require_once ( ABSPATH . 'wp-admin/includes/image.php' );
	require_once ( ABSPATH . 'wp-admin/includes/media.php' );

	if ( ! empty( $_FILES['Filedata'] ) ) {
		$pid              = WPJ_Form::post( 'pid' );
		$uid              = WPJ_Form::post( 'author', get_current_user_id() );
		$width            = WPJ_Form::post( 'width', 0 );
		$height           = WPJ_Form::post( 'height', 0 );
		$uploader_purpose = WPJ_Form::post( 'source' );
		$unique_name      = WPJ_Form::post( 'unique_name' );
		$secure           = WPJ_Form::post( 'secure' );

		function wpj_set_uploadifive_dir_path_upload( $dirs ) {
			$dirs['path'] = $dirs['basedir'] . '/secure' . $dirs['subdir'];
			$dirs['url']  = $dirs['baseurl'] . '/secure' . $dirs['subdir'];

			return $dirs;
		}

		if ( $secure ) {
			if ( false === get_transient( 'wpjobster_check_secure_folder' ) ) {
				// Make sure the 'secure' folder is created
				$upload_dir         = wp_upload_dir();
				$secure_upload_path = $upload_dir['basedir'] . '/secure';

				wp_mkdir_p( $secure_upload_path );

				// Allow images (they are needed for choosing review work sample)
				$allowed_filetypes = apply_filters( 'wpj_secure_directory_allowed_filetypes_filter', ['jpg', 'jpeg', 'png', 'gif', 'mp3', 'ogg'] );
				$rules = "Options -Indexes\n";
				$rules .= "deny from all\n";
				$rules .= "<FilesMatch '\.(" . implode( '|', $allowed_filetypes ) . ")$'>\n";
					$rules .= "Order Allow,Deny\n";
					$rules .= "Allow from all\n";
				$rules .= "</FilesMatch>\n";

				// Add rule to htaccess
				if ( file_exists( $secure_upload_path . '/.htaccess' ) ) {
					$contents = @file_get_contents( $secure_upload_path . '/.htaccess' );

					if ( $contents !== $rules || ! $contents ) {
						// Update the .htaccess rules if they don't match
						@file_put_contents( $secure_upload_path . '/.htaccess', $rules );
					}

				} elseif ( wp_is_writable( $secure_upload_path ) ) {
					// Create the file if it doesn't exist
					@file_put_contents( $secure_upload_path . '/.htaccess', $rules );

				}

				// Top level blank index.php
				if ( ! file_exists( $secure_upload_path . '/index.php' ) && wp_is_writable( $secure_upload_path ) ) {
					@file_put_contents( $secure_upload_path . '/index.php', '<?php' . PHP_EOL . '// Silence is golden.' );
				}

				// Now place index.php files in all sub folders
				$folders = wpj_scan_folders( $secure_upload_path );

				foreach ( $folders as $folder ) {
					// Create index.php, if it doesn't exist
					if ( ! file_exists( $folder . 'index.php' ) && wp_is_writable( $folder ) ) {
						@file_put_contents( $folder . 'index.php', '<?php' . PHP_EOL . '// Silence is golden.' );
					}
				}

				// Check for the files once per day
				set_transient( 'wpjobster_check_secure_folder', true, 3600 * 24 );
			}

			add_filter( 'upload_dir', 'wpj_set_uploadifive_dir_path_upload' );

			$uploaded_file = wp_handle_upload( $_FILES['Filedata'], [
				'test_form' => false,
			] );

			remove_filter( 'upload_dir', 'wpj_set_uploadifive_dir_path_upload' );

		} else {
			$uploaded_file = wp_handle_upload( $_FILES['Filedata'], [
				'test_form' => false
			] );

		}

		$arr_file_type = wp_check_filetype( basename( $_FILES['Filedata']['name'] ) );

		if ( $arr_file_type ) {
			if ( $uploader_purpose == 'avatar' || $uploader_purpose == 'banner' )
				$allowed_file_ext = [ "jpg", "jpeg", "png", "gif" ];

			elseif ( $uploader_purpose == 'audio' )
				$allowed_file_ext = [ "mp3", "wav" ];

			else
				$allowed_file_ext = explode( ',', wpj_get_option( 'wpjobster_allowed_mime_types' ) );

			// check extension
			if ( in_array( strtolower( $arr_file_type['ext'] ), $allowed_file_ext ) && ! empty( $uploaded_file['file'] ) ) {

				// check size
				$size = getimagesize( $uploaded_file['file'] );

				if ( ( isset( $size ) && is_array( $size ) && ( $size[0] >= apply_filters( 'wpj_min_' . $uploader_purpose . '_width_filter', 250 ) || $size[1] >= apply_filters( 'wpj_min_' . $uploader_purpose . '_height_filter', 250 ) ) ) || ( $uploader_purpose != 'avatar' && $uploader_purpose != 'banner' ) ) {

					$status = "ok";

					$attachment = [
						'post_mime_type' => $arr_file_type['type'],
						'post_title'     => apply_filters( 'wpj_uploaded_file_name_filter', 'File' ) . ' ' . addslashes( $_FILES['Filedata']['name'] ),
						'post_content'   => '',
						'post_status'    => 'inherit',
						'post_author'    => $uid,
					];

					if ( $pid ) $attachment['post_parent'] = $pid;

					$attach_id = wp_insert_attachment( $attachment, $uploaded_file['file'] );

					if ( $attach_id && ! empty( $uploaded_file['file'] ) ) {
						$attach_data = wp_generate_attachment_metadata( $attach_id, $uploaded_file['file'] );

						wp_update_attachment_metadata( $attach_id, $attach_data );
					}

					if ( $uploader_purpose == 'banner' || $uploader_purpose == 'avatar' || $uploader_purpose == 'audio' ) {
						update_user_meta( $uid, $uploader_purpose . '_id', $attach_id );
						update_user_meta( $uid, $uploader_purpose, wp_get_attachment_url( $attach_id ) );
						update_post_meta( $attach_id, 'is_' . $uploader_purpose, 1 );

					} else {
						$unique_name_meta = strpos( $unique_name, 'chat_messages' ) !== false ? 'private_messages' : $unique_name;

						update_post_meta( $attach_id, 'is_' . $unique_name_meta, 1 );

					}

					do_action( 'wpj_after_file_complete_upload_action', $attach_id, ( ! empty( $attach_data ) ? $attach_data : '' ) );

				} else $status = 'size';

			} else $status = 'extension';

		}

		echo wp_json_encode(
			[
				'status'      => $status,
				'id'          => ! empty( $attach_id ) ? $attach_id : '',
				'file_name'   => ! empty( $attach_id ) ? basename( get_attached_file( $attach_id ) ) : '',
				'file_url'    => ! empty( $attach_id ) ? wpj_get_attachment_image_url( $attach_id, [ $width, $height ] ) : ''
			]
		);

		if ( is_demo_user() ) { wp_delete_attachment( $attach_id ); }
	}
}