<?php
/**
 * User Profile Block Frontend Template
 *
 * This template is used to render the user profile block on the frontend.
 * It detects the user from query parameters or shows the current user.
 *
 * @since 4.2.0
 *
 * @var array $all_data Block attributes and settings
 * @var string $profile_layout Layout style (layout-1, layout-2, layout-3, layout-4)
 */

// Prevent direct access
if ( ! defined( 'ABSPATH' ) ) {
    exit;
}

// Extract configuration
$profile_base = ! empty( $all_data['profile_base'] ) ? $all_data['profile_base'] : 'id';
// Check for profile_layout in multiple places: direct variable, all_data, or default
$profile_layout = ! empty( $profile_layout ) ? $profile_layout : ( ! empty( $all_data['profile_layout'] ) ? $all_data['profile_layout'] : 'layout-1' );
$block_id = ! empty( $all_data['block_id'] ) ? $all_data['block_id'] : 'wpuf-profile-' . uniqid();

// Determine which user to show
$user_to_show = null;

// Check query parameters based on profile base setting
if ( $profile_base === 'user_id' && ! empty( $_GET['user_id'] ) ) {
    $user_id = intval( $_GET['user_id'] );
    $user_to_show = get_user_by( 'ID', $user_id );
} elseif ( $profile_base === 'user_login' && ! empty( $_GET['user'] ) ) {
    $username = sanitize_user( $_GET['user'] );
    $user_to_show = get_user_by( 'login', $username );
} elseif ( ! empty( $_GET['user'] ) ) {
    // Fallback to user parameter
    $username = sanitize_user( $_GET['user'] );
    $user_to_show = get_user_by( 'login', $username );
} elseif ( ! empty( $_GET['user_id'] ) ) {
    // Legacy fallback to user_id parameter
    $user_id = intval( $_GET['user_id'] );
    $user_to_show = get_user_by( 'ID', $user_id );
} elseif ( ! empty( $_GET['username'] ) ) {
    // Legacy fallback to username parameter
    $username = sanitize_user( $_GET['username'] );
    $user_to_show = get_user_by( 'login', $username );
} elseif ( ! empty( $_GET['id'] ) ) {
    // Legacy fallback to id parameter
    $user_id = intval( $_GET['id'] );
    $user_to_show = get_user_by( 'ID', $user_id );
}

// If no user from params, try to get current user
if ( ! $user_to_show && is_user_logged_in() ) {
    $user_to_show = wp_get_current_user();
}

// If still no user, show a message
if ( ! $user_to_show ) {
    ?>
    <div class="wpuf-user-profile-block <?php echo esc_attr( $profile_layout ); ?>" id="<?php echo esc_attr( $block_id ); ?>">
        <div class="wpuf-no-user-message">
            <div class="wpuf-no-user-content">
                <div class="wpuf-no-user-icon">👤</div>
                <h3><?php _e( 'No User Profile', 'wpuf-pro' ); ?></h3>
                <p><?php _e( 'Please log in or provide a valid user ID/username to view a profile.', 'wpuf-pro' ); ?></p>
            </div>
        </div>
    </div>
    <?php
    return;
}

// Check privacy settings
$current_user = wp_get_current_user();
$can_view_profile = true;

// Check if user has made their profile private
if ( $current_user->ID !== $user_to_show->ID && ! current_user_can( 'manage_options' ) ) {
    $profile_privacy = get_user_meta( $user_to_show->ID, '_wpuf_profile_privacy', true );
    if ( 'private' === $profile_privacy ) {
        $can_view_profile = false;
    }

    // Check if user role should be hidden
    $user_roles = $user_to_show->roles;
    $hidden_roles = apply_filters( 'wpuf_hidden_user_roles', [ 'administrator' ] );

    if ( array_intersect( $user_roles, $hidden_roles ) ) {
        $can_view_profile = false;
    }
}

if ( ! $can_view_profile ) {
    ?>
    <div class="wpuf-user-profile-block <?php echo esc_attr( $profile_layout ); ?>" id="<?php echo esc_attr( $block_id ); ?>">
        <div class="wpuf-profile-private-message">
            <div class="wpuf-profile-private-content">
                <div class="wpuf-profile-private-icon">🔒</div>
                <h3><?php _e( 'Profile Not Available', 'wpuf-pro' ); ?></h3>
                <p><?php _e( 'This user profile is private or not accessible.', 'wpuf-pro' ); ?></p>
            </div>
        </div>
    </div>
    <?php
    return;
}

// Prepare user data for display
$user_data = [
    'id'          => $user_to_show->ID,
    'username'    => $user_to_show->user_login,
    'slug'        => $user_to_show->user_nicename,
    'name'        => $user_to_show->display_name,
    'first_name'  => $user_to_show->first_name,
    'last_name'   => $user_to_show->last_name,
    'user_email'  => $user_to_show->user_email,
    'user_url'    => $user_to_show->user_url,
    'description' => $user_to_show->description,
    'nickname'    => $user_to_show->nickname,
    'roles'       => $user_to_show->roles,
    'avatar_urls' => rest_get_avatar_urls( $user_to_show->ID ),
    'meta'        => get_user_meta( $user_to_show->ID ),
];

// Flatten meta arrays
foreach ( $user_data['meta'] as $key => $value ) {
    if ( is_array( $value ) && count( $value ) === 1 ) {
        $user_data['meta'][ $key ] = $value[0];
    }
}

// Merge user data with block settings for template
$template_data = array_merge( $all_data, [
    'user' => $user_data,
    'current_user_id' => $current_user->ID,
    'can_edit' => ( $current_user->ID === $user_to_show->ID || current_user_can( 'manage_options' ) ),
] );

?>
<div class="wpuf-user-profile-block wpuf-profile-<?php echo esc_attr( $profile_layout ); ?>" id="<?php echo esc_attr( $block_id ); ?>">
    <?php
    // Load layout-specific template
    $layout_template = WPUF_UD_TEMPLATES . '/user-profile/' . $profile_layout . '.php';

    if ( file_exists( $layout_template ) ) {
        include $layout_template;
    } else {
        // Fallback to default layout
        include WPUF_UD_TEMPLATES . '/user-profile/layout-1.php';
    }
    ?>
</div>

<script type="text/javascript">
// Add any frontend JavaScript for interactivity
(function($) {
    'use strict';

    $(document).ready(function() {
        var $profileBlock = $('#<?php echo esc_js( $block_id ); ?>');

        // Tab functionality for layout-1
        $profileBlock.find('.wpuf-tab-button').on('click', function(e) {
            e.preventDefault();

            var $this = $(this);
            var targetTab = $this.data('tab') || $this.attr('href').replace('#', '');

            // Update active tab button
            $this.siblings().removeClass('active');
            $this.addClass('active');

            // Update active tab content
            $profileBlock.find('.wpuf-tab-content > div').hide();
            $profileBlock.find('.wpuf-tab-content-' + targetTab).show();
        });

        // Load dynamic content for tabs (posts, comments)
        $profileBlock.find('[data-load-content]').each(function() {
            var $container = $(this);
            var contentType = $container.data('load-content');
            var userId = <?php echo intval( $user_to_show->ID ); ?>;

            if (contentType === 'posts') {
                loadUserPosts($container, userId);
            } else if (contentType === 'comments') {
                loadUserComments($container, userId);
            }
        });

        function loadUserPosts($container, userId) {
            // Check if wpuf_user_directory is available
            if (typeof wpuf_user_directory === 'undefined') {
                $container.html('<div class="wpuf-error"><p><?php esc_html_e( 'Unable to load posts - configuration error.', 'wpuf-pro' ); ?></p></div>');
                return;
            }

            $.ajax({
                url: wpuf_user_directory.rest_url + 'wp/v2/posts',
                method: 'GET',
                data: {
                    author: userId,
                    per_page: <?php echo intval( $all_data['posts_per_tab'] ?? 5 ); ?>,
                    _embed: true
                },
                beforeSend: function(xhr) {
                    $container.html('<div class="wpuf-loading"><span class="dashicons dashicons-update"></span> <?php esc_html_e( 'Loading posts...', 'wpuf-pro' ); ?></div>');
                    if (wpuf_user_directory.rest_nonce) {
                        xhr.setRequestHeader('X-WP-Nonce', wpuf_user_directory.rest_nonce);
                    }
                },
                success: function(posts) {
                    if (posts.length > 0) {
                        var html = '<div class="wpuf-posts-list">';
                        posts.forEach(function(post) {
                            html += '<div class="wpuf-post-item">';
                            html += '<div class="wpuf-post-icon"><span class="dashicons dashicons-admin-post"></span></div>';
                            html += '<div class="wpuf-post-content">';
                            html += '<h4 class="wpuf-post-title"><a href="' + post.link + '">' + post.title.rendered + '</a></h4>';
                            html += '<div class="wpuf-post-meta">';
                            html += '<span class="wpuf-post-date">' + new Date(post.date).toLocaleDateString() + '</span>';
                            html += '<span class="wpuf-read-more"><a href="' + post.link + '"><?php esc_html_e( 'Read More →', 'wpuf-pro' ); ?></a></span>';
                            html += '</div></div></div>';
                        });
                        html += '</div>';
                        $container.html(html);
                    } else {
                        $container.html('<div class="wpuf-no-content"><p><?php esc_html_e( 'No posts found.', 'wpuf-pro' ); ?></p></div>');
                    }
                },
                error: function() {
                    $container.html('<div class="wpuf-error"><p><?php esc_html_e( 'Error loading posts.', 'wpuf-pro' ); ?></p></div>');
                }
            });
        }

        function loadUserComments($container, userId) {
            // Check if wpuf_user_directory is available
            if (typeof wpuf_user_directory === 'undefined') {
                $container.html('<div class="wpuf-error"><p><?php esc_html_e( 'Unable to load comments - configuration error.', 'wpuf-pro' ); ?></p></div>');
                return;
            }

            $.ajax({
                url: wpuf_user_directory.rest_url + 'wp/v2/comments',
                method: 'GET',
                data: {
                    author: userId,
                    per_page: <?php echo intval( $all_data['posts_per_tab'] ?? 5 ); ?>
                },
                beforeSend: function(xhr) {
                    $container.html('<div class="wpuf-loading"><span class="dashicons dashicons-update"></span> <?php esc_html_e( 'Loading comments...', 'wpuf-pro' ); ?></div>');
                    if (wpuf_user_directory.rest_nonce) {
                        xhr.setRequestHeader('X-WP-Nonce', wpuf_user_directory.rest_nonce);
                    }
                },
                success: function(comments) {
                    if (comments.length > 0) {
                        var html = '<div class="wpuf-comments-list">';
                        comments.forEach(function(comment) {
                            html += '<div class="wpuf-comment-item">';
                            html += '<div class="wpuf-comment-icon"><span class="dashicons dashicons-admin-comments"></span></div>';
                            html += '<div class="wpuf-comment-content">';
                            html += '<div class="wpuf-comment-text">' + comment.content.rendered + '</div>';
                            html += '<div class="wpuf-comment-meta">';
                            html += '<span class="wpuf-comment-date">' + new Date(comment.date).toLocaleDateString() + '</span>';
                            html += '<span class="wpuf-read-more"><a href="' + comment.link + '"><?php esc_html_e( 'Read More →', 'wpuf-pro' ); ?></a></span>';
                            html += '</div></div></div>';
                        });
                        html += '</div>';
                        $container.html(html);
                    } else {
                        $container.html('<div class="wpuf-no-content"><p><?php esc_html_e( 'No comments found.', 'wpuf-pro' ); ?></p></div>');
                    }
                },
                error: function() {
                    $container.html('<div class="wpuf-error"><p><?php esc_html_e( 'Error loading comments.', 'wpuf-pro' ); ?></p></div>');
                }
            });
        }
    });

})(jQuery);
</script>
