#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""Quotation Letter — PT. Bukit Darmo Property — REVISI 2 Okt 2026
Perubahan dari versi 113 (1 Okt):
  - Item 3: "Pro Version Capcut, Canva & AI" Rp 1.500.000
            -> "Meta Ads + Pajak + Formula Ads" Rp 2.000.000
  - Total: Rp 7.000.000 -> Rp 7.500.000
Sisanya identik dengan generator asli (template BIRU, Poppins).
"""
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"]

PAKET_SUBS = [
    (0, "Website Development"),
    (1, "Pembuatan Website Company Profile"),
    (1, "Backup Website Regular (Source Code + Database)"),
    (1, "Website Restore (Hacker Web Problem Solve)"),
    (1, "Analytics Data Report Updated (Regular)"),
    (1, "Free Domain Hosting"),
    (0, "Design Graphics"),
    (1, "Create Design Content (maks 20 Design)"),
    (1, "Create Slide Design Promo (maks 5 Design)"),
    (1, "Copywriting Blog (20 Post)"),
    (1, "Promo Design Feed Instagram"),
    (1, "Carousel Education Content"),
    (0, "AI Video Content"),
    (1, "AI Video Product (maks 10 AI Video Short)"),
    (1, "Mirror Reels Instagram, Facebook, TikTok, Threads"),
    (0, "Corporate SEO"),
    (1, "Google Analytics"),
    (1, "Google Business"),
    (1, "Google Map"),
    (1, "Google Shortlink"),
    (1, "Instagram Insight"),
    (1, "Facebook Insight"),
    (1, "SEO Tools Support"),
    (1, "SEO Robots"),
    (0, "Social Media Campaign"),
    (1, "Business Instagram"),
    (1, "Business Facebook"),
    (0, "Presentasi"),
    (1, "1 kali sebulan via Google Meet"),
]

# >>> PERUBAHAN: item 3 diganti <<<
ITEMS = [
    ("Paket - Professional", "Rp 5.000.000", PAKET_SUBS),
    ("Centang Biru Meta (Verifikasi Akun)", "Rp 500.000", []),
    ("Meta Ads + Pajak + Formula Ads", "Rp 2.000.000", []),
]

CLIENT = {
    "no": "113",
    "nama": "PT. Bukit Darmo Property",
    "alamat": "Jl. Yono Soewoyo No. 9, Fairwaynine Floor 6, Surabaya, Jawa Timur 60226",
    "telp": "Telp: (031) 732 0099",
    "total": 7500000,          # >>> PERUBAHAN: 7.000.000 -> 7.500.000 <<<
    "tanggal": "Surabaya, 2 Oktober 2026",
    "bulan_romawi": "X",
}


def font(name, size):
    return ImageFont.truetype(os.path.join(BASE, f"Poppins-{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)
    img.paste(logo.resize((lw, lh), Image.LANCZOS), (X0, 75), logo.resize((lw, lh), Image.LANCZOS))

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

    y = 250
    col2x = X0 + 520
    d.text((X0, y), "DARI", font=font("Bold", 20), fill=GRAY)
    d.text((X0, y + 32), "StudioSoft", font=font("Bold", 32), fill=DARK)
    for i, t in enumerate(from_addr):
        d.text((X0, y + 82 + i * 30), t, font=font("Regular", 22), fill=BODY)

    d.text((col2x, y), "KEPADA", font=font("Bold", 20), fill=GRAY)
    d.text((col2x, y + 32), client["nama"], font=font("Bold", 26), fill=DARK)
    ay = y + 82
    for ln in auto_wrap(d, client["alamat"], font("Regular", 22), X1 - col2x):
        d.text((col2x, ay), ln, font=font("Regular", 22), fill=BODY)
        ay += 30
    d.text((col2x, ay + 5), client["telp"], font=font("Regular", 22), fill=BODY)
    kepada_bottom = ay + 38

    tx_desc = X0 + 110
    tx_total = X1 - 24
    ty = max(454, kepada_bottom + 30)
    d.rectangle([X0, ty, X1, ty + 50], fill=LIGHT)
    d.text((X0 + 20, ty + 12), "NO", font=font("Bold", 24), fill=DARK)
    d.text((tx_desc, ty + 12), "DESKRIPSI", font=font("Bold", 24), fill=DARK)
    d.text((tx_total, ty + 12), "TOTAL", font=font("Bold", 24), fill=DARK, anchor="ra")

    f_item = font("SemiBold", 22)
    f_kat = font("SemiBold", 17)
    f_sub = font("Regular", 16)
    f_harga = font("SemiBold", 22)
    item_h, sub_h = 40, 20
    ry = ty + 50
    maxw_kat = (tx_total - 240) - (tx_desc + 24)
    maxw_sub = (tx_total - 240) - (tx_desc + 52)

    for i, (item, harga, subs) in enumerate(ITEMS, 1):
        d.text((X0 + 20, ry + 8), str(i), font=font("Regular", 22), fill=BODY)
        d.text((tx_desc, ry + 7), item, font=f_item, fill=DARK)
        d.text((tx_total, ry + 7), harga, font=f_harga, fill=DARK, anchor="ra")
        ry += item_h
        for lvl, s in subs:
            f = f_kat if lvl == 0 else f_sub
            x = tx_desc + 24 if lvl == 0 else tx_desc + 52
            col = DARK if lvl == 0 else BODY
            maxw = maxw_kat if lvl == 0 else maxw_sub
            for ln in auto_wrap(d, "- " + s, f, maxw):
                d.text((x, ry + 1), ln, font=f, fill=col)
                ry += sub_h

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

    d.text((X0, ty2 + 100), "Keterangan :", font=font("SemiBold", 20), fill=GRAY)
    d.text((X0 + 175, ty2 + 100), "Biaya per bulan \u00b7 Minimal kontrak 6 bulan", font=font("Regular", 20), fill=BODY)

    fy = H - SAFE_BOTTOM - 320
    d.text((X0, fy), "PEMBAYARAN", font=font("Bold", 20), fill=GRAY)
    d.text((X0, fy + 36), "Transfer ke (a.n. Uky Yanuhandoko):", font=font("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("Regular", 21), fill=BODY)

    sig_x = X1 - 340
    d.text((sig_x, fy), "Hormat kami,", font=font("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("Regular", 22), fill=BODY)
    d.text((sig_x, line_y + 50), "StudioSoft", font=font("Bold", 24), fill=DARK)

    return img, ty2 + 86, kepada_bottom, ty


if __name__ == "__main__":
    img, bottom, kepada, tabel_top = render(CLIENT)
    png_out = os.path.join(HERE, "Quotation_113_Bukit_Darmo_Property_REV.png")
    pdf_out = os.path.join(HERE, "Quotation_113_Bukit_Darmo_Property_REV.pdf")
    img.save(png_out)
    img.convert("RGB").save(pdf_out, "PDF", resolution=150.0)
    PAY_TOP = H - SAFE_BOTTOM - 320
    print(f"total={rupiah(CLIENT['total'])}")
    print(f"KEPADA bawah={kepada} | tabel mulai={tabel_top} | tabel+total bawah={bottom} | PEMBAYARAN mulai={PAY_TOP}")
    print("tidak bertumpuk:", kepada <= tabel_top, "| tidak menabrak pembayaran:", bottom < PAY_TOP)
    print("OK ->", pdf_out)
