<?php

namespace App\Helpers;

class SvgHelper
{
    /**
     * SVG Sanitizer
     * 
     * Strips potentially dangerous elements and attributes from SVG content
     * to prevent stored XSS attacks.
     */
    public static function sanitize(?string $svg): string
    {
        if (empty($svg)) {
            return '';
        }

        $xml_content = trim($svg);

        // If it looks like just a path (no <svg tag), wrap it
        if (strpos($xml_content, '<svg') === false) {
            $xml_content = '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">' . $xml_content . '</svg>';
        }

        // Only allow specific SVG elements
        $allowed_tags = '<path><circle><rect><line><polyline><polygon><g><svg><ellipse><text><tspan><defs><use><clipPath>';
        $sanitized = strip_tags($xml_content, $allowed_tags);
        
        // Remove any on* event handlers
        $sanitized = preg_replace('/\bon\w+\s*=\s*["\'][^"\']*["\']/', '', $sanitized);
        $sanitized = preg_replace('/\bon\w+\s*=\s*\S+/', '', $sanitized);
        
        // Remove javascript: and data: protocols
        $sanitized = preg_replace('/javascript\s*:/i', '', $sanitized);
        $sanitized = preg_replace('/data\s*:/i', '', $sanitized);
        
        // Ensure the SVG tag has necessary classes for styling if it doesn't have them
        if (strpos($sanitized, '<svg') !== false) {
            // We want to preserve existing viewBox but ensure it can be styled via classes
            // The classes will be added in the Blade files anyway, but let's make sure it's at least a valid SVG string
        }
        
        return $sanitized;
    }
}
