#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Invoice StudioSoft — LEIT September 2026 (Rp 3.000.000)
Paket Optimize Website (Paket 1) — sama dengan Invoice 107 (Agustus 2026).
Template: spek final invoice StudioSoft (3 Agustus 2026).
"""
import os
from PIL import Image, ImageDraw, ImageFont

BASE = os.path.dirname(os.path.abspath(__file__))

W, H = 1240, 1754  # A4 @ 150dpi
SAFE = 90
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, W - SAFE

F_REG = os.path.join(BASE, "Poppins-Regular.ttf")
F_BOLD = os.path.join(BASE, "Poppins-Bold.ttf")


def font(name, size):
    path = F_BOLD if name in ("Poppins-Bold", "Bold", "SemiBold") else F_REG
    return ImageFont.truetype(path, 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


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

# ---- Header band ----
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)
logo_w = 200
logo_h = int(logo.height * logo_w / logo.width)
logo = logo.resize((logo_w, logo_h), Image.LANCZOS)
img.paste(logo, (X0, 75), logo)

d.text((X1, 60), "INVOICE", font=font("Poppins-Bold", 56), fill=(255, 255, 255), anchor="ra")
d.text((X1, 138), "No. INV/2026/0113", font=font("Poppins-Regular", 25), fill=(219, 234, 254), anchor="ra")
d.text((X1, 182), "Surabaya, 4 September 2026", font=font("Poppins-Regular", 21), fill=(219, 234, 254), anchor="ra")

# ---- From / Bill To ----
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(["Jl. Mangga 3 E-346 B, Surabaya",
                       "Email: halo@studiosoft.id",
                       "WA: 0819-3500-0624"]):
    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), "LEIT (Leadership-English Institute)", font=font("Poppins-Bold", 28), fill=DARK)
addr_lines = auto_wrap(
    d,
    "Apartment Waterplace Residence Ruko A/17, Seberang Pakuwon Mall, Kec. Wiyung, Surabaya, Jawa Timur - 60227",
    font("Poppins-Regular", 22),
    X1 - col2x,
)
ay = y + 88
for ln in addr_lines:
    d.text((col2x, ay), ln, font=font("Poppins-Regular", 22), fill=BODY)
    ay += 34
d.text((col2x, ay + 8), "+62 812-3446-2779", font=font("Poppins-Regular", 22), fill=BODY)

# ---- Table: NO | DESKRIPSI ----
ty = 680
d.rectangle([X0, ty, X1, ty + 60], fill=LIGHT)
d.text((X0 + 20, ty + 16), "NO", font=font("Poppins-Bold", 24), fill=DARK)
d.text((X0 + 130, ty + 16), "DESKRIPSI", font=font("Poppins-Bold", 24), fill=DARK)

items_desc = [
    "Paket Optimize Website (Paket 1) - September 2026",
    "Website Maintenance (Backup, Restore, Analytics, Clean)",
    "Design Graphics (Website, Meta & Google)",
    "Copywriting Blog (Maks. 10 Post)",
    "Corporate SEO (Analytics, Business, Map, Shortlink)",
    "Social Media Campaign (IG, FB, Google, Threads, LinkedIn)",
]
ry = ty + 60
row_h = 46
for i, desc in enumerate(items_desc, 1):
    lines = auto_wrap(d, desc, font("Poppins-Regular", 22), X1 - (X0 + 130) - 30)
    n = len(lines)
    rh = max(row_h, n * 34 + 14)
    d.line([X0, ry, X1, ry], fill=LINE)
    d.text((X0 + 20, ry + 12), str(i), font=font("Poppins-Regular", 22), fill=BODY)
    for li, ln in enumerate(lines):
        d.text((X0 + 130, ry + 12 + li * 34), ln, font=font("Poppins-Regular", 22), fill=DARK)
    ry += rh
d.line([X0, ry, X1, ry], fill=LINE)

# ---- Total ----
ty2 = ry + 50
d.rectangle([X1 - 520, ty2, X1, ty2 + 86], fill=LIGHT)
d.text((X1 - 500, ty2 + 25), "TOTAL", font=font("Poppins-Bold", 26), fill=DARK)
d.text((X1 - 28, ty2 + 23), rupiah(3000000), font=font("Poppins-Bold", 26), fill=BLUE, anchor="ra")

# ---- Payment + signature ----
fy = H - SAFE_BOTTOM - 330
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-Bold", 22), fill=DARK)
bank_lines = [
    "1. BCA 6750379638   (Rungkut Mapan, Surabaya)",
    "2. Mandiri 142-00-1068384-4   (Bratang Binangun, Surabaya)",
]
for i, t in enumerate(bank_lines):
    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)

try:
    ttd = Image.open(os.path.join(BASE, "ttd_uky.png")).convert("RGBA")
    tpx = ttd.load()
    for x in range(ttd.width):
        for y in range(ttd.height):
            r, g, b, a = tpx[x, y]
            if r > 240 and g > 240 and b > 240:
                tpx[x, y] = (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
except Exception:
    line_y = fy + 170
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)

# ---- Output ----
png_out = os.path.join(BASE, "Invoice_113_LEIT_September.png")
img.save(png_out)

pdf_out = os.path.join(BASE, "Invoice_113_LEIT_September.pdf")
img_rgb = img.convert("RGB")
img_rgb.save(pdf_out, "PDF", resolution=150.0)
print("OK ->", png_out)
print("OK ->", pdf_out)
