#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""StudioSoft Invoice — TSC (The Skin Code Clinic) — Agustus 2026 — v3
Template BIRU + deskripsi LENGKAP (breakdown sub-item, ala template asli StudioSoft).
- Tanpa Jatuh Tempo
- Item no.2: Maintenance Social Media Instagram
Dibuat Wati, 30 Sep 2026.
"""
from PIL import Image, ImageDraw, ImageFont
import os

HERE = os.path.dirname(os.path.abspath(__file__))
BASE = "/home/mantapman/.openclaw/workspace-atun/invoices_studiosoft_template"

W, H = 1240, 1754
SAFE_LEFT = 90
SAFE_RIGHT = 30
SAFE_BOTTOM = 59

BG = (255, 255, 255)
BLUE = (30, 64, 175)
DARK = (15, 23, 42)
BODY = (71, 85, 105)
GRAY = (100, 116, 139)
LIGHT = (241, 245, 249)
LINE = (203, 213, 225)

X0, X1 = SAFE_LEFT, W - SAFE_RIGHT

from_addr = ["Jl. Mangga 3 E346B Pondok Tjandra", "Waru - Sidoarjo", "WA: 0819-3500-0624"]

ITEMS = [
    ("Website Maintenance", [
        "Pembuatan Website",
        "Pembuatan dan optimasi akun Social Media",
        "Website Update Slide / Content",
        "Backup Website Regular",
        "Analytic Data Report Update",
    ]),
    ("Maintenance Social Media Instagram", [
        "Pengelolaan Feed & Story Instagram",
        "Penjadwalan Konten Bulanan",
        "Optimasi Profil & Highlight",
        "Laporan Performa Instagram",
    ]),
    ("Input Konten", [
        "Layanan Klinik Kecantikan",
        "Informasi Perawatan Kulit",
        "Promo Perawatan",
        "Edukasi Skincare",
    ]),
    ("SEO", [
        "Google Analytic",
        "Google Business",
        "Google Map",
        "Keyword : Klinik Kecantikan Krian, Perawatan Kulit",
    ]),
    ("Optimasi Campaign Insight", [
        "Threads Campaign",
        "Business Instagram Feed & Stories",
        "Konten Edukasi Kulit",
    ]),
]

CLIENT = {
    "no": "103",
    "nama": "TSC (The Skin Code Clinic)",
    "alamat": "Jl. Kyai Mojo Blok A1 No. 5, Dusun Jeruk, Jerukgamping, Kec. Krian, Kabupaten Sidoarjo, Jawa Timur 61262",
    "telp": "WA: +62 813-3511-4324",
    "total": 3000000,
    "tanggal": "Surabaya, 3 Agustus 2026",
    "bulan_romawi": "VIII",
    "periode": "Agustus 2026",
    "kode": "AGN",
}


def font(name, size):
    return ImageFont.truetype(os.path.join(BASE, f"{name}.ttf"), size)


def rupiah(n):
    return "Rp {:,.0f}".format(n).replace(",", ".")


def auto_wrap(draw, text, fnt, maxw):
    words = text.split()
    lines, cur = [], ""
    for w in words:
        t = (cur + " " + w).strip()
        if draw.textlength(t, font=fnt) <= maxw:
            cur = t
        else:
            if cur:
                lines.append(cur)
            cur = w
    if cur:
        lines.append(cur)
    return lines


def render(client):
    img = Image.new("RGB", (W, H), BG)
    d = ImageDraw.Draw(img)

    d.rectangle([0, 0, W, 250], fill=BLUE)
    logo = Image.open(os.path.join(BASE, "assets_studiosoft_logo.png")).convert("RGBA")
    lpix = logo.load()
    for x in range(logo.width):
        for y in range(logo.height):
            r, g, b, a = lpix[x, y]
            if a > 0:
                lpix[x, y] = (255, 255, 255, a)
    lw = 200
    lh = int(logo.height * lw / logo.width)
    logo_resized = logo.resize((lw, lh), Image.LANCZOS)
    img.paste(logo_resized, (X0, 75), logo_resized)

    d.text((X1, 60), "INVOICE", font=font("Poppins-Bold", 56), fill=(255, 255, 255), anchor="ra")
    d.text((X1, 138), f"No. {client['no']}/{client['kode']}/{client['bulan_romawi']}/2026", font=font("Poppins-Regular", 25), fill=(219, 234, 254), anchor="ra")
    d.text((X1, 182), client["tanggal"], font=font("Poppins-Regular", 21), fill=(219, 234, 254), anchor="ra")

    y = 320
    col2x = X0 + 520
    d.text((X0, y), "DARI", font=font("Poppins-Bold", 20), fill=GRAY)
    d.text((X0, y + 34), "StudioSoft", font=font("Poppins-Bold", 32), fill=DARK)
    for i, t in enumerate(from_addr):
        d.text((X0, y + 88 + i * 33), t, font=font("Poppins-Regular", 22), fill=BODY)

    d.text((col2x, y), "KEPADA", font=font("Poppins-Bold", 20), fill=GRAY)
    d.text((col2x, y + 34), client["nama"], font=font("Poppins-Bold", 26), fill=DARK)
    ay = y + 88
    for ln in auto_wrap(d, client["alamat"], font("Poppins-Regular", 22), X1 - col2x):
        d.text((col2x, ay), ln, font=font("Poppins-Regular", 22), fill=BODY)
        ay += 33
    d.text((col2x, ay + 6), client["telp"], font=font("Poppins-Regular", 22), fill=BODY)

    iy = 470
    d.text((X0, iy), "Periode Layanan:", font=font("Poppins-Bold", 20), fill=GRAY)
    d.text((X0 + 300, iy), client["periode"], font=font("Poppins-Regular", 22), fill=BODY)

    tx_desc = X0 + 130
    ty = 505
    d.rectangle([X0, ty, X1, ty + 50], fill=LIGHT)
    d.text((X0 + 20, ty + 12), "NO", font=font("Poppins-Bold", 24), fill=DARK)
    d.text((tx_desc, ty + 12), "DESKRIPSI", font=font("Poppins-Bold", 24), fill=DARK)

    f_item = font("Poppins-SemiBold", 22)
    f_sub = font("Poppins-Regular", 19)
    item_h, sub_h = 40, 24
    ry = ty + 50

    for i, (item, subs) in enumerate(ITEMS, 1):
        d.line([X0, ry, X1, ry], fill=LINE)
        d.text((X0 + 20, ry + 8), str(i), font=font("Poppins-Regular", 22), fill=BODY)
        d.text((tx_desc, ry + 7), item, font=f_item, fill=DARK)
        ry += item_h
        for s in subs:
            d.text((tx_desc + 24, ry + 3), "- " + s, font=f_sub, fill=BODY)
            ry += sub_h
    d.line([X0, ry, X1, ry], fill=LINE)

    ty2 = ry + 26
    kiri = X1 - 520
    d.rectangle([kiri, ty2, X1, ty2 + 86], fill=LIGHT)
    d.text((kiri + 20, ty2 + 25), "TOTAL", font=font("Poppins-Bold", 26), fill=DARK)
    d.text((X1 - 28, ty2 + 23), rupiah(client["total"]), font=font("Poppins-Bold", 26), fill=BLUE, anchor="ra")

    fy = H - SAFE_BOTTOM - 320
    d.text((X0, fy), "PEMBAYARAN", font=font("Poppins-Bold", 20), fill=GRAY)
    d.text((X0, fy + 36), "Transfer ke (a.n. Uky Yanuhandoko):", font=font("Poppins-SemiBold", 22), fill=DARK)
    for i, t in enumerate(["1. BCA 6750379638   (Rungkut Mapan, Surabaya)",
                           "2. Mandiri 142-00-1068384-4   (Bratang Binangun, Surabaya)"]):
        d.text((X0, fy + 78 + i * 34), t, font=font("Poppins-Regular", 21), fill=BODY)

    sig_x = X1 - 340
    d.text((sig_x, fy), "Hormat kami,", font=font("Poppins-Regular", 22), fill=BODY)
    ttd = Image.open(os.path.join(BASE, "ttd_uky.png")).convert("RGBA")
    tpx = ttd.load()
    for x in range(ttd.width):
        for y2 in range(ttd.height):
            r, g, b, a = tpx[x, y2]
            if r > 240 and g > 240 and b > 240:
                tpx[x, y2] = (r, g, b, 0)
    th2 = 150
    tw2 = int(211 * th2 / 183)
    ttd_r = ttd.resize((tw2, th2), Image.LANCZOS)
    img.paste(ttd_r, (sig_x, fy + 40), ttd_r)
    line_y = fy + 40 + th2 + 12
    d.line([sig_x, line_y, X1 - 30, line_y], fill=LINE)
    d.text((sig_x, line_y + 14), "Uky Yanuhandoko S.Kom", font=font("Poppins-Regular", 22), fill=BODY)
    d.text((sig_x, line_y + 50), "StudioSoft", font=font("Poppins-Bold", 24), fill=DARK)

    return img, ty2 + 86, ay


if __name__ == "__main__":
    img, bottom, addr_bottom = render(CLIENT)
    png_out = os.path.join(HERE, "Invoice_103_TSC_The_Skin_Code_Clinic.png")
    pdf_out = os.path.join(HERE, "Invoice_103_TSC_The_Skin_Code_Clinic.pdf")
    img.save(png_out)
    img.convert("RGB").save(pdf_out, "PDF", resolution=150.0)
    print(f"blok KEPADA selesai y={addr_bottom} | total box bawah y={bottom} (aman bila <1375)")
    print("OK ->", pdf_out)
