<?php
namespace UM_Elementor\Helpers;

if (!defined('ABSPATH')) exit; // Exit if accessed directly

/**
 * Utility functions for Elementor widgets
 */
class UM_Elementor_Utils
{

    /**
     * Get user profile URL (WordPress native version)
     */
    public static function getUserProfileUrl($user_id)
    {
        // Try to get author archive URL
        $author_url = get_author_posts_url($user_id);
        
        // If no author posts, return user profile page if exists
        if (empty($author_url) || $author_url === home_url('/')) {
            // Check if there's a custom profile page
            $profile_page = get_option('wp_user_profile_page');
            if ($profile_page) {
                return add_query_arg('user_id', $user_id, get_permalink($profile_page));
            }
            
            // Fallback to author archive
            return $author_url;
        }
        
        return $author_url;
    }

    /**
     * Get user avatar URL (WordPress native version)
     */
    public static function getUserAvatarUrl($user_id, $size = 100)
    {
        return get_avatar_url($user_id, ['size' => $size]);
    }

    /**
     * Get user meta value (WordPress native version)
     */
    public static function getUserMeta($user_id, $meta_key)
    {
        $meta_value = get_user_meta($user_id, $meta_key, true);
        
        // Handle serialized data
        if (is_serialized($meta_value)) {
            $unserialized = maybe_unserialize($meta_value);
            if (is_array($unserialized)) {
                return implode(', ', array_filter($unserialized, 'is_string'));
            }
            return $unserialized;
        }
        
        return $meta_value;
    }

    /**
     * Get user display name based on settings
     */
    public static function getUserDisplayName($user_id, $display_type = 'display_name')
    {
        $user = get_user_by('ID', $user_id);
        
        if (!$user) {
            return '';
        }

        switch ($display_type) {
            case 'first_name':
                return $user->first_name ?: $user->display_name;
            case 'last_name':
                return $user->last_name ?: $user->display_name;
            case 'full_name':
                $full_name = trim($user->first_name . ' ' . $user->last_name);
                return $full_name ?: $user->display_name;
            case 'full_name_reverse':
                $full_name = trim($user->last_name . ', ' . $user->first_name);
                return $full_name ?: $user->display_name;
            case 'username':
                return $user->user_login;
            case 'nickname':
                return $user->nickname ?: $user->display_name;
            case 'display_name':
            default:
                return $user->display_name;
        }
    }
} 
