<?php
/**
 * Structure Viewer — Filters
 *
 * Exclusion patterns and file-type filter definitions.
 */

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

final class SV_Filters {

    /** Static file-type definitions used for the Explorer tag strip. */
    public static function file_type_filters() {
        return [
            'php'    => [ 'PHP',        'php' ],
            'js'     => [ 'JavaScript', 'js' ],
            'css'    => [ 'CSS',        'css' ],
            'images' => [ 'Images',     'jpg,jpeg,png,gif,svg,webp,bmp,ico' ],
            'html'   => [ 'HTML',       'html,htm' ],
            'json'   => [ 'JSON',       'json' ],
            'txt'    => [ 'TXT',        'txt' ],
            'md'     => [ 'Markdown',   'md' ],
            'xml'    => [ 'XML',        'xml' ],
            'sql'    => [ 'SQL',        'sql' ],
        ];
    }

    /**
     * Build the full exclusion pattern list from saved settings.
     *
     * Sources merged in order:
     *   1. Always-excluded (security / noise)
     *   2. System directories (toggle)
     *   3. Hidden files glob (toggle)
     *   4. User-defined patterns
     */
    public static function exclusion_patterns() {
        $always = [ '*.log', 'thumbs.db' ];

        $settings = SV_Settings::get();

        $system = ( $settings['exclude_system_dirs'] ?? true )
            ? [ 'node_modules', '.git', '.svn', 'vendor', '.DS_Store' ]
            : [];

        $hidden = ( $settings['show_hidden_files'] ?? false )
            ? []      // user wants to see them → don't exclude
            : [ '.*' ]; // default: exclude dotfiles

        $user = is_array( $settings['exclude_patterns'] ?? null )
            ? $settings['exclude_patterns']
            : [];

        return array_values( array_unique( array_merge( $always, $system, $hidden, $user ) ) );
    }

    /**
     * Return only the file types that actually exist under the given item directory.
     */
    public static function available_types_for( $type, $item ) {
        $all_types = self::file_type_filters();

        if ( empty( $item ) ) {
            return $all_types;
        }

        $items_dir = ( $type === 'plugin' ) ? WP_PLUGIN_DIR : get_theme_root();
        $base      = realpath( $items_dir . '/' . $item );

        if ( ! $base || ! is_dir( $base ) ) {
            return $all_types;
        }

        // Collect present extensions
        $found_exts = [];
        $it = new RecursiveIteratorIterator(
            new RecursiveDirectoryIterator( $base, RecursiveDirectoryIterator::SKIP_DOTS )
        );
        foreach ( $it as $file ) {
            if ( $file->isFile() ) {
                $ext = strtolower( $file->getExtension() );
                if ( $ext ) {
                    $found_exts[ $ext ] = true;
                }
            }
        }

        $available    = [];
        $image_exts   = [ 'jpg', 'jpeg', 'png', 'gif', 'svg', 'webp', 'bmp', 'ico' ];

        foreach ( $all_types as $key => $info ) {
            if ( $key === 'images' ) {
                foreach ( $image_exts as $e ) {
                    if ( isset( $found_exts[ $e ] ) ) {
                        $available[ $key ] = $info;
                        break;
                    }
                }
            } else {
                foreach ( explode( ',', $info[1] ) as $e ) {
                    if ( isset( $found_exts[ $e ] ) ) {
                        $available[ $key ] = $info;
                        break;
                    }
                }
            }
        }

        return $available;
    }

    /** AJAX: return available file types for the current selection. */
    public static function ajax_get_available_types() {
        check_ajax_referer( STRUCTUREVIEWER_NONCE, 'nonce' );

        if ( ! current_user_can( 'manage_options' ) ) {
            wp_send_json_error( [ 'message' => 'Insufficient permissions.' ] );
        }

        $type = isset( $_POST['type'] ) ? sanitize_text_field( wp_unslash( $_POST['type'] ) ) : 'plugin';
        $item = isset( $_POST['item'] ) ? SV_Sanitizer::item_name( sanitize_text_field( wp_unslash( $_POST['item'] ) ) ) : '';

        wp_send_json_success( self::available_types_for( $type, $item ) );
    }
}
