# Backend integration guide

This document described a hypothetical REST API for the old local-first
prototype. **The real backend is implemented** — Laravel session auth +
web routes. The actual contract the frontend (`public/js/core.js` `api()`
fetch wrapper and Blade forms) talks to is:

## Sessions & auth

All requests are same-origin cookie session + CSRF token
(`X-CSRF-TOKEN` header for JSON calls, `@csrf` for forms). There are no
Bearer tokens, no `/api` prefix.

- `POST /register` `{name, email, password, password_confirmation}` → session
- `POST /login` `{email, password, remember?}` → session (`?next=` honoured via `safeNext`)
- `POST /logout`, `POST /recover`, `POST /reset-password`
- `PATCH /account/profile` — `{name, password?, password_confirmation?, current_password?}`

JSON endpoints return JSON; validation failures are `422 {errors}` —
`api()` throws `apiError` with `.status`/`.errors`. `419` = session
expired (surface, never reload — unsaved edits would be lost).

## Invitations (owner)

```
POST   /invitations                  { template_id, title? }        → 201 invitation (client shape)
GET    /editor/{id}                  → editor page, NC.invitation + NC.templates
PATCH  /invitations/{id}             { revision, title?, data? }    → 200 invitation | 409 | 422 | 403
POST   /invitations/{id}/publish     { revision, custom_slug? }     → 200 invitation | 409 | 422
POST   /invitations/{id}/unpublish   (form or JSON)
POST   /invitations/{id}/duplicate   → 201
POST   /invitations/{id}/archive  ·  /restore
DELETE /invitations/{id}
GET    /invitations/{id}/rsvps.csv   (owner CSV export, formula-safe)
```

**Concurrency:** every `PATCH` and `publish` requires `revision` (int ≥
0) compared under a row lock; responses return the new `revision`.
`409 {message, revision}` means another write won — the client must not
overwrite local state. Status mutations (archive/restore/unpublish)
bump `revision` server-side only.

**Publish contract:** server validates the whole stored `WeddingData`
payload (schema + unsafe URL/media refs are never grandfathered), then
readiness: names per language (BN names allowed on bn/bilingual), every
event needs date+time+venue, deadline ≤ first event. Errors keyed
`data.*`. `custom_slug`: Plus/Pro, first publish only, normalized via
`Invitation::slugify` (latin + Bengali), reserved/`untitled-*`/duplicate
→ 422; slug immutable after `published_at` is set.

**Quotas:** `max_invitations` counts draft+published (archived free).
Enforced on create, duplicate, restore AND any archived→active
transition — all under owner-row lock.

## Public invitation & RSVP

```
GET  /i/{slug}        published only → page + NC.invitation (public shape), NC.mediaAlt
POST /i/{slug}/rsvp   { name, phone?, email?, attendance, guestCount?, eventIds?, message? }
                    → 201 { ok, rsvpId } | 422 | 429 (rate limit)
```

RSVP semantics: enabled flag + `Asia/Dhaka` end-of-day deadline; response
cap = plan `rsvp_cap` (responses, not headcount); independent
email/phone duplicate checks only when a contact is given (anonymous
replies always allowed); `declined` → 0 guests, attending/maybe ≥ 1;
`askPerEvent` off ignores `eventIds`. Owner self-RSVP allowed and counted
(local default). Unpublished mid-request → 404 via locked recheck.

## Media

```
GET    /account/media            { assets: [ {id, url, altText, width, height, sizeBytes} ] }
POST   /account/media            multipart: photo + alt_text   → 201 { asset }
PATCH  /account/media/{uuid}     { alt_text }
DELETE /account/media/{uuid}
GET    /media/{uuid}             owner OR any guest while a published invitation owned by
                                 the owner references that exact URL
```

`WeddingData` photo fields accept curated `/assets/…` paths or canonical
`/media/{uuid}` owned by the invitation owner — re-verified inside the
write transaction. `NC.mediaAlt` maps referenced URLs → alt text only.

## Templates & admin

- `GET /designs`, `GET /designs/{slug}` — catalog + live preview.
- Admin (`admin` middleware): `GET /admin?tab=…` (overview · templates ·
  users · orders · support), `POST /admin/templates`,
  `PATCH /admin/templates/{id}` (variants JSON validated), `POST
  /admin/templates/{id}/toggle`, `PATCH /admin/users/{user}/access`,
  `PATCH /admin/orders/{order}/fulfillment`, `POST
  /admin/support/{ticket}/reply`, close ticket — all locked + audited
  (`audit_logs`). Template edits freeze `template_snapshot` on legacy
  invitations inside the same lock.

## Support

- `POST /account/support` `{subject, body}` → ticket.
- `POST /account/support/{ticket}/reply` (owner) ·
  `POST /admin/support/{ticket}/reply` (admin) — transactional, locked,
  closed-ticket protected, `support_messages` + `AuditLog`.

## Checkout — DEMO ONLY, local/testing

`GET /checkout?kind=plan|template|print&id=&cart=` renders the quote +
demo form. `POST /checkout {checkout_token, kind, id?, cart?, pm?}` →
order + entitlement, once per `checkout_token` (unique, idempotent
replay). Strict server-side cart validation + re-pricing; no
downgrades/double-sells. **503 outside local/testing** — there is no
real payment gateway; bKash/Nagad/SSLCommerz are future webhook
integration points, not implemented.

## Legacy

`/{page}.html` → 301 named-route redirects (`invite.html?i=slug` →
`/i/{slug}`). `/demo/reset` exists only under `APP_ENV=local|testing`.
