<?php
/**
 * Structure Viewer — Sanitizer helpers
 */

if ( ! defined( 'ABSPATH' ) ) {
    exit( 'Direct access denied.' );
}

final class SV_Sanitizer {

    /**
     * Sanitize a plugin or theme folder name.
     * Strips anything that is not alphanumeric, dash, underscore, or dot.
     */
    public static function item_name( $name ) {
        $name = sanitize_text_field( wp_unslash( (string) $name ) );
        $name = preg_replace( '/[^a-zA-Z0-9\-_\.]/', '', $name );
        // Prevent path traversal
        $name = str_replace( [ '..', '/', '\\' ], '', $name );
        return $name;
    }

    /** Human-readable file size. */
    public static function format_file_size( $bytes ) {
        if ( $bytes >= 1073741824 ) {
            return number_format( $bytes / 1073741824, 2 ) . ' GB';
        }
        if ( $bytes >= 1048576 ) {
            return number_format( $bytes / 1048576, 2 ) . ' MB';
        }
        if ( $bytes >= 1024 ) {
            return number_format( $bytes / 1024, 2 ) . ' KB';
        }
        return $bytes . ' bytes';
    }

    /** CSS class for a file icon based on extension. */
    public static function file_icon_class( $filename ) {
        $ext = strtolower( pathinfo( $filename, PATHINFO_EXTENSION ) );
        $map = [
            'php'  => 'sv-icon-php',
            'js'   => 'sv-icon-js',
            'css'  => 'sv-icon-css',
            'html' => 'sv-icon-html',
            'htm'  => 'sv-icon-html',
            'json' => 'sv-icon-json',
            'xml'  => 'sv-icon-xml',
            'txt'  => 'sv-icon-txt',
            'md'   => 'sv-icon-md',
            'sql'  => 'sv-icon-sql',
            'jpg'  => 'sv-icon-image',
            'jpeg' => 'sv-icon-image',
            'png'  => 'sv-icon-image',
            'gif'  => 'sv-icon-image',
            'svg'  => 'sv-icon-image',
            'zip'  => 'sv-icon-archive',
            'rar'  => 'sv-icon-archive',
            'tar'  => 'sv-icon-archive',
            'gz'   => 'sv-icon-archive',
        ];
        return $map[ $ext ] ?? 'sv-icon-default';
    }
}