<?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' );

	$dir      = '/wp-content/uploads/html5fileupload';
	$dir_path = 'wp-content/uploads/html5fileupload';

	if ( ! is_dir( $path_to_wp . $dir ) ) {
		@mkdir( $path_to_wp . $dir, 0777 );
	}

	$error     = false;
	$dir       = $dir . "/";
	$serverdir = $path_to_wp . $dir;

	$tmp       = explode( ',', $_POST['file'] );
	$file      = base64_decode( $tmp[1] );

	$extension = @strtolower( @end( @explode( '.', $_POST['filename'] ) ) );
	$filename  = str_replace( [ " ", ",", "\"", "'" ], "-", $_POST['name'] ) . '.' . $extension;

	$handle    = fopen( $serverdir . $filename, 'w' );

	fwrite( $handle, $file );
	fclose( $handle );

	$response = [
		"result"               => true,
		"filepath"             => ABSPATH . $dir_path . "/" . $filename,
		"absolutedir_str_path" => $path_to_wp . $dir . $filename,
		"url"                  => site_url() . $dir . $filename,
		"filename"             => $filename
	];

	$pid = $_POST['data']['ID'];
	$uid = $_POST['data']['author'];

	$uploader_purpose = $_POST['data']['source'];

	$response['error'] = '';

	if ( $uploader_purpose == 'job' ) {
		$allowed_size_width  = wpj_get_option( 'wpjobster_min_img_upload_width' );
		$allowed_size_height = wpj_get_option( 'wpjobster_min_img_upload_height' );

		$attachments = wpj_get_job_images( $pid );

	} elseif ( $uploader_purpose == 'cover' ) {
		$allowed_size_width  = wpj_get_option( 'wpjobster_min_cover_img_upload_width' );
		$allowed_size_height = wpj_get_option( 'wpjobster_min_cover_img_upload_height' );

		$attachments = [];

	}

	if ( ! is_numeric( $allowed_size_width ) || empty( $allowed_size_width ) )
		$allowed_size_width = 720;

	if ( ! is_numeric( $allowed_size_height ) || empty( $allowed_size_height ) )
		$allowed_size_height = 405;

	if ( $uploader_purpose == 'job' && count( $attachments ) >= wpj_get_media_max_upload_number( $uploader_purpose ) ) {
		$response['error'] = sprintf( __( 'Only %s images are allowed.', 'wpjobster' ), wpj_get_media_max_upload_number( $uploader_purpose ) );
	}

	if ( $response['error'] == '' ) {

		// download file to temp dir
		$temp_file   = $response['filepath'];
		$image_attrs = getimagesize( $temp_file );

		$img_size_inbytes  = filesize( $temp_file );
		$response['debug'] = json_encode( $image_attrs );
		if ( $img_size_inbytes > wpj_get_media_max_upload_size( $uploader_purpose ) ) {
			$response['error'] = sprintf( __( 'Filesize is too big. Only %sMB is allowed.', 'wpjobster' ), wpj_get_media_max_upload_size( $uploader_purpose ) / 1048576 );
		}
		if ( $image_attrs['1'] < $allowed_size_height || $image_attrs['0'] < $allowed_size_width ) {
			$response['error'] = sprintf( __( 'Minimum file size: %1$s x %2$s px.', 'wpjobster' ), $allowed_size_width, $allowed_size_height );
		}

		if ( ! is_wp_error( $temp_file ) && $response['error'] == '' ) {

			// array based on $_FILE as seen in PHP file uploads
			$file = [
				'name'     => basename( $response['url'] ),
				'type'     => $image_attrs['mime'],
				'tmp_name' => $temp_file,
				'error'    => 0,
				'size'     => filesize( $temp_file ),
			];

			$overrides = [ 'test_form' => false ];
			define( 'ALLOW_UNFILTERED_UPLOADS', true );

			// move the temporary file into the uploads directory
			$results = wp_handle_sideload( $file, $overrides );

			if ( ! empty( $results['error'] ) ) {
				$response['error'] = $results['error'];
				exit;

			} else {
				$uploaded_file      = $results['file'];
				$uploaded_file_type = $results['type'];

			}

		}

		if ( $response['error'] == '' ) {
			$attachment = [
				'post_mime_type' => $uploaded_file_type,
				'post_title'     => apply_filters( 'wpj_uploaded_file_name_filter', 'File' ) . ' ' . addslashes( $temp_file ),
				'post_content'   => '',
				'post_status'    => 'inherit',
				'post_parent'    => $pid,
				'post_author'    => $uid,
			];

			$attach_id   = wp_insert_attachment( $attachment, $uploaded_file, $pid );
			$attach_data = wp_generate_attachment_metadata( $attach_id, $uploaded_file );

			wp_update_attachment_metadata( $attach_id, $attach_data );

			if ( $uploader_purpose == 'job' ) {
				update_post_meta( $attach_id, 'is_job', 1 );
			}

			if ( $uploader_purpose == 'cover' ) {
				update_post_meta( $attach_id, 'is_cover', 1 );
				update_post_meta( $pid, 'cover-image', $attach_id );
			}

			$response['attach_id'] = $attach_id;

			$attach_size    = $uploader_purpose == 'cover' ? [ 980, 180 ] : [ 90, 90 ];
			$response['go'] = wpj_get_attachment_image_url( $attach_id, $attach_size );

			do_action( 'wpj_after_file_complete_upload_action', $attach_data, $attach_id );

		}

	}

	echo json_encode( $response );

} else {

	$filename = basename( $_SERVER['QUERY_STRING'] );
	$file_url = dirname( __FILE__ ) . '/tmp/' . $filename;

	header( 'Content-Type:               application/octet-stream' );
	header( "Content-Transfer-Encoding:  Binary" );
	header( "Content-disposition:        attachment; filename=\"" . basename( $file_url ) . "\"" );

	readfile( $file_url );

	exit;

}