# Phase 2 — Public Page Builder (CMS Foundation)

**Status:** complete · **Date:** 2026-10-18 · **Commits:** none yet (Phase 1 + Phase 2 both still uncommitted, by design — awaiting review)

---

## 1. Scope

Adds the CMS layer behind the public pages: a registry of every public page, typed
section editing with draft/publish, revisions + restore, and per-page SEO — without
changing a single byte of the public site until an admin actually edits something.

**Deliberately out of scope (unchanged):**
- The homepage keeps its existing `/admin/home-sections` editor (no duplicate module).
- All 62 public routes, controllers, permissions, search/filters/map/planner/share
  links, report workflow, DEMO labels and publication visibility are untouched.
- No payment, booking, or unrelated modules.

---

## 2. Changed files

### 2.1 New files — 3,116 lines

| Lines | File | Purpose |
|---:|---|---|
| 686 | `app/Http/Controllers/Admin/PageBuilderController.php` | index, edit, update (save draft), publish, preview, history, restore, reorder, toggle, section-reset, SEO save, media upload |
| 642 | `resources/views/admin/page-builder/edit.blade.php` | editor UI — accordions **closed by default**, typed fields, style panel, SEO panel, sticky save bar, unsaved-changes indicator |
| 409 | `tests/Feature/PageBuilderTest.php` | 20 tests covering the safety contract |
| 312 | `app/Support/PublicPageResolver.php` | draft-vs-public resolution; **zero rows → config defaults** |
| 259 | `config/public_pages.php` | registry: 26 pages, section schema, field types, SEO defaults |
| 156 | `app/Models/PublicPage.php` | snapshot / recordRevision / restoreSnapshot / markPublished |
| 147 | `app/Support/PublicPageSchema.php` | config accessors + `data-ps`/`data-psf` blade-hook scanning |
| 133 | `resources/views/admin/page-builder/index.blade.php` | page list + status badges |
| 99 | `resources/views/admin/page-builder/history.blade.php` | revisions list + restore |
| 56 | `app/Models/PageSection.php` | |
| 54 | `app/Http/View/Composers/PublicPageComposer.php` | shares `$publicSeo`/`$pageSections`; never overwrites caller data (preview) |
| 54 | `database/migrations/2026_10_18_000001_create_public_pages_table.php` | |
| 41 | `database/migrations/2026_10_18_000002_create_page_sections_table.php` | |
| 35 | `database/migrations/2026_10_18_000003_create_public_page_revisions_table.php` | |
| 33 | `app/Models/PublicPageRevision.php` | |

### 2.2 Modified files

| File | Change |
|---|---|
| `routes/web.php` | +16 — 12 `admin.page-builder.*` routes, `where('key','[a-z0-9-]+')` |
| `database/seeders/RolesPermissionsSeeder.php` | `page-builder` module (88→89 keys, 27 modules); manager = view+edit+publish, staff = view |
| `app/Http/Middleware/AdminMiddleware.php` | `page-builder.view/edit/publish` overrides for the 13 page-builder routes (fail-closed generic rules don't cover the new module) |
| `app/Providers/AppServiceProvider.php` | `View::composer('frontend.*', PublicPageComposer::class)` |
| `resources/views/frontend/stories-of-braj.blade.php` | +62 — reference page wired to `$pageSections` with `data-ps`/`data-psf` hooks |
| `resources/views/frontend/layouts/app.blade.php` | `<head>` honours `$publicSeo` **only when set**, else `@yield` unchanged (Phase 1 + 2) |
| `resources/views/admin/layouts/app.blade.php` | sidebar **FRONTEND → Page Builder** nav item, `@userCan('page-builder.view')` |
| `resources/views/admin/roles/index.blade.php` | `'page-builder' => 'fa-layer-group'` icon map |
| `resources/views/admin/teams/edit.blade.php` | same icon map |

---

## 3. Migrations

All three are **additive** — nothing dropped, renamed or altered. Taken against
`dham_seva_db` after a backup: `backups/pre_phase2_20261018_155121.sql` (329.2 KB).

```
 INFO Running migrations.

 2026_10_18_000001_create_public_pages_table .. 216.12ms DONE
 2026_10_18_000002_create_page_sections_table .. 108.02ms DONE
 2026_10_18_000003_create_public_page_revisions_table .. 145.84ms DONE

--- seeder (idempotent) ---

 INFO Seeding database.
 Database\Seeders\RolesPermissionsSeeder .. 465 ms DONE
```

Verification:

```
permissions total: 89
page-builder actions: view,edit,publish
tables: 53 → 56
```

Delivered end state: **`public_pages` 0 · `page_sections` 0 · `public_page_revisions` 0**
(the rows my own verification runs created were cleared so the phase ships with no
data and therefore no output change).

---

## 4. Real test output

```
$ php artisan test --filter=PageBuilderTest
{"result":"passed","tests":20,"passed":20,"assertions":77}

$ php artisan test
{"result":"passed","tests":161,"passed":161,"assertions":742,"duration_ms":46685}
```

Baseline was **141 / 665**; Phase 2 adds 20 tests / 77 assertions → **161 / 742, 0 failures.**

What the 20 tests pin down:

1. three tables exist, additive, start empty
2. zero rows → config defaults rendered, `robots: index,follow`
3. **a draft never reaches a visitor** (public HTML contains none of the draft text)
4. admin preview shows the draft and is `noindex,nofollow` + `X-Robots-Tag`
5. publish flips the public content and writes a `publish` revision
6. required section cannot be hidden via save, nor via toggle (422), unknown section rejected
7. restore writes back into **this page only** (`PublicPage::count()` still 1)
8. 403 without permission; view-only cannot publish; edit-only cannot publish; publish perm required for publish
9. unknown page key → 404, DB untouched
10. typed validation rejects `javascript:` URLs and malformed colours; nothing stored
11. untouched colour style fields are not stored (no silent override)
12. SEO stored separately; publish puts `<title>`/robots live
13. SEO rejects malformed canonical + unknown robots value
14. image upload rejects a non-image file
15. blade-hook scan: `stories-of-braj` wired, `about` reported as not converted

Build / runtime checks:

```
$ php artisan optimize:clear && php artisan view:cache && npm run build
frontend-BDIgyiyt.css   25.80 kB │ gzip: 5.46 kB
app-BjNBO3H8.css        61.45 kB │ gzip: 10.56 kB
✓ built in 4.79s
```

Live smoke — 11 public routes all **HTTP 200**: `/`, `/about`, `/explore`,
`/yatri-guide`, `/directory`, `/map`, `/search`, `/planner`, `/stories`,
`/stories-of-braj`, `/auth/login`.

Browser console on public page, Page Builder index and editor: **0 errors each.**

---

## 5. Genuine screenshots

Preserved under `docs/phase2-evidence/` (captured from the live app at
`http://127.0.0.1:8000`, admin session `admin@dhamseva.com`):

| File | What it shows |
|---|---|
| `01-public-stories-of-braj.png` | public page — original design, no visible change |
| `02-admin-page-builder-index.png` | index: 26 registered / 1 wired / 25 schema pending / 0 drafts + "How publishing works" |
| `03-admin-page-builder-editor.png` | editor: section accordion, `live 6/6` + `required` badges, `published` + "never edited (original content in use)", sticky Save draft bar |
| `04-sidebar-nav-item.png` | sidebar **FRONTEND → Page Builder**, active state |

Live flow verified by hand (not just tests):

1. edit `Pill` → **Save Draft** → `status=draft`, `revisions=1`, message
   *"Draft saved — the live site still shows the last published version."*
2. fetch `/stories-of-braj` → still `Coming Soon`, draft text **absent** ✅
3. **Preview** → shows the draft, `robots=noindex,nofollow` ✅
4. **Publish** → public HTML now shows the draft text, `robots=index,follow` ✅
5. **Restore section** → row deleted, content returns to config defaults
6. cleared all rows → public HTML back to the original markup

---

## 6. Bugs found and fixed during verification

These were caught by the tests and the live run above — all fixed before this report.

| # | Bug | Severity | Fix |
|---|---|---|---|
| 1 | `PublicPageResolver`'s **static cache leaked across requests** — under tests/Octane/queue a page saved moments earlier resolved to a stale (even `null`) row, so the just-saved draft silently fell back to defaults | high | cache now keyed to the current `Request` object (`syncRequest()`), strong reference held so the id can't be recycled |
| 2 | **Visibility toggle could never switch a section OFF** — an unchecked checkbox is absent from the POST, and `?? true` defaulted it to active | high | `array_key_exists()` + a hidden `0` companion input |
| 3 | Fix #2 then **broke required sections**: their box is `disabled` (never submitted), so the lone `0` hid them and failed validation on every save | high | hidden companion emitted **only** for non-required sections |
| 4 | `<input type="color">` can never be empty — it always posts `#000000`, so every untouched colour **silently overrode the page's own styling** (verified: published `h1` went black-on-black) | high | named field is an empty hidden input; the unnamed picker only syncs once touched; `↺ Use page default` clears it |
| 5 | `'in:index,follow,noindex,follow,noindex,nofollow'` — Laravel's `in:` **splits on commas**, so `noindex,nofollow` could never be saved (the select offered a value validation always rejected) | high | `Rule::in([...])` with an array |
| 6 | Regex delimiter bug: **PHP scans for the closing delimiter even inside `[...]`**, and my class contained `#`/`~` → pattern truncated → every `url` field threw `Internal error` / `Unknown modifier` (a 500 waiting to happen) | high | `isSafeAssetPath()` helper; delimiter chars kept out of the class |
| 7 | `image` fields were **not validated at all** — `javascript:alert(1)` was accepted into a `url(...)` context | high | `isSafeAssetPath()` rejects any value carrying a URI scheme, plus quotes/`;`/`<>`/`\`/parens (no `url(...)` or `src="..."` breakout) |
| 8 | `{{ nl2br(e(...)) }}` double-escaped the output → subtitle rendered as literal `&lt;br /&gt;`, **line break lost** | medium | `{!! nl2br(e(...)) !!}` |
| 9 | Preview threw `BadMethodCallException` — `view()->header()` (a `View` has no `header()`) | medium | `response()->view(...)->header(...)` |
| 10 | Public `robots` was forced to `noindex,nofollow` whenever a draft existed, **even though a public request never receives draft content** — would have de-indexed the live page | medium | override removed; only the admin preview is forced noindex |

Also a design correction: `trim()` in field cleaning removed the trailing space of
`"Stories of "`, which would have broken the highlight spacing. Rather than exempt
some fields from trimming, the field set was redesigned to **`title` + `highlight`**
with the blade splitting the string — spacing can no longer be wrong, and it's a
clearer form for an admin.

---

## 7. Limitations

1. **25 of 26 pages are `schema pending`.** Their blades are not yet converted, so
   they show no sections — only their SEO panel is editable. This is intentional:
   converting a blade is what creates a schema, and doing 25 blind rewrites in one
   phase would violate the "no broad rewrites" rule. `stories-of-braj` is the single
   fully wired reference page (7 fields → now `title`/`highlight` restructure keeps it
   at 6 editable fields, `live 6/6`).
2. **The homepage is not in this module** — it stays on `/admin/home-sections`.
3. **No media library.** Upload validates type/size/dimensions server-side and
   returns the URL into the field; there is no browse/reuse UI yet.
4. **Repeater fields** are supported by the schema and the editor JS, but no wired
   page uses one yet, so that path is untested end-to-end.
5. **Section reorder/visibility** are exercised by tests for the controller contract;
   the UI exposes reorder only where a page has ≥2 sections, which no wired page has yet.
6. Restore is per-page scoped and proven so by test, but the history UI has only been
   exercised with 5 revisions on one page.
7. Everything (Phase 1 **and** Phase 2) is **uncommitted** — the working tree holds
   ~29 changed/untracked paths awaiting your review and a commit decision.

## 8. Blockers

None.

## 9. Next

On approval: commit Phase 1 and Phase 2 (separately or together, your call), then
Phase 3 — converting the marketing/about/discovery blades to section schemas, which
turns those 25 `schema pending` rows into editable content.
