<?php

// phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedNamespaceFound -- APD is the established namespace shared with the Pro add-on and retained for backward compatibility.
namespace APD\Support;

defined('ABSPATH') || exit;

class SvgUploads
{
    public function register() : void
    {
        add_filter('upload_mimes', [$this, 'allowMimeTypes']);
        add_filter('wp_handle_upload_prefilter', [$this, 'sanitizeUpload']);
        add_filter('wp_handle_sideload_prefilter', [$this, 'sanitizeUpload']);
    }

    public function allowMimeTypes(array $mimes) : array
    {
        if (current_user_can(Capabilities::MANAGE) || current_user_can('manage_options')) {
            $mimes['svg'] = 'image/svg+xml';
        } else {
            unset($mimes['svg'], $mimes['svgz']);
        }

        return $mimes;
    }

    public function sanitizeUpload(array $file) : array
    {
        $name = isset($file['name']) ? (string) $file['name'] : '';
        if (strtolower((string) pathinfo($name, PATHINFO_EXTENSION)) !== 'svg') {
            return $file;
        }

        if (! current_user_can(Capabilities::MANAGE) && ! current_user_can('manage_options')) {
            $file['error'] = __('SVG uploads are restricted to Asuka Designer administrators.', 'asuka-product-designer');
            return $file;
        }

        $temporaryPath = isset($file['tmp_name']) ? (string) $file['tmp_name'] : '';
        $contents = $temporaryPath !== '' && is_readable($temporaryPath) ? file_get_contents($temporaryPath) : false;
        $sanitized = is_string($contents) ? SvgSanitizer::sanitize($contents) : '';
        if ($sanitized === '') {
            $file['error'] = __('The SVG contains unsupported or unsafe content.', 'asuka-product-designer');
            return $file;
        }

        if (file_put_contents($temporaryPath, $sanitized, LOCK_EX) === false) {
            $file['error'] = __('The SVG could not be sanitized.', 'asuka-product-designer');
            return $file;
        }

        $file['type'] = 'image/svg+xml';
        return $file;
    }
}
