# MASTER DEVELOPMENT PROMPT — v2.1
# NATIONAL DIGITAL JOURNALISM NETWORK — PAKISTAN
## A National-to-Local Journalism, News Publishing, Reporter Empowerment and Community Information Platform

> **How to use this document.** Save it in the repository root as `docs/PROJECT_REQUIREMENTS.md` and point Claude Code to it from `CLAUDE.md`. It is the single source of truth. Where this document and any later instruction conflict, the later written instruction from the project owner wins, and the conflict must be recorded in `docs/DECISIONS.md`.

---

# PART 0 — READ THIS FIRST

## 0.1 What this document is

This is the full specification for a production-grade, bilingual (Urdu + English), database-driven digital journalism platform for Pakistan. It is not a blog, not a WordPress site and not a visual prototype.

## 0.2 The ten non-negotiable principles

Every design and code decision must respect these. If a feature request conflicts with one of them, stop and flag it.

1. **The reader comes first.** Accurate, fast, readable, findable news at the smallest geographic level.
2. **Merit over connections.** A reporter's standing comes from verified, accurate, consistent work, never from seniority, politics or press-club membership.
3. **Nothing is fake.** No fabricated reporter counts, engagement numbers, users, reviews, share counters or "operational" claims for inactive areas.
4. **Editorial accountability is never bypassed.** Instant publishing, trusted status and advertising relationships never exempt anyone from review, correction or complaint.
5. **Editorial and commercial are separate.** Advertising never influences coverage, rankings or awards, and paid content is always labelled.
6. **Private data stays private.** CNICs, identity documents, residential addresses, tipster identities and disciplinary records are never public and never in general exports.
7. **Reporter and source safety.** The platform must never become a tool that exposes a local journalist or a whistleblowing source to physical risk.
8. **Urdu is a first-class language.** Proper Nastaleeq typography and real RTL layouts, not mirrored English CSS.
9. **Authorization is server-side.** Every permission is checked by policies and scopes on the server. Hidden buttons are not security.
10. **Done means tested.** A feature is not complete until its backend, authorization, validation and tests work. A frontend alone is not a feature.

## 0.3 Definition of Done (applies to every module)

A module is "Done" only when all of these hold:

- [ ] Migrations, models, relationships, factories and seeders exist.
- [ ] Business logic lives in Services or Actions, not controllers.
- [ ] Form Requests validate all input, and Policies or Gates authorize every action, including geographic scope.
- [ ] Both `ur` (RTL) and `en` (LTR) interfaces render correctly for the module.
- [ ] Sensitive actions write to `audit_logs`.
- [ ] The module's features are registered in the Feature Registry, with a working ON/OFF switch (Part 45).
- [ ] Feature tests cover the happy path, authorization failures, validation failures and at least one abuse case.
- [ ] No N+1 queries on list pages (verified with `Model::preventLazyLoading()` in non-production).
- [ ] `docs/CHANGELOG.md` and `docs/DEVELOPMENT_STATUS.md` are updated.
- [ ] Pint, Larastan (level 6 or higher) and the full test suite pass.

## 0.4 Glossary

| Term | Meaning |
|---|---|
| Story | One news item (`news_articles`). Language-independent: location, category, reporter, evidence, status. |
| Translation | A language version of a story (`news_translations`): headline, body, slug, SEO. Each has its own status. |
| Scope | A geographic boundary (country, province, district, tehsil or locality) that limits what a role may access. |
| Coverage area | A location a reporter is approved to report from. |
| Trusted Reporter | A reporter status that makes them *eligible* for instant publishing. The permission itself is granted separately. |
| Instant publishing | Publishing without pre-publication review. Post-publication review is still mandatory. |
| Material change | An edit that changes facts: names, numbers, dates, places, allegations, quotes, casualty figures or the headline's claim. |
| Pilot region | A location whose `operational_status` is `pilot_active`. |

---

# PART 1 — YOUR ROLE AND RESPONSIBILITIES

Act as a senior multidisciplinary software team:

- Principal Software Architect
- Senior Laravel Developer / PHP Developer
- MySQL Database Architect
- Frontend Developer and UI/UX Designer (with Urdu/RTL specialism)
- SEO Specialist (news SEO, multilingual)
- Cybersecurity Engineer
- Digital Journalism Product Consultant (editorial standards, source protection)
- Quality Assurance Engineer
- Technical Project Manager

Your job is to architect, build, test, document and prepare for deployment a complete digital journalism platform for Pakistan.

Understand the whole business model before writing code: regional journalism, reporter management, editorial verification, reader experience, advertising revenue, SEO, security and future expansion.

- Do not sacrifice important requirements for convenience.
- Do not produce a visual-only prototype.
- Build a real, database-driven, working application.
- When a requirement is ambiguous, choose a sensible, reversible default, record it in `docs/DECISIONS.md`, and carry on. Stop and ask only for genuine business decisions (listed in Part 44).

---

# PART 2 — PROJECT VISION

Establish a National-to-Local Digital Journalism Network for Pakistan.

**Primary stakeholders**

1. Reporters and journalists
2. Readers and the general public
3. Local businesses and institutions
4. Administrators and editorial teams

**Future stakeholders**

5. Press clubs
6. Newspapers and media houses
7. Journalist recruitment organisations

**Core objective:** create real opportunities for authentic local journalists, especially junior reporters who are overlooked by traditional press clubs and media houses.

A reporter's importance is determined by:

- Authentic reporting
- Accuracy
- Editorial quality
- Consistency
- Community trust
- Professional activity
- Verified reporting history

It is not determined primarily by seniority, age, personal connections, political influence or press-club membership.

A reporter in a small tehsil should be able to build a professional identity, grow an audience and earn money through local advertising, **safely**.

The reader remains the central priority. The platform provides national information while making local news discoverable down to the smallest geographic level.

**Success metrics for the pilot.** These must be measurable in the admin analytics:

- Median time from submission to editorial decision (target: under 6 hours during staffed hours).
- Share of published stories with at least one documented source (target: 100%).
- Correction rate, and time from complaint to resolution.
- Active reporters per pilot tehsil (real counts only).
- Returning-reader rate and search-to-click rate.
- Reporter earnings paid out on time (target: 100% within the agreed payout cycle).

---

# PART 3 — FINAL PRODUCT DECISIONS

These are finalised.

| Area | Decision |
|---|---|
| Identity | National Digital Journalism Network for Pakistan |
| Languages | Urdu and English, from day one |
| Urdu typography | **Noto Nastaliq Urdu** (free Google Font, SIL Open Font License), self-hosted (see Part 7.2) |
| Payments | **Manual.** Ads are posted online, staff contact the advertiser and collect payment offline, then approve the ad. No payment gateway (Part 24). |
| Feature control | Every feature has an admin **ON/OFF switch** (Part 45) |
| Direction | Full RTL for Urdu, LTR for English |
| Launch | Nationwide architecture from day one, with a controlled pilot in selected Punjab districts and tehsils, then gradual national expansion |
| Technology | Custom Laravel, MySQL/MariaDB, WHM/cPanel-compatible, **no WordPress** |

The architecture must support nationwide operations even during the pilot.

---

# PART 4 — TECHNOLOGY STACK

## 4.1 Core

| Layer | Choice | Notes |
|---|---|---|
| Framework | Latest stable Laravel supported by the server's PHP | Verify the current version and its minimum PHP at install time. Record both in `docs/DECISIONS.md`. |
| Language | PHP 8.3+ (or whatever the chosen Laravel requires) | Extensions: `mbstring`, `intl`, `pdo_mysql`, `gd` and/or `imagick`, `exif`, `fileinfo`, `bcmath`, `redis` (optional), `zip`, `openssl` |
| Database | MySQL 8.0+ (preferred) or MariaDB 10.6+ | `utf8mb4` / `utf8mb4_unicode_ci` throughout. InnoDB only. |
| Frontend | Blade, Tailwind CSS (with logical-property utilities: `ms-`, `me-`, `ps-`, `pe-`, `start-`, `end-`), Alpine.js | No SPA. Progressive enhancement. Must work without JavaScript for reading. |
| Build | Vite | Production assets are built locally or in CI and deployed. Do not rely on Node being present on the server. |
| Auth | Laravel's first-party auth scaffolding (Breeze-style or Fortify) | 2FA (TOTP) **mandatory** for all editorial and admin roles. Optional for reporters. |
| Authorization | RBAC plus geographic scopes (Part 8) | `spatie/laravel-permission` may be used for roles and permissions. Geographic scope is a separate, custom layer. |
| Search | MySQL FULLTEXT with Urdu normalisation (Part 19.4) | Behind a `SearchService` interface so Meilisearch can be swapped in later without touching controllers. |
| Cache | Laravel Cache: Redis if available, otherwise file/database | Tag-free cache key design, so file/database drivers still work. |
| Queues | Laravel Queues: `database` driver by default, Redis if available | See Part 38 for cPanel worker strategy. |
| Images | `intervention/image` (GD or Imagick) | WebP, responsive sizes, **EXIF/GPS stripping** (Part 32.3). |
| API | Versioned REST under `/api/v1`, Laravel Sanctum | Read-only public endpoints first. Authenticated reporter endpoints later for mobile apps. |
| Testing | Pest (or PHPUnit) and Laravel Dusk (optional, for RTL smoke tests) | |
| Quality | Laravel Pint, Larastan | Run before every commit. |

## 4.2 Hosting

WHM/cPanel on AlmaLinux, VPS or dedicated server, with SSH, Composer, cron and PHP-FPM.

## 4.3 Architecture style

A **modular monolith**. Organise code by domain module, for example:

```
app/
  Domain/
    Locations/      (models, services, policies, events)
    Identity/       (users, roles, scopes, verification)
    Reporters/
    Newsroom/       (stories, translations, versions, workflow)
    Engagement/     (reactions, ratings, views, shares)
    Tips/
    Issues/
    Advertising/
    Finance/
    Moderation/     (warnings, appeals, complaints)
    Seo/
    Shared/         (audit, settings, notifications, media)
```

Do not use microservices. Do not add infrastructure (Elasticsearch, Kafka, Kubernetes, Node servers) without a documented need. Everything must stay maintainable on cPanel.

---

# PART 5 — NATIONAL AND REGIONAL ARCHITECTURE

One centralised national platform:

```
Country (Pakistan)
 └─ Province / Territory   (Punjab, Sindh, KP, Balochistan, ICT, AJK, Gilgit-Baltistan)
     └─ District
         └─ Tehsil / Taluka / Sub-division
             └─ Union Council / Locality
```

- One central database and one central application.
- One national administration system and one editorial policy framework.
- Regional administrative permissions.
- Location-based news management and location-based reporter management.
- **Do not** create separate websites or databases for districts.
- Regional editors may access only their authorised regions. National editors and Super Administrators may access broader areas, according to their permissions.
- Adding a new country must later be a data change, not a code rewrite.

**Naming note:** sub-district units have different names in different provinces (tehsil, taluka, sub-division). Store a configurable `level_label` per province, in both languages, so Sindh can display "Taluka" while the data model stays uniform.

---

# PART 6 — LOCATION MANAGEMENT SYSTEM

## 6.1 Tables

`countries`, `provinces`, `districts`, `tehsils`, `localities`. Pakistan is the initial country.

Each row has a permanent numeric ID, `name_en`, `name_ur`, a unique (per parent) `slug`, a parent FK, `operational_status`, `is_enabled`, an optional `intro_en` / `intro_ur`, an optional `census_code`, an optional lat/lng, and timestamps.

## 6.2 Admin capabilities

Admins can add, edit and disable provinces, districts, tehsils and localities; import locations through CSV with preview; export location data; assign reporters to coverage areas; and approve additional coverage areas.

Do not hardcode any location.

## 6.3 Operational status

`planned` → `registration_open` → `pilot_active` → `fully_operational`, and `temporarily_paused` at any stage.

| Status | Public landing page | Reporter registration | News submission |
|---|---|---|---|
| planned | Hidden / `noindex` | Closed | Closed |
| registration_open | "Coming soon" notice, `noindex` | Open | Closed |
| pilot_active | Visible. Indexed only when content thresholds are met (Part 20) | Open | Open |
| fully_operational | Visible | Open | Open |
| temporarily_paused | Visible with a notice. Existing articles remain | Closed | Closed |

A location may exist with no active reporters. Never display fabricated reporter counts, and never imply that an inactive area is operational.

## 6.4 Boundary changes (critical, and easy to miss)

Pakistan's administrative boundaries change, and changes are sometimes reversed. Taunsa, the pilot example used in this document, shows this: a Punjab chief minister notified it as a new district with three tehsils in December 2022, and an interim provincial government later annulled that notification. **Verify every pilot location against the latest official notification before seeding.**

The system must therefore support:

- **Re-parenting** a tehsil to a different district, and **promoting** a tehsil to a district.
- **Splitting** and **merging** locations.
- **301 redirects** from old location URLs to new ones (`location_redirects` table).
- **Historical accuracy:** an article keeps the location it was published under. Store denormalised `province_id`, `district_id` and `tehsil_id` on the story at publication time, plus a `location_snapshot` JSON column (names in both languages), so old articles never silently "move".
- A location `effective_from` / `effective_to` and a change log in `audit_logs`.

## 6.5 Initial location data (supplied)

The file `database/seeders/data/pakistan_locations_seed.csv` contains the starting province/territory → district → tehsil list for **all of Pakistan**: 169 districts and 709 sub-district units, collected from public sources on 19 Nov 2026.

| Province / territory | Type | Districts | Tehsils / talukas / zones |
|---|---|---|---|
| Punjab | province | 42 | 162 |
| Khyber Pakhtunkhwa | province | 39 | 172 |
| Sindh | province | 30 | 138 (talukas) |
| Balochistan | province | 37 | 163 |
| Islamabad Capital Territory | federal_territory | 1 | 5 (zones) |
| Azad Jammu and Kashmir | administered_territory | 10 | 35 |
| Gilgit-Baltistan | administered_territory | 10 | 34 |
| **Total** | | **169** | **709** |

**Columns:** `country_code, province_type, province_slug, province_name_en, province_name_ur, division_en, district_slug, district_name_en, district_name_ur, tehsil_slug, tehsil_name_en, tehsil_name_ur, subunit_label_en, subunit_label_ur, operational_status, is_enabled, needs_verification, verification_note, source_url, source_checked`.

**Seeder rules:**
- Build `LocationSeeder` to read this CSV through the **same import service** as the admin CSV import (Part 33), so the seeder and the admin importer share one code path.
- Upsert by `(parent, slug)`, so re-running the seeder is safe and never duplicates rows.
- Every location is seeded as `operational_status = planned`. Admins open regions one by one.
- Rows with `needs_verification = 1` are imported with a "needs verification" badge in admin. They cannot be set to `pilot_active` until an admin confirms them (records who and when).
- `tehsil_name_ur` is filled only where the tehsil shares its district's name. **All other Urdu tehsil names are blank** and must be filled and checked by a native Urdu editor in admin before that location goes public. Never machine-transliterate place names into the public site.
- `division_en` is informational only (divisions are not part of the platform hierarchy). It is blank for Balochistan, because divisions there were reorganised and the source did not state them reliably.
- Sindh uses "Taluka / تعلقہ" as the sub-district label. Karachi's seven districts list subdivisions/towns.
- Store `province_type` on the `provinces` table (province / federal_territory / administered_territory), so labels and breadcrumbs can say "Province" or "Territory" correctly.
- Islamabad has no tehsils. Its five zones are used as sub-units, and sectors (F-7, G-9 and so on) can later be added as localities. These rows are flagged for review.
- Gilgit-Baltistan: Darel, Tangir, Gupis-Yasin and Roundu were announced as districts in 2019 but had not been established as of 2024, so they are listed as tehsils with a note.
- Known areas of change to re-check before opening each region: the status of Taunsa and Jampur districts; Lahore (10 tehsils since August 2024, with a proposed Lahore North/South split); newer KP districts (Allai, Upper Swat, Central Dir); recent district and division changes in Balochistan; and the 2019 announced districts in Gilgit-Baltistan.

## 6.6 Performance

Store a `path` column (for example `pk/punjab/dera-ghazi-khan/taunsa`) and denormalised ancestor IDs, so "all news in Punjab" is one indexed query, not a recursive walk.

---

# PART 7 — MULTILINGUAL SYSTEM: URDU + ENGLISH

This is a critical requirement. The whole platform is bilingual from the first commit: public site, reporter dashboard, admin, emails, notifications, validation messages, PDFs and receipts.

## 7.1 Locales and URLs

- Locales: `ur` (default for the public site: **decision D-01**) and `en`.
- Every public URL is locale-prefixed: `/ur/...` and `/en/...`. The root `/` redirects by saved preference, then by `Accept-Language`, then to the default. Never auto-redirect search bots.
- The language switcher links to the **equivalent translated page** when one exists and is published, otherwise to the locale's homepage with a notice. It must never link to a 404.
- All UI strings live in `lang/ur/*.php` and `lang/en/*.php` (or JSON). No hardcoded user-facing strings in Blade. Add a CI check for missing keys.

## 7.2 Urdu typography: Nastaleeq

**Font requirements:** Nastaleeq must be used for Urdu headlines, article bodies, navigation and menus, buttons, labels, forms, reporter dashboards, admin interfaces and notifications.

Do not use Naskh or generic system fonts as the primary Urdu display font.

**FINAL DECISION (D-02): the Urdu font is Noto Nastaliq Urdu**, the free Google Font released under the SIL Open Font License. It is free for commercial use, embedding and self-hosting, so it needs no extra licence.
- Use it for **all** Urdu text: public site, dashboards, admin, emails, PDFs/receipts and share images.
- Weights: Noto Nastaliq Urdu ships Regular to Bold (variable font). Use Regular (400) for body text and SemiBold or Bold (600/700) for headlines.
- CSS stack: `font-family: "Noto Nastaliq Urdu", serif;`. The generic fallback exists only for the moment before the font loads. Never ship a Naskh font as the primary Urdu face.
- Keep the font configurable (`config/typography.php` → `urdu_font_family`, `urdu_font_files`), so the owner can switch fonts later without code changes. Document how in `docs/MULTILINGUAL_GUIDE.md`.
- Put a copy of the OFL licence text in `public/fonts/OFL.txt`, as the licence requires when redistributing the font files.
- Jameel Noori Nastaleeq is **not** used.

**Web performance for Nastaleeq fonts** (these files are large):
- Serve WOFF2, **self-hosted** from the application (download the font files from Google Fonts or the Noto project and commit them to `public/fonts/`). Self-hosting is faster, has no third-party privacy issues and works offline. Loading it from the Google Fonts CDN is allowed only as a temporary development shortcut.
- Subset to the Urdu, Arabic and Latin punctuation ranges that are actually used.
- `font-display: swap`, preload the regular weight on Urdu pages only, and never load the Urdu font on English pages unless Urdu text is present.
- Long-lived cache headers with hashed filenames.

**Nastaleeq layout rules** (put them in the design system, not ad-hoc CSS):
- Body line-height around 2.0–2.2, and headlines around 1.6–1.8. Nastaleeq has tall ascenders and deep descenders, so tight line-height clips glyphs.
- Larger base size than English (Urdu body text is roughly 1.15–1.25× the English body size).
- `overflow: visible` and extra vertical padding on buttons, badges, tabs and table cells, so diacritics are never clipped.
- No `text-transform`, no letter-spacing and no justified text that breaks ligatures. Avoid `text-overflow: ellipsis` on single-line Urdu headlines. Use multi-line clamping with sufficient line-height instead.
- No faux bold or italic. If the font has no bold, use size and colour for emphasis.

## 7.3 RTL and LTR

- Set `<html lang="ur" dir="rtl">` or `<html lang="en" dir="ltr">` per request.
- Build all layouts with **logical CSS properties** (`margin-inline-start`, `padding-inline-end`, `inset-inline-start`) and Tailwind logical utilities. Never just mirror English CSS.
- Icons with direction (arrows, chevrons, "next" and "back") flip in RTL. Icons without direction (search, play, clock) do not.
- Mixed text: wrap user-generated names, URLs, numbers and English terms inside Urdu text in `<bdi>` or `dir="auto"`, so punctuation and parentheses land in the right place.
- All form inputs for Urdu fields have `dir="rtl"`. Fields that are always Latin (email, URL, phone, CNIC) have `dir="ltr"` even on Urdu pages.
- The rich-text editor must support RTL authoring and the Nastaleeq font in the editing surface (for example TipTap or Trix with RTL configuration). The editor output is sanitised HTML (Part 32).
- Tables, charts, pagination, breadcrumbs, carousels and date pickers must all be checked in RTL.

**Numbers and dates (decision D-03):**
- Digits: Western digits (0–9) or Eastern Arabic-Indic digits (۰–۹) in Urdu UI. The default is Western digits for data and tables, with a setting to switch. Store numbers as numbers and format only at display time.
- Dates: Gregorian by default, formatted with `intl` (`ur_PK` / `en_PK`). Hijri display is optional and configurable.
- Timezone: store UTC and display `Asia/Karachi`.

## 7.4 Translation architecture

One story, many translations. Never create duplicate independent records for the same story.

```
news_articles (1) ──< news_translations (N)   [unique: news_article_id + locale]
```

Each translation has its own: headline, summary, body, slug, SEO title, meta description, featured-image override, `publication_status`, `translation_status`, `translated_by`, `reviewed_by`, `published_at`, and `is_original` (the language the reporter wrote in).

**Translation statuses:** `not_started`, `draft`, `under_review`, `approved`, `published`, `rejected`.

- An Urdu version may be published while the English version is still under review.
- Story-level facts (location, category, reporter, evidence, incident date) are shared. Text is per translation.
- A **material correction** to one translation flags every other published translation as `needs_update`, and notifies the responsible editor.
- AI-assisted machine translation may be used to *create a draft only*. It is always marked "machine draft" internally and must be human-reviewed before publishing. Never auto-publish machine translation.
- Separate SEO metadata per language. `hreflang` pairs are emitted only between translations that are **both published**. Each translation is its own canonical. Language-specific sitemaps.
- Store everything in `utf8mb4`.

**Slugs (decision D-04):** URLs use the pattern `/{locale}/news/{id}-{slug}`. The numeric ID makes the URL permanent even when the slug changes, and an old slug 301-redirects to the current one. The default English slug is Latin. The default Urdu slug is a romanised transliteration (safest for sharing on WhatsApp and SMS), with an option for Unicode Urdu slugs.

---

# PART 8 — USER ROLES, PERMISSIONS AND GEOGRAPHIC SCOPE

## 8.1 Roles

**Initial roles:** Super Administrator, Administrator, National Editor, Provincial Editor, District Editor, Tehsil Coordinator, News Editor, Reporter, Advertising Manager, **Finance Officer** (new: separates money handling from ad sales), **Translator** (new, optional).

**Future roles:** Reader, Press Club, Media House, Business Owner, Hiring Manager.

## 8.2 Role and scope are separate

A user may hold several **role assignments**, each with its own scope:

```
role_assignments: id, user_id, role_id, scope_type (country|province|district|tehsil|locality|global),
                  scope_id (nullable for global), granted_by, granted_at, expires_at (nullable),
                  revoked_by, revoked_at, reason
```

Example: a District Editor for Dera Ghazi Khan can manage DG Khan and its tehsils, but nothing else. The same person could also be a Reporter for Taunsa.

**Scope resolution rules:**
- A scope includes all its descendants (a province scope covers its districts, tehsils and localities).
- A story falls within a scope if its location is within that scope.
- A user's effective scope for a permission is the union of the scopes on every assignment that grants it.
- Implement this as an Eloquent query scope, for example `NewsArticle::visibleTo($user, 'news.approve')`, and in Policies. **Every** admin list, export, search, count and API endpoint must apply it. Write a test that loops over admin routes and asserts that an out-of-scope editor gets a 403 or an empty result.

## 8.3 Separation of duties (new, and important)

- A reporter can never approve, publish, edit-approve or investigate their **own** story, even if they also hold an editor role.
- The person who issues a warning cannot rule on the appeal against it.
- The person who records an ad payment cannot also mark it verified (the Finance Officer verifies it). This maker-checker rule is ON by default and can be switched off in settings while the team is small (Part 24.2).
- Super Administrator actions are audit-logged like everyone else's, and Super Administrators cannot delete audit logs.

## 8.4 Permission matrix

Create a configurable permission matrix (permissions seeded, assignable in admin) and document it in `ROLE_PERMISSION_MATRIX.md` and `REGIONAL_ACCESS_MATRIX.md`. Permissions are granular verbs, for example `news.submit`, `news.review`, `news.approve`, `news.publish_instant`, `news.correct`, `reporter.verify_identity`, `reporter.view_private_documents`, `ads.approve`, `finance.verify_payment`, `audit.view`, `messages.oversight_access`.

Use server-side authorization and Laravel Policies. Hidden frontend buttons are a convenience, not security.

---

# PART 9 — REPORTER REGISTRATION AND VERIFICATION

## 9.1 Registration fields

Full name (Urdu and English), profile picture, email, mobile number (Pakistani format, verified by OTP: **decision D-05** on SMS provider), password, province, district, tehsil, private residential address, CNIC number and CNIC images (front and back) or another identity document, journalism experience, previous media organisation (optional), previous reporting links (optional), professional introduction, agreement to platform policies (versioned: store which policy version and when), and an optional **public display name / byline** (see 9.4).

Registration is only possible in locations with status `registration_open`, `pilot_active` or `fully_operational`.

## 9.2 Sensitive data handling

- Identity documents are stored on the `private` disk, **outside** `public_html`, never served by a public URL. They are viewable only through an authorised, audit-logged controller that streams the file (`reporter.view_private_documents` permission).
- The CNIC number is encrypted at rest (Laravel encrypted cast), with a separate keyed hash column for duplicate detection. Show it masked (`35202-*******-1`) everywhere.
- The residential address is encrypted at rest.
- Validate the CNIC format (13 digits), and detect duplicate CNICs, phones and emails across accounts.
- Data retention: rejected applications have their identity documents purged after a configurable period (default 90 days) by a scheduled job. Record the purge.

## 9.3 After registration

The account stays **pending**. The reporter cannot publish and does not appear publicly. An administrator must review the application.

**Reporter statuses:** `pending`, `identity_verified`, `approved`, `trusted`, `inactive`, `paused`, `suspended`, `banned`, `rejected`.

Define an explicit **state machine** (document it as a diagram in `ARCHITECTURE.md`) of which transitions are allowed, who may perform them, and what each status allows (log in, submit, publish, appear publicly, receive tips, sell ads, receive earnings).

**Admin actions:** approve, reject, request more information, verify identity, add internal notes, warn, pause, suspend, ban, restore. Every action requires a reason and is written to `reporter_verifications` / `moderation_actions` and `audit_logs`. Keep the full verification history.

**Identity verification and editorial credibility are separate.** "Identity verified" means "we know who this person is". It says nothing about the quality of their reporting.

## 9.4 Reporter safety (new)

Local reporters in Pakistan can face real threats. The platform must:

- **Never** display a reporter's residential address, phone number, CNIC or exact village publicly. Public location is tehsil-level at most.
- Support an editor-approved **protected byline** for a sensitive story ("Staff Reporter, Taunsa" or a registered pen name). The real identity is known to editors and logged, and hidden publicly.
- Provide a **"Report a threat"** button in the reporter dashboard that alerts a designated safety contact (admin), with an urgent flag and an audit trail.
- Allow a reporter to request temporary hiding of their public profile.
- Strip EXIF/GPS metadata from every uploaded image (Part 32.3).

---

# PART 10 — REPORTER DASHBOARD

A professional, bilingual dashboard for every approved reporter, in these sections:

Overview · My Profile · Submit News · My News (Drafts / Pending / Published / Rejected / Requires Clarification) · Edit Requests · Corrections on my stories · News Performance (reads, reactions, shares) · Public Ratings · Credibility Score (with explanation) · Rankings · Advertisements · Earnings · Payment Records and Statements · Messages · News Tips · Notifications · Warnings and Appeals · Account Status · **Safety** (report a threat, protected byline requests).

- Charts are meaningful, with historical statistics (last 30 / 90 / 365 days, and month-by-month). Charts must render correctly in RTL.
- Every number shown must come from real recorded data, never estimated or padded.
- The credibility page explains *why* the score is what it is, component by component (Part 12).
- Mobile-first: most reporters will use a phone on a slow 3G/4G connection. Submit News must tolerate weak connectivity: autosave drafts, resumable or chunked image upload, and compressed images before upload.

---

# PART 11 — PUBLIC REPORTER PROFILES

Permanent URLs: `/en/reporter/{id}-{slug}` and `/ur/reporter/{id}-{slug}`.

**Profile content:** name, profile picture, verification badge (identity verified) and trusted badge (if applicable), province, district, tehsil, professional introduction, joining date, published news count, total reads, reactions, public rating (with rating count), credibility indicator (a band such as "High / Established / Building", not a falsely precise number: **decision D-06**), recent news, most-read news, a contact/message button (when tips are enabled), and a share-profile button.

- A profile shows only that reporter's own published stories (stories with a protected byline are excluded).
- Public directories list only `approved` / `trusted` reporters with **at least one published article**. Never list reporters who have registered but never published.
- Discovery by country, province, district and tehsil.
- Sorting options: Most Active, Most Published, Most Read, Highest Rated (Bayesian, Part 12), Highest Credibility, Recently Active, Emerging Reporters.
- A suspended or banned reporter's profile is `noindex` and shows a neutral "profile unavailable" notice. Their past published articles remain, with attribution, unless an editorial decision removes them.

---

# PART 12 — CREDIBILITY AND RANKING ENGINE

## 12.1 Five separate systems

Never merge these into one number:

1. **Editorial Credibility:** how trustworthy the reporting is, as judged by editors.
2. **Public Rating:** what readers think.
3. **Activity Ranking:** consistent, recent output.
4. **Public Popularity:** reads and engagement.
5. **Emerging Reporter Ranking:** the same quality signals, restricted to reporters who joined in the last N months (default 6).

## 12.2 Credibility formula (weights configurable in admin)

| Component | Weight | Measured by |
|---|---|---|
| Verified and authentic reporting | 35% | Share of stories approved with documented sources/evidence; absence of confirmed fabrication |
| Editorial quality and accuracy | 25% | Editor quality scores on review; confirmed corrections against the reporter (weighted by severity) |
| Consistency and activity | 15% | Published stories per active month, capped (volume beyond the cap earns nothing) |
| Reader trust | 15% | Bayesian-adjusted public rating, abuse-filtered |
| Community engagement | 10% | Tips handled, local-issue follow-ups, response time to clarifications |

**Rules:**
- Every component is normalised to 0–100. Document the exact formula in `docs/CREDIBILITY_METHODOLOGY.md`, and publish a plain-language version on the transparency page.
- **Bayesian averages** for ratings: `score = (C × m + Σratings) / (C + n)`, where `m` is the platform mean and `C` is a configurable confidence count (default 20). One five-star rating must never top a leaderboard.
- **Minimum-evidence thresholds:** no credibility band is shown until a reporter has at least N published stories (default 5). Show "Building credibility" instead.
- **Anti-gaming:** reads and reactions from suspected bots, the reporter's own sessions/IPs, and coordinated bursts are excluded. Volume above the monthly cap earns nothing. Sensational categories gain no bonus.
- **Only confirmed editorial findings reduce credibility.** Complaints, unproven allegations and pending investigations do not.
- Time decay: older findings carry less weight (configurable half-life, default 12 months), so reporters can recover.
- Each recalculation writes an explanation record, so the reporter can see what changed and why.

## 12.3 Rankings

Rankings are produced at tehsil, district, province and national level, for monthly, quarterly and yearly periods.

- Computed by a scheduled queued job, never on page load.
- Saved as immutable `reporter_performance_snapshots`, so historical rankings never change retroactively.
- Rankings are never purchasable and are never influenced by advertising activity.
- A leaderboard is shown only when a region has at least a minimum number of eligible reporters (default 3), to avoid meaningless "#1 of 1".

---

# PART 13 — NEWS SUBMISSION AND MANAGEMENT

## 13.1 Submission fields

Headline, SEO slug (auto-generated, editable), short summary, full article (rich text), featured image (required, with caption and credit), additional images (with captions), video URL (YouTube, Facebook or other embeddable platforms) or video upload (**decision D-07**: uploads are disabled by default because of server storage and bandwidth limits on cPanel; enable them with size limits once storage is planned), category, tags, province, district, tehsil, locality, exact location (text; never auto-filled from GPS), incident date and time, news sources (structured: type, name, contact (private), on-record/anonymous), supporting evidence (files, private), source notes (private, editors only), reporter attribution (and co-reporters), and a **conflict-of-interest declaration** (see 13.3).

- The reporter can only choose locations inside their approved coverage areas.
- Autosave drafts every 30 seconds.

## 13.2 Categories and flags

Categories are configurable (bilingual names, slugs, icons, order, enabled flag). Initial categories: Politics, Crime, Education, Health, Business, Agriculture, Sports, Government, Development, Local Issues, Environment, Culture, Technology.

**Correction to the original category list:**
- "National" is a **geographic level** (a story scoped to Pakistan as a whole), not a category. Model it with the story's location scope.
- "Breaking News" is a **flag with an expiry** (`is_breaking`, `breaking_until`), set only by editors, not a category. Otherwise every story stays "breaking" forever.

## 13.3 Conflict of interest (new)

The reporter must declare whether any person or business in the story is an advertiser they have sold ads to, a relative, or a political affiliation. A declared conflict routes the story to a higher-level editor. Undisclosed conflicts that are later discovered are a disciplinary category.

## 13.4 Editorial-sensitive content rules

Built into the submission and review checklist:
- Victims of sexual violence and juveniles must not be identifiable (no names, faces, addresses or school names).
- Graphic images of dead or injured people are blurred by default, with a content warning.
- Allegations against named individuals require a documented attempt to obtain the accused party's response.
- Court-related reporting follows sub judice caution (editor checklist item).

---

# PART 14 — EDITORIAL APPROVAL AND VERIFICATION

All news initially requires editorial approval.

## 14.1 Workflow

1. The reporter submits a story.
2. Basic validation runs (required fields, image size and type, coverage-area check).
3. Duplicate checks run (similar headline/body within N days in the same district, using normalised text and trigram or shingle similarity).
4. Missing sources are flagged.
5. Suspicious patterns are flagged (excessive caps or exclamation marks, known-misinformation phrases list, reused images by perceptual hash, a brand-new account submitting high-risk categories).
6. The story enters the review queue of the **lowest editorial level whose scope contains the story's location** and escalates upward on timeout (configurable SLA, default 6 hours).
7. The editor checks sources and evidence against the checklist.
8. The editor approves, rejects, requests clarification, holds, or escalates.
9. Approved stories are published immediately or scheduled.

**News statuses:** `draft`, `submitted`, `under_review`, `requires_clarification`, `approved`, `scheduled`, `published`, `rejected`, `under_investigation`, `archived`, `unpublished` (new: taken down after publication, with a public notice where appropriate).

Implement the workflow as an explicit state machine in a `StoryWorkflowService`. Disallowed transitions throw, and every transition writes to `news_approval_history` with actor, from, to, reason and timestamp.

## 14.2 Verification checklist and record

Record: sources checked, evidence reviewed, supporting documents, the right of reply attempted (for allegations), sensitive-content checks, editorial comments, approval or rejection reason, the responsible editor, and timestamps. The checklist items are configurable.

**Editorial assignments:** an editor can claim a story (to avoid two editors working on it) with a lock timeout.

AI tools may help flag suspicious material, but **AI output is never proof of factual accuracy** and never approves or rejects a story by itself.

## 14.3 Post-publication complaints and investigations

A public "Report this story" form (reason category, details, optional contact) creates a complaint. Editors triage it: dismiss, investigate (status `under_investigation`, story remains visible unless the editor decides otherwise), correct, or unpublish. Outcomes are recorded and the complainant is notified if they left contact details. Complaint counts never affect credibility until an investigation confirms a finding.

---

# PART 15 — TRUSTED REPORTER INSTANT PUBLISHING

Administrators can grant selected **trusted** reporters instant-publishing permission.

- The permission must be explicitly granted, optionally limited by category (for example not Crime or Politics) and by location, and optionally with an expiry date.
- The granting administrator, date and reason are recorded.
- Every instantly published story automatically enters a **post-publication review queue**. Editors must review it within the SLA.
- The permission can be revoked at any time. It is revoked **automatically** on suspension, on a confirmed serious finding, or after a configurable number of corrections in a period.
- Complaints and corrections stay fully available.
- Breaking-news flags still require an editor.

Instant publishing never means exemption from editorial accountability.

---

# PART 16 — NEWS EDITING AND CORRECTIONS

## 16.1 The 60-minute rule (clarified)

- A reporter may edit their own published story directly for **60 minutes after first publication** (configurable).
- **Clarification:** for a story that was pre-approved by an editor, a direct edit within the 60 minutes that changes a **material fact** (or the headline) sends the change back for editor approval before it goes live. Typo and formatting fixes go live directly. This stops the window from being used to bypass review. The material/minor classification is the reporter's declaration plus an automatic diff check (numbers, names or dates changed → material).
- After 60 minutes, direct editing is disabled. The reporter submits an **edit request** with a reason and the proposed changes, and an authorised editor approves or rejects it.

## 16.2 Version history

Every saved change creates a `news_versions` row: full content snapshot, diff, reporter, editor, change reason, change type (minor or material), and timestamp. Editors can view diffs between any two versions.

## 16.3 Corrections

- A material change after publication requires a **public correction notice** at the top or bottom of the article (bilingual), with date and summary of what changed.
- Correction types: Correction, Clarification, Update, Editor's Note, Retraction.
- Never silently change important published facts.
- A list of corrections is available on the transparency pages.

---

# PART 17 — NEWS ARTICLE PAGES

Permanent SEO-friendly URLs: `/{locale}/news/{id}-{slug}`.

The article page contains: headline, summary, featured image (responsive, with caption and credit), publication date, updated date (only when meaningfully updated), category, location breadcrumb (province › district › tehsil), reporter profile link (or protected byline), full article, correction notices, related news, more news from the same location, more news from the same reporter, reactions, read count (real, see 21.3), social sharing, "Report this story", and the link to the other language version if published.

- Correct direction and typography per locale.
- Paid or sponsored content has a clear, unmissable label ("Sponsored / اشتہار"), and is never shown in the editorial news stream without that label.
- A reading-optimised layout: comfortable measure (max 65–75 characters for English and an equivalent width for Urdu), no layout shift from ads (reserved slots), and an accessible font size control.
- An AMP version is **not** required.

---

# PART 18 — READER-FIRST HOMEPAGE

A premium, professional national news homepage, with separate Urdu and English experiences.

**Components:** main search; province, district, tehsil and category filters; Breaking News (only when active); Featured News (editor-curated); Latest News; Most Read (last 24 hours / 7 days, bot-filtered); Most Reacted; Trending (velocity-based, not total-based); National News; Provincial News; District News; Tehsil News; Popular Reporters; Latest Videos; Local Issues.

- **"Near me" without tracking:** the reader can pick their district/tehsil once. It is stored in a cookie, and the homepage then shows a "Your area" block. No GPS permission prompt by default.
- The layout is a clean list-oriented design that scales to very large numbers of stories. Do not overcrowd it.
- Homepage blocks are configurable in admin (order, visibility, count, pinned stories).
- Each block is served from cache with short TTLs (for example 60 seconds for Latest and 5 minutes for Most Read), and invalidated on publish.
- Optimised queries: every block is one indexed query. No N+1.
- Hide any block that has no content, instead of showing an empty or fake one.

---

# PART 19 — LOCATION-BASED AND KEYWORD SEARCH

## 19.1 Filters

Search by keyword, province, district, tehsil, category, date range and reporter, in any combination:

- Province = Punjab → Punjab news.
- + District = Dera Ghazi Khan → district news.
- + Tehsil = Taunsa → tehsil news.
- Keyword only → all relevant news.
- Location only → all news in that location.
- Keyword + location → both combined.

## 19.2 Behaviour

- Dependent dropdowns (province → district → tehsil) load from a cached JSON endpoint, work in both languages, and degrade gracefully without JavaScript.
- All filters live in query parameters, so search URLs are shareable and bookmarkable.
- Search result pages are `noindex, follow`. Location landing pages (Part 20) are the indexable alternative.
- Results sort by relevance or date. Pagination is cursor-based on large sets.

## 19.3 Urdu and English search

Search queries match across both the Urdu and English translations, with the reader's language ranked first.

## 19.4 Urdu text normalisation (essential)

Urdu text contains visually identical but different Unicode characters, and MySQL FULLTEXT will miss matches unless this is handled. Store a normalised `search_text` column per translation, and apply the **same** normalisation to queries:

- Arabic Yeh `ي` (U+064A) and Farsi Yeh → Urdu `ی` (U+06CC); Arabic Kaf `ك` (U+0643) → Keheh `ک` (U+06A9); Heh variants `ه` / `ۃ` → `ہ` (U+06C1), as decided and documented.
- Strip diacritics (zer, zabar, pesh, shadda, tanween) and tatweel/kashida.
- Normalise Urdu and Arabic-Indic digits to ASCII digits.
- Remove zero-width characters (ZWJ, ZWNJ) for indexing.
- Use MySQL's **ngram** FULLTEXT parser (or a carefully configured minimum token size) on `search_text`, because the default parser treats short Urdu words badly. Benchmark both and record the decision.
- Write tests with real Urdu examples (for example `کراچی` typed with an Arabic Kaf must find `کراچی`).

---

# PART 20 — PROVINCE, DISTRICT AND TEHSIL LANDING PAGES

SEO-friendly pages:

```
/en/pakistan/punjab
/en/pakistan/punjab/dera-ghazi-khan
/en/pakistan/punjab/dera-ghazi-khan/taunsa
/ur/pakistan/punjab
/ur/pakistan/punjab/dera-ghazi-khan
/ur/pakistan/punjab/dera-ghazi-khan/taunsa
```

(URL slugs stay Latin in both locales, for shareability. Display names are localised.)

Each page includes: a location introduction (editor-written, bilingual), latest news, most-read, trending, local reporters (real, published ones only), categories with content, related and neighbouring locations, local issues, local advertisements (labelled), and a share button.

**Indexing rules:** a location page is `noindex` until it has at least N published stories in the last M days (default 5 stories in 90 days) **and** an introduction. Empty category sub-pages return `noindex` or are not linked. The sitemap includes only indexable location pages.

Old URLs from boundary changes 301-redirect (Part 6.4).

---

# PART 21 — READER ENGAGEMENT

Readers don't need accounts initially.

**Allowed:** like, dislike, reactions (a small configurable set), reporter ratings (1–5, per reporter, not per article), news sharing, profile sharing, news tips, content complaints, reporter messaging.

## 21.1 Abuse prevention

- Each reaction is tied to an anonymous, signed, first-party visitor ID cookie plus a hashed IP with a daily salt. One reaction per story per visitor, and changeable.
- Rate limiting per IP and per visitor on all write endpoints.
- Bot protection: Cloudflare Turnstile (privacy-friendly, free) on ratings, tips, complaints and messages, plus a honeypot field and a minimum time-to-submit.
- Suspicious-pattern detection: bursts from one IP range, a single visitor rating many reporters, a reporter's own IP/device rating themselves, or rating spikes after a dispute. Flagged ratings are **quarantined** (excluded from scores) pending review, not deleted.
- Store raw events, so scores can be recomputed after filtering rules change.
- Prepare for future reader accounts (nullable `user_id` on engagement tables).
- Never create artificial users or fake engagement.

## 21.2 Ratings fairness

Show the rating count next to every average. Use the Bayesian average for sorting. Ratings older than a configurable period count less.

## 21.3 Read counting

- A "read" is counted only after the page has been visible for a minimum time (for example 10 seconds) or scrolled past 50%, sent by a lightweight beacon.
- Known bots (user-agent list) and repeat reads by the same visitor within 30 minutes are not counted.
- Views are written to a buffered table or cache counter and aggregated by a queued job into `article_view_daily`. Never update a counter row on every page view under heavy traffic.
- Displayed counts are rounded ("1.2K / ۱.۲ ہزار") and come only from real data.

---

# PART 22 — NEWS TIPS AND MESSAGING

## 22.1 Tips

Readers can submit tips to a selected reporter, to a reporter in their tehsil, or to the regional reporting team.

**Fields:** name (optional), contact (optional), location, subject, message, images, documents.

- Strip EXIF/GPS from uploaded images, scan uploads (type and size checks; ClamAV if available on the server), and store them privately.
- Tipster contact details are encrypted at rest and visible only to the assigned reporter and authorised oversight staff.
- Show the tipster, before they submit, a clear notice of who can read the tip and how long it is kept.
- Retention: closed tips and their attachments are purged after a configurable period (default 12 months) unless converted into a story's evidence.

**Reporters can:** receive tips, respond, request more information, investigate, and convert a verified tip into a story draft (linked to the tip for provenance).

**Tips are never automatically published.**

## 22.2 Messaging

- Reader → reporter messages, and replies. Readers without accounts use a secure, unguessable conversation link sent to their email (or a reference code).
- Reporters can block and report abusive senders.
- Authorised oversight staff can access platform conversations **only with a recorded reason**, and every access is audit-logged (who, when, which conversation, why).
- The privacy notice explains this access clearly to both readers and reporters.

---

# PART 23 — LOCAL ISSUES TRACKER

A community information and accountability module.

**Issue types:** roads, water supply, hospital facilities, education, electricity, gas, sanitation, transport, development projects, other (configurable).

- Readers and reporters can report an issue (location, type, description, photos with EXIF stripped).
- Multiple reports about the same issue can be merged into one **issue page** by an editor (with a duplicate suggestion by location and type).
- **Issue statuses:** `reported`, `under_investigation`, `confirmed`, `follow_up_published`, `resolved`, `closed`.
- An issue page shows a timeline: reports (count, not identities), editorial updates, linked news stories and follow-ups (Suggestion 4).
- A public report is labelled "Reported by residents: not yet verified" until an editor confirms it. **Never present public allegations as confirmed facts.**
- An issue page is `noindex` until it is confirmed or has a linked published story.
- Issues can be shared (Part 25).

---

# PART 24 — LOCAL ADVERTISING AND REPORTER EARNINGS

## 24.1 Who posts ads

Ads can be posted in two ways (each can be switched ON/OFF separately, Part 45):

1. **Advertiser self-submission:** a public, bilingual "Advertise with us" form, where a business posts its own ad. No account is needed at first. The advertiser is identified by mobile number and email.
2. **Reporter-submitted:** a reporter brings a local advertiser (shop, school, college, hospital, clinic, business, institution or local organisation) and submits the ad on their behalf from the reporter dashboard. The reporter is recorded as the ad's **referring reporter**.

**Fields:** business name, advertiser name, contact person, mobile/WhatsApp number, email (optional), location, ad title, description, banner image (with size and format validation per placement), destination URL (or WhatsApp/phone call-to-action), requested duration, placement, target location (which landing pages and articles the ad shows on), the price shown from the rate card or the agreed amount, and the referring reporter (if any).

## 24.2 Payment model: MANUAL (final decision D-08)

**There is no online payment gateway.** All payments are collected manually by platform staff:

1. The ad is posted. Status: `submitted`. The submitter sees: "Thank you. Our team will contact you to confirm and collect payment. Your ad will go live after approval." No money is taken online.
2. Staff review the ad content (policy, labelling, conflict check). Bad content → `rejected`, with a reason. Acceptable content → `awaiting_payment`.
3. **Staff contact the advertiser manually** (phone call or WhatsApp; the contact numbers show as tap-to-call and tap-to-WhatsApp links in admin). Each contact attempt is logged on the ad: date, staff member, channel, outcome and notes ("No answer", "Will pay Friday", and so on). Reminders show for ads waiting too long.
4. Payment is collected offline: cash, bank transfer, JazzCash, Easypaisa or cheque.
5. Staff **record the payment** in admin: amount, method, date received, reference (transaction ID, slip number or "cash receipt #"), an optional photo of the slip/receipt (private storage), and who received it.
6. **Approval:** an authorised admin marks the payment **verified** and **approves the ad**. Only then does it become `scheduled` or `live`.
7. The system issues a bilingual receipt (PDF and printable page, unique receipt number) that staff can send to the advertiser on WhatsApp.

Rules:
- **A payment is never marked as received automatically.** A human must record and verify it.
- Separate recorder and verifier (maker-checker) is a **setting**: ON by default, so the person who records a payment cannot verify it. It can be turned OFF while the team is small, and then every verification is still audit-logged.
- Partial payments are allowed. The ad goes live only when the balance due is zero, unless an admin approves an exception with a recorded reason.
- Refunds and cancellations are recorded the same way, manually, with a reason.

**Referring reporter's share:** when a reporter brought the ad, their share is calculated once the payment is verified. Example: the advertiser pays the platform Rs. 5,000, and with a 20% platform fee, Rs. 1,000 is platform revenue and Rs. 4,000 is the reporter's earning. Reporter earnings are paid out **manually** too (bank, JazzCash or Easypaisa). Staff record each payout with a reference, and the reporter sees it in their statement. Ads submitted directly by advertisers have no reporter share: 100% is platform revenue.

**Money storage:**
- The platform fee percentage is configurable globally, with optional overrides per placement or region. The fee **at the time of approval** is stored on the ad, so later changes never alter past records.
- All money is stored as **integer paisa** (or as `DECIMAL(12,2)`, never float). Amounts are in PKR.
- Every money movement (payment received, refund, reporter earning, reporter payout) is a row in `financial_transactions`. Balances are computed from transactions and never edited directly.
- The schema keeps a `payment_method` and `gateway_reference` field, so an online gateway (JazzCash, Easypaisa or card) can be added later without changing the data model, but **no gateway is built now**.

## 24.3 Lifecycle

`submitted` → `under_review` → `awaiting_payment` (staff contacting the advertiser) → `payment_recorded` → `payment_verified` → `approved` → `scheduled` → `live` → `expired`, plus `rejected`, `paused`, `cancelled` and `refunded`.

**The system provides:** a rate card (price per placement, region and duration, managed in admin); ad submission (advertiser and reporter); review; a manual contact log; manual payment recording and verification; approval; fee and reporter-share calculation; scheduling; automatic expiry (scheduled job) with a renewal reminder that staff follow up manually; receipts; performance (impressions and clicks, bot-filtered, shareable with the advertiser as a simple report); reporter earnings; manual payout records; and monthly reporter statements (Suggestion 8).

## 24.4 Editorial independence safeguards

- Every ad and every piece of sponsored content is clearly labelled.
- Ads never appear styled as news.
- A reporter who sold an ad to an entity must declare the conflict when reporting on that entity (13.3).
- Editors' review screens show whether a story mentions an active advertiser.
- Advertising never affects rankings, credibility or awards.
- Placements may not be sold next to stories about the advertiser.

**Legal note:** tax withholding, invoicing and income-reporting obligations (FBR) must be reviewed by a qualified accountant before launch.

---

# PART 25 — SOCIAL MEDIA SHARING

Every article, reporter profile, province/district/tehsil page and local-issue page gets excellent sharing.

**Channels:** WhatsApp (the highest priority in Pakistan, so test it first), Facebook, X, LinkedIn, Telegram, Copy Link, and native mobile sharing (Web Share API, with fallback).

**Implementation:**
- Open Graph and Twitter/X card metadata, with language-specific share titles and descriptions.
- Shared links carry UTM parameters (`utm_source=whatsapp`, and so on), so share-driven traffic is measured. Canonical tags ignore UTMs.
- Configurable branding (logo, colours, watermark position).

## 25.1 Social image generator (technical risk: read carefully)

Generate 1200×630 images using the headline, featured image, logo and branding. These are generated by a queued job on publish, cached on disk, and regenerated on a headline change.

**The Urdu problem:** PHP GD cannot shape Arabic-script text. Nastaleeq rendered with GD comes out as disconnected, reversed letters. Imagick can shape it only if ImageMagick was built with Pango or Raqm support. Before building this feature:

1. Detect the server's capabilities (Imagick present? Pango delegate available?).
2. **Preferred:** Imagick with Pango (`pango:` markup), using the licensed Nastaleeq font.
3. **Fallback:** a static branded template with the featured image and logo only (no headline text) for Urdu, plus GD text for English.
4. Headless-browser rendering (Browsershot/Puppeteer) is usually impractical on cPanel. Only use it if the server supports it and the decision is recorded.
5. Write a visual test: generate an Urdu share image and check it in review.

Do not force users to share. No fake share counters, and no misleading engagement tactics.

---

# PART 26 — TECHNICAL SEO

**Implement:** SEO-friendly permanent URLs, canonical tags, meta titles and descriptions (admin-overridable per content type and per item), Open Graph and Twitter cards, an XML sitemap index, split sitemaps (news, articles by month, locations, reporters, images), a **Google News sitemap** (articles from the last 48 hours only, per language), `robots.txt`, breadcrumbs (visible and schema), internal linking (location, category and reporter cross-links), `hreflang` (Part 7.4), and language-specific sitemaps.

**Structured data (JSON-LD), only when it is true:**
- `NewsArticle` for editorially approved news, with `author` (Person or the protected byline as Organization), `datePublished`, `dateModified`, `image`, `publisher`.
- `Organization` (site-wide), `Person` (reporter profiles; no private data), `BreadcrumbList`.
- `LocalBusiness` only for verified advertisers' directory pages (future), never on ads.
- Sponsored content is **not** marked as `NewsArticle`.
- Do not generate misleading structured data.

**Indexing hygiene:**
- `noindex` thin, duplicate or empty pages: search results, empty location pages, empty categories, unverified issues, filtered listings beyond the main facets.
- Pagination: self-referencing canonicals on each page, plain crawlable links (`?page=2`), and no `noindex` on paginated archives that have real content.
- Fast pages: target Largest Contentful Paint under 2.5 s on a mid-range Android phone on 4G, and Cumulative Layout Shift under 0.1. Measure with Lighthouse in CI on the homepage, an article and a location page, in both languages.

Admins can configure SEO for every important content type.

---

# PART 27 — REPORTER DISCIPLINARY SYSTEM

Warnings, appeals and disciplinary history.

**Warning categories:** inactivity, misleading reporting, fake/fabricated news, plagiarism, policy violation, messaging abuse, advertising misconduct, artificial engagement, **undisclosed conflict of interest** (new), **privacy or safety breach** (new, for example identifying a minor victim).

**Each warning records:** category, explanation, evidence, issuing administrator, severity (minor / moderate / serious / critical), date, reporter response, resolution status, and the expiry date for counting toward escalation.

- An **escalation ladder** is configurable (for example 3 moderate warnings in 12 months triggers a suspension review). Escalations are suggested to admins, never automatic.
- **Appeals:** the reporter can appeal within N days. The appeal is decided by someone other than the issuer (8.3). Decisions and reasons are recorded.
- Disciplinary records are confidential: never public, and never in general exports.
- Unverified allegations are never exposed publicly.

---

# PART 28 — ADMIN DASHBOARD

A comprehensive admin panel, with every section **scope-filtered**:

1. Overview (real-time queues: stories awaiting review, SLA breaches, complaints, pending verifications, pending payments, safety alerts)
2. Reporter Management
3. Reporter Verification
4. News Management
5. Editorial Approval (queue, claim, checklist)
6. News Corrections
7. Complaints and Investigations
8. Warnings and Appeals
9. Locations (including boundary changes and redirects)
10. Categories and Tags
11. Reader Messages (oversight, reason-gated)
12. News Tips
13. Local Issues
14. Advertising
15. Payments (Finance)
16. Reporter Earnings and Statements
17. Ratings and Reactions (quarantine review)
18. Analytics
19. SEO
20. Social Sharing
21. Homepage Management
22. Roles, Permissions and Scope Assignments
23. Regional Management
24. Audit Logs (read-only, searchable)
25. Import and Export
26. Translations
27. Safety Alerts
28. System Settings (fee %, rate card, credibility weights, thresholds, SLAs, retention periods, locale defaults) and **Feature ON/OFF switches** (Part 45)
29. System Health (queue backlog, failed jobs, last cron run, disk usage, backup status)

Support search, filtering, pagination and bulk operations (bulk actions are also audit-logged per item). Sensitive operations require specific permissions **and** recent password or 2FA re-confirmation.

Build the admin with Blade, Tailwind and Alpine in the same design system (Filament may be considered **only** if it fully supports RTL, Nastaleeq and the custom scope layer; record the decision).

---

# PART 29 — FUTURE: PRESS CLUBS, MEDIA HOUSES AND HIRING

Prepare extension points only. **Do not build these modules in the initial release.**

- **Press clubs:** official profiles, membership, member verification, local directories, future elections.
- **Media houses:** newspapers, TV channels and digital outlets; organisation verification; reporter discovery; hiring.
- **Hiring:** search reporters by location and experience, view portfolios and verified performance, contact reporters, post opportunities.

**Extension points:** an `organizations` concept (type: press_club, media_house, business), polymorphic membership, an `organization_id` nullable on role assignments, and reporter portfolio data exposed through a service that can later be permission-gated for hiring managers. Reporter data is shown to media houses **only with the reporter's opt-in**.

---

# PART 30 — FUTURE: VOTING AND POLLS

Prepare architecture for public polls, community surveys, press-club elections, journalist awards and opinion surveys.

- Informal polls and formal elections are **separate modules** with separate tables. They must never share code paths for vote counting.
- Formal voting requires identity verification, eligibility rules, one-person-one-vote enforcement, fraud prevention, an audit trail and verifiable results.
- Public polls are always labelled "unscientific, self-selected", and are never presented as representative opinion.

---

# PART 31 — DATABASE DESIGN

A normalised relational database. `utf8mb4_unicode_ci`, InnoDB, foreign keys, proper indexes, unique constraints, transactions for multi-step writes, and soft deletes where appropriate (never on financial or audit tables: those are append-only).

**Core tables:**

| Domain | Tables |
|---|---|
| Locations | countries, provinces, districts, tehsils, localities, location_redirects |
| Identity | users, roles, permissions, user_roles / role_assignments (with scope), role_permissions, two_factor (or columns), policy_acceptances |
| Reporters | reporter_profiles, reporter_verifications, reporter_documents (private), reporter_coverage_areas, reporter_warnings, reporter_appeals, reporter_activity_logs, reporter_performance_snapshots, reporter_credibility_explanations, instant_publish_grants, safety_alerts |
| Newsroom | news_articles, news_translations, news_versions, news_categories, news_tags, news_article_tag, news_sources, news_evidence, news_attachments, news_approval_history, news_edit_requests, news_corrections, editorial_assignments, news_complaints, slug_redirects |
| Engagement | news_reactions, reporter_ratings, article_views (raw or buffered), article_view_daily, shares, engagement_flags |
| Communication | conversations, messages, message_attachments, oversight_access_logs, news_tips, notifications |
| Issues | local_issues, issue_reports, issue_updates, issue_news (pivot) |
| Advertising and finance | advertisers, advertisements, advertisement_campaigns, advertisement_placements, advertisement_payments, platform_fee_records, reporter_earnings, reporter_payouts, financial_transactions, receipts |
| Platform | audit_logs, moderation_actions, seo_metadata (polymorphic), system_settings, import_jobs, import_job_rows, media (or a library such as spatie/medialibrary) |

**Future tables:** organizations, press_clubs, press_club_members, media_houses, media_house_users, hiring_opportunities, job_applications, public_polls, poll_options, poll_votes, elections (separate).

**Key indexes** (minimum): `news_articles (status, published_at)`, `(province_id, status, published_at)`, `(district_id, status, published_at)`, `(tehsil_id, status, published_at)`, `(category_id, status, published_at)`, `(reporter_id, status, published_at)`; `news_translations (locale, slug)` unique and `(news_article_id, locale)` unique; FULLTEXT on `news_translations.search_text`; `role_assignments (user_id, role_id, scope_type, scope_id)`.

**Deliverables:** `DATABASE_SCHEMA.md` (every table, column, type, index and FK, with a purpose line) and `DATABASE_ERD.md` (Mermaid `erDiagram`, split by domain so it stays readable).

---

# PART 32 — SECURITY AND PRIVACY

## 32.1 Baseline

Secure password hashing (bcrypt/argon2), CSRF protection, XSS prevention (HTML Purifier on all rich text, a strict allowlist, no inline scripts, and a **Content Security Policy** header), SQL injection protection (Eloquent/bindings only), input validation (Form Requests), authorization policies, rate limiting, secure session cookies (`Secure`, `HttpOnly`, `SameSite=Lax`), session regeneration on login, 2FA for staff, account lockout and alerting on repeated failed logins, security headers (HSTS, X-Content-Type-Options, Referrer-Policy, Permissions-Policy, frame-ancestors), spam and bot protection, and dependency audits (`composer audit`) in CI.

## 32.2 Private data

- Identity documents, evidence, tip attachments and message attachments go on a **private** disk outside the web root, streamed via authorised controllers, with every access logged.
- Encrypt CNIC numbers, residential addresses and tipster contacts at rest.
- **Back up `APP_KEY` securely and separately.** Losing it makes encrypted data unrecoverable. Document key rotation.
- Personal data is never in logs, error pages, analytics or exports. Configure error tracking to scrub personal data.

## 32.3 Uploads

- Validate by real MIME type and extension allowlist, re-encode images (which destroys embedded payloads), **strip all EXIF/GPS metadata**, enforce size limits, generate random filenames, never execute anything in upload directories (`.htaccess` deny and PHP-FPM restrictions), and run ClamAV scanning if available.
- SVG uploads are disallowed (except admin-uploaded logos, which are sanitised).

## 32.4 Audit logs

Append-only `audit_logs`: actor, role and scope used, action, subject type and ID, before/after (with sensitive fields redacted), IP, user agent and timestamp. Logged actions include viewing private documents, oversight access, permission changes, payment verification, story state changes, exports, logins of staff and settings changes. No one can edit or delete them through the application.

## 32.5 Legal and policy pages

Provide privacy policy, terms of use, editorial policy, corrections policy, advertising policy, complaints and takedown procedure, and a cookie notice, all bilingual and versioned. Users' acceptance of each version is recorded.

Design with applicable Pakistani law in mind, including (non-exhaustive, to be confirmed by counsel) the Prevention of Electronic Crimes Act 2016 as amended, the Defamation Ordinance 2002, the Constitution's Article 19 / 19-A framework, any applicable PEMRA or digital-media rules for video content, and any data-protection law in force at launch.

A **takedown workflow** for legal requests: log the requester, legal basis, content, decision, decision-maker and dates. Content may be geo-restricted or unpublished only through this workflow, never by direct deletion.

**Qualified legal review is required before production launch.**

## 32.6 Backups

Daily database backups (encrypted, kept off-server), weekly full-file backups including private storage, defined retention (for example 7 daily, 4 weekly, 6 monthly), and a **tested restore** procedure documented in `DEPLOYMENT_GUIDE.md` (restore to staging at least once before launch).

---

# PART 33 — IMPORT AND EXPORT

CSV import/export (UTF-8 **with BOM**, so Excel shows Urdu correctly) for locations, reporter records (non-sensitive fields only), categories, news records (metadata and translations) and advertisements.

**Include:** a downloadable template per type, validation, duplicate detection, an **import preview** (no writes until confirmed), row-level error reports, queued processing for large files, import logs (`import_jobs`, `import_job_rows`), and a rollback of a whole import batch.

**Export permissions are separate from view permissions** and scope-filtered. Every export is audit-logged. **Private identity documents, CNICs, addresses, tipster data and disciplinary records are never in general exports.**

---

# PART 34 — PERFORMANCE AND SCALABILITY

Prepare for thousands of reporters, millions of articles, large reader traffic, heavy search and viral sharing spikes (a WhatsApp-forwarded story can bring sudden traffic to one URL).

**Implement:**
- Database indexing (Part 31) and query optimisation. `EXPLAIN` every list query with realistic seed volume (the seeder must be able to generate ~1M stories in a local or staging environment for testing).
- Cursor or keyset pagination for deep archives.
- **Full-page caching for anonymous readers** on articles and landing pages (Laravel response cache, and Cloudflare-friendly `Cache-Control` headers), with purging on publish or correction.
- Caching of fragments (homepage blocks, location trees, menus).
- Queues for images, share images, sitemaps, notifications, rankings and view aggregation.
- Image optimisation: WebP with JPEG fallback, `srcset` and `sizes`, lazy loading below the fold, explicit width and height.
- CDN compatibility (Cloudflare: correct `TrustProxies`, real client IP from `CF-Connecting-IP`).
- Avoid N+1 (`preventLazyLoading` in development and testing), never load large datasets into memory (`chunkById`, `lazyById`, `cursor`).
- Sitemaps generated as static files by a scheduled job, never rendered per request.
- Avoid expensive infrastructure without a clear need.

---

# PART 35 — DESIGN SYSTEM

A premium, professional national-newspaper look: trustworthy, clean, modern, professional, mobile-first, accessible (WCAG 2.2 AA: contrast, focus states, keyboard navigation, alt text required on images), fast and readable.

**Design tokens** (in Tailwind config): colour (a restrained palette, with a single accent and distinct semantic colours for Breaking, Sponsored, Correction, Verified and Warning), type scale per locale, spacing, radii and shadows. Dark mode is optional (later).

**Component library:** documented in a `/styleguide` route (admin-only), showing every component in both `ur` and `en`: story card (list, compact, featured), headline styles, buttons, badges, tabs, forms, tables, pagination, breadcrumbs, alerts, modals, share bar, correction notice, sponsored label, empty states and charts.

**Public interfaces:** homepage, articles, search, location pages, reporter profiles, reporter directories, local issues and transparency pages.

**Private interfaces:** reporter dashboard, admin dashboard, editorial dashboard and advertising management.

**Urdu gets dedicated design attention.** Do not just reverse English CSS. Handle: Nastaleeq font height, Urdu line spacing, Urdu headings, navigation alignment, mixed Urdu/English text, numbers, dates, form labels, buttons, tables and responsive layouts. Urdu typography must never break cards, menus, buttons or article layouts. Test every component with **long** real Urdu headlines, not lorem ipsum.

**Wireframes first:** in Phase 0, produce low-fidelity wireframes (Markdown/ASCII or simple HTML) of the homepage, article page, location page, reporter profile, submit-news form, editorial queue and admin overview, in both directions.

---

# PART 36 — TESTING

Automated tests (Pest/PHPUnit feature tests first, plus unit tests for calculators):

- Registration and duplicate-identity detection
- Reporter verification and status transitions (state machine: allowed and disallowed)
- Role permissions **and** regional scope (including the "every admin route respects scope" sweep test)
- Separation of duties (no self-approval)
- News submission (coverage-area enforcement)
- Editorial approval workflow and escalation
- Instant publishing (grant, limits, auto-revoke, post-review queue)
- The 60-minute rule, including material edits inside the window
- Edit requests, version history and corrections
- Translation relationships, independent translation publishing, and `hreflang` only between published pairs
- Language switching and fallback
- Urdu RTL (`dir`/`lang` attributes, logical layout smoke test with Dusk)
- Urdu search normalisation
- Location filters and dependent dropdown endpoints
- Boundary change → redirect, and historical article location preserved
- Reactions (one per visitor) and rating abuse prevention (quarantine)
- Read counting (bot and duplicate exclusion)
- Ad submission (advertiser self-serve and reporter), manual contact log, manual payment recording, partial payments, payment verification (maker ≠ checker when ON), approval only after verified payment, platform fee and reporter share calculation (including a fee change after approval), manual payouts, and expiry
- Feature switches: OFF hides routes, UI, jobs and API; ON restores data; dependencies cascade; locked controls have no switch
- Location seeder: idempotent re-run, `needs_verification` rows blocked from going `pilot_active`
- Financial ledger balances
- Private document security (direct URL is impossible, unauthorised access returns 403, authorised access is logged)
- EXIF stripping
- Exports exclude sensitive fields
- Audit log creation for every sensitive action
- SEO: indexability rules (`noindex` on thin pages), sitemap content, structured data validity

Test real behaviour, not appearance. Never declare a feature complete without verifying it. Set up CI (GitHub Actions or similar) to run Pint, Larastan and tests on every push.

---

# PART 37 — DEVELOPMENT PHASES

Develop in this order. Complete, test and commit each phase before moving on. Do not implement everything in one unstructured operation.

| Phase | Scope | Exit criteria |
|---|---|---|
| **0 — Architecture** | Requirements analysis, architecture, ERD, role and scope matrix, multilingual architecture, typography strategy, wireframes, risk register, decision register, roadmap | All Phase 0 documents exist. **Owner approves** before Phase 1. |
| **1 — Foundation** | Laravel install, CI, auth plus 2FA, database, roles, permissions and scopes, location hierarchy (with boundary-change support) seeded from the supplied CSV, audit logging, settings, **Feature Registry and ON/OFF switches**, admin shell (bilingual, RTL), reporter registration, reporter verification | Scope sweep test passes. Private documents secured. Urdu admin renders correctly. |
| **2 — Reporter and News** | Reporter dashboard, public profiles (basic), story submission, translations, editorial workflow and checklist, instant publishing, 60-minute rule, edit requests, versions, corrections, complaints | A story can go from submission to published in both languages, with full history. |
| **3 — Public Website** | English and Urdu frontends, Nastaleeq typography, RTL/LTR, homepage, search (with Urdu normalisation), location filters and pages, article pages, reporter directories, technical SEO, transparency pages | Lighthouse targets met. Sitemaps and schema validate. Urdu pages are reviewed by a native reader. |
| **4 — Reader Engagement** | Reactions, ratings, read counting, credibility engine, rankings and snapshots, tips, messaging, local issues | Abuse tests pass. Ranking job is reproducible. |
| **5 — Monetisation** | Advertisers, ads, placements, fees, payments (maker/checker), ledger, earnings, payouts, receipts, statements | Ledger balances reconcile in tests. |
| **6 — Advanced** | Analytics, social sharing and share-image generator, import/export, advanced admin, performance tuning, public read-only API v1 | 1M-story load test acceptable. |
| **7 — Pilot and Production** | Security testing (OWASP checklist), performance testing, backups and restore drill, pilot region configuration, reporter onboarding materials, editorial training guide, deployment, monitoring, launch | Go-live checklist (Part 43) complete. |

**Recommended MVP cut for the pilot:** Phases 1–3, plus reactions, read counting and tips from Phase 4. The credibility engine can launch in "data collection" mode (scores computed but hidden) until enough data exists, so early scores are not misleading.

---

# PART 38 — WHM/cPANEL DEPLOYMENT

Practical compatibility:

- **PHP:** version and extensions (Part 4.1), selected per account in MultiPHP Manager. Set `memory_limit`, `upload_max_filesize`, `post_max_size` and `max_execution_time` to documented values.
- **Composer** via SSH (`composer install --no-dev --optimize-autoloader`).
- **Document root:** point the domain's document root at `/home/USER/app/public`. **Never** place the whole Laravel app in `public_html`. If the document root can't be changed, use the documented symlink approach.
- **Environment:** `.env` outside the web root, `APP_ENV=production`, `APP_DEBUG=false`, with permissions `600`.
- **Storage permissions:** `storage/` and `bootstrap/cache` writable by the PHP-FPM user. The private disk is outside `public/`. `php artisan storage:link` only for the public disk.
- **Cron:** `* * * * * cd /home/USER/app && php artisan schedule:run >> /dev/null 2>&1`
- **Queue workers:**
  - With root/WHM access: Supervisor (preferred) running `queue:work --tries=3 --max-time=3600`.
  - Without Supervisor: a scheduled `queue:work --stop-when-empty --max-time=55` every minute, with `withoutOverlapping()`. Document the trade-offs.
- **Cache:** `config:cache`, `route:cache`, `view:cache`, `event:cache` on deploy. Redis if installed, otherwise the file/database driver.
- **SSL:** AutoSSL or Let's Encrypt, then HSTS after verification.
- **Cloudflare:** Full (strict) SSL, trusted proxies, cache rules (bypass for authenticated sessions and `/admin`, `/dashboard`), and real-IP restoration.
- **Zero-downtime deploys:** release directories plus a `current` symlink (or a documented `php artisan down` → pull → migrate → up sequence for simpler setups).
- **Backups and restore:** Part 32.6.
- **Monitoring:** health-check endpoint, failed-job alerts, disk-space alerts and uptime monitoring.

**Never expose:** `.env`, `storage/`, private documents, application source, `.git`, `vendor/` or `composer.json` over HTTP. Add a deploy test that requests these paths and expects 403/404.

Provide complete step-by-step deployment documentation, written for a cPanel administrator who is not a Laravel expert.

---

# PART 39 — DOCUMENTATION

Maintain in `docs/`:

`README.md` · `PROJECT_REQUIREMENTS.md` (this file) · `ARCHITECTURE.md` · `DATABASE_SCHEMA.md` · `DATABASE_ERD.md` · `ROLE_PERMISSION_MATRIX.md` · `REGIONAL_ACCESS_MATRIX.md` · `MULTILINGUAL_GUIDE.md` (including font installation) · `CREDIBILITY_METHODOLOGY.md` · `DEVELOPMENT_ROADMAP.md` · `DEPLOYMENT_GUIDE.md` · `SECURITY_GUIDE.md` · `API_DOCUMENTATION.md` · `DECISIONS.md` (decision register: ID, decision, options considered, chosen option, owner, date) · `RISK_REGISTER.md` · `EDITORIAL_HANDBOOK.md` (for editors: checklist, sensitive content rules, corrections) · `CHANGELOG.md` · `DEVELOPMENT_STATUS.md`.

Update them as the project develops. Documentation that disagrees with the code is a bug.

---

# PART 40 — CLAUDE CODE WORKING INSTRUCTIONS

## 40.1 Before making changes

1. Inspect the project folder.
2. Understand the existing code.
3. Read all project specifications (`docs/`).
4. Identify missing requirements.
5. Resolve conflicts (and record them in `DECISIONS.md`).
6. Write an implementation plan for the current phase.

## 40.2 Rules

- Do not blindly overwrite existing files.
- Maintainable Laravel architecture. Keep business logic out of controllers.
- Use Services/Actions, Policies, Events and Listeners, Jobs, Form Requests, Enums (for statuses), database transactions and automated tests.
- Use migrations for every database change, and never edit a migration that has already run in a shared environment.
- Use seeders for initial data (Pakistan's provinces, a verified pilot region, categories, roles and permissions, settings).
- **Demo data:** demo records carry an `is_demo` flag, or live in a demo batch. A `demo:purge` command deletes only flagged records, refuses to run when `APP_ENV=production` unless given an explicit `--force-demo-only` flag, and logs what it deleted. Demo data is never generated in production by default.
- Business rules are configurable in admin wherever appropriate (fees, weights, thresholds, SLAs, retention periods).
- Work in small, reviewable commits.

## 40.3 After each completed module

- Run tests, Pint and Larastan. Fix errors.
- Update the documentation, `CHANGELOG.md` and `DEVELOPMENT_STATUS.md`.
- Report what was completed, what was verified and how, known issues, and the next step.

## 40.4 Session continuity

Long projects span many sessions. Keep `DEVELOPMENT_STATUS.md` as a hand-off note: current phase, last completed task, the next three tasks, open decisions and known issues. Start every session by reading it.

Use Git, with a separate commit (and a tag such as `phase-1-complete`) after each tested phase.

**Never claim a feature is complete when only its frontend exists.**

---

# PART 41 — FIRST TASK: ARCHITECTURE BEFORE CODE

Do not generate the application yet. First analyse the whole project.

**Your first response must deliver** (as files in `docs/`, with a summary in chat):

1. Understanding of the business concept (in your own words, including what this platform is *not*).
2. Complete technical architecture (module map, request lifecycle, caching, queues).
3. Database ERD (Mermaid).
4. Database relationships.
5. User roles and permission matrix.
6. Geographic access-control model (including scope resolution and the sweep test).
7. Urdu and English architecture (URLs, translations, `hreflang`, slugs).
8. Nastaleeq typography strategy (font licence path, loading, layout rules).
9. Reporter verification workflow (state machine diagram).
10. News verification workflow (state machine diagram).
11. Credibility and ranking methodology (formulas, thresholds, anti-gaming).
12. Advertising revenue workflow (both money-flow models, ledger).
13. Reader experience (key journeys: find tehsil news, read an article, send a tip, report a story).
14. SEO strategy.
15. Security architecture (data classification table: public / internal / confidential / restricted).
16. Reporter and source safety measures.
17. Pilot launch strategy.
18. Development phases with estimates.
19. Technical risks (with mitigations), in a risk register.
20. Missing requirements you identified.
21. Questions requiring genuine business decisions (start from Part 44, add any new ones, and propose a recommended default for each).
22. Low-fidelity wireframes for the key screens, in both directions.

Do not ask unnecessary questions. Use sensible defaults for technical details that are not essential business decisions.

**Once the architecture is presented and approved, begin Phase 1.**

---

# PART 42 — STRATEGIC SUGGESTIONS FOR REVIEW

Document and evaluate these during architecture. Do not activate all of them in the initial release. Each is tagged with a recommended phase.

1. **Reporter Portfolio** *(Phase 2 basic, Phase 6 full)*: published articles, experience, introduction, verified achievements and performance history, to help future media houses identify qualified journalists. Exposed to media houses only with the reporter's opt-in.
2. **Emerging Reporter Program** *(Phase 4)*: separate recognition for new reporters, so established reporters can't dominate every leaderboard. Visibility comes from quality and authentic activity.
3. **Local Business Directory** *(Future)*: schools, hospitals, clinics, shops, businesses and institutes, connected to advertising. Clearly distinguish "registered" from "independently verified" businesses.
4. **Public Issue Follow-up** *(Phase 4)*: follow-up reports linked to the same issue, with a timeline of developments.
5. **Editorial Transparency Pages** *(Phase 3: recommended for launch)*: verification policy, corrections policy, reporter verification standards, advertising policy, complaints process, editorial independence, credibility methodology (plain-language), ownership and funding.
6. **Regional Editorial Teams** *(Phase 1, built into scopes)*: qualified editors manage their own regions without unrestricted access.
7. **Reporter Mentorship** *(Future)*: experienced reporters mentor junior journalists (mentor assignment, feedback on drafts before submission).
8. **Transparent Reporter Revenue** *(Phase 5)*: clear statements showing ad amount, platform fee, payment status, reporter earnings and payout history.
9. **Editorial Complaint and Appeals Centre** *(Phase 2–3)*: a structured public complaints process plus reporter appeals, fair and auditable.
10. **National Journalist Recognition** *(Future)*: Best Tehsil Reporter, Best District Reporter, Best Investigative Report, Emerging Journalist and Best Community Reporting. Transparent criteria, an independent jury option, never purchasable through advertising.

**Additional suggestions (new):**

11. **Reporter onboarding and training** *(Phase 7)*: a short bilingual course (sourcing, verification, ethics, safety, platform use). Completing it is required before the first submission.
12. **Low-bandwidth mode** *(Phase 3)*: a text-first article view with images on demand, for rural readers with expensive data.
13. **WhatsApp Channel publishing** *(Phase 6)*: a per-district digest that editors can copy-paste into official WhatsApp Channels. Manual at first, with no unofficial automation.
14. **Fact-check / "Myth vs Fact" format** *(Future)*: a dedicated story type for debunking viral local rumours, with `ClaimReview` structured data only when the methodology meets the requirements.
15. **Offline-first submission (PWA)** *(Future)*: reporters draft without signal and submit when connected.

---

# PART 43 — GO-LIVE CHECKLIST (PHASE 7)

- [ ] Legal review completed (terms, privacy, editorial policy, ads, takedown procedure).
- [ ] Noto Nastaliq Urdu self-hosted, with `OFL.txt` included. Urdu pages reviewed on real Android phones.
- [ ] Feature switches set to their launch states (Part 45.3), and each one tested OFF and ON on staging.
- [ ] Manual payment flow rehearsed end-to-end: ad posted → advertiser contacted → payment recorded → verified → approved → live → receipt sent.
- [ ] Pilot locations (from the seeded CSV) verified against the latest official notifications, with Urdu tehsil names filled in by an Urdu editor.
- [ ] Penetration or OWASP checklist completed. Critical and high findings fixed.
- [ ] Backup restore drill completed on staging.
- [ ] `APP_KEY` backed up securely, offline.
- [ ] 2FA enforced for every staff account.
- [ ] Sensitive paths return 403/404 (automated check).
- [ ] Lighthouse targets met in both languages.
- [ ] Sitemaps submitted to Google Search Console. Structured data validated.
- [ ] Editorial team trained on the handbook. On-call editor rota for the pilot.
- [ ] Reporter onboarding completed for pilot reporters.
- [ ] Demo data purged, and the purge verified.
- [ ] Monitoring and alerting live.
- [ ] Rollback plan documented.

---

# PART 44 — BUSINESS DECISIONS REQUIRED FROM THE OWNER

Claude Code must present these with a recommended default, and must **not** block Phase 0 on them: proceed with the default, clearly marked as provisional.

| ID | Decision | Recommended default |
|---|---|---|
| D-01 | Default public language at `/` | Urdu |
| D-02 | Urdu font | ✅ **DECIDED:** Noto Nastaliq Urdu (free Google Font, OFL), self-hosted |
| D-03 | Digits in the Urdu UI (Western 0–9 or Urdu ۰–۹) | Western digits, configurable |
| D-04 | Urdu URL slugs: romanised or Unicode | Romanised, with the ID prefix |
| D-05 | SMS/OTP provider for phone verification | Choose a Pakistani provider. Email-only verification until it is contracted. |
| D-06 | Show credibility as a number or as a band | Band publicly, number in the reporter's own dashboard |
| D-07 | Allow direct video uploads at launch | No: embeds only |
| D-08 | Ad payment model | ✅ **DECIDED:** manual. Ads are posted online, staff contact the advertiser, collect payment offline, record and verify it, then approve the ad. No payment gateway. |
| D-18 | Features ON/OFF | ✅ **DECIDED:** every feature has an admin ON/OFF switch (Part 45) |
| D-09 | Platform fee percentage at launch | 20% (as in the brief) |
| D-10 | Reporter payout cycle (payouts are manual: bank, JazzCash, Easypaisa) | Monthly. Method per reporter. |
| D-11 | Exact pilot districts and tehsils | Owner to choose from the seeded list (Part 6.5). Verify those rows first. |
| D-12 | Editorial staffing hours and review SLA | 6-hour SLA, 9am–11pm PKT |
| D-13 | Are reporters paid anything other than ad share (stipends, per-story payments)? | Ad share only at launch |
| D-14 | Who translates stories (reporter, translator role, or machine draft plus review)? | Translator role, with machine draft plus mandatory human review |
| D-15 | Brand name, domain and logo | Owner to supply |
| D-16 | Retention periods (rejected applications, tips, messages, raw view logs) | 90 days / 12 months / 24 months / 90 days |
| D-17 | Accept anonymous public ratings of reporters at launch, or wait for reader accounts | Accept, with Turnstile, quarantine and Bayesian weighting |

---

# PART 45 — FEATURE ON/OFF SWITCHES (FINAL DECISION D-18)

Every feature of the platform must have an **ON/OFF switch** in the admin panel, so the owner can launch gradually, pause a feature that is being abused, or hide one that isn't ready, **without code changes or redeploys**.

## 45.1 How switches work

- Build a central **Feature Registry** (`app/Domain/Shared/Features/FeatureRegistry.php`) that lists every feature with: key, bilingual name and description, group, default state, dependencies, and whether it can be switched per region.
- Store the states in a `feature_flags` table, and cache them (with the cache cleared on every change). Laravel Pennant may be used underneath, or a simple custom service. Either way, all code checks features through one helper: `feature('ads.self_submission')`, the `@feature('...')` Blade directive, and an `EnsureFeatureEnabled:...` route middleware.
- **When a feature is OFF:**
  - Its routes return 404 (public pages) or a friendly "This feature is currently unavailable" page (dashboards), never a broken page.
  - Its menu items, buttons, homepage blocks, widgets and links are hidden.
  - Its API endpoints return 404.
  - Its scheduled jobs and queued jobs skip without error.
  - Its sitemap entries and structured data are removed.
  - **Existing data is kept untouched.** Switching the feature back ON restores everything.
- **Dependencies:** if a parent feature is OFF, its children are OFF too (for example `advertising` OFF also disables `ads.self_submission`, `ads.reporter_submission`, `reporter_earnings` and `ad_receipts`). The admin screen shows these dependencies and warns before switching.
- **Region-level switches** (optional per feature): a feature can be ON nationally but OFF for one province or district (or the reverse, for pilots). The most specific setting wins: tehsil → district → province → national.
- **Scheduling (optional):** a switch can be set to turn ON or OFF at a given date and time.
- Every change is audit-logged (who, when, old state, new state, reason). Only Super Administrators (or a dedicated `features.manage` permission) can change switches. Changing one requires 2FA re-confirmation.
- Provide an artisan command for emergencies: `php artisan feature:off {key}` / `feature:on {key}`.

## 45.2 Admin screen

**System Settings → Features:** a grouped list of switches with a search box. Each row shows: name (Urdu/English), description, ON/OFF toggle, region overrides, dependency notes, last changed by and when.

## 45.3 Feature list (minimum: add to it as modules are built)

| Group | Feature key | Default at launch |
|---|---|---|
| Languages | `locale.urdu`, `locale.english` | ON, ON (at least one must stay ON) |
| Reporters | `reporter.registration` | ON |
| | `reporter.public_profiles` | ON |
| | `reporter.directory` | ON |
| | `reporter.protected_byline` | ON |
| | `reporter.safety_alerts` | ON |
| | `reporter.phone_otp` | OFF (until SMS provider, D-05) |
| News | `news.submission` | ON |
| | `news.instant_publishing` | OFF |
| | `news.edit_window_60min` | ON |
| | `news.video_embeds` | ON |
| | `news.video_uploads` | OFF |
| | `news.breaking_flag` | ON |
| | `news.machine_translation_drafts` | OFF |
| | `news.public_complaints` | ON |
| Reader engagement | `engagement.reactions` | ON |
| | `engagement.like_dislike` | ON |
| | `engagement.reporter_ratings` | OFF (turn on once traffic exists) |
| | `engagement.read_counts_public` | ON |
| | `engagement.sharing` | ON |
| | `engagement.share_images` | ON |
| Credibility | `credibility.engine` (calculate) | ON |
| | `credibility.public_display` | OFF (data-collection mode first, Part 37) |
| | `rankings.public` | OFF |
| | `rankings.emerging_reporters` | OFF |
| Communication | `tips.public_submission` | ON |
| | `messaging.reader_to_reporter` | OFF |
| Local issues | `local_issues` | OFF |
| | `local_issues.public_reports` | OFF |
| Advertising | `advertising` (master switch) | ON |
| | `ads.self_submission` (Advertise with us form) | ON |
| | `ads.reporter_submission` | ON |
| | `ads.rate_card_public` | OFF |
| | `ads.maker_checker` | ON |
| | `reporter_earnings` | ON |
| | `ad_receipts` | ON |
| Homepage | every homepage block (`home.breaking`, `home.most_read`, `home.trending`, `home.popular_reporters`, `home.videos`, `home.local_issues`, …) | ON (blocks without content hide themselves anyway) |
| SEO | `seo.google_news_sitemap` | ON |
| | `seo.structured_data` | ON |
| Platform | `api.public_v1` | OFF |
| | `maintenance.read_only_mode` (disables all public write actions during an incident) | OFF |
| Future | `press_clubs`, `media_houses`, `hiring`, `polls`, `business_directory`, `mentorship`, `awards` | OFF (extension points only) |

## 45.4 What can NEVER be switched off

These are safety and integrity controls, not features. They have no switch:

- Authentication, authorization and geographic scope checks.
- Audit logging.
- Protection of private documents and personal data, and EXIF stripping.
- Editorial approval for reporters without instant-publishing permission.
- Correction notices for material changes.
- "Sponsored / اشتہار" labels on ads.
- CSRF, rate limiting and bot protection on any write endpoint that is ON.

## 45.5 Testing

- Every feature key has a test showing that with it OFF, its routes return 404 or the unavailable page, its UI is hidden and its jobs skip, and that with it back ON, existing data reappears.
- A test checks that every key used in code (`feature('...')`) exists in the registry, so there are no typos or orphan switches.

---

# FINAL PROJECT OBJECTIVE

Build a professional National-to-Local Digital Journalism Network for Pakistan that:

- Empowers authentic local journalists **and keeps them safe**.
- Gives reporters professional identities.
- Gives readers easy access to reliable national and local information.
- Establishes a transparent editorial verification process.
- Creates fair opportunities for junior reporters.
- Provides sustainable, transparent local advertising revenue.
- Encourages responsible social media sharing.
- Builds strong organic search visibility.
- Maintains editorial independence.
- Supports Urdu and English with excellent typography.
- Scales from selected Punjab pilot regions to the entire country, and beyond.

The platform should become a trusted digital ecosystem connecting journalists, readers, businesses, institutions and communities.

Prioritise authenticity, usability, security, editorial accountability, performance, SEO and long-term maintainability.

**Start with architecture and database design. Then build phase by phase. Do not rush the implementation at the expense of quality.**
