# Architecture

NikahCard is a Laravel 13 application (PHP 8.3+). Blade views render every
page; each view injects a `window.NC` bootstrap payload built by
`Controller::nc()` that the plain-file frontend in `public/js` consumes —
there is no npm/Vite build step. MySQL is the application database
(`nikahcard`); the PHPUnit suite runs entirely on SQLite `:memory:`.

```
Blade page + window.NC bootstrap
        │  page scripts call fetch() services (js/core.js api())
        ▼
routes/web.php (+ media.php, operations.php)
        │  FormRequest / controller validation, ownership + role checks
        ▼
Controllers → Models + app/Services
        │  DB::transaction + lockForUpdate on shared rows
        ▼
MySQL (app)  ·  SQLite :memory: (tests)
```

## The invitation engine

**An invitation is data + a renderer, not a static page.**

- `templates` table (`Template` model): slug, categories, languages,
  `renderer` key, `variants` (theme token sets), `sections`, `caps`
  (what the editor may expose), `min_plan`, `price_bdt`, `version`, status.
- `invitations` table (`Invitation` model): `data` = the customer-owned
  `WeddingData` blob, `slug`, `status` (draft/published/archived),
  `revision` (optimistic-concurrency counter), `published_at`,
  `template_version`, `template_snapshot`.
- `public/js/engine.js` renders `WeddingData` inside a template — the same
  renderer powers `/i/{slug}` (live) and scaled previews (`mode=preview`),
  so previews can never drift from the published look.
- Customer data never contains layout code. `WeddingData` is validated
  server-side; the editor renders values as text/escaped attributes.

## Backend contract

| Piece | Responsibility |
| --- | --- |
| `Controller::nc()` | Builds `window.NC`: plans, photos, print products, event timezone, templates, user |
| `UpdateInvitationRequest` | PATCH contract: owner 403, `revision` required, full `WeddingData` schema via `WeddingDataValidator` |
| `WeddingDataValidator` | Allowed keys, types/bounds, event ids, safe URLs, curated/owned-media photos, language/variant membership, cap-off grandfathering. Safety invariants (URL/photo/media ownership) always apply — only *cap usage* is grandfathered |
| `InvitationEntitlements` | Plan slot checks inside a transaction on the locked user row; draft+published count, archived excluded |
| `MediaStorage` / `MediaController` | Owner media library: decode-verify, EXIF normalize, quota-lock, private disk behind `/media/{uuid}` |
| `AdminOperationsController` / `SupportReplyController` | Locked role/plan/fulfillment mutations + `AuditLog` |
| `CheckoutController` | **Demo only** — refuses outside local/testing; strict cart validation, server re-pricing, idempotent `checkout_token`, no downgrades/double-sells |

## Concurrency & integrity

- **Optimistic concurrency:** every invitation write compares the client
  `revision` under a row lock — a stale tab gets `409 {revision}` instead
  of silently clobbering newer edits. Successful mutations increment
  `revision` exactly once.
- **Template snapshots (TPL-02):** each invitation stores a whitelisted
  copy of the template at creation (`template_snapshot`); admin design
  edits freeze unsnapshotted rows to the *pre-change* design inside the
  same lock. `Invitation::renderTemplate()` resolves snapshot → live
  fallback, so admin edits never rewrite a couple's existing invitation.
- **Lock order is always owner row → invitation row** (update, publish,
  restore, media destroy, quota checks) so concurrent writes serialize.
- **Quotas** apply on any transition that activates an invitation —
  create, duplicate, restore, and archived → draft/published.
- **RSVPs** run inside a locked transaction: enabled/deadline
  (`Asia/Dhaka` end-of-day) → cap → independent email/phone duplicate
  checks → create. Anonymous replies are allowed; the public response is
  `{ok, rsvpId}` only.

## Public surface

- `/i/{slug}` — published invitation (404 + `invite-unavailable` otherwise).
- `POST /i/{slug}/rsvp` — rate-limited guest RSVP.
- `GET /media/{uuid}` — private media: owner, or any guest while a
  *published* invitation owned by the asset's owner references it.
- `/{page}.html` — legacy redirect shim to named routes.

## Plans & entitlements

`config/nikahcard.php` defines Free/Go/Plus/Pro (`max_invitations`,
`rsvp_cap`, feature lists, BDT prices). `templates.min_plan` gates design
access; `users.unlocked_templates` holds one-off design purchases. Plan
slots count *active* invitations; the RSVP cap counts *responses* (not
headcount). Commercial terms (duration, refunds, expiry) are undecided —
no expiry logic exists.

## Demo data & environments

`DatabaseSeeder` seeds demo accounts/data only under `local`/`testing`;
`TemplateSeeder` runs in every environment. The demo reset endpoint
(`/demo/reset`) and demo payment note are likewise local/testing-only.
`APP_ENV` decides; there is no real payment gateway anywhere.
