from config import NOTIF_CHANNEL
from PIL import Image, ImageDraw, ImageFont
import io


def generate_order_card(order_id: str, prod_name: str, harga: int, method: str, avatar: bytes = None) -> io.BytesIO:
    w, h = 800, 420
    img = Image.new('RGB', (w, h), color=(255, 255, 255))
    draw = ImageDraw.Draw(img)

    try:
        font_big   = ImageFont.truetype("fonts/DejaVuSans-Bold.ttf", 42)
        font_label = ImageFont.truetype("fonts/DejaVuSans-Bold.ttf", 26)
        font_small = ImageFont.truetype("fonts/DejaVuSans.ttf", 20)
    except:
        font_big   = ImageFont.load_default()
        font_label = font_big
        font_small = font_big

    av_size = 160
    av_x = 30
    av_y = (h - av_size) // 2

    padding = 12
    draw.rounded_rectangle(
        [av_x - padding, av_y - padding, av_x + av_size + padding, av_y + av_size + padding],
        radius=16,
        fill=(150, 80, 255)
    )

    if avatar:
        try:
            av_img = Image.open(io.BytesIO(avatar)).convert("RGBA")
            av_img = av_img.resize((av_size, av_size))
            mask = Image.new("L", (av_size, av_size), 0)
            mask_draw = ImageDraw.Draw(mask)
            mask_draw.ellipse([0, 0, av_size, av_size], fill=255)
            av_img.putalpha(mask)
            img.paste(av_img, (av_x, av_y), av_img)
        except Exception:
            pass

    draw.rounded_rectangle([0, 0, w-1, h-1], radius=24, outline=(0, 0, 0), width=4)

    tx = av_x + av_size + 50
    draw.text((tx, 30), "PENTA HOSTINGER", font=font_big, fill=(0, 0, 0))
    draw.line([tx, 85, w-30, 85], fill=(0, 0, 0), width=2)
    draw.text((tx, 100), f"ORDER ID : {order_id}", font=font_label, fill=(0, 0, 0))
    draw.text((tx, 150), f"METHOD   : {method.upper()}", font=font_label, fill=(0, 0, 0))
    draw.text((tx, 200), f"ITEM     : {prod_name[:25]}", font=font_label, fill=(0, 0, 0))

    harga_text = f"HARGA    : Rp{int(harga):,}" if harga else "HARGA    : -"
    draw.text((tx, 250), harga_text, font=font_label, fill=(0, 0, 0))

    draw.line([tx, h-60, w-30, h-60], fill=(0, 0, 0), width=2)
    draw.text((tx, h-40), "Terimakasih sudah berbelanja di Penta Hostinger!", font=font_small, fill=(80, 80, 80))

    buf = io.BytesIO()
    img.save(buf, format='PNG')
    buf.seek(0)
    buf.name = "notif.png"
    return buf


async def get_avatar(bot, user_id: int):
    try:
        buf = io.BytesIO()
        await bot.download_profile_photo(user_id, file=buf)
        buf.seek(0)
        data = buf.read()
        if not data:
            return None
        return data
    except Exception:
        return None


async def send_notif_order(bot, order: dict):
    try:
        avatar = await get_avatar(bot, order['user_id'])
        card = generate_order_card(
            order_id=order['order_id'],
            prod_name=order.get('prod_name', '-'),
            harga=int(order['amount']),
            method=order['method'],
            avatar=avatar
        )
        caption = (
            "ORDER BARU MASUK BERHASIL\n\n"
            f"Order ID : {order['order_id']}\n"
            f"User ID  : {order['user_id']}\n"
            f"Produk   : {order.get('prod_name', '-')}\n"
            f"Total    : Rp{int(order['amount']):,}\n"
            f"Metode   : {order['method'].upper()}\n"
            f"Waktu    : {order['created_at']}\n\n"
            "TERIMAKASIH SUDAH BERBELANJA DI PENTA HOSTINGER"
        )
        await bot.send_file(NOTIF_CHANNEL, file=card, caption=caption)
    except Exception as e:
        print(f"Notif error: {e}")


async def send_notif_topup(bot, order: dict):
    try:
        avatar = await get_avatar(bot, order['user_id'])
        card = generate_order_card(
            order_id=order['order_id'],
            prod_name="Top Up Saldo",
            harga=int(order['amount']),
            method="Transfer",
            avatar=avatar
        )
        caption = (
            "TOPUP BARU MASUK BERHASIL\n\n"
            f"Order ID : {order['order_id']}\n"
            f"User ID  : {order['user_id']}\n"
            f"Nominal  : Rp{int(order['amount']):,}\n"
            f"Waktu    : {order['created_at']}\n\n"
            "TERIMAKASIH SUDAH BERBELANJA DI PENTA HOSTINGER"
        )
        await bot.send_file(NOTIF_CHANNEL, file=card, caption=caption)
    except Exception as e:
        print(f"Notif error: {e}")


async def send_notif_vps_success(bot, user_id: int, order_id: str, prod_name: str, os_slug: str, region_slug: str, ip: str):
    try:
        try:
            user = await bot.get_entity(user_id)
            username = f"@{user.username}" if user.username else user.first_name
        except Exception:
            username = str(user_id)

        avatar = await get_avatar(bot, user_id)
        card = generate_order_card(
            order_id=order_id,
            prod_name=prod_name,
            harga=0,
            method="VPS",
            avatar=avatar
        )
        caption = (
            "ORDER BARU MASUK BERHASIL\n\n"
            f"Order ID : {order_id}\n"
            f"User     : {username}\n"
            f"Paket    : {prod_name}\n"
            f"OS       : {os_slug}\n"
            f"Region   : {region_slug}\n\n"
            "TERIMAKASIH SUDAH BERBELANJA DI PENTA HOSTINGER"
        )
        await bot.send_file(NOTIF_CHANNEL, file=card, caption=caption)
    except Exception as e:
        print(f"Notif error: {e}")