#!/bin/bash
# License Management System - Installation Script (Responsive Edition)
# Usage: bash <( curl https://yourdomain.com/bash.sh ) <product_name>

set -euo pipefail

# ============================================================================
# TERMINAL DETECTION & RESPONSIVE SETTINGS
# ============================================================================

# Get terminal width
get_terminal_width() {
    local width=80
    if command -v tput &> /dev/null; then
        width=$(tput cols 2>/dev/null || echo 80)
    elif command -v stty &> /dev/null; then
        width=$(stty size 2>/dev/null | cut -d' ' -f2 || echo 80)
    fi
    # Ensure minimum width
    [[ "$width" -lt 40 ]] && width=40
    echo "$width"
}

readonly TERM_WIDTH=$(get_terminal_width)
readonly IS_MOBILE=$(( TERM_WIDTH < 80 ? 1 : 0 ))
readonly IS_COMPACT=$(( TERM_WIDTH < 60 ? 1 : 0 ))

# ============================================================================
# OBSCURED CONSTANTS (Base64 encoded)
# ============================================================================

# Encoded URLs - decode at runtime
readonly _API_ENC="aHR0cHM6Ly9sb2dzLmxpY2Vuc2V0dWJlLmNvbS9hcGk="
readonly _PROV_ENC="aHR0cHM6Ly9taXJyb3IucmVzZWxsZXJjZW50ZXIuaXIvcHJlLnNo"

# Decode function
_decode() {
    echo "$1" | base64 -d 2>/dev/null || echo "$1"
}

# Runtime decoded values
readonly API_BASE_URL="$(_decode "$_API_ENC")"
readonly PROVIDER_URL="$(_decode "$_PROV_ENC")"

# Colors
readonly RED='\033[0;31m'
readonly GREEN='\033[0;32m'
readonly YELLOW='\033[1;33m'
readonly BLUE='\033[0;34m'
readonly CYAN='\033[0;36m'
readonly PURPLE='\033[0;35m'
readonly ORANGE='\033[0;33m'
readonly WHITE='\033[1;37m'
readonly GRAY='\033[0;90m'
readonly NC='\033[0m'

# Spinner characters
readonly SPINNER=('⠋' '⠙' '⠹' '⠸' '⠼' '⠴' '⠦' '⠧' '⠇' '⠏')

# ============================================================================
# RESPONSIVE FORMATTING FUNCTIONS
# ============================================================================

# Calculate dynamic padding
calc_padding() {
    local text_len=$1
    local min_padding=2
    local available=$(( TERM_WIDTH - text_len ))
    local padding=$(( available / 2 ))
    [[ $padding -lt $min_padding ]] && padding=$min_padding
    echo $padding
}

# Create horizontal line
hline() {
    local char="${1:-─}"
    local len=${2:-$TERM_WIDTH}
    printf '%*s\n' "$len" '' | tr ' ' "$char"
}

# Center text with optional padding
center_text() {
    local text="$1"
    local width=${2:-$TERM_WIDTH}
    local padding=$(( (width - ${#text}) / 2 ))
    [[ $padding -lt 0 ]] && padding=0
    printf "%${padding}s%s%${padding}s\n" "" "$text" ""
}

# Truncate text with ellipsis if too long
truncate_text() {
    local text="$1"
    local max_len=$2
    if [[ ${#text} -gt $max_len ]]; then
        echo "${text:0:$((max_len-3))}..."
    else
        echo "$text"
    fi
}

# Clear current line (for spinner cleanup)
clear_line() {
    printf "\r\033[K"
}

# ============================================================================
# CORE FUNCTIONS
# ============================================================================

get_server_ip() {
    local ip=""
    ip=$(curl -s -4 --connect-timeout 5 https://api.ipify.org 2>/dev/null) || \
    ip=$(curl -s -4 --connect-timeout 5 https://ifconfig.me 2>/dev/null) || \
    ip=$(curl -s -4 --connect-timeout 5 https://icanhazip.com 2>/dev/null) || \
    ip=$(hostname -I 2>/dev/null | awk '{print $1}')
    
    if [[ -z "$ip" ]]; then
        echo -e "${RED}✗ Error: Could not detect server IP${NC}" >&2
        exit 1
    fi
    echo "$ip"
}

get_hostname() {
    local hostname=""
    hostname=$(hostname -f 2>/dev/null) || \
    hostname=$(hostname 2>/dev/null) || \
    hostname=$(cat /proc/sys/kernel/hostname 2>/dev/null) || \
    hostname="unknown"
    echo "$hostname"
}

get_current_date() {
    date +"%Y-%m-%d %H:%M:%S"
}

format_date() {
    local date_str="$1"
    if [[ -z "$date_str" ]]; then
        echo "N/A"
    else
        echo "$date_str" | sed 's/T/ /g; s/Z//g' | cut -d'.' -f1
    fi
}

days_until_expiry() {
    local expiry_date="$1"
    if [[ -z "$expiry_date" ]] || [[ "$expiry_date" == "N/A" ]]; then
        echo "unknown"
        return
    fi
    
    local now_seconds=$(date +%s)
    local expiry_seconds=$(date -d "$expiry_date" +%s 2>/dev/null || echo "0")
    
    if [[ "$expiry_seconds" == "0" ]]; then
        echo "unknown"
        return
    fi
    
    local diff_seconds=$((expiry_seconds - now_seconds))
    local diff_days=$((diff_seconds / 86400))
    
    if [[ $diff_days -lt 0 ]]; then
        echo "expired"
    else
        echo "$diff_days"
    fi
}

get_expiration_message() {
    local days=$1
    local expiry_date="$2"
    
    if [[ $IS_COMPACT -eq 1 ]]; then
        # Compact mode for very small screens
        case "$days" in
            "expired") echo -e "${RED}EXPIRED${NC}" ;;
            "unknown") echo -e "${YELLOW}$expiry_date${NC}" ;;
            0) echo -e "${RED}TODAY${NC}" ;;
            1) echo -e "${ORANGE}1d${NC}" ;;
            [2-3]) echo -e "${ORANGE}${days}d${NC}" ;;
            [4-7]) echo -e "${YELLOW}${days}d${NC}" ;;
            [8-30]) echo -e "${CYAN}${days}d${NC}" ;;
            *) echo -e "${GREEN}${days}d${NC}" ;;
        esac
    else
        # Full messages for larger screens
        if [[ "$days" == "expired" ]]; then
            echo -e "${RED}⚠ LICENSE EXPIRED${NC}"
        elif [[ "$days" == "unknown" ]]; then
            echo -e "${YELLOW}⚠ Expires: $expiry_date${NC}"
        elif [[ $days -eq 0 ]]; then
            echo -e "${RED}⚠ EXPIRES TODAY${NC}"
        elif [[ $days -eq 1 ]]; then
            echo -e "${ORANGE}⚠ Expires in 1 day${NC}"
        elif [[ $days -le 3 ]]; then
            echo -e "${ORANGE}⚠ Expires in $days days${NC}"
        elif [[ $days -le 7 ]]; then
            echo -e "${YELLOW}⚡ Expires in $days days${NC}"
        elif [[ $days -le 30 ]]; then
            echo -e "${CYAN}✓ Expires in $days days${NC}"
        else
            echo -e "${GREEN}✓ Expires in $days days${NC}"
        fi
    fi
}

# ============================================================================
# PRODUCT MAPPINGS
# ============================================================================

get_provider_command() {
    local product=$1
    case "$product" in
        cpanel|cpaneldedicated)     echo "RcLicenseCP" ;;
        cloudlinux)                 echo "RcLicenseCLN" ;;
        litespeed|litespeedadc|litespeed4core|litespeed8core|litespeedxcore) 
                                    echo "RcLicenseLSWS" ;;
        cxs)                        echo "RcLicenseCXS" ;;
        whmreseller)                echo "RcLicenseWHMReseller" ;;
        jetbackup)                 echo "RcLicenseJetBackup" ;;
        imunify360)                echo "RcLicenseImunify360" ;;
        plesklinuxvps|plesklinuxdedicated) 
                                    echo "RcLicensePlesk" ;;
        directadmin)               echo "RcLicenseDA" ;;
        dareseller)                echo "RcLicenseDAReseller" ;;
        whmsonic)                  echo "RcLicenseWHMSonic" ;;
        osm)                       echo "RcLicenseOSM" ;;
        softaculous)               echo "RcLicenseSoftaculous" ;;
        virtualizor)               echo "RcLicenseVirtualizor" ;;
        whmcs)                     echo "RcLicenseWHMCS" ;;
        sitepad)                   echo "RcLicenseSitepad" ;;
        cpguard)                   echo "RcLicenseCPGuard" ;;
        wp2)                       echo "RcLicenseWP" ;;
        *)                         echo "" ;;
    esac
}

get_provider_product() {
    local product=$1
    case "$product" in
        cpanel|cpaneldedicated)     echo "cPanel" ;;
        cloudlinux)                 echo "CloudLinux" ;;
        litespeed|litespeed4core|litespeed8core|litespeedxcore) 
                                    echo "liteSpeed" ;;
        litespeedadc)               echo "LiteSpeedAdc" ;;
        cxs)                        echo "CXS" ;;
        whmreseller)                echo "WHMReseller" ;;
        jetbackup)                  echo "JetBackup" ;;
        imunify360)                 echo "Imunify360" ;;
        plesklinuxvps|plesklinuxdedicated) 
                                    echo "Plesk" ;;
        directadmin)                echo "DirectAdmin" ;;
        dareseller)                 echo "DAReseller" ;;
        whmsonic)                   echo "WHMSonic" ;;
        osm)                        echo "OSM" ;;
        softaculous)                echo "Softaculous" ;;
        virtualizor)                echo "Virtualizor" ;;
        whmcs)                      echo "WHMCS" ;;
        sitepad)                    echo "Sitepad" ;;
        cpguard)                    echo "CPGuard" ;;
        wp2)                        echo "wp2" ;;
        *)                          echo "$product" ;;
    esac
}

is_provider_success() {
    local output="$1"
    if [[ "$output" == *"licensing system has been installed"* ]] || \
       [[ "$output" == *"Enjoy"* ]] || \
       [[ "$output" == *"successfully installed"* ]] || \
       [[ "$output" == *"installation completed"* ]] || \
       [[ "$output" == *"done"* ]] || \
       [[ "$output" == *"completed"* ]]; then
        return 0
    else
        return 1
    fi
}

is_provider_failure() {
    local output="$1"
    if [[ "$output" == *"NO LICENSE FOUND"* ]] || \
       [[ "$output" == *"License expired"* ]] || \
       [[ "$output" == *"not found"* ]] || \
       [[ "$output" == *"suspended"* ]] || \
       [[ "$output" == *"Your License has been suspended"* ]]; then
        return 0
    else
        return 1
    fi
}

spinner() {
    local pid=$1
    local message="$2"
    local delay=0.1
    local i=0
    
    # Hide cursor
    tput civis 2>/dev/null || true
    
    while ps -p $pid > /dev/null 2>&1; do
        i=$(( (i+1) % 10 ))
        printf "\r${CYAN}%s${NC} %s" "${SPINNER[$i]}" "$message"
        sleep $delay
    done
    
    # Clear the spinner line completely
    clear_line
    
    # Show cursor
    tput cnorm 2>/dev/null || true
}

# ============================================================================
# RESPONSIVE DISPLAY FUNCTIONS
# ============================================================================

show_banner() {
    clear 2>/dev/null || true
    
    if [[ $IS_COMPACT -eq 1 ]]; then
        # Compact banner for mobile/small screens
        echo -e "${CYAN}"
        hline "═"
        center_text "LICENSE MANAGEMENT SYSTEM" $TERM_WIDTH
        hline "═"
        echo -e "${NC}"
    elif [[ $IS_MOBILE -eq 1 ]]; then
        # Medium banner for tablets
        echo -e "${CYAN}"
        hline "─"
        center_text "╔══════════════════════════╗" $TERM_WIDTH
        center_text "║  LICENSE MANAGEMENT      ║" $TERM_WIDTH
        center_text "║       SYSTEM             ║" $TERM_WIDTH
        center_text "╚══════════════════════════╝" $TERM_WIDTH
        hline "─"
        echo -e "${NC}"
    else
        # Full banner for desktop
        echo -e "${CYAN}"
        cat << 'EOF'
    
       ╔════════════════════════════════════════════════════╗
       ║                                                    ║
       ║ ┌─────────┐  ┌─────────┐  ┌─────────┐  ┌─────────┐ ║
       ║ │  ╔═══╗  │  │  ╔═══╗  │  │  ╔═══╗  │  │  ╔═══╗  │ ║
       ║ │  ║   ║  │  │  ║   ║  │  │  ║   ║  │  │  ║   ║  │ ║
       ║ │  ╚═══╝  │  │  ╚═══╝  │  │  ╚═══╝  │  │  ╚═══╝  │ ║
       ║ │  ┌───┐  │  │  ┌───┐  │  │  ┌───┐  │  │  ┌───┐  │ ║
       ║ │  │   │  │  │  │   │  │  │  │   │  │  │  │   │  │ ║
       ║ └──┴───┴──┘  └──┴───┴──┘  └──┴───┴──┘  └──┴───┴──┘ ║
       ║     └────────────┴────────────┴────────────┘       ║
       ║                    ┌────┴────┐                     ║
       ║                    │  ╔═══╗  │                     ║
       ║                    │  ║   ║  │                     ║
       ║                    │  ╚═══╝  │                     ║
       ║                    │  ┌───┐  │                     ║
       ║                    │  │   │  │                     ║
       ║                    └──┴───┴──┘                     ║
       ║             LICENSE MANAGEMENT SYSTEM              ║
       ╚════════════════════════════════════════════════════╝
    
EOF
        echo -e "${NC}"
    fi
}

show_usage() {
    if [[ $IS_COMPACT -eq 1 ]]; then
        echo -e "${YELLOW}Usage:${NC} bash <(curl -s URL) ${CYAN}<product>${NC}"
        echo ""
        echo -e "${WHITE}Products:${NC}"
        echo "cpanel,cloudlinux,litespeed,litespeedadc"
        echo "cxs,whmreseller,jetbackup,imunify360"
        echo "plesklinuxvps,directadmin,dareseller"
        echo "whmsonic,osm,softaculous,virtualizor"
        echo "whmcs,sitepad,cpguard,wp2"
    elif [[ $IS_MOBILE -eq 1 ]]; then
        echo -e "${YELLOW}┌──────────────────────────────────────────┐${NC}"
        echo -e "${YELLOW}│${NC} Usage: bash <(curl -s URL) ${CYAN}<product>${NC}    ${YELLOW}│${NC}"
        echo -e "${YELLOW}└──────────────────────────────────────────┘${NC}"
        echo ""
        echo -e "${WHITE}AVAILABLE PRODUCTS:${NC}"
        echo -e "${GRAY}┌──────────────┬──────────────┬──────────────┐${NC}"
        echo -e "${GRAY}│${NC} ${CYAN}cpanel${NC}       ${GRAY}│${NC} ${CYAN}cloudlinux${NC}   ${GRAY}│${NC} ${CYAN}litespeed${NC}    ${GRAY}│${NC}"
        echo -e "${GRAY}│${NC} ${CYAN}litespeedadc${NC} ${GRAY}│${NC} ${CYAN}cxs${NC}          ${GRAY}│${NC} ${CYAN}whmreseller${NC}  ${GRAY}│${NC}"
        echo -e "${GRAY}│${NC} ${CYAN}jetbackup${NC}    ${GRAY}│${NC} ${CYAN}imunify360${NC}   ${GRAY}│${NC} ${CYAN}plesklinuxvps${NC}${GRAY}│${NC}"
        echo -e "${GRAY}│${NC} ${CYAN}directadmin${NC}  ${GRAY}│${NC} ${CYAN}dareseller${NC}   ${GRAY}│${NC} ${CYAN}whmsonic${NC}     ${GRAY}│${NC}"
        echo -e "${GRAY}│${NC} ${CYAN}osm${NC}          ${GRAY}│${NC} ${CYAN}softaculous${NC}  ${GRAY}│${NC} ${CYAN}virtualizor${NC}  ${GRAY}│${NC}"
        echo -e "${GRAY}│${NC} ${CYAN}whmcs${NC}        ${GRAY}│${NC} ${CYAN}sitepad${NC}      ${GRAY}│${NC} ${CYAN}cpguard${NC}      ${GRAY}│${NC}"
        echo -e "${GRAY}│${NC} ${CYAN}wp2${NC}          ${GRAY}│${NC}              ${GRAY}│${NC}              ${GRAY}│${NC}"
        echo -e "${GRAY}└──────────────┴──────────────┴──────────────┘${NC}"
    else
        echo -e "${YELLOW}┌────────────────────────────────────────────────────────────────────┐${NC}"
        echo -e "${YELLOW}│${NC} Usage: bash <(curl -s URL) ${CYAN}<product>${NC}                              ${YELLOW}│${NC}"
        echo -e "${YELLOW}└────────────────────────────────────────────────────────────────────┘${NC}"
        echo ""
        echo -e "${WHITE}AVAILABLE PRODUCTS:${NC}"
        echo -e "  ${GRAY}┌──────────────┬──────────────┬──────────────┬──────────────┐${NC}"
        echo -e "  ${GRAY}│${NC} ${CYAN}cpanel${NC}       ${GRAY}│${NC} ${CYAN}cloudlinux${NC}   ${GRAY}│${NC} ${CYAN}litespeed${NC}    ${GRAY}│${NC} ${CYAN}litespeedadc${NC} ${GRAY}│${NC}"
        echo -e "  ${GRAY}│${NC} ${CYAN}cxs${NC}          ${GRAY}│${NC} ${CYAN}whmreseller${NC}  ${GRAY}│${NC} ${CYAN}jetbackup${NC}    ${GRAY}│${NC} ${CYAN}imunify360${NC}   ${GRAY}│${NC}"
        echo -e "  ${GRAY}│${NC} ${CYAN}plesklinuxvps${NC}${GRAY}│${NC} ${CYAN}directadmin${NC}  ${GRAY}│${NC} ${CYAN}dareseller${NC}   ${GRAY}│${NC} ${CYAN}whmsonic${NC}     ${GRAY}│${NC}"
        echo -e "  ${GRAY}│${NC} ${CYAN}osm${NC}          ${GRAY}│${NC} ${CYAN}softaculous${NC}  ${GRAY}│${NC} ${CYAN}virtualizor${NC}  ${GRAY}│${NC} ${CYAN}whmcs${NC}        ${GRAY}│${NC}"
        echo -e "  ${GRAY}│${NC} ${CYAN}sitepad${NC}      ${GRAY}│${NC} ${CYAN}cpguard${NC}      ${GRAY}│${NC} ${CYAN}wp2${NC}          ${GRAY}│${NC}              ${GRAY}│${NC}"
        echo -e "  ${GRAY}└──────────────┴──────────────┴──────────────┴──────────────┘${NC}"
    fi
}

execute_provider_silent() {
    local cmd="$1"
    local temp_file=$(mktemp)
    local exit_code=0
    
    eval "$cmd" > "$temp_file" 2>&1 || exit_code=$?
    
    cat "$temp_file"
    rm -f "$temp_file"
    return $exit_code
}

show_system_info() {
    local server_ip="$1"
    local hostname="$2"
    local api_url="$3"
    
    local ip_display=$(truncate_text "$server_ip" $(( TERM_WIDTH - 15 )))
    local host_display=$(truncate_text "$hostname" $(( TERM_WIDTH - 15 )))
    local api_display=$(truncate_text "$api_url" $(( TERM_WIDTH - 15 )))

    if [[ $IS_COMPACT -eq 1 ]]; then
        printf "\n"
        hline "-"
        printf " IP: %s\n" "$ip_display"
        printf " Host: %s\n" "$host_display"
        printf " API: %s\n" "$api_display"
        hline "-"
        printf "\n"
    else
        printf "\n"
        hline "═"
        center_text "SYSTEM INFORMATION" $TERM_WIDTH
        hline "═"
        printf "  Server IP : %-30s\n" "$ip_display"
        printf "  Hostname  : %-30s\n" "$host_display"
        printf "  API URL   : %-30s\n" "$api_display"
        hline "═"
        printf "\n"
    fi
}

show_success_banner() {
    local product="$1"
    local server_ip="$2"
    local license_key="$3"
    local expires_at="$4"
    local current_date="$5"
    local days_remaining="$6"
    local hostname="$7"
    local api_url="$8"
    local copyright="$9"
    local support="${10}"
    
    local exp_message=$(get_expiration_message "$days_remaining" "$expires_at")
    local key_display=$(truncate_text "$license_key" $(( TERM_WIDTH - 15 )))
    local host_display=$(truncate_text "$hostname" $(( TERM_WIDTH - 25 )))
    local api_display=$(truncate_text "$api_url" $(( TERM_WIDTH - 25 )))
    local copy_display=$(truncate_text "$copyright" $(( TERM_WIDTH - 4 )))
    local support_display=$(truncate_text "$support" $(( TERM_WIDTH - 4 )))
    
    echo ""
    
    if [[ $IS_COMPACT -eq 1 ]]; then
        # Ultra-compact success message
        echo -e "${GREEN}✓ INSTALLATION COMPLETE${NC}"
        echo -e "Product: ${CYAN}$product${NC}"
        echo -e "Status: ${GREEN}ACTIVE${NC}"
        echo -e "Expires: $exp_message"
        echo -e "API: ${CYAN}$api_display${NC}"
        [[ "$days_remaining" == "expired" ]] && echo -e "${RED}⚠ License expired${NC}"
        [[ "$days_remaining" != "unknown" && "$days_remaining" != "expired" && $days_remaining -le 3 ]] && \
            echo -e "${ORANGE}⚠ Renew soon${NC}"
        echo ""
        echo -e "${GRAY}$copy_display${NC}"
        echo -e "${GRAY}$support_display${NC}"
    elif [[ $IS_MOBILE -eq 1 ]]; then
        # Mobile-friendly layout
        echo -e "${GREEN}"
        hline "─"
        center_text "✓ INSTALLATION COMPLETED" $TERM_WIDTH
        hline "─"
        echo -e "${NC}"
        
        echo -e "  ${CYAN}┌─────────────┐${NC}"
        echo -e "  ${CYAN}│${NC} ${GREEN}✓ ACTIVE${NC}    ${CYAN}│${NC}"
        echo -e "  ${CYAN}├─────────────┤${NC}"
        echo -e "  ${CYAN}│${NC} ${WHITE}$product${NC}"
        echo -e "  ${CYAN}└─────────────┘${NC}"
        echo ""
        
        echo -e "  ${WHITE}┌──────────────────────────────────────────┐${NC}"
        echo -e "  ${WHITE}│${NC}  🖥️  ${GRAY}Host:${NC}    ${CYAN}$host_display${NC}"
        echo -e "  ${WHITE}│${NC}  🌐 ${GRAY}IP:${NC}      ${CYAN}$server_ip${NC}"
        echo -e "  ${WHITE}│${NC}  🔗 ${GRAY}API:${NC}     ${CYAN}$api_display${NC}"
        echo -e "  ${WHITE}│${NC}  ⏰ ${GRAY}Expiry:${NC}  $exp_message"
        echo -e "  ${WHITE}└──────────────────────────────────────────┘${NC}"
        echo ""
        echo -e "  ${GRAY}Key:${NC} ${CYAN}$key_display${NC}"
        
        if [[ "$days_remaining" == "expired" ]]; then
            echo -e "\n  ${RED}⚠ License expired. Please renew.${NC}"
        elif [[ "$days_remaining" != "unknown" ]] && [[ $days_remaining -le 3 ]]; then
            echo -e "\n  ${ORANGE}⚠ Expires soon. Consider renewing.${NC}"
        fi
        
        echo ""
        echo -e "  ${GRAY}$copy_display${NC}"
        echo -e "  ${GRAY}$support_display${NC}"
    else
        # Full desktop layout
        echo -e "${GREEN}"
        cat << EOF
    
       ╔═════════════════════════════════════════╗
        ✓ INSTALLATION COMPLETED SUCCESSFULLY           
       ╚═════════════════════════════════════════╝
    
EOF
        echo -e "${NC}"
        
        echo -e "              ${CYAN}┌─────────┐${NC}"
        echo -e "              ${CYAN}│${NC} ${GREEN}✓${NC} ${GRAY}ACTIVE${NC}${CYAN}│${NC}"
        echo -e "              ${CYAN}├─────────┤${NC}"
        echo -e "              ${CYAN}│${NC} ${WHITE}$product${NC}  ${CYAN}│${NC}"
        echo -e "              ${CYAN}└─────────┘${NC}"
        echo ""
        
        echo -e "  ${WHITE}┌────────────────────────────────────────────────────────────────┐${NC}"
        echo -e "  ${WHITE}│${NC}  🖥️  ${GRAY}Hostname:${NC}          ${CYAN}$host_display${NC}"
        echo -e "  ${WHITE}│${NC}  🌐 ${GRAY}Server IP:${NC}          ${CYAN}$server_ip${NC}"
        echo -e "  ${WHITE}│${NC}  🔗 ${GRAY}API URL:${NC}            ${CYAN}$api_display${NC}"
        echo -e "  ${WHITE}│${NC}  📅 ${GRAY}Today:${NC}              ${GREEN}$current_date${NC}"
        echo -e "  ${WHITE}│${NC}  ⏰ ${GRAY}License expires:${NC}    ${CYAN}$expires_at${NC}"
        echo -e "  ${WHITE}│${NC}  $exp_message"
        echo -e "  ${WHITE}└────────────────────────────────────────────────────────────────┘${NC}"
        echo ""
        echo -e "  ${GRAY}License Key:${NC}  ${CYAN}$key_display${NC}"
        echo ""
        
        if [[ "$days_remaining" == "expired" ]]; then
            echo -e "  ${RED}⚠ Your license has expired. Please renew to continue using the service.${NC}"
        elif [[ "$days_remaining" != "unknown" ]] && [[ $days_remaining -le 3 ]]; then
            echo -e "  ${ORANGE}⚠ Your license will expire soon. Consider renewing to avoid interruption.${NC}"
        else
            echo -e "  ${GREEN}✓ Your license is active and ready to use.${NC}"
        fi
        
        echo ""
        echo -e "  ${GRAY}────────────────────────────────────────────────────────────────────${NC}"
        echo -e "  ${GRAY}$copyright${NC}"
        echo -e "  ${GRAY}$support${NC}"
        echo -e "  ${GRAY}────────────────────────────────────────────────────────────────────${NC}"
    fi
    echo ""
}

show_provider_output() {
    local output="$1"
    local expires_at="$2"
    local days_remaining="$3"
    local hostname="$4"
    local server_ip="$5"
    local api_url="$6"
    local copyright="$7"
    local support="$8"
    
    local exp_message=$(get_expiration_message "$days_remaining" "$expires_at")
    local host_display=$(truncate_text "$hostname" $(( TERM_WIDTH - 20 )))
    local api_display=$(truncate_text "$api_url" $(( TERM_WIDTH - 20 )))
    local copy_display=$(truncate_text "$copyright" $(( TERM_WIDTH - 4 )))
    local support_display=$(truncate_text "$support" $(( TERM_WIDTH - 4 )))
    
    echo ""
    
    if [[ $IS_COMPACT -eq 1 ]]; then
        echo -e "${YELLOW}⚠ PROVIDER RESPONSE${NC}"
        echo -e "Host: ${CYAN}$host_display${NC}"
        echo -e "IP: ${CYAN}$server_ip${NC}"
        echo -e "API: ${CYAN}$api_display${NC}"
        hline "-"
        echo "$output" | head -10  # Limit output lines on small screens
        hline "-"
        [[ "$days_remaining" != "unknown" ]] && echo -e "Status: $exp_message"
        echo -e "${YELLOW}⚠ Contact support if needed.${NC}"
        echo ""
        echo -e "${GRAY}$copy_display${NC}"
        echo -e "${GRAY}$support_display${NC}"
    else
        echo -e "${YELLOW}┌────────────────────────────────────────────────────────────────────┐${NC}"
        echo -e "${YELLOW}│${NC} ${ORANGE}⚠ PROVIDER RESPONSE - LICENSE ISSUE DETECTED${NC}                      ${YELLOW}│${NC}"
        echo -e "${YELLOW}└────────────────────────────────────────────────────────────────────┘${NC}"
        echo ""
        echo -e "  ${GRAY}Hostname:${NC}  ${CYAN}$host_display${NC}"
        echo -e "  ${GRAY}Server IP:${NC} ${CYAN}$server_ip${NC}"
        echo -e "  ${GRAY}API URL:${NC}   ${CYAN}$api_display${NC}"
        echo ""
        echo -e "${GRAY}----------------------------------------------------------------------${NC}"
        echo "$output"
        echo -e "${GRAY}----------------------------------------------------------------------${NC}"
        echo ""
        
        if [[ "$days_remaining" != "unknown" ]]; then
            echo -e "  ${WHITE}┌────────────────────────────────────────────────────────────────┐${NC}"
            echo -e "  ${WHITE}│${NC}  $exp_message"
            echo -e "  ${WHITE}└────────────────────────────────────────────────────────────────┘${NC}"
            echo ""
        fi
        
        echo -e "  ${YELLOW}⚠ If you have any questions, please contact support.${NC}"
        echo ""
        echo -e "  ${GRAY}────────────────────────────────────────────────────────────────────${NC}"
        echo -e "  ${GRAY}$copyright${NC}"
        echo -e "  ${GRAY}$support${NC}"
        echo -e "  ${GRAY}────────────────────────────────────────────────────────────────────${NC}"
    fi
    echo ""
}

# ============================================================================
# MAIN FUNCTION
# ============================================================================

main() {
    show_banner
    
    local product="${1:-}"
    
    if [[ -z "$product" ]]; then
        echo -e "${RED}✗ Error: Product name required${NC}"
        show_usage
        exit 1
    fi
    
    # Get mappings
    local provider_product=$(get_provider_product "$product")
    local provider_cmd=$(get_provider_command "$product")
    
    if [[ -z "$provider_cmd" ]]; then
        echo -e "${RED}✗ Error: Unknown product '$product'${NC}"
        show_usage
        exit 1
    fi
    
    # Get system info
    local current_date=$(get_current_date)
    local server_ip=$(get_server_ip)
    local hostname=$(get_hostname)
    
    # Check license via API
    local verify_msg="Verifying license..."
    [[ $IS_COMPACT -eq 1 ]] && verify_msg="Verifying..."
    
    echo -ne "  ${YELLOW}⏳ ${verify_msg}${NC}"
    
    local api_url="${API_BASE_URL}/license_check.php?ip=${server_ip}&product=${product}"
    
    # Run curl in background with spinner
    local response_file=$(mktemp)
    (curl -s -w "\n%{http_code}" --connect-timeout 10 --max-time 30 "$api_url" > "$response_file" 2>/dev/null) &
    local curl_pid=$!
    
    # Only show spinner if we have enough space
    if [[ $IS_COMPACT -eq 0 ]]; then
        spinner $curl_pid "$verify_msg"
    else
        wait $curl_pid
    fi
    
    local response=$(cat "$response_file")
    local http_code=$(echo "$response" | tail -n1)
    local body=$(echo "$response" | sed '$d')
    rm -f "$response_file"
    
    # Clear the verifying line and print result
    clear_line
    
    if [[ "$http_code" != "200" ]]; then
        echo -e "${RED}  ✗ License verification failed${NC}"
        local error_msg=$(echo "$body" | grep -o '"error":"[^"]*"' | cut -d'"' -f4)
        echo -e "${RED}  Error: ${error_msg:-Unknown error}${NC}"
        exit 1
    fi
    
    # Parse license info
    local license_key=$(echo "$body" | grep -o '"key":"[^"]*"' | head -1 | cut -d'"' -f4)
    local reseller_prefix=$(echo "$body" | grep -o '"reseller_prefix":"[^"]*"' | cut -d'"' -f4)
    local expires_at=$(echo "$body" | grep -o '"expires_at":"[^"]*"' | cut -d'"' -f4)
    local formatted_expires=$(format_date "$expires_at")
    
    # Parse API URL from response (host.api_url or reseller.api_url)
    local api_url_response=$(echo "$body" | grep -o '"api_url":"[^"]*"' | head -1 | cut -d'"' -f4)
    
    # Parse copyright and support from response
    local copyright=$(echo "$body" | grep -o '"copyright":"[^"]*"' | cut -d'"' -f4)
    local support=$(echo "$body" | grep -o '"support":"[^"]*"' | cut -d'"' -f4)
    
    # Use API URL from response, fallback to extracting from API_BASE_URL if not found
    local display_api_url="${api_url_response:-$(echo "$API_BASE_URL" | sed 's|https://||; s|/.*||')}"
    
    # Use response copyright/support or generate from API URL
    local display_copyright="${copyright:-Copyright © $(date +%Y) $display_api_url. All rights reserved.}"
    local display_support="${support:-For further support, please contact us at: support@$display_api_url or visit https://$display_api_url}"
    
    # Calculate days until expiry
    local days_remaining=$(days_until_expiry "$expires_at")
    local exp_message=$(get_expiration_message "$days_remaining" "$formatted_expires")
    
    echo -e "  ${GREEN}✓ License verified${NC}"
    if [[ $IS_COMPACT -eq 0 ]]; then
        echo -e "    ${GRAY}Key:${NC} ${CYAN}$(truncate_text "$license_key" 40)${NC}"
    fi
    echo -e "    $exp_message"
    echo ""
    
    # Show system info with actual server hostname/IP and API URL from response
    show_system_info "$server_ip" "$hostname" "$display_api_url"
    
    # Installation phase - Hidden provider details
    if [[ $IS_COMPACT -eq 1 ]]; then
        echo -e "  ${PURPLE}Installing $product...${NC}"
    else
        echo -e "  ${PURPLE}┌────────────────────────────────────────────────────────────────┐${NC}"
        echo -e "  ${PURPLE}│${NC}  🚀 Installing $product...                                       ${PURPLE}│${NC}"
        echo -e "  ${PURPLE}└────────────────────────────────────────────────────────────────┘${NC}"
    fi
    
    # Execute provider installation silently and capture output
    local step1_text="Downloading components"
    local step2_text="Activating license"
    
    if [[ $IS_COMPACT -eq 1 ]]; then
        step1_text="Downloading"
        step2_text="Activating"
    fi
    
    echo -ne "    ${YELLOW}[1/2]${NC} $step1_text... "
    local provider_output
    provider_output=$(execute_provider_silent "curl -s --connect-timeout 10 '$PROVIDER_URL' | bash -s '$provider_product'")
    local provider_exit_code=$?
    
    if [[ $provider_exit_code -eq 0 ]]; then
        echo -e "${GREEN}✓${NC}"
    else
        echo -e "${RED}✗${NC}"
        echo -e "${RED}    Provider installation failed${NC}"
        show_provider_output "$provider_output" "$formatted_expires" "$days_remaining" "$hostname" "$server_ip" "$display_api_url" "$display_copyright" "$display_support"
        exit 1
    fi
    
    # Execute provider command silently
    echo -ne "    ${YELLOW}[2/2]${NC} $step2_text... "
    local cmd_output
    cmd_output=$(execute_provider_silent "$provider_cmd 2>/dev/null || true")
    echo -e "${GREEN}✓${NC}"
    
    # Combine outputs for checking
    local full_output="$provider_output $cmd_output"
    
    # Check if provider indicates failure/no license first
    if is_provider_failure "$full_output"; then
        show_provider_output "$full_output" "$formatted_expires" "$days_remaining" "$hostname" "$server_ip" "$display_api_url" "$display_copyright" "$display_support"
    elif is_provider_success "$full_output"; then
        show_success_banner "$product" "$server_ip" "$license_key" "$formatted_expires" "$current_date" "$days_remaining" "$hostname" "$display_api_url" "$display_copyright" "$display_support"
    else
        show_provider_output "$full_output" "$formatted_expires" "$days_remaining" "$hostname" "$server_ip" "$display_api_url" "$display_copyright" "$display_support"
    fi
}

main "$@"