# AI try-on

Customers upload a selfie, pick a BeAuthentic colour and get a preview of their hair in that colour — or every colour at once on the **colour board**. Results link straight to the exact product variant ("Get this look"), and purchases after a try-on are attributed back to it.

Pages: `/try-it-on` (optionally `?product={slug}` to preselect), `/try-it-on/colour-board`, `/account/saved-looks`, public share pages `/looks/{token}`. Admin: **Admin → AI Try-On** (`/admin/ai`, admin only).

## Connecting a provider (Admin → AI Try-On → Provider & API keys)

1. Pick the **model**:
   - `gpt-image-1` — best quality
   - `gpt-image-1-mini` — cheaper and faster
   - `dall-e-2` — legacy
   - "Other model…" — for newer ones
2. Paste your **API key** (platform.openai.com → API keys) and press **Save OpenAI**.
3. Press **Test connection**. It checks the key and model with OpenAI without generating an image, so nothing is charged. It explains what to fix:
   - a rejected key;
   - a model your account can't use yet (OpenAI may require organisation verification for image models);
   - no credit.
4. In **Settings**, choose the provider and save.

How the key is handled:
- It's **encrypted with `APP_KEY`** in the database.
- It's never sent back to the browser; you only see `sk-…abcd`.
- Changes are audited **without** the value.
- A key saved in admin **overrides `.env`**; "Remove saved key" falls back to `.env`.

Two cautions:
- If `APP_KEY` changes, saved keys can't be decrypted. The app then falls back to `.env`, and you re-enter the key.
- Replicate works the same way (token, `owner/model` and webhook secret).

## Nothing is faked in production

| Provider (`AI_PROVIDER`) | Use | Notes |
|---|---|---|
| `disabled` | default | Pages show "isn't set up yet" with links to the quiz and shop. |
| `openai` | production | `POST {base_url}/images/edits` (multipart), synchronous, base64 result. |
| `replicate` | production | Creates a prediction with a webhook; result arrives at `/webhooks/ai/replicate` (or by polling). |
| `fake` | local / tests only | Tints the photo with GD and stamps **DEV PREVIEW**. `isConfigured()` is `false` when `APP_ENV=production`, so it can never serve customers. |

If the selected provider isn't configured (missing key/model) the feature reports itself unavailable — it never falls back to a fake result. The admin settings form refuses to select an unconfigured provider.

## Flow

```
upload ─▶ ImageNormalizer (type/size/dimensions, EXIF rotate + strip, ≤1536px JPEG)
       ─▶ TryOnService::guard (enabled, provider ready, consent, daily limit, IP limit, monthly budget)
       ─▶ ai_generations row per colour (status queued) + ai_tryon_started
       ─▶ GenerateTryOn (dispatch per AI_DISPATCH)
       ─▶ provider->generate()  ── succeeded ─▶ store output, cost, latency, ai_tryon_completed, AITryOnCompleted
                                 ├─ processing ─▶ webhook or poll → complete()
                                 └─ failed ────▶ error_code shown as a friendly message; not counted toward limits
```

`AI_DISPATCH`:

- `after_response` (default, cPanel-friendly) — runs after the HTTP response is sent; the page polls every 2 s.
- `queue` — database queue, drained by the scheduler each minute (slower first result).
- `sync` — inside the request (tests).

`complete()` is idempotent (row lock + status check), so a webhook and a poll arriving together store one result.

## Prompting

The prompt is `Settings → AI → prompt template` with placeholders `{colour}`, `{hex}`, `{hint}`, `{product}`. Per-variant `ai_reference_hex` and `ai_prompt_hint` (product editor) override the colour's hex and add guidance. Nothing about colours is hard-coded.

## Privacy

- Explicit consent checkbox (16+, AI processing, auto-deletion) is required; `consented_at` is stored.
- Photos and results live on the **private** disk (`MEDIA_PRIVATE_DISK`). Images are served only through `/ai/images/{uuid}/{before|after}`: a **signed, expiring** URL *and* an ownership check (account owner, or the guest session that made it). Responses are `Cache-Control: no-store, private`.
- Admins with `manage-ai` can view **results only, never originals**, and only after clicking "Show images".
- `ai:cleanup` (every 15 min) deletes originals after `input_retention_minutes` (default 60) and unsaved results after `output_retention_hours` (default 24); stuck generations are failed. A colour board's shared photo is kept until all its colours finish.
- Saved looks (signed-in customers) are kept until the customer deletes them. Sharing creates an unguessable token that exposes the result only.
- Guest previews move into the customer's account when they sign in (from the server-side `ai.generations` session list).
- EXIF (including GPS) is stripped before anything is sent to a provider.

## Cost control

- Daily limits: guests, signed-in users, and customers who have bought before (separate settings). Failed generations don't count.
- Per-IP hourly limit (RateLimiter, database cache).
- `cost_per_generation_kobo` is recorded on every successful generation; `monthly_budget_kobo` (0 = no cap) pauses the feature when this month's spend reaches it.

## Analytics

`ai_events` (unique per event + generation + order): `ai_tryon_started`, `ai_tryon_completed`, `ai_product_clicked`, `ai_added_to_cart`, `ai_look_saved`, `ai_look_shared`, `ai_purchase`.

Checkout stores the session's recent generation IDs in `orders.attribution.ai_generation_ids`; when the order is paid, each order line whose variant matches a successful generation records `ai_purchase` with the line value. The admin AI dashboard shows totals, success rate, spend, add-to-bag and purchase conversion, revenue, ROI, average latency, per-colour performance and recent errors — all computed from these tables.

## Adding a provider

Implement `App\Contracts\AIImageProviderInterface` (`key`, `label`, `isConfigured`, `generate`, `fetch`), returning `TryOnResult::succeeded|processing|failed`. Register it in `config/ai.php` → `providers`. Map provider errors to `rejected` (moderation), `timeout`, or `provider_error`.
