<?php
$user_id = $user->ID;
$tab_title = ! empty( $tab_title ) ? $tab_title : __( 'Files', 'wpuf-pro' );

// Get user uploaded files from attachments
$files = get_posts([
    'post_type'      => 'attachment',
    'author'         => $user_id,
    'posts_per_page' => -1, // Get all files for grouping
    'post_status'    => 'inherit'
]);

// Get gallery image size from template data or use default
$gallery_image_size = 150; // Default size

// Check if gallery_img_size is passed in template_data
if ( ! empty( $template_data['gallery_img_size'] ) ) {
    // Convert WordPress image size names to pixel values
    $size_map = [
        'thumbnail' => 150,
        'medium' => 300,
        'medium_large' => 768,
        'large' => 1024,
        'full' => 1536,
        '1536x1536' => 1536,
        '2048x2048' => 2048
    ];
    
    $size_value = $template_data['gallery_img_size'];
    
    // Check if it's a named size
    if ( isset( $size_map[ $size_value ] ) ) {
        $gallery_image_size = $size_map[ $size_value ];
    } elseif ( is_numeric( $size_value ) ) {
        // If it's already a number, use it
        $gallery_image_size = intval( $size_value );
    }
}

/**
 * Filters the returned current gallery image width for user profile file tab section
 *
 * @since 3.4.11
 *
 * @param string $gallery_image_size The current image width
 */
$gallery_image_size = apply_filters( 'wpuf_profile_gallery_image_size', $gallery_image_size );

// Group files by type
$grouped_files = [
    'images' => [],
    'documents' => [],
    'videos' => [],
    'audio' => [],
    'archives' => [],
    'others' => []
];

foreach ( $files as $file ) {
    $file_type = get_post_mime_type( $file->ID );
    
    if ( strpos( $file_type, 'image/' ) === 0 ) {
        $grouped_files['images'][] = $file;
    } elseif ( in_array( $file_type, ['application/pdf', 'application/msword', 'application/vnd.openxmlformats-officedocument.wordprocessingml.document', 'application/vnd.ms-excel', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', 'application/vnd.ms-powerpoint', 'application/vnd.openxmlformats-officedocument.presentationml.presentation', 'text/plain'] ) ) {
        $grouped_files['documents'][] = $file;
    } elseif ( strpos( $file_type, 'video/' ) === 0 ) {
        $grouped_files['videos'][] = $file;
    } elseif ( strpos( $file_type, 'audio/' ) === 0 ) {
        $grouped_files['audio'][] = $file;
    } elseif ( in_array( $file_type, ['application/zip', 'application/x-rar-compressed', 'application/x-7z-compressed', 'application/x-tar', 'application/gzip'] ) ) {
        $grouped_files['archives'][] = $file;
    } else {
        $grouped_files['others'][] = $file;
    }
}

// Remove empty groups
$grouped_files = array_filter( $grouped_files );

// File type labels
$type_labels = [
    'images' => __( 'Images', 'wpuf-pro' ),
    'documents' => __( 'Documents', 'wpuf-pro' ),
    'videos' => __( 'Videos', 'wpuf-pro' ),
    'audio' => __( 'Audio', 'wpuf-pro' ),
    'archives' => __( 'Archives', 'wpuf-pro' ),
    'others' => __( 'Others', 'wpuf-pro' )
];

// File type icons
$type_icons = [
    'images' => '🖼️',
    'documents' => '📄',
    'videos' => '🎥',
    'audio' => '🎵',
    'archives' => '📦',
    'others' => '📎'
];
?>

<div class="wpuf-profile-section wpuf-ud-files-area">
    <h3 class="profile-section-heading"><?php echo esc_html( $tab_title ); ?></h3>
    
    <?php if ( ! empty( $grouped_files ) ) : ?>
        <!-- File Type Tabs -->
        <div class="wpuf-file-tabs" style="margin-bottom: 20px;">
            <div class="wpuf-tab-nav" style="display: flex; flex-wrap: wrap; gap: 10px; border-bottom: 1px solid #ddd; padding-bottom: 10px;">
                <?php 
                $first_tab = true;
                foreach ( $grouped_files as $type => $type_files ) : 
                    $count = count( $type_files );
                ?>
                    <button class="wpuf-file-tab-btn" 
                            data-tab="<?php echo esc_attr( $type ); ?>"
                            <?php echo $first_tab ? 'data-active="true"' : ''; ?>
                            style="padding: 8px 16px; border: none; background: <?php echo $first_tab ? '#007cba' : '#f0f0f0'; ?>; color: <?php echo $first_tab ? '#fff' : '#333'; ?>; border-radius: 4px; cursor: pointer; font-size: 14px; transition: all 0.3s;">
                        <span style="margin-right: 5px;"><?php echo $type_icons[$type]; ?></span>
                        <?php echo esc_html( $type_labels[$type] ); ?>
                        <span style="margin-left: 5px; padding: 2px 6px; background: rgba(0,0,0,0.1); border-radius: 10px; font-size: 12px;">
                            <?php echo esc_html( $count ); ?>
                        </span>
                    </button>
                <?php 
                    $first_tab = false;
                endforeach; 
                ?>
            </div>
        </div>
        
        <!-- File Groups -->
        <?php 
        $first_group = true;
        foreach ( $grouped_files as $type => $type_files ) : 
        ?>
            <div class="wpuf-file-group file-container" data-type="<?php echo esc_attr( $type ); ?>" 
                 style="<?php echo ! $first_group ? 'display: none;' : ''; ?>">
                
                <?php foreach ( $type_files as $file ) : ?>
                    <?php
                    $file_url = wp_get_attachment_url( $file->ID );
                    $file_type = get_post_mime_type( $file->ID );
                    $is_image = strpos( $file_type, 'image/' ) === 0;
                    ?>
                    
                    <div class="single-file">
                        <a href="<?php echo esc_url( $file_url ); ?>" target="_blank">
                            <?php if ( $is_image ) : ?>
                                <?php
                                // Use the appropriate image size based on gallery_img_size setting
                                $image_size = ! empty( $template_data['gallery_img_size'] ) ? $template_data['gallery_img_size'] : 'thumbnail';
                                ?>
                                <img style="width: <?php echo intval( $gallery_image_size ); ?>px;" 
                                     src="<?php echo esc_url( wp_get_attachment_image_url( $file->ID, $image_size ) ); ?>" 
                                     alt="<?php echo esc_attr( $file->post_title ); ?>"
                                     class="preview-image">
                            <?php else : ?>
                                <?php
                                // Determine file icon based on mime type
                                $icon = 'file.svg';
                                if ( strpos( $file_type, 'pdf' ) !== false ) {
                                    $icon = 'pdf.svg';
                                } elseif ( strpos( $file_type, 'excel' ) !== false || strpos( $file_type, 'spreadsheet' ) !== false ) {
                                    $icon = 'xls.svg';
                                } elseif ( strpos( $file_type, 'zip' ) !== false || strpos( $file_type, 'compressed' ) !== false ) {
                                    $icon = 'zip.svg';
                                } elseif ( strpos( $file_type, 'document' ) !== false || strpos( $file_type, 'msword' ) !== false ) {
                                    $icon = 'doc.svg';
                                }
                                
                                $icon_path = defined( 'WPUF_UD_ASSET_URI' ) ? WPUF_UD_ASSET_URI . '/images/' . $icon : '';
                                ?>
                                <?php if ( $icon_path && file_exists( str_replace( WPUF_UD_ROOT_URI, WPUF_UD_ROOT, $icon_path ) ) ) : ?>
                                    <img style="width: <?php echo intval( $gallery_image_size ); ?>px;" 
                                         src="<?php echo esc_url( $icon_path ); ?>" 
                                         alt="<?php echo esc_attr( $file->post_title ); ?>">
                                <?php else : ?>
                                    <div class="file-placeholder" style="width: <?php echo intval( $gallery_image_size ); ?>px; height: <?php echo intval( $gallery_image_size ); ?>px; background: #f0f0f0; display: flex; align-items: center; justify-content: center;">
                                        <span style="font-size: 12px; color: #666;"><?php echo esc_html( strtoupper( pathinfo( $file_url, PATHINFO_EXTENSION ) ) ); ?></span>
                                    </div>
                                <?php endif; ?>
                            <?php endif; ?>
                        </a>
                        <div class="file-title" style="margin-top: 5px; font-size: 12px; text-align: center;">
                            <?php echo esc_html( wp_trim_words( $file->post_title, 3 ) ); ?>
                        </div>
                    </div>
                <?php endforeach; ?>
            </div>
        <?php 
            $first_group = false;
        endforeach; 
        ?>
        
    <?php else : ?>
        <p><?php esc_html_e( 'No files found', 'wpuf-pro' ); ?></p>
    <?php endif; ?>
</div>

<?php if ( ! empty( $grouped_files ) ) : ?>
<script type="text/javascript">
(function() {
    document.addEventListener('DOMContentLoaded', function() {
        const tabButtons = document.querySelectorAll('.wpuf-file-tab-btn');
        const fileGroups = document.querySelectorAll('.wpuf-file-group');
        
        tabButtons.forEach(function(button) {
            button.addEventListener('click', function(e) {
                e.preventDefault();
                
                const targetType = this.getAttribute('data-tab');
                
                // Update button states
                tabButtons.forEach(function(btn) {
                    btn.style.background = '#f0f0f0';
                    btn.style.color = '#333';
                    btn.removeAttribute('data-active');
                });
                
                this.style.background = '#007cba';
                this.style.color = '#fff';
                this.setAttribute('data-active', 'true');
                
                // Show/hide file groups
                fileGroups.forEach(function(group) {
                    if (group.getAttribute('data-type') === targetType) {
                        group.style.display = 'block';
                    } else {
                        group.style.display = 'none';
                    }
                });
            });
        });
    });
})();
</script>
<?php endif; ?>