#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""StudioSoft Invoice — TSC (The Skin Code Clinic) Agustus 2026
Template BIRU (header biru + logo StudioSoft kiri atas), berdasarkan
generate_batch_3jt.py (Invoice_103_TSC.png) dengan penyesuaian:
- Tanpa Jatuh Tempo (template biru memang tidak ada)
- Item list: 5 item, no.2 = Maintenance Social Media Instagram
Output: PDF A4 150dpi -> invoices_augustus_2026/Invoice_103_TSC_The_Skin_Code_Clinic.pdf
"""
from PIL import Image, ImageDraw, ImageFont
import os

HERE = os.path.dirname(os.path.abspath(__file__))
BASE = os.path.join(os.path.dirname(HERE), "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 list TSC (sesuai permintaan Bos: no.2 = Maintenance Social Media Instagram)
ITEMS = [
    "Website Maintenance",
    "Maintenance Social Media Instagram",
    "Input Konten",
    "SEO",
    "Optimasi Campaign Insight",
]

CLIENT = {
    "no": "103",
    "nama": "The Skin Code Clinic",
    "alamat": "Jl. Kyai Mojo Blok A1 No. 5, Dusun Jeruk, Jerukgamping, Kec. Krian, Kabupaten Sidoarjo, Jawa Timur 61262",
    "kota": "Krian",
    "telp": "+62 813-3511-4324",
    "total": 3000000,
}


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']}/AGN/VIII/2026", font=font("Poppins-Regular", 25), fill=(219, 234, 254), anchor="ra")
    d.text((X1, 182), "Surabaya, 3 Agustus 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(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", 28), fill=DARK)
    addr_maxw = X1 - col2x
    addr_lines = auto_wrap(d, client["alamat"], font("Poppins-Regular", 22), addr_maxw)
    ay = y + 88
    for ln in addr_lines:
        d.text((col2x, ay), ln, font=font("Poppins-Regular", 22), fill=BODY)
        ay += 34
    if client.get("telp") and client["telp"] != "-":
        d.text((col2x, ay + 8), client["telp"], 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)

    ry = ty + 60
    row_h = 46
    for i, desc in enumerate(ITEMS, 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(client["total"]), font=font("Poppins-Bold", 26), fill=BLUE, anchor="ra")

    # Payment + signature
    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)
    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)

    # Signature: Hormat kami + ttd + nama + StudioSoft
    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 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)
    d.line([sig_x, fy + 40 + th2 + 12, X1 - 30, fy + 40 + th2 + 12], fill=LINE)
    line_y = fy + 40 + th2 + 12
    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


if __name__ == "__main__":
    img = 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_rgb = img.convert("RGB")
    img_rgb.save(pdf_out, "PDF", resolution=150.0)
    print("OK ->", png_out)
    print("OK ->", pdf_out)
