#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""StudioSoft Invoice — TS Law (Tito Supriyanto Law Firm) — September 2026
Template BIRU + deskripsi LENGKAP (breakdown sub-item per item, ala template
asli StudioSoft / invoice Arek Lancor). Tanpa Jatuh Tempo.
Dibuat Wati, 30 Sep 2026 (revisi: deskripsi diperlengkap).
"""
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  # A4 @ 150dpi
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"]

# Item + breakdown sub-item (mengikuti gaya template asli StudioSoft)
ITEMS = [
    ("Website Maintenance", [
        "Pembuatan Website",
        "Pembuatan dan optimasi akun Social Media",
        "Website Update Slide / Content",
        "Backup Website Regular",
        "Website Restore",
        "Analytic Data Report Update",
    ]),
    ("Input Konten", [
        "Jasa Hukum Perusahaan",
        "Layanan Legal UMKM & Startup",
        "Edukasi Hukum",
        "Konsultasi Hukum",
    ]),
    ("SEO", [
        "Google Analytic",
        "Google Business",
        "Google Map",
        "Keyword : Konsultan Hukum Surabaya, Law Firm",
    ]),
    ("Optimasi Campaign Insight", [
        "LinkedIn Campaign",
        "Threads Campaign",
        "Business Facebook Fan Pages",
    ]),
]

CLIENT = {
    "no": "104",
    "nama": "TS Law (Tito Supriyanto Law Firm)",
    "alamat": "Raya Tidar Mas Square, Tidar, Surabaya - Indonesia",
    "telp": "WA: +62 819 0922 2026",
    "total": 3000000,
    "tanggal": "Surabaya, 1 September 2026",
    "bulan_romawi": "IX",
    "periode": "September 2026",
}


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)

    # ── Header band biru ──
    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']}/INV/{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")

    # ── DARI / KEPADA ──
    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)

    # ── Periode layanan ──
    iy = 505
    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)

    # ── Tabel NO | DESKRIPSI (dengan breakdown sub-item) ──
    tx_desc = X0 + 130
    ty = 566
    d.rectangle([X0, ty, X1, ty + 56], fill=LIGHT)
    d.text((X0 + 20, ty + 14), "NO", font=font("Poppins-Bold", 24), fill=DARK)
    d.text((tx_desc, ty + 14), "DESKRIPSI", font=font("Poppins-Bold", 24), fill=DARK)

    f_item = font("Poppins-SemiBold", 22)
    f_sub = font("Poppins-Regular", 19)
    item_h, sub_h = 42, 25
    maxw = X1 - (tx_desc + 40)
    ry = ty + 56

    for i, (item, subs) in enumerate(ITEMS, 1):
        d.line([X0, ry, X1, ry], fill=LINE)
        d.text((X0 + 20, ry + 9), str(i), font=font("Poppins-Regular", 22), fill=BODY)
        d.text((tx_desc, ry + 8), 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)

    # ── Total ──
    ty2 = ry + 30
    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")

    # ── Pembayaran + tanda tangan ──
    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


if __name__ == "__main__":
    img, bottom = render(CLIENT)
    png_out = os.path.join(HERE, "Invoice_104_TSLaw_September_2026.png")
    pdf_out = os.path.join(HERE, "Invoice_104_TSLaw_September_2026.pdf")
    img.save(png_out)
    img.convert("RGB").save(pdf_out, "PDF", resolution=150.0)
    print("Tabel selesai di y =", bottom, "(aman bila < 1375)")
    print("OK ->", pdf_out)
