#!/bin/bash
# ==========================================
#  PREMIUM RENEW VLESS (FIXED ALIGNMENT)
#  MODIFIED BY GEMINI AI
# ==========================================

# --- CONFIG COLORS & SYMBOLS ---
R='\033[0m'             # Reset
P='\033[1;37m'          # Putih
M='\033[1;31m'          # Merah
H='\033[1;32m'          # Hijau
K='\033[1;33m'          # Kuning
C='\033[1;36m'          # Cyan
Kedip='\033[5m'         # Efek Kedip

# Background Blocks
BG_M='\033[41m\033[1;37m' # Merah Block
BG_G='\033[42m\033[1;37m' # Hijau Block
BG_K='\033[43m\033[1;30m' # Kuning Block

# --- CONFIG LAYOUT (LEBAR TOTAL 55 KARAKTER) ---
ki="${C}│${R}"
ka="${C}│${R}"
Garis="${C}───────────────────────────────────────────────────────${R}"
Atas="${C}┌$Garis┐${R}"
Tengah="${C}├$Garis┤${R}"
Bawah="${C}└$Garis┘${R}"

# --- SYSTEM CHECK ---
# Pattern VLESS (#&)
GREP_PATTERN="^#&"
CONFIG_FILE="/etc/xray/config.json"

# ==========================================
#  LOOPING UTAMA
# ==========================================
while true; do
    clear
    echo -e ""
    echo -e "           ${Kedip}${K}🔄  RENEW VLESS ACCOUNT 🔄${R}"
    echo -e ""

    # --- 1. AMBIL DATA USER KE ARRAY ---
    mapfile -t user_list < <(grep -E "$GREP_PATTERN " "$CONFIG_FILE" | cut -d ' ' -f 2 | sort | uniq)
    total_client=${#user_list[@]}

    # --- CEK JIKA KOSONG ---
    if [[ ${total_client} == '0' ]]; then
        echo -e "$Atas"
        echo -e "$ki${BG_M}                   NO CLIENT DATA                    ${R}$ka"
        echo -e "$Tengah"
        printf "$ki ${M}%-53s${R}$ka\n" "You have no existing clients!"
        echo -e "$Bawah"
        echo ""
        read -n 1 -s -r -p " Press any key to back on menu"
        menu
        break
    fi

    # --- 2. TAMPILKAN LIST USER ---
    echo -e "$Atas"
    echo -e "$ki${BG_K}                    LIST VLESS USER                    ${R}$ka"
    echo -e "$Tengah"
    
    # Header Kolom (Total 55)
    printf "$ki ${P}%-4s %-20s %-12s %-15s${R}$ka\n" "NO" "USER" "EXPIRED" "STATUS"
    echo -e "$Tengah"

    no=1
    now_sec=$(date +%s)

    for user in "${user_list[@]}"; do
        # Ambil tanggal expired
        exp=$(grep -wE "$GREP_PATTERN $user" "$CONFIG_FILE" | cut -d ' ' -f 3 | sort | uniq)
        
        # --- LOGIKA HITUNG HARI ---
        exp_sec=$(date -d "$exp" +%s)
        diff=$(( (exp_sec - now_sec) / 86400 ))
        
        # Pisahkan Warna dan Teks
        if [[ $diff -ge 1 ]]; then
            sts_color="${Kedip}${H}"
            sts_text="${diff} Days"
        elif [[ $diff -eq 0 ]]; then
            sts_color="${K}"
            sts_text="Today"
        else
            sts_color="${M}"
            sts_text="Expired"
        fi

        # Print Baris Tabel (Presisi 55 Karakter)
        printf "$ki ${C}%-4s ${P}%-20s ${K}%-12s ${sts_color}%-15s${R}$ka\n" "$no)" "$user" "$exp" "$sts_text"
        ((no++))
    done
    
    # --- MENU KEMBALI ---
    echo -e "$Tengah"
    printf "$ki  ${M}%-53s${R}$ka\n" "0)  BACK TO MAIN MENU"
    echo -e "$Bawah"
    echo -e ""
    echo -e " ${P}Select user to renew (Number/Name)${R}"
    echo -e " ${C}───────────────────────────────────────────────────────${R}"

    # --- 3. INPUT USER ---
    echo -ne " ${C}➤ Select User : ${P}"
    read selection

    if [ -z "$selection" ]; then continue; fi
    if [[ "$selection" == "0" ]]; then menu; break; fi

    if [[ $selection =~ ^[0-9]+$ ]]; then
        if [[ $selection -ge 1 && $selection -le $total_client ]]; then
            user="${user_list[$((selection-1))]}"
        else
            echo -e " ${M}[!] Error: Number out of range!${R}"; sleep 1; continue
        fi
    else
        user="$selection"
        if ! grep -qws "$GREP_PATTERN $user" "$CONFIG_FILE"; then
            echo -e " ${M}[!] Error: Username not found!${R}"; sleep 1; continue
        fi
    fi

    # --- 4. INPUT DATA RENEW ---
    echo -e ""
    echo -e " ${P}Input New Configuration for: ${H}$user${R}"
    
    # Input Hari
    echo -ne " ${C}➤ Renew Duration (Days) : ${P}"
    read masaaktif
    if [[ ! $masaaktif =~ ^[0-9]+$ ]]; then
        echo -e " ${M}[!] Error: Input must be a number!${R}"; sleep 1; continue
    fi

    # Input Quota & IP (Fitur Vless)
    echo -ne " ${C}➤ Limit Quota (GB)      : ${P}"
    read Quota
    if [ -z ${Quota} ]; then Quota="0"; fi

    echo -ne " ${C}➤ Limit IP Address      : ${P}"
    read iplim
    if [ -z ${iplim} ]; then iplim="0"; fi

    # --- 5. PROSES UPDATE LIMIT ---
    # Hapus file lama
    rm -f /etc/kyt/limit/vless/ip/${user}
    rm -f /etc/vless/$user

    # Buat Limit IP Baru
    mkdir -p /etc/kyt/limit/vless/ip
    echo ${iplim} >> /etc/kyt/limit/vless/ip/${user}

    # Buat Limit Quota Baru
    if [ ! -e /etc/vless/ ]; then mkdir -p /etc/vless/; fi
    c=$(echo "${Quota}" | sed 's/[^0-9]*//g')
    d=$((${c} * 1024 * 1024 * 1024))
    if [[ ${c} != "0" ]]; then
        echo "${d}" >/etc/vless/${user}
    fi

    # --- 6. PROSES KALKULASI TANGGAL ---
    exp_old=$(grep -wE "$GREP_PATTERN $user" "$CONFIG_FILE" | cut -d ' ' -f 3 | sort | uniq)
    now=$(date +%Y-%m-%d)
    d1=$(date -d "$exp_old" +%s)
    d2=$(date -d "$now" +%s)

    # Smart Calculation
    if [[ $d1 -ge $d2 ]]; then
        exp_new=$(date -d "$exp_old + $masaaktif days" +"%Y-%m-%d")
    else
        exp_new=$(date -d "$now + $masaaktif days" +"%Y-%m-%d")
    fi

    # --- 7. EKSEKUSI UPDATE ---
    # Update Config Utama
    sed -i "/^#& $user/c\#& $user $exp_new" "$CONFIG_FILE"
    
    # Update Config Backup (Sesuai script asli Anda: .vless.conf)
    # Jika di VPS Anda menggunakan .vless.db, ganti baris bawah ini
    sed -i "/^#& $user/c\#& $user $exp_new" /root/akun/vless/.vless.conf 2>/dev/null
    
    systemctl restart xray > /dev/null 2>&1

    # --- 8. TAMPILAN SUKSES ---
    clear
    echo -e ""
    echo -e "         ${Kedip}${H}✅ ACCOUNT RENEWED SUCCESSFULLY ✅${R}"
    echo -e ""
    echo -e "$Atas"
    echo -e "$ki${BG_G}                    RENEWAL DETAILS                    ${R}$ka"
    echo -e "$Tengah"
    printf "$ki ${P}%-20s ${C}: ${K}%-30s${R}$ka\n" "Client Name" "$user"
    printf "$ki ${P}%-20s ${C}: ${M}%-30s${R}$ka\n" "Expires Old" "$exp_old"
    printf "$ki ${P}%-20s ${C}: ${H}%-30s${R}$ka\n" "Expires New" "$exp_new"
    printf "$ki ${P}%-20s ${C}: ${P}%-30s${R}$ka\n" "Added Days" "+$masaaktif Days"
    echo -e "$Tengah"
    printf "$ki ${P}%-20s ${C}: ${P}%-30s${R}$ka\n" "New Quota" "$Quota GB"
    printf "$ki ${P}%-20s ${C}: ${P}%-30s${R}$ka\n" "New Limit IP" "$iplim Device"
    echo -e "$Bawah"
    echo -e ""
    
    echo -e "${C} Account renewed. Returning to list...${R}"
    read -n 1 -s -r -p " Press any key to continue"
done