<?php
if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

/**
 * Checked if not exists Wings3dpr_Extend_Mime_Type class.
 */
if ( ! class_exists( 'Wings3dpr_Extend_Mime_Type' ) ) {

	/**
	 * Wings3dpr_Extend_Mime_Type class file.
	 */
	class Wings3dpr_Extend_Mime_Type {

		/**
		 * Wings3dpr_Extend_Mime_Type construct.
		 */
		public function __construct() {
			global $wp_version;
			add_filter( 'upload_mimes', array( $this, 'stp_mime_types' ) );

			if ( version_compare( $wp_version, '5.1' ) >= 0 ) {
				add_filter( 'wp_check_filetype_and_ext', array( $this, 'add_allow_upload_extension_exception' ), 10, 5 );
			} else {
				add_filter( 'wp_check_filetype_and_ext', array( $this, 'add_allow_upload_extension_exception' ), 10, 4 );
			}
		}

		/**
		 * Filter to add custom MIME types for file uploads.
		 *
		 * @param array $mimes An array of MIME types.
		 * @return array Modified array of MIME types.
		 */
		public function stp_mime_types( $mimes ) {
			$custom_mimes = $this->get_mime_types();
			return array_merge( $mimes, $custom_mimes ); // Ensure proper merging.
		}

		/**
		 * Add exception for allowed upload extensions based on file type.
		 *
		 * @param array  $data        Array containing information about the file upload.
		 * @param array  $file        Array of file data.
		 * @param string $filename   The name of the file.
		 * @return array Modified file data with additional information if applicable.
		 */
		public function add_allow_upload_extension_exception( $data, $file, $filename, $mimes, $real_mime = null ) {
			$f_sp = explode(".", $filename);
			$f_exp_count  = count ($f_sp);
		
			if($f_exp_count <= 1){
				return $data;
			}else{
				$f_name = $f_sp[0];
				$ext  = $f_sp[$f_exp_count - 1];
			}
	
			$extendedMimes = $this->get_mime_types();
	
			if(isset($extendedMimes[$ext])){
				$type = $extendedMimes[$ext];
				$proper_filename = '';
				return compact('ext', 'type', 'proper_filename');
			}
			return $data;
		}

		/**
		 * Support gltf and glb file.
		 */
		public function get_mime_types() {
			$mimes = array(
				'glb'  => 'model/gltf-binary',
				'gltf' => 'model/gltf+json',  
				'obj'  => 'model/obj',
				'3ds'  => 'application/x-3ds',
				'step' => 'application/step',
				'stl'  => 'application/vnd.ms-pki.stl',
				'fbx'  => 'application/octet-stream',
				'3dml' => 'text/vnd.in3d.3dml',
				'dae'  => 'application/collada+xml',
				'wrl'  => 'model/vrml',
				'3mf'  => 'application/vnd.ms-3mfdocument',
				'bin'  => 'application/octet-stream',
				'hdr'  => 'image/vnd.radiance',
			);
			return $mimes;
		}
		
	}
}
