"""
order_service.py — what the operator needs to PREPARE an order (client brief 2026-10-21, sheet 7).

  * `detail`: everything about an order — each ordered photo (which card it comes from, with a thumbnail), the
    product, the quantity, the price, how many prints there are to make;
  * `lab_entries`: the HD originals of the prints, one file per line with a readable name (family code, class,
    format, quantity: `235-RZJ-7VU_2B_13x18_x2.jpg`), to send to the lab as one folder;
  * `recap_pdf`: the printable recap sheet of the order — code, class, format, quantity and a "Prepared" box per
    line, a total to print, and nothing else.
"Validating" an order (a "Done" marker, no e-mail) is a column of its own, never the batch status: the batch status
is what tells the family its prints are ready (admin.py).
"""
import io
import json
import logging
import re
import unicodedata
from pathlib import Path
from typing import Callable, Optional

from PIL import Image, ImageDraw, ImageFont

from core import storage
from core.storage import Key
from services import media_service, photo_service, shipping_service, upload_service

log = logging.getLogger("meeconic.orders")

_FONTS = Path(__file__).resolve().parent.parent / "fonts"
_SIZE_RE = re.compile(r"(\d+(?:[.,]\d+)?)\s*[x×]\s*(\d+(?:[.,]\d+)?)", re.IGNORECASE)


def _ascii(text: str) -> str:
    return "".join(c for c in unicodedata.normalize("NFD", text) if unicodedata.category(c) != "Mn")


def format_token(name: str) -> str:
    """"Tirage papier 13×18" → "13x18"; a name with no size → its readable slug ("Porte-cles-photo")."""
    m = _SIZE_RE.search(name or "")
    if m:
        return f"{m.group(1).replace(',', '.')}x{m.group(2).replace(',', '.')}"
    slug = re.sub(r"[^A-Za-z0-9]+", "-", _ascii(name or "")).strip("-")
    return (slug or "product")[:30]


# What the lab needs to read, not the catalogue's marketing name (client 2026-10-28: "only the format, 10x15, 18x24…,
# just the print; key ring and so on"). A print -> its size; an object -> the object, with its size when it has one
# (a magnet 10x15 must not be printed as a plain 10x15 photo).
_ARTICLES = {"le", "la", "les", "l", "un", "une", "des", "the", "a", "an", "el", "los", "las", "uno", "una"}
_GENERIC = {"portrait", "portraits", "tirage", "tirages", "photo", "photos", "grand", "grande", "petit", "petite",
            "impression", "copie", "print", "prints", "foto", "fotos", "copia", "retrato", "format", "formato"}


def short_name(name: str) -> str:
    """"Le grand portrait (18 × 24)" -> "18×24"; "Le magnet frigo (10 × 15)" -> "Magnet 10×15";
    "Le calendrier 2027 avec la photo…" -> "Calendrier"; "Porte-clé" -> "Porte-clé"."""
    m = _SIZE_RE.search(name or "")
    size = f"{m.group(1).replace(',', '.')}×{m.group(2).replace(',', '.')}" if m else ""
    words = [re.sub(r"^[lLdD]['’]", "", w) for w in re.findall(r"[^\W\d_][\w'’-]*", (name or "").split("(")[0])]
    words = [w for w in words if w and w.lower() not in _ARTICLES]
    first = words[0][:1].upper() + words[0][1:] if words else ""
    if size:
        return size if not first or first.lower() in _GENERIC else f"{first} {size}"
    return first or (name or "")[:30]


def lab_token(name: str) -> str:
    """short_name for a file name: "18x24", "Magnet-10x15", "Porte-cle", "Calendrier"."""
    slug = re.sub(r"[^A-Za-z0-9.]+", "-", _ascii(short_name(name).replace("×", "x"))).strip("-")
    return (slug or "product")[:30]


def _class_token(name: str) -> str:
    return re.sub(r"[^A-Za-z0-9]+", "-", _ascii(name or "")).strip("-") or "class"


def line_name(line: dict, lang: str = "fr") -> str:
    names = line.get("format_names") or {}
    return names.get(lang) or names.get("fr") or line.get("format_label") or line.get("format_id", "")


def photo_origin(school_id: str, code: str, filename: str) -> Optional[dict]:
    """The card (class + number) a photo sits in, or None for the older layouts."""
    sib = upload_service.siblings_names(school_id)
    for r in photo_service.folder_rows(school_id, code):
        if storage.exists(photo_service.folder_path(school_id, r) / filename):
            sibling = r["class_name"] in sib
            return {"class_name": r["class_name"], "seq": r["seq"], "sibling_photo": sibling,
                    "label": upload_service.card_label(r["class_name"], r["seq"], sibling)}
    return None


def build_line(school_id: str, code: str, item: dict, fmt: dict) -> dict:
    """An order line as it is stored: what it delivers travels WITH the order, so a product edited or deleted later
    changes nothing for it. Shared by the family checkout and the admin's test order (they must give the same zip).
    Raises ValueError when the photo is not the family's."""
    if media_service.safe_photo_path(school_id, code, item["photo_filename"]) is None:
        raise ValueError(f"Photo introuvable : {item['photo_filename']}")
    # Which card the photo comes from travels with the line too: the dashboards credit a solo photo to the child's
    # class and split the Siblings photo between the family's classes (brief sheet 8).
    origin = photo_origin(school_id, code, item["photo_filename"])
    return {**item, "kind": fmt["kind"], "digital": fmt["digital"], "physical": fmt["physical"],
            "format_names": {lg: fmt[f"name_{lg}"] for lg in ("fr", "en", "es")},
            **({"components": [{"format_id": c["format_id"], "qty": c["qty"], "physical": c["physical"],
                                "format_names": {lg: c[f"name_{lg}"] for lg in ("fr", "en", "es")},
                                **({"template": c["template"]} if c.get("template") else {})}
                               for c in fmt["components"]]} if fmt.get("components") else {}),
            # The montage template as it is NOW: the lab folder of this order uses this copy forever, so a
            # template replaced next year never changes a paid calendar (template_service).
            **({"template": fmt["template"]} if fmt.get("template") and fmt["physical"] else {}),
            **({"origin_class": origin["class_name"], "origin_sibling": origin["sibling_photo"]} if origin else {})}


def lines(school_id: str, row, lang: str = "fr") -> list[dict]:
    """The order's lines, enriched for the screen. A photo that was deleted since (retention) is `missing`."""
    code = row["family_code"]
    out = []
    for it in json.loads(row["items_json"] or "[]"):
        key = media_service.safe_photo_path(school_id, code, it["photo_filename"])
        origin = photo_origin(school_id, code, it["photo_filename"]) if key else None
        physical = it.get("physical", not it.get("digital", False))
        out.append({
            "photo_filename": it["photo_filename"], "format_id": it["format_id"], "name": line_name(it, lang),
            "quantity": it["quantity"], "unit_price": it["unit_price"],
            "total": round(it["unit_price"] * it["quantity"], 2), "physical": bool(physical),
            "digital": bool(it.get("digital", False)), "is_magic": bool(it.get("is_magic")),
            "job_label": it.get("job_label"), "kind": it.get("kind"),
            # What the pack contains, as it was when the order was paid; quantities are per pack.
            "components": [{"name": line_name(c, lang), "qty": int(c["qty"]), "physical": bool(c.get("physical", True)),
                            "template": c.get("template")}
                           for c in it.get("components") or []],
            "template": it.get("template"),          # the copy taken at payment (template_service), None = the bare photo
            "class_name": origin["class_name"] if origin else (row["class_name"] or ""),
            "card": origin["label"] if origin else None,
            "missing": key is None,
            "thumb_url": media_service.admin_thumb_url(school_id, code, it["photo_filename"]) if key else None,
        })
    return out


def print_units(l: dict) -> list[tuple[str, int]]:
    """[(format name, how many)] to print for a line: a pack's physical components, else the line itself."""
    return [(name, n) for name, n, _tpl in print_jobs(l)]


def print_jobs(l: dict) -> list[tuple[str, int, Optional[dict]]]:
    """print_units with the montage template of each (None = the photo as it is)."""
    if l.get("components"):
        return [(c["name"], c["qty"] * l["quantity"], c.get("template")) for c in l["components"] if c["physical"]]
    return [(l["name"], l["quantity"], l.get("template"))] if l["physical"] else []


def detail(school_id: str, row, lang: str = "fr") -> dict:
    ls = lines(school_id, row, lang)
    prints = sum(n for l in ls for _name, n in print_units(l))
    return {"lines": ls, "prints": prints, "photos": len({l["photo_filename"] for l in ls}),
            "validated_at": row["validated_at"], "validated_by": row["validated_by"]}


def lab_entries(school_id: str, row, folder: str) -> tuple[list[tuple[str, "Key | Callable[[], bytes]"]], list[str]]:
    """[(path inside the zip, storage key)] of the originals to print, plus the names of those no longer there.
    A product with a template gives the finished montage instead (client 2026-11-15: "ready to send to print"),
    made while the zip is sent, one at a time (a calendar is ~3500 px wide: a whole order in memory would not be)."""
    code = row["family_code"]
    entries: list[tuple[str, Key]] = []
    missing: list[str] = []
    used: set[str] = set()
    for l in lines(school_id, row, "fr"):
        units = print_jobs(l)
        if not units:
            continue                                   # a digital-only line is not sent to the lab
        key = media_service.safe_photo_path(school_id, code, l["photo_filename"])
        if key is None:
            missing.append(l["photo_filename"])
            continue
        # A pack: one file per product in it, named after the pack AND the product ("..._Pack-Souvenir_13x18_x2").
        pack = f"{format_token(l['name'])}_" if l.get("components") else ""
        for unit_name, qty, tpl in units:
            base = f"{code}_{_class_token(l['class_name'])}_{pack}{lab_token(unit_name)}_x{qty}"
            ext = ".jpg" if tpl else (Path(l["photo_filename"]).suffix.lower() or ".jpg")
            name, n = f"{base}{ext}", 2
            while name in used:                        # the same photo twice in the same format
                name, n = f"{base}_{n}{ext}", n + 1
            used.add(name)
            entries.append((f"{folder}/{name}", _montage(school_id, tpl, key) if tpl else key))
    return entries, missing


def _montage(school_id: str, tpl: dict, key: Key) -> Callable[[], bytes]:
    def make() -> bytes:
        from services import template_service
        return template_service.render(school_id, tpl, storage.read_bytes(key))
    return make


# ── The recap sheet ─────────────────────────────────────────────────────────────────────────────────

_TXT = {
    "fr": {"title": "Fiche de commande", "order": "Commande", "paid": "Payée en ligne", "placed": "le {d}", "test": "TEST", "test_line": "COMMANDE TEST : non payée, ne pas imprimer",
           "home": "Domicile", "ship_to": "Livrer à", "handed_home": "Colis envoyé",
           "school": "École", "code": "Code famille", "delivery": "Remise en classe", "col_photo": "Photo",
           "col_product": "Produit", "col_qty": "Qté", "col_done": "Préparé", "pack": "Pack",
           "unit": ("tirage", "tirages"), "photo": ("photo", "photos"), "to_print": "à imprimer",
           "different": "différente", "differents": "différentes", "in_pack": "dans le pack",
           "none": "Aucun tirage dans cette commande.", "page": "Page {a} sur {b}",
           "check": "Contrôle", "prepared_by": "Préparé par", "date": "Date", "handed": "Remis à l'enseignant"},
    "en": {"title": "Order sheet", "order": "Order", "paid": "Paid online", "placed": "on {d}", "test": "TEST", "test_line": "TEST ORDER: not paid, do not print",
           "home": "Home", "ship_to": "Ship to", "handed_home": "Parcel sent",
           "school": "School", "code": "Family code", "delivery": "Handed out in class", "col_photo": "Photo",
           "col_product": "Product", "col_qty": "Qty", "col_done": "Prepared", "pack": "Pack",
           "unit": ("print", "prints"), "photo": ("photo", "photos"), "to_print": "to print",
           "different": "different", "differents": "different", "in_pack": "in the pack",
           "none": "No print in this order.", "page": "Page {a} of {b}",
           "check": "Check", "prepared_by": "Prepared by", "date": "Date", "handed": "Handed to the teacher"},
    "es": {"title": "Hoja de pedido", "order": "Pedido", "paid": "Pagado en línea", "placed": "el {d}", "test": "PRUEBA", "test_line": "PEDIDO DE PRUEBA: no pagado, no imprimir",
           "home": "Domicilio", "ship_to": "Enviar a", "handed_home": "Paquete enviado",
           "school": "Colegio", "code": "Código familia", "delivery": "Entrega en clase", "col_photo": "Foto",
           "col_product": "Producto", "col_qty": "Cant.", "col_done": "Preparado", "pack": "Pack",
           "unit": ("copia", "copias"), "photo": ("foto", "fotos"), "to_print": "a imprimir",
           "different": "distinta", "differents": "distintas", "in_pack": "en el pack",
           "none": "Ninguna copia en este pedido.", "page": "Página {a} de {b}",
           "check": "Control", "prepared_by": "Preparado por", "date": "Fecha", "handed": "Entregado al docente"},
}
_RED = (196, 30, 58)
_PAGE_W, _PAGE_H, _DPI = 1240, 1754, 150          # A4 at 150 dpi
_M = 80                                           # page margin
# One ink (navy), one accent (gold, only for a pack), tone steps instead of boxes and pills.
_NAVY, _INK, _GREY, _LINE = (10, 31, 68), (31, 36, 48), (92, 100, 116), (226, 229, 235)
_SOFT, _GOLD, _GOLD_PALE = (244, 242, 236), (112, 82, 10), (250, 242, 218)    # gold text >= 4.5:1 on its band


def _font(kind: str, size: int) -> ImageFont.FreeTypeFont:
    return ImageFont.truetype(str(_FONTS / {"regular": "Inter-Regular.ttf", "bold": "Inter-Bold.ttf",
                                            "semibold": "Inter-SemiBold.ttf", "mono": "JetBrainsMono-Bold.ttf"}[kind]), size)


def _fit(draw, text: str, font, width: int) -> str:
    if draw.textlength(text, font=font) <= width:
        return text
    while text and draw.textlength(text + "…", font=font) > width:
        text = text[:-1]
    return text + "…"


def recap_thumbs(school_id: str, row, order_lines: list[dict], px: int = 192) -> dict:
    """{photo file name: small square picture} for the recap's rows (the person preparing the order sees WHICH photo).
    A photo deleted since (retention) is just left out."""
    out = {}
    for l in order_lines:
        name = l["photo_filename"]
        if name in out:
            continue
        key = media_service.safe_photo_path(school_id, row["family_code"], name)
        if key is None:
            continue
        try:
            with Image.open(storage.local_path(key)) as im:
                im = im.convert("RGB")
                side = min(im.size)
                im = im.crop(((im.width - side) // 2, (im.height - side) // 2,
                              (im.width + side) // 2, (im.height + side) // 2)).resize((px, px), Image.LANCZOS)
            out[name] = im
        except Exception as exc:
            log.warning("Recap: thumbnail of %s unavailable (%s)", name, exc)
    return out


def _date(iso: str) -> str:
    try:
        return f"{iso[8:10]}/{iso[5:7]}/{iso[:4]} · {iso[11:16]}" if iso and len(iso) >= 16 else (iso or "")
    except Exception:
        return ""


def _n(t: dict, key: str, n: int) -> str:
    one, many = t[key]
    return f"{n} {one if n == 1 else many}"


def recap_pdf(school_name: str, row, order_lines: list[dict], classes: list[str], lang: str = "fr",
              thumbs: Optional[dict] = None, school_id: Optional[str] = None) -> bytes:
    """The A4 sheet that goes with the order to the person preparing it (and to the lab): who, which class it is
    handed out in, then one row per thing to print with the photo it is made from and a box to tick. A pack is a
    block: its name on a gold band with its photo, the prints it contains under it. The family code is printed ONCE.
    Paper rules (2026-10-28 review): three type sizes, one ink and one accent, sentence case, the text face for the
    code, square corners, tone steps instead of boxes, the total right after the rows, Meeconic's real logo."""
    from services import brand_service
    t = _TXT.get(lang, _TXT["fr"])
    # The admin's test order (admin.py) gives the same sheet, marked so it cannot be taken for a paid one.
    test = (row["payment_status"] if "payment_status" in row.keys() else "") == "test"
    # Sent by post (shipping_service): the sheet must say where, or the parcel ends up in the class pile.
    home = shipping_service.ships_home(row)
    ship = shipping_service.address_of(row)
    ship_h = 116 if ship else 0
    thumbs = thumbs or {}
    rows: list[tuple] = []                     # ("pack", line, n) | ("item", line, name, qty, in_pack)
    for l in order_lines:
        units = print_units(l)
        if not units:
            continue
        if l.get("components"):
            rows.append(("pack", l, sum(q for _n2, q in units)))
            rows += [("item", l, name, qty, True) for name, qty in units]
        else:
            rows.append(("item", l, l["name"], l["quantity"], False))
    total = sum(r[3] for r in rows if r[0] == "item")
    n_photos = len({r[1].get("photo_filename") for r in rows if r[1].get("photo_filename")})

    L, Mm, S = 52, 27, 20                      # the three sizes: large, medium, small
    f = {"L": _font("bold", L), "Mb": _font("bold", Mm), "M": _font("semibold", Mm), "S": _font("regular", S),
         "Ss": _font("semibold", S)}
    # The uploaded logo is ready to go in the band, but it stays off until the client says they want it there
    # (Dario 2026-10-29). To turn it on: logo = brand_service.logo_image(300, 60, school_id).
    logo = None
    logo_on_dark = brand_service.logo_tone(school_id) == "light"

    pages: list[Image.Image] = []
    page_no = 0

    def new_page():
        nonlocal page_no
        page_no += 1
        img = Image.new("RGB", (_PAGE_W, _PAGE_H), "white")
        d = ImageDraw.Draw(img)
        d.rectangle((0, 0, _PAGE_W, 112), fill=_NAVY)
        if logo is not None:                                 # Meeconic's own logo; a dark one gets a white plate
            lx, ly = _M, (112 - logo.height) // 2
            if not logo_on_dark:
                d.rectangle((lx - 14, ly - 10, lx + logo.width + 14, ly + logo.height + 10), fill="white")
            img.paste(logo, (lx, ly), logo)
        else:
            d.text((_M, 56), "MEECONIC", font=f["Mb"], fill="white", anchor="lm")
        d.text((_PAGE_W - _M, 56), t["title"], font=f["M"], fill=(205, 214, 232), anchor="rm")
        y = 152
        d.text((_M, y), f"{t['order']} {row['id'][:8].upper()}", font=f["L"], fill=_NAVY, anchor="lt")
        if test:                       # on EVERY page: a loose test sheet must never pass for a paid order
            d.text((_PAGE_W - _M, y + 4), t["test"], font=f["L"], fill=_RED, anchor="rt")
        y += 72
        if page_no == 1:
            when = _date(row["created_at"] if "created_at" in row.keys() else "")
            if test:
                d.text((_M, y), t["test_line"], font=f["Ss"], fill=_RED, anchor="lt")
            else:
                status = t["paid"] + (f" {t['placed'].format(d=when)}" if when else "")
                d.text((_M, y), status, font=f["S"], fill=_GREY, anchor="lt")
            y += 56
            # three facts, once: the school, the family code, the class the prints are handed out in
            gap, inner = 16, _PAGE_W - 2 * _M - 32
            widths = [int(inner * .46), int(inner * .28), inner - int(inner * .46) - int(inner * .28)]
            x0 = _M
            for (label, value), cw in zip(((t["school"], school_name or "—"), (t["code"], row["family_code"]),
                                           (t["delivery"], ", ".join(classes) or "—") if not home
                                           else (t["ship_to"], t["home"])), widths):
                d.rectangle((x0, y, x0 + cw, y + 108), fill=_SOFT)
                d.text((x0 + 24, y + 22), label, font=f["S"], fill=_GREY)
                font, size = f["Mb"], Mm
                while size > S and d.textlength(value, font=font) > cw - 48:      # a long school name shrinks
                    size -= 1
                    font = _font("bold", size)
                d.text((x0 + 24, y + 56), _fit(d, value, font, cw - 48), font=font, fill=_NAVY)
                x0 += cw + gap
            y += 148
            if ship:
                d.rectangle((_M, y - 24, _PAGE_W - _M, y + 76), fill=_GOLD_PALE)
                d.text((_M + 24, y - 12), f"{t['ship_to']} : {ship['name']}", font=f["Ss"], fill=_NAVY)
                where = ", ".join(x for x in (ship["address"], ship.get("address2"),
                                              f"{ship['postcode']} {ship['city']}", "France") if x)
                d.text((_M + 24, y + 24), _fit(d, where, f["M"], _PAGE_W - 2 * _M - 48), font=f["M"], fill=_NAVY)
                y += ship_h
        else:
            y += 20
        d.rectangle((_M, y, _PAGE_W - _M, y + 48), fill=_SOFT)
        for text, x, anchor in ((t["col_photo"], _M + 20, "lm"), (t["col_product"], _M + 150, "lm"),
                                (t["col_qty"], _PAGE_W - _M - 200, "mm"), (t["col_done"], _PAGE_W - _M - 62, "mm")):
            d.text((x, y + 24), text, font=f["Ss"], fill=_GREY, anchor=anchor)
        return img, d, y + 48

    def thumb(img, d, name, x, y, size):
        pic = thumbs.get(name)
        if pic is None:
            d.rectangle((x, y, x + size, y + size), fill=_SOFT)
        else:
            img.paste(pic.resize((size, size), Image.LANCZOS), (x, y))

    def row_h(r) -> int:
        return 104 if r[0] == "pack" else (76 if r[4] else 128)

    def block_h(i: int) -> int:
        """A pack is kept on one page with its prints: its band never ends a page alone."""
        h = row_h(rows[i])
        if rows[i][0] == "pack":
            for x in rows[i + 1:]:
                if x[0] != "item" or not x[4]:
                    break
                h += row_h(x)
        return h

    bottom = _PAGE_H - 140                                   # above the footer
    end_h = 36 + 120 + 30 + 150                              # the total, a gap, the control block
    # Dry run of the page breaks: when the last page has no room left for the total and the control block, the
    # last group of rows moves with them to the next page (never a page holding only the control block).
    first_top, next_top = 476 + ship_h, 292                  # where the rows start on page 1 / on the next pages
    forced, yy, page_first = None, first_top, 0
    for i, r in enumerate(rows):
        starts = r[0] == "pack" or not r[4]
        if starts and yy + min(block_h(i), bottom - 400) > bottom:
            yy, page_first = next_top, i
        yy += row_h(r)
    if rows and yy + end_h > bottom:
        last = max(i for i, r in enumerate(rows) if r[0] == "pack" or not r[4])
        if last > page_first:
            forced = last

    img, d, y = new_page()
    if not rows:
        d.text((_M + 20, y + 40), t["none"], font=f["M"], fill=_GREY)
        y += 120
    for i, r in enumerate(rows):
        h = row_h(r)
        starts = r[0] == "pack" or not r[4]
        if starts and (y + min(block_h(i), bottom - 400) > bottom or i == forced):
            pages.append(img)
            img, d, y = new_page()
        l = r[1]
        meta = "  ·  ".join(x for x in (l.get("card") or l.get("class_name") or "", l.get("photo_filename") or "") if x)
        if r[0] == "pack":
            d.rectangle((_M, y + 12, _PAGE_W - _M, y + h), fill=_GOLD_PALE)
            d.rectangle((_M, y + 12, _M + 8, y + h), fill=_GOLD)
            thumb(img, d, l.get("photo_filename"), _M + 28, y + 22, 72)          # the pack's photo, once
            mid = y + 12 + (h - 12) // 2
            d.text((_M + 120, mid - 14), f"{t['pack']} · {l['name']}", font=f["Mb"], fill=_NAVY, anchor="lm")
            d.text((_M + 120, mid + 20), _fit(d, meta, f["S"], 560), font=f["S"], fill=_GREY, anchor="lm")
            right = f"×{l['quantity']}  ·  {_n(t, 'unit', r[2])} {t['in_pack']}"
            d.text((_PAGE_W - _M - 24, mid), right, font=f["Ss"], fill=_GOLD, anchor="rm")
            y += h
            continue
        _kind, l, name, qty, in_pack = r
        mid = y + h // 2
        if in_pack:                                          # a print of the pack, grouped under its band
            d.rectangle((_M, y, _M + 8, y + h), fill=_GOLD_PALE)
            d.text((_M + 120, mid), _fit(d, short_name(name), f["M"], _PAGE_W - _M - 420), font=f["M"], fill=_INK, anchor="lm")
        else:
            thumb(img, d, l.get("photo_filename"), _M + 16, y + 14, 100)
            d.text((_M + 150, mid - 16), _fit(d, short_name(name), f["M"], _PAGE_W - _M - 450), font=f["M"], fill=_INK, anchor="lm")
            d.text((_M + 150, mid + 20), _fit(d, meta, f["S"], _PAGE_W - _M - 450), font=f["S"], fill=_GREY, anchor="lm")
        cx = _PAGE_W - _M - 200
        d.ellipse((cx - 30, mid - 30, cx + 30, mid + 30), fill=_SOFT)
        d.text((cx, mid), str(qty), font=f["Mb"], fill=_NAVY, anchor="mm")
        bx = _PAGE_W - _M - 62
        d.rectangle((bx - 22, mid - 22, bx + 22, mid + 22), outline=_NAVY, width=3)       # the box to tick
        d.line((_M, y + h, _PAGE_W - _M, y + h), fill=_LINE, width=2)                    # a real table's rows
        y += h

    if rows:                                                 # the total, right after the rows
        y += 36
        d.rectangle((_M, y, _PAGE_W - _M, y + 120), fill=_NAVY)
        d.text((_M + 40, y + 60), f"{_n(t, 'photo', n_photos)} {t['different'] if n_photos == 1 else t['differents']}",
               font=f["S"], fill=(190, 200, 222), anchor="lm")
        unit = f"{t['unit'][0] if total == 1 else t['unit'][1]} {t['to_print']}"
        d.text((_PAGE_W - _M - 40, y + 62), unit, font=f["M"], fill="white", anchor="rm")
        d.text((_PAGE_W - _M - 56 - d.textlength(unit, font=f["M"]), y + 60), str(total), font=f["L"], fill="white",
               anchor="rm")
        y += 120                                              # past the total: the control block checks from here
    # The control block, on the last page above the footer: who prepared the order, when, and that it reached the
    # teacher (written by hand). A page of its own when the rows leave no room for it.
    box_y, box_h = _PAGE_H - 120 - 150, 150
    if y + 30 > box_y:
        pages.append(img)
        img, d, y = new_page()
    d.rectangle((_M, box_y, _PAGE_W - _M, box_y + box_h), fill=_SOFT)
    d.text((_M + 30, box_y + 34), t["check"], font=f["Mb"], fill=_NAVY, anchor="lm")
    fy = box_y + 104                                         # the writing line, under each label
    fields = [(t["prepared_by"], _M + 30, _M + 400), (t["date"], _M + 440, _M + 640)]
    for label, x0, x1 in fields:
        d.text((x0, fy - 34), label, font=f["S"], fill=_GREY, anchor="lm")
        d.line((x0, fy + 10, x1, fy + 10), fill=_GREY, width=2)                       # a form field to write on
    hx = _M + 680
    d.rectangle((hx, fy - 22, hx + 44, fy + 22), outline=_NAVY, width=3)
    d.text((hx + 62, fy), t["handed_home"] if home else t["handed"], font=f["M"], fill=_INK, anchor="lm")
    pages.append(img)
    for i, pg in enumerate(pages, start=1):
        dd = ImageDraw.Draw(pg)
        dd.text((_M, _PAGE_H - 60), "Meeconic  ·  contact@meeconic.com", font=f["S"], fill=_GREY, anchor="lm")
        dd.text((_PAGE_W - _M, _PAGE_H - 60), t["page"].format(a=i, b=len(pages)), font=f["S"], fill=_GREY, anchor="rm")
    buf = io.BytesIO()
    pages[0].save(buf, "PDF", resolution=_DPI, save_all=True, append_images=pages[1:], title=f"{t['order']} {row['id'][:8]}")
    return buf.getvalue()
