# PHASE 0 — Public Frontend Redesign + Admin Page Builder: Audit & Plan

**Date:** 2026-10-18
**Baseline:** `93e70f8` "STEP 10: Region & 84 Kos data audit report" (branch `main`)
**Requested baseline:** `e2d0b08` (STEP 09) **or latest verified HEAD** → actual HEAD is one commit ahead (`93e70f8`), which is a docs-only audit commit. No code divergence.
**Working tree:** clean except untracked `public/images/directory/demo/` (generated by `DirectoryDemoDataSeeder` — expected, git-ignored).
**Audit only:** no files deleted, no migrations run, no code rewritten.

---

## 1. Runtime / stack facts

| Item | Value |
|---|---|
| Framework | Laravel 13.29, PHP 8.4.23 |
| Routes | 307 total, **62 public GET** |
| Public blade views | 48 files, **1,170 KB** total |
| Inline `<style>` blocks | **63** across public views |
| Inline `<script>` blocks | 32 |
| Hex color literals in public views | **1,729** |
| Hex literals in `resources/css/*.css` | 89 |
| CSS assets | `resources/css/app.css` (7.1 KB, Tailwind v4 + brand tokens + light-mode override layer), `resources/css/frontend.css` (19.7 KB, hand-rolled design system) |
| `resources/js` | **does not exist** (all JS inline or CDN: Alpine, Leaflet 1.9, Font Awesome, Google Fonts) |
| Test suite | 141 tests / 665 assertions, green, pinned to `dham_seva_test` by `DatabaseGuard` |
| Live dev server | `http://127.0.0.1:8000` (background) |

---

## 2. Public route inventory (62 GET)

### A. Static marketing pages — **zero DB content** (DbRefs = 0)
| Route | View | KB |
|---|---|---|
| `/about` | `frontend/about` | 63.2 |
| `/culture` | `frontend/culture` | 75.6 |
| `/about/founder` | `frontend/founder` | 46.4 |
| `/seva` | `frontend/seva` | 38.3 |
| `/about/guru-parampara` | `frontend/guru-parampara` | 23.7 |
| `/about/team` | `frontend/team` | 35.0 |
| `/stories-of-braj` | `frontend/stories-of-braj` | 2.2 |

Near-static (2–3 refs): `/faq` (27.4 KB), `/volunteer` (7.4), `/donate/show` (37.6), `/gallery` (16.9, controller 100% hardcoded demo data).

**This group is the biggest content-editing gap — admin cannot change a single word today.**

### B. CMS-driven today
| Route | Storage | Admin surface |
|---|---|---|
| `/` (home) | `homepage_sections` (28 rows) + `config/homepage_sections.php` (28 schemas, 35 render-order keys, 9 style fields) | `/admin/home-sections` — content, visibility, style, preview.css, reorder |
| `/{slug}` (catch-all) | `pages` (7 rows, SEO columns: meta_title/description/keywords/robots/canonical/og_image/schema_type/focus_keyword) | `/admin/pages` |
| `/site/{userId}/{slug}` | `website_pages` (**0 rows**, raw HTML + `website_page_histories`) | `/admin/website-pages` — **built but unused** |

### C. Data-driven module pages (content from DB, layout hardcoded)
`/explore`, `/explore/{slug}`, `/places/{slug}`, `/explore/{place}/{type}[/{slug}]`, `/temples|ghats|kunds/{slug}`, `/directory` (+4 sub-routes), `/search`, `/map`, `/84-kos`, `/planner`, `/stay|food|transport|shopping`, `/stories` (+3), `/events` (+3), `/news` (+2), `/gau-seva` (+2), `/organizations` (+2), `/contact`, `/profile`, `/faq`, `/gallery`, `/donate`, `/volunteer`, `/auth/login`.

### D. Chrome (shared header/footer/nav)
`header_settings` (2 rows — **1 orphan row exists**), `menus` (2), `menu_items` (12). Admin: `/admin/header/settings` (58.5 KB), Menu Builder.

---

## 3. Content-source classification summary

| Class | Count | Editable today? |
|---|---|---|
| Fully static blades | 7 pages (+4 near-static) | ❌ no |
| Section-CMS (config schema + DB rows) | 1 homepage only | ✅ yes |
| Full CMS with SEO | `pages` catch-all | ✅ yes |
| Page builder (raw HTML + revisions) | `website_pages`, 0 rows | ✅ but unused & raw-HTML |
| Data-driven module pages (DB records, hardcoded page shell) | ~35 routes | ⚠️ records yes, page shell/SEO no |
| Shared chrome | header/footer/menus | ✅ yes |

---

## 4. Reusable assets found (build on these, do not rebuild)

1. **`config → DB rows → blade hooks → generated scoped CSS` pipeline** — proven on home:
   `config/homepage_sections.php` ↔ `homepage_sections` ↔ `data-hs="key"` hooks ↔ `app/Support/HomeSectionCss.php` (sanitised, whitelisted, returns `''` when nothing configured → **default output stays byte-identical**).
2. **Schema-driven dynamic form generator** — `admin/home-sections/edit.blade.php` (41 KB): field types `text|textarea|image|color|repeater|nested-repeater|icon|toggle`, visibility switch, style panel, live "LIVE/PENDING" badges, unsaved-state handling, `bladeReads()` live-field detection.
3. **Controlled icon library** — `admin/partials/_icon_picker.blade.php` (38.9 KB).
4. **Standalone colour picker** — `shared/website/customize/_color_picker_standalone.blade.php` (22.2 KB, gradient/HSL + localStorage palette).
5. **Slug/image handling** — `Admin/Concerns/ManagesSlugAndImages` (validation-safe slug merge, upload to `public/{dir}`, relative paths, safe delete).
6. **Media model** — `media` morph (56 rows), `sort_order` + `is_cover`, gallery CRUD precedent in directory + places.
7. **Revision history precedent** — `website_page_histories` (`old_values`/`new_values` JSON, written from model `boot()`).
8. **SEO output layer** — `frontend/layouts/app.blade.php` already supports `@yield` for title/description/keywords/robots/canonical/OG/Twitter + JSON-LD.
9. **Permissions already present, no module implemented:** `media.view/manage`, `audit.view`, `approval.review` — available for the builder's media + revision trail (avoids inventing new permission concepts).
10. **Place sections pattern** — `place_sections` (22 keys, 154 rows) = per-entity section enable/edit model.

---

## 5. Gap analysis vs. requirement

| Requirement | Status |
|---|---|
| Edit section content of any public page | ❌ home only |
| Section visibility ON/OFF per page | ❌ home only |
| Section reorder per page | ❌ home only |
| Typed, validated fields (no raw HTML default) | ✅ pattern exists (home), ⚠️ `website_pages` is raw HTML |
| Save Draft / Preview / Publish per page | ⚠️ only `pages` + `website_pages` |
| Revision history + restore | ⚠️ only `website_pages` (0 rows) |
| Page-level SEO for all public pages | ❌ only `pages` (7 rows) |
| Media picker + alt text | ⚠️ upload helpers exist, no selector UI, no alt fields |
| Shared design tokens | ❌ 1,729 hex literals in views, 63 inline style blocks |
| Shared header/footer | ✅ exists (header/footer always-dark, 2-tier header + mega menu) |
| Accessibility/nav/legal elements protected | ⚠️ must be enforced by `required` flags (nothing exists yet) |

---

## 6. Proposed architecture (least disruptive)

### Principle
**Generalise the homepage pattern that already works.** Zero new behaviour when no admin data exists → default rendering stays byte-identical (the `HomeSectionCss` precedent).

### 6.1 New tables (2 additive migrations, reversible, no destructive change)

```
public_pages
  id, page_key (unique: 'explore','yatri-guide','stay', …), route_name, path,
  title, status (draft|published), is_active,
  seo_title, seo_description, seo_keywords, seo_focus_keyword, seo_canonical_url,
  seo_robots, seo_og_title, seo_og_description, seo_og_image, seo_schema (json),
  published_at, updated_by, timestamps
  -- column names mirror the existing `pages` SEO block for consistency

page_sections
  id, public_page_id FK, section_key, sort_order (int),
  is_active bool, content json, style json,
  unique(public_page_id, section_key)
  -- structural clone of homepage_sections (content/style JSON, is_active, sort_order)

public_page_revisions
  id, public_page_id FK, action (save_draft|publish|restore|section_removed),
  payload json (full snapshot of page + its sections), user_id, timestamps
```

### 6.2 Homepage stays where it is
`/admin/home-sections` already satisfies the spec for home (visibility, order, style, content, preview). Phase 2 builds the generic builder for the **other** pages; unifying home into `public_pages` is optional and **not** in initial scope (avoids touching working backend).

### 6.3 Schema config
`config/public_pages.php` — one entry per page key: `route_name`, `path`, `label`, `sections[]` where each section declares `label`, `required`, `removable`, `fields[]` (typed: text, textarea, richtext-lite, image+alt+focal, icon, color, url, toggle, select, repeater) and `defaults` (current live markup/content).

### 6.4 Rendering
- `app/Support/PublicPageResolver.php` (+ `View\Composers\PublicPageComposer`) → route → `page_key` → page + active sections sorted → shared as `$publicPage`, `$pageSections`.
- Blade: each public page keeps its own file but its content block becomes a loop rendering typed partials `frontend/sections/{type}.blade.php`.
- **No rows → no output change.** Existing markup stays as `defaults` in config so first render without DB edits is identical (verified by HTML hash comparison in Phase 4).
- SEO: composer sets the existing `@yield`s from `public_pages.seo_*`, falling back to current behaviour when empty.

### 6.5 Admin UI
- New sidebar entry under **Frontend** → **Page Builder** (`/admin/page-builder`).
- Routes: `admin.page-builder.{index,edit,update,preview,publish,restore,sections.toggle,sections.reorder,seo,media}`.
- Permissions: new module `page-builder => view, edit, publish` (1 additive migration inserting 3 keys + seeder sync) **and** `AdminMiddleware` override entry (fail-closed default keeps unlisted routes denied).
- Editor: same accordion pattern as home-sections — **all accordions closed by default**, per-section visibility toggle, drag order, typed field renderers, `required` sections cannot be hidden/removed (safeguard + confirm dialog), unsaved-changes indicator, Save Draft / Preview / Publish.
- Preview: authorized route rendering the public blade with draft data + `noindex` header.

### 6.6 Media
Reuse `media` table + `ManagesSlugAndImages` upload rules (type/size/dimension validation), add per-field `alt` + `focal_position`, and a selector modal (existing upload + choose). Broken-reference prevention: deleting/replacing keeps the previous file until the new one is committed (two-phase write) — extend current unlink behaviour carefully.

### 6.7 Design system (Phase 1)
- Central tokens in `resources/css/frontend.css` `:root` (`--braj-*`: colour, type scale, spacing, radius, shadow, breakpoints) + existing `@theme` brand tokens in `app.css`.
- Hindi/English type: keep Cormorant Garamond + Inter (Latin) and add a Devanagari stack (`Noto Sans Devanagari` / `Mukta`) for `:lang(hi)` blocks.
- Extract shared primitives (`.btn-*`, `.card`, `.badge`, form controls, section wrapper) into `frontend.css`; replace per-page inline style blocks **page by page** (mechanical, verifiable).
- Header/footer remain shared (already are). Admin panel styling untouched.

---

## 7. Risk register

| Risk | Mitigation |
|---|---|
| `home.blade.php` 220 KB / 32 style blocks — highest regression risk | Home CMS already exists; Phase 3 touches design only, with rendered-HTML hash comparison before/after |
| 1,729 hex literals + 63 inline style blocks | Tokenise incrementally per page; never batch-rewrite across files |
| "No fabrication" policy | Admin edits replace literal strings only; no new statistics/hours/contacts generated by the system |
| Draft leakage | `status='published' && is_active` gate in resolver; preview is auth-only + `noindex`; tests assert absence of draft content publicly |
| Section removal breaks required content | `required` flag enforced server-side (422) and client-side (disabled toggle + confirm) |
| Duplicate canonical / broken SEO | Canonical auto-derived from `page_key` path; validation rejects absolute URLs pointing to other routes; `meta_robots=noindex` auto-set for drafts |
| Permission regressions | Reuse `page-builder` module + `AdminMiddleware` override map; super-admin unaffected; add tests for non-super denial |
| Test DB safety | Keep `DatabaseGuard`; never run `config:cache`/`optimize` in dev; backups before migrations |
| Pre-existing issues (footer `footer_cta_phrase_color` missing column, UTC timezone, 2 orphan `header_settings` rows) | Report separately; fix only on approval |

---

## 8. Test plan (Phase 4)

New Feature tests (all on `dham_seva_test`):
`PageBuilderIndexTest`, `PageSectionVisibilityTest`, `PageSectionOrderTest`, `PageSectionFieldValidationTest`, `PageDraftPreviewTest`, `PageSeoOutputTest`, `PageRevisionRestoreTest`, `PageRequiredSectionGuardTest`, `PagePermissionTest`, `PublicRouteRegressionTest` (assert all 62 public routes still respond 200/404 as before), `DesignTokenParityTest` (rendered-HTML hash for unedited pages).

Existing 141 tests must stay green after every phase.

---

## 9. Delivery phases (reviewable, one at a time)

| # | Phase | Deliverable | Primary files |
|---|---|---|---|
| 1 | Audit | this document | `docs/phase0-…md` |
| 2 | Design system + CMS foundation | tokens, shared primitives, migrations, resolver, admin Page Builder shell | `resources/css/frontend.css`, `app.css`, 3 migrations, `config/public_pages.php`, `app/Support/*`, `app/Http/Controllers/Admin/PageBuilder*`, `admin/page-builder/*`, permission seed |
| 3 | Homepage redesign | tokenised home, markup cleanup (CMS unchanged) | `frontend/home.blade.php` |
| 4 | Remaining public pages | static marketing pages first (biggest gain), then explore/map/84-kos/yatri/planner/discovery/stories/events/entity details/directory/search | `frontend/*.blade.php` |
| 5 | SEO / responsive / accessibility / regression QA | metadata verification, focus states, keyboard nav, mobile breakpoints, full test run | views + tests |
| 6 | Launch readiness | final verification report, known limitations | `docs/` |

**Per-phase reporting:** changed files, migrations, tests run (real output), screenshots/genuine live verification only when actually performed, limitations, blockers.

---

## 10. Out of scope (confirmed)
No payment/booking systems, no new unrelated modules, no backend rewrite, no deletion of working modules. Existing admin CRUD, permissions, search/filters/map/planner/share links, report workflow, DEMO labelling and publication visibility rules remain intact.
