<?php

class Wiaas_Document_Upload {

	private static $allowed_extensions = array(
		'pdf','docx','doc','xlsx','xls','odt','ods', 'zip'
	);

	public static function init() {
		add_filter( 'upload_dir', array( __CLASS__, 'upload_dir' ) );
	}


	/**
	 * Allowed extensions for wiaas documents uploads
	 * @return array
	 */
	public static function allowed_extensions() {
		return self::$allowed_extensions;
	}


	/**
	 * Handle wiaas document upload
	 *
	 * @param string $file_id
	 *
	 * @return int|WP_Error
	 */
	public static function upload_document_version($file_id = 'file') {

		wc_maybe_define_constant( 'WIAAS_DOCUMENT_UPLOAD', true );

		// validate file

		if (!isset($_FILES[$file_id])) {
			return new WP_Error( 'wiaas_upload_error_missing_file', 'No file!' );
		}

		$file_name = $_FILES[$file_id]['name'];
		$name = esc_attr($file_name);

		$ext = explode('.', $name);
		$ext = end($ext);
		$ext = strtolower($ext);

		if(!in_array($ext, self::$allowed_extensions)) {
			return new WP_Error( 'wiaas_upload_error_invalid_extension', 'Invalid file extension!' );
		}

		$file = wp_handle_upload(
			$_FILES[$file_id],
			array( 'test_form' => false ),
			current_time('mysql'));

		if ( isset($file['error']) )
			return new WP_Error( 'wiaas_upload_error', $file['error'] );

		return wiaas_get_doc_version_from_path($file['file']);
	}

	/**
	 * Updates wordpress upload dir so that wiaas documents are uploaded to wiaas specific upload dir
	 * @param $pathdata
	 *
	 * @return mixed
	 */
	public static function upload_dir( $pathdata ) {

		if (defined('WIAAS_DOCUMENT_UPLOAD') ) {
			if ( empty( $pathdata['subdir'] ) ) {
				$pathdata['path']   = $pathdata['path'] . wiaas_documents_base_dir();
				$pathdata['url']    = $pathdata['url'] . wiaas_documents_base_dir();
				$pathdata['subdir'] = wiaas_documents_base_dir();
			} else {
				$new_subdir = wiaas_documents_base_dir() . $pathdata['subdir'];

				$pathdata['path']   = str_replace( $pathdata['subdir'], $new_subdir, $pathdata['path'] );
				$pathdata['url']    = str_replace( $pathdata['subdir'], $new_subdir, $pathdata['url'] );
				$pathdata['subdir'] = str_replace( $pathdata['subdir'], $new_subdir, $pathdata['subdir'] );
			}
		}

		return $pathdata;
	}
}

Wiaas_Document_Upload::init();
