#!/bin/bash

BASE_URL="https://autoscript.interflazz.my.id/v2"
BRAND="INTERFLAZZ.MY.ID"
WHATSAPP="https://wa.me/6285956131443"
TELEGRAM="https://t.me/interflazz"

green="\e[38;5;82m"
red="\e[38;5;196m"
yellow="\e[38;5;226m"
blue="\e[38;5;39m"
purple="\e[38;5;141m"
cyan="\e[38;5;51m"
white="\e[97m"
orange="\e[38;5;130m"
bold_white="\e[1;37m"
reset="\e[0m"

DB_FILE="/etc/xray/vless/.vless.db"
CONFIG_FILE="/etc/xray/vless/config.json"
BASE_DIR="/etc/xray/vless"

update_box_width() {
    local cols

    cols=$(tput cols 2>/dev/null || echo 80)

    if [ "$cols" -gt 72 ]; then
        BOX_WIDTH=72
    elif [ "$cols" -lt 30 ]; then
        BOX_WIDTH=30
    else
        BOX_WIDTH=$((cols - 2))
    fi

    BOX_INNER=$((BOX_WIDTH - 4))
}

repeat_char() {
    local count="$1"
    local char="$2"
    local line

    printf -v line '%*s' "$count" ""
    printf '%s' "${line// /$char}"
}

box_top() {
    update_box_width

    printf "%b┌" "$orange"
    repeat_char $((BOX_WIDTH - 2)) "─"
    printf "┐%b\n" "$reset"
}

box_middle() {
    update_box_width

    printf "%b├" "$orange"
    repeat_char $((BOX_WIDTH - 2)) "─"
    printf "┤%b\n" "$reset"
}

box_bottom() {
    update_box_width

    printf "%b└" "$orange"
    repeat_char $((BOX_WIDTH - 2)) "─"
    printf "┘%b\n" "$reset"
}

box_empty() {
    update_box_width

    printf "%b│%b" "$orange" "$reset"
    printf "%*s" $((BOX_WIDTH - 2)) ""
    printf "%b│%b\n" "$orange" "$reset"
}

box_center() {
    update_box_width

    local text="$1"
    local color="${2:-$white}"
    local length=${#text}
    local available="$BOX_INNER"

    if [ "$length" -gt "$available" ]; then
        box_left "$text" "$color"
        return
    fi

    local left=$(((available - length) / 2))
    local right=$((available - length - left))

    printf "%b│%b " "$orange" "$reset"
    printf "%*s" "$left" ""
    printf "%b%s%b" "$color" "$text" "$reset"
    printf "%*s" "$right" ""
    printf " %b│%b\n" "$orange" "$reset"
}

box_left() {
    update_box_width

    local text="$1"
    local color="${2:-$white}"
    local available="$BOX_INNER"
    local length=${#text}
    local offset=0
    local part
    local part_length
    local right

    if [ "$length" -eq 0 ]; then
        box_empty
        return
    fi

    while [ "$offset" -lt "$length" ]; do
        part="${text:$offset:$available}"
        part_length=${#part}
        right=$((available - part_length))

        printf "%b│%b " "$orange" "$reset"
        printf "%b%s%b" "$color" "$part" "$reset"
        printf "%*s" "$right" ""
        printf " %b│%b\n" "$orange" "$reset"

        offset=$((offset + available))
    done
}

show_access_denied() {
    local reason="$1"

    clear

    box_top
    box_center "$BRAND" "$green"
    box_center "AUTOSCRIPT PREMIUM" "$bold_white"
    box_middle
    box_center "AKSES DITOLAK!" "$red"
    box_middle
    box_left "IP VPS : $vps_ip" "$yellow"
    box_left "$reason" "$yellow"
    box_middle
    box_center "HUBUNGI ADMIN" "$bold_white"
    box_left "WhatsApp ~ $WHATSAPP" "$green"
    box_left "Telegram ~ $TELEGRAM" "$cyan"
    box_bottom

    exit 1
}

pause_menu() {
    echo ""
    read -n 1 -s -r -p "Tekan tombol apa saja untuk kembali..."
    echo ""
}

ensure_files() {
    mkdir -p "$BASE_DIR/usage"

    if [ ! -f "$DB_FILE" ]; then
        touch "$DB_FILE"
    fi
}

get_days_left() {
    local exp="$1"
    local exp_timestamp
    local current_timestamp
    local days_left

    exp_timestamp=$(date -d "$exp" +%s 2>/dev/null)
    current_timestamp=$(date +%s)

    if [ -z "$exp_timestamp" ]; then
        echo "0"
        return
    fi

    days_left=$(((exp_timestamp - current_timestamp) / 86400))

    if [ "$days_left" -lt 0 ]; then
        days_left=0
    fi

    echo "$days_left"
}

show_account_table() {
    local index=1
    local user
    local exp
    local uuid
    local days_left

    printf " ┌────┬────────────────────┬─────────────┐\n"
    printf " │ No │ Username           │ Sisa Aktif  │\n"
    printf " ├────┼────────────────────┼─────────────┤\n"

    while read -r marker user exp uuid; do
        [ "$marker" != "###" ] && continue
        [ -z "$user" ] && continue

        days_left=$(get_days_left "$exp")

        printf " │ %-2s │ %-18s │ %-9s   │\n" \
            "$index" \
            "$user" \
            "${days_left} hari"

        index=$((index + 1))
    done <"$DB_FILE"

    printf " └────┴────────────────────┴─────────────┘\n"
}

vps_ip=$(wget -qO- ipv4.icanhazip.com)

if [ -z "$vps_ip" ]; then
    vps_ip=$(curl -4 -s ipv4.icanhazip.com)
fi

if [ -z "$vps_ip" ]; then
    vps_ip="Tidak diketahui"
fi

data_acc=$(
    curl -s "${BASE_URL}/access" |
        grep "### $vps_ip " |
        awk '{print $3}'
)

if [ -z "$data_acc" ]; then
    show_access_denied "VPS belum memiliki izin akses script."
fi

expiry_date=$(date -d "$data_acc" +%s 2>/dev/null)
current_date=$(date +%s)

if [ -z "$expiry_date" ]; then
    show_access_denied "Data masa aktif script tidak valid."
fi

if [ "$expiry_date" -le "$current_date" ]; then
    show_access_denied "Masa aktif akses script telah berakhir."
fi

remaining_days=$(((expiry_date - current_date) / 86400))

ensure_files

account_count=$(grep -c '^### ' "$DB_FILE" 2>/dev/null || echo "0")

clear

box_top
box_center "$BRAND" "$green"
box_center "RENEW AKUN VLESS" "$bold_white"
box_bottom

if [ "$account_count" -eq 0 ]; then
    echo ""

    box_top
    box_center "TIDAK ADA AKUN" "$yellow"
    box_middle
    box_center "Belum ada akun VLESS terdaftar." "$white"
    box_bottom

    pause_menu
    exit 0
fi

echo ""
show_account_table
echo ""

while true; do
    read -rp "Pilih nomor akun [1-${account_count}] : " account_number

    if [[ "$account_number" =~ ^[0-9]+$ ]] &&
       [ "$account_number" -ge 1 ] &&
       [ "$account_number" -le "$account_count" ]; then
        break
    fi

    echo -e "${red}Nomor akun tidak valid.${reset}"
done

user=$(
    grep '^### ' "$DB_FILE" |
        awk '{print $2}' |
        sed -n "${account_number}p"
)

old_exp=$(
    grep '^### ' "$DB_FILE" |
        awk '{print $3}' |
        sed -n "${account_number}p"
)

uuid=$(
    grep '^### ' "$DB_FILE" |
        awk '{print $4}' |
        sed -n "${account_number}p"
)

if [ -z "$user" ] ||
   [ -z "$old_exp" ] ||
   [ -z "$uuid" ]; then

    echo -e "${red}Data akun VLESS tidak valid.${reset}"
    pause_menu
    exit 1
fi

old_exp_timestamp=$(date -d "$old_exp" +%s 2>/dev/null)

if [ -z "$old_exp_timestamp" ]; then
    echo -e "${red}Tanggal kadaluarsa akun tidak valid.${reset}"
    pause_menu
    exit 1
fi

today=$(date +%Y-%m-%d)
today_timestamp=$(date -d "$today" +%s)

days_left=$(((old_exp_timestamp - today_timestamp) / 86400))

if [ "$days_left" -lt 0 ]; then
    days_left=0
fi

old_quota=$(cat "${BASE_DIR}/${user}" 2>/dev/null)
old_ip_limit=$(cat "${BASE_DIR}/${user}IP" 2>/dev/null)

old_quota=${old_quota:-0}
old_ip_limit=${old_ip_limit:-0}

clear

box_top
box_center "$BRAND" "$green"
box_center "RENEW AKUN VLESS" "$bold_white"
box_middle
box_left "Username        : $user" "$white"
box_left "UUID            : $uuid" "$white"
box_left "Kadaluarsa Lama : $old_exp" "$white"
box_left "Sisa Aktif      : $days_left Hari" "$yellow"
box_bottom

echo ""

while true; do
    read -rp "Tambah masa aktif [hari] : " active_days

    if [[ "$active_days" =~ ^[1-9][0-9]*$ ]]; then
        break
    fi

    echo -e "${red}Masa aktif harus berupa angka lebih dari 0.${reset}"
done

while true; do
    read -rp "Batas kuota GB [0 = Unlimited] : " quota

    if [[ "$quota" =~ ^[0-9]+$ ]]; then
        break
    fi

    echo -e "${red}Kuota harus berupa angka 0 atau lebih.${reset}"
done

while true; do
    read -rp "Batas IP [0 = Unlimited] : " ip_limit

    if [[ "$ip_limit" =~ ^[0-9]+$ ]]; then
        break
    fi

    echo -e "${red}Batas IP harus berupa angka 0 atau lebih.${reset}"
done

if [ "$old_exp_timestamp" -gt "$today_timestamp" ]; then
    base_exp="$old_exp"
else
    base_exp="$today"
fi

new_exp=$(date -d "${base_exp} +${active_days} days" +"%Y-%m-%d" 2>/dev/null)

if [ -z "$new_exp" ]; then
    echo -e "${red}Gagal menghitung tanggal kadaluarsa baru.${reset}"
    pause_menu
    exit 1
fi

if [ "$quota" -eq 0 ]; then
    rm -f "${BASE_DIR}/${user}"
    quota_display="Unlimited"
else
    quota_bytes=$((quota * 1024 * 1024 * 1024))
    printf '%s\n' "$quota_bytes" >"${BASE_DIR}/${user}"
    quota_display="${quota} GB"
fi

printf '%s\n' "$ip_limit" >"${BASE_DIR}/${user}IP"

if [ "$ip_limit" -eq 0 ]; then
    ip_display="Unlimited"
else
    ip_display="${ip_limit} Perangkat"
fi

if [ ! -f "$CONFIG_FILE" ]; then
    echo -e "${red}File config VLESS tidak ditemukan.${reset}"
    pause_menu
    exit 1
fi

if grep -q "^### ${user} ${old_exp}$" "$CONFIG_FILE"; then
    sed -i \
        "s/^### ${user} ${old_exp}$/### ${user} ${new_exp}/" \
        "$CONFIG_FILE"
else
    sed -i \
        "s/^### ${user} .*/### ${user} ${new_exp}/" \
        "$CONFIG_FILE"
fi

sed -i \
    "/^### ${user} /c\### ${user} ${new_exp} ${uuid}" \
    "$DB_FILE"

if systemctl restart vless@config >/dev/null 2>&1; then
    service_status="Berhasil"
    service_color="$green"
else
    service_status="Gagal"
    service_color="$red"
fi

clear

box_top
box_center "$BRAND" "$green"
box_center "RENEW AKUN VLESS BERHASIL" "$bold_white"
box_middle
box_left "Username        : $user" "$white"
box_left "UUID            : $uuid" "$white"
box_left "Tambah Aktif    : $active_days Hari" "$white"
box_left "Kuota           : $quota_display" "$white"
box_left "Batas IP        : $ip_display" "$white"
box_left "Kadaluarsa Lama : $old_exp" "$yellow"
box_left "Kadaluarsa Baru : $new_exp" "$green"
box_left "Sisa Aktif Baru : $(get_days_left "$new_exp") Hari" "$green"
box_left "Service VLESS   : $service_status" "$service_color"
box_bottom

echo ""

box_top
box_center "INFORMASI SCRIPT" "$bold_white"
box_middle
box_left "Masa Aktif Script : $remaining_days Hari" "$yellow"
box_left "WhatsApp ~ $WHATSAPP" "$green"
box_left "Telegram ~ $TELEGRAM" "$cyan"
box_bottom

exit 0