<?php
/**
 * About Tab Template 2 - Dynamic Fields Support with Emerald/Teal Theme
 *
 * @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 );

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-20 !wpuf-bg-gray-50 !wpuf-rounded-xl">
            <div class="!wpuf-mb-4">
                <svg class="!wpuf-w-24 !wpuf-h-24 !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-xl !wpuf-font-medium !wpuf-text-gray-900 !wpuf-mb-2"><?php esc_html_e( 'No fields configured', 'wpuf-pro' ); ?></p>
            <p class="!wpuf-text-base !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'
    ];

    // Hard gate: profile_user_role check (which profile type shows this field)
    $profile_only = [ 'profile_user_role' => $normalized_field['profile_user_role'] ];
    if ( ! \WPUF\UserDirectory\ShortCode::can_user_see_field( $profile_role, $profile_only, $viewer_role ) ) {
        continue;
    }

    // Viewer access check (roles only – subscription is checked inside wpuf_ud_render_meta_field)
    $can_see = \WPUF\UserDirectory\ShortCode::can_user_see_field( $profile_role, $normalized_field, $viewer_role );

    // Meta fields with a custom restriction message must still reach wpuf_ud_render_meta_field
    // so the message is rendered even when the viewer's role doesn't match
    $show_custom_message = ! $can_see
        && ( $field['type'] === 'meta_field' || $field['type'] === 'meta' )
        && ! empty( $field['field_view_type'] ) && $field['field_view_type'] === 'show_custom_message'
        && ! empty( $field['custom_message'] );

    if ( $can_see || $show_custom_message ) {
        $visible_fields[] = $field;

        if ( $show_custom_message ) {
            $has_content = true; // custom message counts as content
            continue;
        }

        // 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'] === 'social' || $field['type'] === 'social_media' ) {
            // Check for social media links
            $user_social_links = wpuf_ud_get_user_social_links( $user );
            if ( ! empty( $user_social_links ) ) {
                $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-20 !wpuf-bg-gray-50 !wpuf-rounded-xl">
        <div class="!wpuf-mb-4">
            <svg class="!wpuf-w-24 !wpuf-h-24 !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-xl !wpuf-font-medium !wpuf-text-gray-900 !wpuf-mb-2"><?php esc_html_e( 'No information available', 'wpuf-pro' ); ?></p>
        <p class="!wpuf-text-base !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 with about-2 design
                    ?>
                    <h1 class="profile-section-heading !wpuf-text-2xl !wpuf-font-bold !wpuf-text-gray-900 !wpuf-mb-4 !wpuf-mt-10 first:!wpuf-mt-0">
                        <?php wpuf_ud_render_field_icon( $field['field_icon'] ?? '' ); ?>
                        <?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, '2' );
                    break;

                case 'social':
                case 'social_media':
                    // Display social media links with about-2 emerald theme
                    $user_social_links = wpuf_ud_get_user_social_links( $user );

                    if ( ! empty( $user_social_links ) ) : ?>
                        <div class="wpuf-profile-section wpuf-social-section !wpuf-mb-10">
                            <h1 class="profile-section-heading !wpuf-text-2xl !wpuf-font-bold !wpuf-text-gray-900 !wpuf-mb-4">
                                <?php echo esc_html( $field['label'] ); ?>
                            </h1>
                            <div class="social-media-grid !wpuf-grid !wpuf-grid-cols-2 lg:!wpuf-grid-cols-4 !wpuf-gap-4">
                                <?php
                                // Get social fields and icons from centralized functions
                                $social_fields = wpuf_ud_get_social_fields();
                                $social_icons = wpuf_ud_get_social_icons( '!wpuf-w-3 !wpuf-h-3' );

                                foreach ( $user_social_links as $social_field => $url ) :
                                    $label = $social_fields[ $social_field ] ?? '';
                                    ?>
                                    <a href="<?php echo esc_url( $url ); ?>" target="_blank" class="social-media-item !wpuf-flex !wpuf-items-center !wpuf-justify-between !wpuf-p-3 !wpuf-bg-white !wpuf-rounded-md !wpuf-border !wpuf-border-gray-200 hover:!wpuf-border-emerald-200 hover:!wpuf-bg-emerald-50 !wpuf-transition-all !wpuf-duration-200 !wpuf-no-underline !wpuf-group">
                                        <div class="!wpuf-flex !wpuf-items-center !wpuf-gap-3">
                                            <div class="social-icon !wpuf-w-6 !wpuf-h-6 !wpuf-bg-emerald-600 !wpuf-rounded-full !wpuf-flex !wpuf-items-center !wpuf-justify-center !wpuf-text-white group-hover:!wpuf-bg-emerald-700 !wpuf-transition-colors">
                                                <?php echo $social_icons[$social_field] ?? '<span class="!wpuf-text-xs !wpuf-font-bold">' . esc_html( strtoupper( substr( $label, 0, 1 ) ) ) . '</span>'; ?>
                                            </div>
                                            <span class="social-name !wpuf-font-medium !wpuf-text-sm !wpuf-text-gray-900"><?php echo esc_html( $label ); ?></span>
                                        </div>
                                        <svg width="15" height="17" viewBox="0 0 15 17" fill="none" xmlns="http://www.w3.org/2000/svg" class="!wpuf-opacity-40 group-hover:!wpuf-opacity-70 !wpuf-transition-opacity">
                                            <path d="M6.64384 4.14385C7.13608 3.65157 7.80379 3.375 8.50003 3.375H14C14.3452 3.375 14.625 3.65483 14.625 4C14.625 4.34518 14.3452 4.625 14 4.625H8.50003C8.13535 4.625 7.78561 4.76987 7.52776 5.02773C7.26982 5.28559 7.12501 5.63533 7.12501 6V8.50001C7.12501 8.84518 6.84517 9.12501 6.5 9.12501C6.15482 9.12501 5.875 8.84518 5.875 8.50001V6C5.875 5.30381 6.15156 4.63613 6.64384 4.14385Z" fill="#9CA3AF"/>
                                            <path d="M10.5581 0.558059C10.8021 0.31398 11.1979 0.31398 11.442 0.558059L14.4419 3.55806C14.686 3.80214 14.686 4.19787 14.4419 4.44195L11.442 7.44194C11.1979 7.68602 10.8021 7.68602 10.5581 7.44194C10.314 7.19786 10.314 6.80213 10.5581 6.55806L13.1161 4L10.5581 1.44194C10.314 1.19787 10.314 0.802136 10.5581 0.558059Z" fill="#9CA3AF"/>
                                            <path d="M1.99999 6.625C1.90054 6.625 1.80515 6.6645 1.73483 6.73483C1.6645 6.80516 1.62499 6.90055 1.62499 6.99999V15C1.62499 15.0995 1.6645 15.1949 1.73483 15.2652C1.80515 15.3355 1.90054 15.375 1.99999 15.375H11C11.0994 15.375 11.1948 15.3355 11.2652 15.2652C11.3355 15.1949 11.375 15.0995 11.375 15V9.99998C11.375 9.65483 11.6548 9.37502 12 9.37502C12.3452 9.37502 12.625 9.65483 12.625 9.99998V15C12.625 15.4309 12.4538 15.8443 12.1491 16.1491C11.8443 16.4538 11.431 16.625 11 16.625H1.99999C1.56902 16.625 1.1557 16.4538 0.850947 16.1491C0.546198 15.8443 0.375 15.4309 0.375 15V6.99999C0.375 6.56902 0.546198 6.1557 0.850947 5.85095C1.1557 5.5462 1.56902 5.375 1.99999 5.375H3.5C3.84518 5.375 4.12499 5.65482 4.12499 6C4.12499 6.34517 3.84518 6.625 3.5 6.625H1.99999Z" fill="#9CA3AF"/>
                                        </svg>
                                    </a>
                                <?php endforeach; ?>
                            </div>
                        </div>
                    <?php endif;
                    break;

                case 'post_type':
                case 'post':
                    // Render user posts using reusable function
                    wpuf_ud_render_posts_table( $field, $user_id, '2' );
                    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-emerald-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-emerald-600 hover:!wpuf-text-emerald-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 with emerald theme
                    wpuf_ud_render_files_grid( $field, $user_id, $template_data, 'emerald' );
                    break;
            }
            ?>
        <?php endforeach; ?>
    </div>
</div>

<?php endif; // End of has_content check

do_action( 'wpuf_user_profile_after_content' );
?>
