<?php if ( ! empty( $_FILES ) ) {

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

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

	$uploader_purpose = WPJ_Form::post( 'uploader_purpose' );

	$attach_id = 0;
	$error     = false;

	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 == 'portfolio' ) {
		$allowed_size_width  = wpj_get_option( 'wpjobster_profile_min_img_upload_width' );
		$allowed_size_height = wpj_get_option( 'wpjobster_profile_min_img_upload_height' );

		$attachments = wpj_get_portfolio_images( $pid );

	} elseif ( $uploader_purpose == 'message' ) {
		$allowed_size_width  = '';
		$allowed_size_height = '';

		$attachments = [];

	} 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 ) || ! $allowed_size_width )
		$allowed_size_width = 720;

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

	try {
		if ( ( $uploader_purpose == 'job' || $uploader_purpose == 'cover' ) && $post->post_author != get_current_user_id() && ! current_user_can( 'manage_options' ) )
			throw new RuntimeException( __( 'You can upload pictures only to your own job.', 'wpjobster' ) );

		if ( $uploader_purpose == 'portfolio' && $pid != get_current_user_id() && ! current_user_can( 'manage_options' ) )
			throw new RuntimeException( __( 'You can upload pictures only to your portfolio.', 'wpjobster' ) );

		if ( ( $uploader_purpose == 'job' || $uploader_purpose == 'portfolio' || $uploader_purpose == 'message' ) && count( $attachments ) >= wpj_get_media_max_upload_number( $uploader_purpose ) )
			throw new RuntimeException( sprintf( __( 'Only %s images are allowed.', 'wpjobster' ), wpj_get_media_max_upload_number( $uploader_purpose ) ) );

		if ( ! isset( $_FILES['file']['error'] ) || is_array( $_FILES['file']['error'] ) )
			throw new RuntimeException( __( 'Invalid parameters.', 'wpjobster' ) );

		switch ( $_FILES['file']['error'] ) {
			case UPLOAD_ERR_OK:
				break;
			case UPLOAD_ERR_NO_FILE:
				throw new RuntimeException( __( 'No file sent.', 'wpjobster' ) );
			case UPLOAD_ERR_INI_SIZE:
			case UPLOAD_ERR_FORM_SIZE:
				throw new RuntimeException( sprintf( __( 'Filesize is too big. Only %sMB is allowed.', 'wpjobster' ), wpj_get_media_max_upload_size( $uploader_purpose ) / 1048576 ) );
			default:
				throw new RuntimeException( __( 'Unknown errors.', 'wpjobster' ) );
		}

		if ( $_FILES['file']['size'] > wpj_get_media_max_upload_size( $uploader_purpose ) )
			throw new RuntimeException( sprintf( __( 'Filesize is too big. Only %sMB is allowed.', 'wpjobster' ), wpj_get_media_max_upload_size( $uploader_purpose ) / 1048576 ) );

		if ( class_exists( 'finfo' ) ) {
			$finfo = new finfo( FILEINFO_MIME_TYPE );

			if ( false === $ext = array_search(
				$finfo->file( $_FILES['file']['tmp_name'] ),
				[
					'jpg'   => 'image/jpeg',
					'png'   => 'image/png',
					'gif'   => 'image/gif',
					'3g2'   => 'video/3gpp2',
					'3gp'   => 'video/3gpp',
					'asf'   => 'video/x-ms-asf',
					'avi'   => 'video/x-msvideo',
					'f4v'   => 'video/x-f4v',
					'fli'   => 'video/x-fli',
					'flv'   => 'video/x-flv',
					'fvt'   => 'video/vnd.fvt',
					'h261'  => 'video/h261',
					'h263'  => 'video/h263',
					'h264'  => 'video/h264',
					'jpgv'  => 'video/jpeg',
					'jpm'   => 'video/jpm',
					'm4v'   => 'video/x-m4v',
					'mj2'   => 'video/mj2',
					'mov'   => 'video/quicktime',
					'movie' => 'video/x-sgi-movie',
					'mpg'   => 'video/mpeg',
					'mp4'   => 'video/mp4',
					'mp4a'  => 'audio/mp4',
					'mpeg'  => 'video/mpeg',
					'mxu'   => 'video/vnd.mpegurl',
					'ogv'   => 'video/ogg',
					'pyv'   => 'video/vnd.ms-playready.media.pyv',
					'qt'    => 'video/quicktime',
					'uvh'   => 'video/vnd.dece.hd',
					'uvm'   => 'video/vnd.dece.mobile',
					'uvp'   => 'video/vnd.dece.pd',
					'uvs'   => 'video/vnd.dece.sd',
					'uvu'   => 'video/vnd.uvvu.mp4',
					'uvv'   => 'video/vnd.dece.video',
					'viv'   => 'video/vnd.vivo',
					'webm'  => 'video/webm',
					'wm'    => 'video/x-ms-wm',
					'wmv'   => 'video/x-ms-wmv',
					'wmx'   => 'video/x-ms-wmx',
					'wvx'   => 'video/x-ms-wvx'
				],
				true
			) ) {
				throw new RuntimeException( __( 'Invalid file format.', 'wpjobster' ) );
			}
		}

		if ( isset( $_FILES['file']['tmp_name'] ) && strpos( $finfo->file( $_FILES['file']['tmp_name'] ), 'video' ) === false ) {
			$tmp_name = $_FILES['file']['tmp_name'];
			list( $file_width, $file_height ) = getimagesize( $tmp_name );

		} else {
			$file_width  = 0;
			$file_height = 0;

		}

		if (
			$uploader_purpose != 'message'
			&& $file_width != 0
			&& $file_height != 0
			&& (
				$file_width < $allowed_size_width
				|| $file_height < $allowed_size_height
			)
		) {
			throw new RuntimeException( sprintf( __( 'Minimum file size: %1$s x %2$s px.', 'wpjobster' ), $allowed_size_width, $allowed_size_height ) );
		}

	} catch ( RuntimeException $e ) {
		$error = $e->getMessage();

	}

	if ( $error === false ) {

		$uploaded_bits = wp_upload_bits(
			$_FILES['file']['name'],
			null,
			file_get_contents( $_FILES['file']['tmp_name'] )
		);

		if ( false !== $uploaded_bits['error'] ) {
			$error = $uploaded_bits['error'];

		} else {
			$uploaded_file     = $uploaded_bits['file'];
			$uploaded_url      = $uploaded_bits['url'];
			$uploaded_filetype = wp_check_filetype( basename( $uploaded_bits['file'] ), null );

			if ( $uploader_purpose == 'job' || $uploader_purpose == 'cover' ) {
				$attachment = [
					'post_mime_type' => $uploaded_bits['type'],
					'post_title'     => apply_filters( 'wpj_uploaded_file_name_filter', 'File' ) . ' ' . addslashes( $_FILES['file']['name'] ),
					'post_content'   => '',
					'post_status'    => 'inherit',
					'post_parent'    => $pid,
					'post_author'    => get_current_user_id(),
				];

			} elseif ( $uploader_purpose == 'portfolio' ) {
				$attachment = [
					'post_mime_type' => $uploaded_bits['type'],
					'post_title'     => apply_filters( 'wpj_uploaded_file_name_filter', 'File' ) . ' ' . addslashes( $_FILES['file']['name'] ),
					'post_content'   => '',
					'post_status'    => 'publish',
					'post_author'    => $pid,
				];

			} elseif ( $uploader_purpose == 'message' ) {
				$attachment = [
					'post_mime_type' => $uploaded_bits['type'],
					'post_title'     => apply_filters( 'wpj_uploaded_file_name_filter', 'File' ) . ' ' . addslashes( $_FILES['file']['name'] ),
					'post_content'   => $pid,
					'post_status'    => 'publish',
					'post_author'    => get_current_user_id()
				];

			}

			$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 == 'portfolio' ) {
				update_post_meta( $attach_id, 'is_portfolio', 1 );
			}

			if ( $uploader_purpose == 'message' ) {
				update_post_meta( $attach_id, 'is_message', 1 );
			}

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

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

	echo wp_json_encode( [
		'id'        => $attach_id,
		'thumb_url' => wpj_get_attachment_image_url( $attach_id, 'square_150' ),
		'full_url'  => wpj_get_attachment_image_url( $attach_id, 'full' ),
		'error'     => $error,
	] );
}