<?php
/**
 * Client Display Helper
 *
 * @package     EasyInvoice
 * @subpackage  Helpers
 * @since       2.0.0
 */

namespace EasyInvoice\Helpers;

/**
 * Helper class for displaying client information with fallback logic
 */
class ClientDisplayHelper {
    
    /**
     * Get display name for client with fallback logic
     * 
     * Priority: business_client_name > first_name + last_name > display_name
     * 
     * @param int $client_id WordPress user ID
     * @return string Client display name
     */
    public static function getClientDisplayName(int $client_id): string {
        if ($client_id <= 0) {
            return '';
        }
        
        $user = get_user_by('id', $client_id);
        if (!$user) {
            return '';
        }
        
        // First priority: Business/Client Name
        $business_name = get_user_meta($client_id, 'easy_invoice_business_client_name', true);
        if (!empty($business_name)) {
            return $business_name;
        }
        
        // Second priority: First Name + Last Name
        $first_name = get_user_meta($client_id, 'first_name', true);
        $last_name = get_user_meta($client_id, 'last_name', true);
        
        if (!empty($first_name) || !empty($last_name)) {
            $full_name = trim($first_name . ' ' . $last_name);
            if (!empty($full_name)) {
                return $full_name;
            }
        }
        
        // Third priority: WordPress display name
        if (!empty($user->display_name)) {
            return $user->display_name;
        }
        
        // Last resort: Username
        return $user->user_login;
    }
    
    /**
     * Get client display name for invoice or quote
     * 
     * @param \EasyInvoice\Models\Invoice|\EasyInvoice\Models\Quote $document
     * @return string Client display name
     */
    public static function getDocumentClientDisplayName($document): string {
        if (!$document) {
            return '';
        }
        
        // Try to get customer name directly from document
        if (method_exists($document, 'getCustomerName')) {
            $customer_name = $document->getCustomerName();
            if (!empty($customer_name)) {
                return $customer_name;
            }
        }
        
        // Fallback to client ID lookup
        if (method_exists($document, 'getClientId')) {
            $client_id = $document->getClientId();
            if ($client_id > 0) {
                return self::getClientDisplayName($client_id);
            }
        }
        
        return '';
    }
}
