<?php
/**
 * About Tab Template - Dynamic Fields Support
 *
 * @since 4.2.0
 */

$user_id = $user->ID;
$current_user = wp_get_current_user();
$profile_role = isset( $user->roles[0] ) ? $user->roles[0] : '';
$viewer_role = is_user_logged_in() ? ( isset( $current_user->roles[0] ) ? $current_user->roles[0] : 'guest' ) : 'guest';

// Get directory ID from template data - check multiple sources
$directory_id = '';

// Try template_data first
if ( ! empty( $template_data['directory_id'] ) ) {
    $directory_id = $template_data['directory_id'];
} elseif ( ! empty( $template_data['all_data']['id'] ) ) {
    $directory_id = $template_data['all_data']['id'];
} elseif ( ! empty( $template_data['id'] ) ) {
    $directory_id = $template_data['id'];
} elseif ( isset( $profile_data ) && ! empty( $profile_data['directory_id'] ) ) {
    // Try profile_data if available
    $directory_id = $profile_data['directory_id'];
}

// Get profile fields from database
$profile_fields = \WPUF\UserDirectory\ShortCode::get_profile_fields( $directory_id );

// Debug removed - issue found and fixed

do_action( 'wpuf_user_profile_before_content' );

// If no fields configured, show empty state
if ( empty( $profile_fields ) ) {
    ?>
    <div class="wpuf-profile-section !wpuf-mb-8">
        <div class="!wpuf-flex !wpuf-flex-col !wpuf-items-center !wpuf-justify-center !wpuf-py-16 !wpuf-bg-gray-50 !wpuf-rounded-lg !wpuf-border !wpuf-border-gray-200">
            <div class="!wpuf-mb-4">
                <svg class="!wpuf-w-20 !wpuf-h-20 !wpuf-text-gray-300" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.5" d="M16 7a4 4 0 11-8 0 4 4 0 018 0zM12 14a7 7 0 00-7 7h14a7 7 0 00-7-7z"></path>
                </svg>
            </div>
            <p class="!wpuf-text-lg !wpuf-font-medium !wpuf-text-gray-900 !wpuf-mb-1"><?php esc_html_e( 'No fields configured', 'wpuf-pro' ); ?></p>
            <p class="!wpuf-text-sm !wpuf-text-gray-500"><?php esc_html_e( 'Please configure About tab fields in the directory settings.', 'wpuf-pro' ); ?></p>
        </div>
    </div>
    <?php
    do_action( 'wpuf_user_profile_after_content' );
    return;
}


// Process fields in order and check if we have any content
$has_content = false;
$visible_fields = [];

// Filter visible fields based on permissions
foreach ( $profile_fields as $field ) {
    // Normalize field structure for permission checking
    // Handle both single and array formats for roles
    $normalized_field = [
        'profile_user_role' => $field['profile_user_roles'] ?? $field['profile_user_role'] ?? 'all',
        'viewer_role' => $field['viewer_roles'] ?? $field['viewer_role'] ?? 'all'
    ];

    // Check permissions
    if ( \WPUF\UserDirectory\ShortCode::can_user_see_field( $profile_role, $normalized_field, $viewer_role ) ) {
        $visible_fields[] = $field;

        // Check if this field will have content
        if ( $field['type'] === 'section' ) {
            $has_content = true; // Sections always show
        } elseif ( $field['type'] === 'meta_field' || $field['type'] === 'meta' ) {
            // Check if the meta field has a value
            $meta_key = $field['meta_key'] ?? '';
            if ( ! empty( $meta_key ) ) {
                $value = '';
                if ( $meta_key === 'user_login' ) {
                    $value = $user->user_login;
                } elseif ( $meta_key === 'user_email' ) {
                    $value = $user->user_email;
                } elseif ( $meta_key === 'display_name' ) {
                    $value = $user->display_name;
                } elseif ( $meta_key === 'user_url' ) {
                    $value = $user->user_url;
                } elseif ( $meta_key === 'description' ) {
                    $value = get_user_meta( $user_id, 'description', true );
                } else {
                    // Check user meta
                    $meta_value = get_user_meta( $user_id, $meta_key, true );
                    if ( empty( $meta_value ) && ! empty( $user->data->$meta_key ) ) {
                        $value = $user->data->$meta_key;
                    } else {
                        $value = $meta_value;
                    }
                }

                if ( ! empty( $value ) && $value !== '-1' ) {
                    $has_content = true;
                }
            }
        } elseif ( $field['type'] === 'post_type' || $field['type'] === 'post' ) {
            // Check if user has posts of this type
            $post_type = $field['post_type'] ?? 'post';
            $user_posts = get_posts([
                'author' => $user_id,
                'post_type' => $post_type,
                'post_status' => 'publish',
                'posts_per_page' => 1
            ]);
            if ( ! empty( $user_posts ) ) {
                $has_content = true;
            }
        } elseif ( $field['type'] === 'image_file' || $field['type'] === 'file' ) {
            // Check for user files/images using helper function
            $meta_key = $field['meta_key'] ?? '';
            if ( wpuf_ud_user_has_files( $user_id, $meta_key ) ) {
                $has_content = true;
            }
        } elseif ( $field['type'] === 'comment' ) {
            // Check if user has comments
            $comment_args = [
                'user_id' => $user_id,
                'number'  => 1,
                'status'  => 'approve'
            ];
            $comments = get_comments( $comment_args );
            if ( ! empty( $comments ) ) {
                $has_content = true;
            }
        } else {
            $has_content = true; // Other field types assume content
        }
    }
}


// Show empty state if no content
if ( ! $has_content ) : ?>
<div class="wpuf-profile-section !wpuf-mb-8">
    <div class="!wpuf-flex !wpuf-flex-col !wpuf-items-center !wpuf-justify-center !wpuf-py-16 !wpuf-bg-gray-50 !wpuf-rounded-lg !wpuf-border !wpuf-border-gray-200">
        <div class="!wpuf-mb-4">
            <svg class="!wpuf-w-20 !wpuf-h-20 !wpuf-text-gray-300" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.5" d="M16 7a4 4 0 11-8 0 4 4 0 018 0zM12 14a7 7 0 00-7 7h14a7 7 0 00-7-7z"></path>
            </svg>
        </div>
        <p class="!wpuf-text-lg !wpuf-font-medium !wpuf-text-gray-900 !wpuf-mb-1"><?php esc_html_e( 'No information available', 'wpuf-pro' ); ?></p>
        <p class="!wpuf-text-sm !wpuf-text-gray-500"><?php esc_html_e( 'This user hasn\'t added any information yet.', 'wpuf-pro' ); ?></p>
    </div>
</div>
<?php else : ?>

<!-- Render Dynamic Fields in Order -->
<div class="wpuf-profile-section !wpuf-mb-8">
    <div class="profile-fields-content">
        <?php foreach ( $visible_fields as $field ) : ?>
            <?php
            switch ( $field['type'] ) {
                case 'section':
                    // Render section header
                    ?>
                    <h1 class="!wpuf-text-2xl !wpuf-font-bold !wpuf-text-gray-800 !wpuf-mb-4 !wpuf-pb-3 !wpuf-border-b !wpuf-border-gray-200 !wpuf-mt-8 first:!wpuf-mt-0">
                        <?php echo esc_html( $field['label'] ); ?>
                    </h1>
                    <?php
                    break;

                case 'meta_field':
                case 'meta':
                    // Render meta field using reusable function
                    wpuf_ud_render_meta_field( $field, $user, $user_id, '1' );
                    break;

                    case 'post_type':
                    case 'post':
                        // Render user posts using reusable function
                        wpuf_ud_render_posts_table( $field, $user_id, '1' );
                        break;

                    case 'comment':
                        // Display user comments
                        $post_type = $field['post_type'] ?? '';
                        $count = $field['count'] ?? 5;

                        $comment_args = [
                            'user_id' => $user_id,
                            'number'  => $count,
                            'status'  => 'approve'
                        ];

                        if ( ! empty( $post_type ) ) {
                            $comment_args['post_type'] = $post_type;
                        }

                        $comments = get_comments( $comment_args );

                        if ( ! empty( $comments ) ) : ?>
                            <div class="wpuf-comments-field !wpuf-mb-6">
                                <h1 class="!wpuf-font-bold !wpuf-text-2xl !wpuf-text-gray-700 !wpuf-mb-3">
                                    <?php echo esc_html( $field['label'] ); ?>
                                </h1>
                                <div class="comments-list !wpuf-space-y-3">
                                    <?php foreach ( $comments as $comment ) : ?>
                                        <div class="comment-item !wpuf-bg-gray-50 !wpuf-rounded-lg !wpuf-p-4">
                                            <div class="!wpuf-mb-2">
                                                <a href="<?php echo get_comment_link( $comment ); ?>" target="_blank" class="!wpuf-text-sm !wpuf-font-medium !wpuf-text-blue-600 hover:!wpuf-text-blue-800 !wpuf-no-underline">
                                                    <?php echo esc_html( get_the_title( $comment->comment_post_ID ) ); ?>
                                                </a>
                                                <span class="!wpuf-text-xs !wpuf-text-gray-500 !wpuf-ml-2">
                                                    <?php echo esc_html( get_comment_date( 'M j, Y', $comment ) ); ?>
                                                </span>
                                            </div>
                                            <div class="!wpuf-text-sm !wpuf-text-gray-600">
                                                <?php echo wp_trim_words( $comment->comment_content, 20 ); ?>
                                            </div>
                                        </div>
                                    <?php endforeach; ?>
                                </div>
                            </div>
                        <?php endif;
                        break;

                    case 'file':
                    case 'image_file':
                        // Display user files using reusable function
                        wpuf_ud_render_files_grid( $field, $user_id, $template_data, 'gray' );
                        break;
                }
                ?>
            <?php endforeach; ?>
        </div>
    </div>

<?php endif; // End of has_content check

do_action( 'wpuf_user_profile_after_content' );
?>
