<?php

namespace Quicker\Core;

defined( 'ABSPATH' ) || exit;

use Quicker\Utils\Singleton;

/**
 * Handle media uploads for Quicker plugin
 */
class MediaHandler {

	use Singleton;

	/**
	 * Initialize the media handler
	 */
	public function init() {
		add_filter( 'upload_mimes', array( $this, 'allow_svg_mime' ) );
		add_filter( 'wp_handle_upload_prefilter', array( $this, 'handle_svg_upload' ) );
	}

	/**
	 * Handle SVG upload permissions for Quick View Icon
	 *
	 * @param array $file Upload file data
	 * @return array Modified file data
	 */
	public function handle_svg_upload( $file ) {
		// Check if we're in the Quick View Icon upload context
		// phpcs:ignore WordPress.Security.NonceVerification.Missing -- Nonce verified by WordPress media upload handler
		if ( isset( $_POST['field_id'] ) && sanitize_text_field( wp_unslash( $_POST['field_id'] ) ) === 'qview_icon' ) {
			if ( $file['type'] === 'image/svg+xml' ) {
				// Allow SVG for qview_icon
				return $file;
			}
		} elseif ( $file['type'] === 'image/svg+xml' ) {
			// Block SVG uploads for other fields
			$file['error'] = __( 'SVG uploads are only allowed for Quick View Icon.', 'quicker' );
		}
		return $file;
	}

	/**
	 * Add SVG to allowed mime types only for Quick View Icon
	 *
	 * @param array $mimes Allowed mime types
	 * @return array Modified mime types
	 */
	public function allow_svg_mime( $mimes ) {
		// phpcs:ignore WordPress.Security.NonceVerification.Missing -- Nonce verified by WordPress media upload handler
		if ( isset( $_POST['field_id'] ) && sanitize_text_field( wp_unslash( $_POST['field_id'] ) ) === 'qview_icon' ) {
			$mimes['svg'] = 'image/svg+xml';
		}
		return $mimes;
	}
}
