# Content Access Tiers — Mobile App API Guide

This guide covers the content access tier system added to the PCA (Pastor Chris Answers) API: how articles are gated by viewer type, which endpoints changed, the new locked-teasers endpoint, and how the mobile app should integrate.

**Base URL:** `https://pastorchrisonline.org/pcqaapi/api.php`

All requests are unchanged in transport (GET query params, JSON responses, `JSON_NUMERIC_CHECK` so numeric fields arrive as JSON numbers).

---

## 1. Concepts

### Content access levels (`access_level` on every article)

| Value | Meaning |
|---|---|
| `general` | Everyone — including guests (not logged in). All pre-existing articles are `general`. |
| `active` | Full body for registered/logged-in users. **Guests see these in listings as teasers** (metadata only, body withheld). |
| `premium` | Paid premium members only. Hidden from everyone else's listings. |
| `staff` | Staff members only. Hidden from everyone else's listings. |

### User membership (`membership` + `isStaff` on every user)

Two independent fields, determined server-side from the logged-in user's account. Exposed on profile/login responses.

| Field | Values | Meaning |
|---|---|---|
| `membership` | `free` (default) or `paid` | Billing tier. `paid` unlocks `premium` content. |
| `isStaff` | `true` or `false` | Staff flag. Unlocks `staff` content. A user can be **both** paid and staff. |

Resulting access matrix:

| Viewer | Can read | Sees in listings |
|---|---|---|
| **Guest** (no `u`, invalid `u`, or deleted account) | `general` | `general` (full) + `active` (teasers, body stripped) |
| `free` user, not staff | `general`, `active` | `general`, `active` |
| `paid` user, not staff | `general`, `active`, `premium` | same as readable |
| `free` user with `isStaff: true` | `general`, `active`, `staff` (not `premium`) | same as readable |
| `paid` user with `isStaff: true` | `general`, `active`, `premium`, `staff` (everything) | same as readable |

### How the API decides who sees what

The API is **stateless**: the app must send the logged-in user's id as the `u` query parameter on content endpoints.

- `u` **omitted, empty, `0`, or pointing to a non-existent/deleted account** → treated as **guest** (`general` readable; `active` shown as teasers).
- `premium` and `staff` articles are **filtered out server-side** — they never appear in feeds, category lists, or search results for unauthorized viewers, so content cannot leak to old app versions or unauthorized users.
- `active` articles **are listed to guests** (so the feed looks complete), but for guest requests the server blanks their `content` and adds `restricted: true` — full details require login.
- To show `premium`/`staff` articles as teasers, the app fetches them from the **`content/restricted`** endpoint (see §3.4).

---

## 2. New / changed response fields

| Field | Where | Type | Description |
|---|---|---|---|
| `access_level` | Every article payload (`content/posts`, `content/post`, `content/category`, `content/search`, `content/search-v1`, `content/restricted`, QOTD `tod`) | string | One of `general`, `active`, `premium`, `staff`. |
| `banner` | Every article payload (same endpoints as `access_level`) | string \| null | Absolute URL of the article's creative banner image (e.g. `https://pastorchrisonline.org/pcqaapi/upload/article-banners/{slug}.jpg`). **Only `premium`/`staff` articles ever carry a banner** — for `general`/`active` the field is `null` even if a value exists in storage. Included on locked teasers (`content/restricted`, restricted `content/post`) so premium/staff shelves and lock screens can display the creative. |
| `restricted` | Any listed article (`content/posts`, `content/category`, `content/search`, QOTD) shown to a viewer who can't read it; always on `content/post` when locked; `content/restricted` sets it at envelope level | bool | `true` = the viewer may **not** read this article; `content` is empty. Absent on readable articles. |
| `membership` | `user/profile`, `auth/login`, `auth/kc` profile payloads | string | Viewer's billing tier: `free` or `paid`. |
| `isStaff` | Same payloads as `membership` | bool | `true` when the account has the staff flag. Independent of `membership`. |
| `subscription` | `user/profile` only | object \| null | The viewer's latest **active** premium subscription (see §3.5), or `null` when they have none (free users, or paid users whose subscription lapsed). |
| `days_remaining` | `subscription` object and every `user/subscriptions` history row | number | Whole days until `end_at` (min `0`). |
| `content` | Locked articles only | string | Always `""` for restricted items — the body is stripped server-side. |
| `pagination` | `content/restricted` | object | `start`, `offset`, `limit`, `total`, `offset_all` (same shape as search). |

---

## 3. Endpoint reference

All endpoints below accept the optional `u` parameter. **Always send `u` when a user is logged in; omit it (or send `0`) for guests.**

### 3.1 Feed — `GET ?ty=content/posts`

```
api.php?ty=content/posts&offset=1&u={userID}
```

- Readable articles are returned with their full `content`; `premium`/`staff` items the viewer can't read are excluded entirely.
- **Guests additionally receive `active` items** — served inline with the general content — but with `"content": ""` and `"restricted": true`. Treat any listed item with `restricted: true` as a teaser: render the title/cover, and on tap show the "Sign up / log in" prompt (§3.2).
- `access_level` is included on every item.
- The Question-of-the-Day object (`tod`) follows the same rules: guests get it stripped + `restricted: true` when it's `active`; `tod` is `null`/header-only when today's topic is `premium`/`staff` — handle that gracefully.

```json
{
  "tod": null,
  "data": [
    {
      "id": 501,
      "title": "How do I grow in faith?",
      "title_formatted": null,
      "likes": 4,
      "content": "<p>Full answer body…</p>",
      "short": "65f1a2b3c4d5e",
      "type": 0,
      "categoryID": 3,
      "access_level": "general",
      "created_at": "2026-10-01 09:12:44",
      "category_title": "Faith"
    }
  ],
  "success": true
}
```

### 3.2 Single article — `GET ?ty=content/post`

```
api.php?ty=content/post&s={short}&u={userID}
```

Three outcomes:

1. **Accessible** → normal payload, `content` populated, no `restricted` field.
2. **Exists but locked for this viewer** → `success: true`, metadata present, `content: ""`, `restricted: true`. Show a lock/upgrade screen instead of the article body.
3. **Unknown slug** → `data: null`, `success: true`.

```json
{
  "data": {
    "likes": 0,
    "id": 510,
    "title": "Deep prayer protocols",
    "title_formatted": null,
    "content": "",
    "short": "691c4fe097870",
    "type": 0,
    "categoryID": 2,
    "access_level": "premium",
    "created_at": "2026-10-10 14:03:21",
    "category_title": "Prayer",
    "restricted": true
  },
  "success": true
}
```

**Recommended UI by `access_level` when `restricted: true`:**

| `access_level` | Suggested prompt |
|---|---|
| `active` | "Sign up / log in to read this" |
| `premium` | "Unlock Premium" (upgrade CTA — only if viewer's `membership` isn't `paid`; a free staff member also can't read premium) |
| `staff` | "Staff exclusive" (no upgrade CTA) |

### 3.3 Category & search (unchanged semantics, now gated)

```
api.php?ty=content/category&cat={id}&offset=1&u={userID}
api.php?ty=content/search&q={query}&offset=1&u={userID}
api.php?ty=content/search-v1&q={query}&offset=1&u={userID}     (legacy)
```

- Return only accessible articles; each item includes `access_level`.
- `content/search` pagination (`total`, `offset_all`) counts only accessible matches.

### 3.4 NEW: Locked teasers — `GET ?ty=content/restricted`

```
api.php?ty=content/restricted&offset=1&u={userID}
```

Returns the articles this viewer will **never** see in their listings — i.e. everything outside their listed set (title/metadata only — `content` is always `""`), newest first, paginated like the feed. Use it to build a separate "Premium"/"Locked" shelf so users see what exists behind the wall.

```json
{
  "data": [
    {
      "id": 510,
      "title": "Deep prayer protocols",
      "title_formatted": null,
      "content": "",
      "short": "691c4fe097870",
      "type": 0,
      "categoryID": 2,
      "access_level": "premium",
      "created_at": "2026-10-10 14:03:21",
      "category_title": "Prayer"
    }
  ],
  "restricted": true,
  "success": true,
  "pagination": {
    "start": 0,
    "offset": 1,
    "limit": 16,
    "total": 37,
    "offset_all": 3
  }
}
```

Notes:
- A **guest's** restricted list contains `premium` + `staff` articles only — `active` items are excluded because they are already served inline in the guest feed/listings as teasers (§3.1). A `free` non-staff user's list contains `premium` + `staff`; a `paid` non-staff user's list contains only `staff` articles; a `free` staff user's list contains only `premium` articles; a `paid` staff user's list is empty (they can read everything).
- Tapping a teaser should route to `content/post` as usual — if the user's access changed since the list was fetched, the single-article endpoint is authoritative and may now return the full content.

### 3.5 Profile / auth — membership & subscription

`GET ?ty=user/profile&userID={id}` and the login/KingsChat auth responses include:

```json
"membership": "paid",
"isStaff": true
```

`user/profile` additionally includes a `subscription` object — the latest **active** (non-expired) subscription, or `null`:

```json
"subscription": {
  "id": 1,
  "plan": "premium",
  "status": "active",
  "start_at": "2026-10-01 00:00:00",
  "end_at": "2026-11-01 00:00:00",
  "days_remaining": 17,
  "amount": "4.99",
  "currency": "USD",
  "payment_ref": "GPA.1234-5678",
  "source": "playstore"
}
```

Store these with the session so the app can:
- hide/show upgrade CTAs (`membership`),
- show staff-only UI (`isStaff`),
- badge premium features and show renewal/expiry dates (`subscription`),
- re-request profile after a purchase restores/upgrade flow completes.

### 3.6 NEW: Subscription history — `GET ?ty=user/subscriptions`

```
api.php?ty=user/subscriptions&offset=1&u={userID}
```

Returns **all** subscription records for the user (any status: `active`, `expired`, `cancelled`), newest first, each with a computed `days_remaining`. Paginated identically to `content/restricted`. Requires a valid `u` (a real, non-deleted account) — otherwise returns `success: false` with `"Invalid credentials."`.

```json
{
  "data": [
    {
      "id": 2,
      "userID": 1234,
      "plan": "premium",
      "status": "expired",
      "start_at": "2026-01-01 00:00:00",
      "end_at": "2026-02-01 00:00:00",
      "amount": "4.99",
      "currency": "USD",
      "payment_ref": "GPA.0000-1111",
      "source": "playstore",
      "created_at": "2026-01-01 09:15:00",
      "days_remaining": 0
    }
  ],
  "success": true,
  "pagination": {
    "start": 0,
    "offset": 1,
    "limit": 16,
    "total": 2,
    "offset_all": 1
  }
}
```

Use it for a "Billing history" screen in the app.

---

## 4. Recommended app integration

1. **Always attach the user id.** Add `&u={userID}` to every `content/*` request when logged in; omit for guests. Old app versions that don't send `u` behave as guests and never receive restricted content — no server config needed.
2. **Render feeds from the gated endpoints.** Most items are readable as-is; check each item's `restricted` flag — guests will receive `active` items with `content: ""` and `restricted: true`, which should render as teasers with a "Sign in" prompt rather than as articles.
3. **Optional teaser interleaving.** Fetch `content/restricted` and merge its items into the feed UI with a lock overlay (use `access_level` for the lock style / CTA).
4. **Single-article screen:** if `data.restricted == true`, do **not** render `content` (it is empty anyway); show the lock/upgrade view described in §3.2 with a back action. Suggest refresh-on-purchase.
5. **Membership-aware UI:** read `membership` and `isStaff` from the profile; when the user upgrades or is granted staff, refresh the profile (and any cached feeds) so locked items unlock immediately.
6. **QOTD:** guard for `tod: null` (today's question may be locked for this viewer). Optionally offer a "Unlock today's question" card pointing at `content/post`.
7. **Purchase/restore flows:** after a successful premium purchase or restore, re-fetch `user/profile` for the updated `membership`.

### Worked example — home feed with locked teasers

```
GET ?ty=content/posts&offset=1&u=1234          → readable items (each has access_level)
GET ?ty=content/restricted&offset=1&u=1234     → locked items (restricted: true, content: "")
merge → render rows; locked rows show overlay; tap → content/post&s={short}&u=1234
```

---

## 5. Caveats

- **Audio files are not tier-gated.** Audio is served as static files (`upload/audio/{short}.mp3`) outside the API; a restricted article's audio URL is guessable from its `short` slug. Do not surface audio controls on locked teasers.
- **`content/search-v1`** is legacy; prefer `content/search`. Both are gated identically.
- **Deleted accounts** (`status = 'deleted'`) are treated as guests even if an old token carries their id.
- Staff and paid are orthogonal: `isStaff` unlocks staff content only; `paid` unlocks premium content only; a `paid` staff user gets everything.
- **Subscription records are inserted externally** (see §7) — this API only reads them.

---

## 6. Quick verification checklist

- [ ] Guest (`u` omitted) feed shows `general` articles with full `content` **plus** `active` articles with `"content": ""` and `restricted: true` — never `premium`/`staff`.
- [ ] Logged-in free user receives `active` articles with full `content` and no `restricted` flag.
- [ ] Paid user additionally sees `premium` articles but **not** `staff` articles (unless also staff).
- [ ] Staff user (free) additionally sees `staff` articles but **not** `premium` articles.
- [ ] Paid staff user (`membership: "paid"`, `isStaff: true`) sees everything.
- [ ] `content/post` on a locked slug returns `restricted: true` with empty `content`.
- [ ] `content/restricted` returns exactly the articles missing from the viewer's listings (guest: `premium` + `staff` only), with `pagination.total` matching.
- [ ] `premium`/`staff` articles carry a `banner` image URL (when one was uploaded in the backend); `general`/`active` articles always have `banner: null`.
- [ ] Profile shows the correct `membership` (`free`/`paid`) and `isStaff` (`true`/`false`).
- [ ] Paid user with an active subscription sees a `subscription` object on `user/profile` with `days_remaining` > 0; free users and lapsed subscribers get `subscription: null`.
- [ ] `user/subscriptions` returns the user's full history newest-first with `pagination.total` matching; invalid `u` returns an error.
- [ ] Old app build (no `u`) still works: `general` full + `active` teasers, no premium/staff leaks.

---

## 7. Subscriptions (backend contract)

### Table — `qa_subscriptions`

One row per purchased/activated premium period. Created via `php migrations/create-qa-subscriptions.php` (or `migrations/run.php`).

| Column | Type | Notes |
|---|---|---|
| `id` | int, PK | auto-increment |
| `userID` | int | FK to `qa_users.id` (indexed) |
| `plan` | varchar(20) | `'premium'` (single plan for now) |
| `status` | varchar(20) | `active` \| `expired` \| `cancelled` — new rows should be `active` |
| `start_at` | datetime | period start |
| `end_at` | datetime | period end — access is valid while `status='active' AND end_at > NOW()` |
| `amount` | decimal(10,2) | nullable |
| `currency` | varchar(10) | nullable (e.g. `USD`) |
| `payment_ref` | varchar(100) | external receipt/transaction id |
| `source` | varchar(30) | e.g. `manual`, `appstore`, `playstore`, `stripe` |
| `created_at` | timestamp | defaults to now |

**Who inserts rows:** an external purchase-verification system (or manual SQL). To grant a user premium access, insert an `active` row **and** set `qa_users.membership = 'paid'`.

### Expiry cron — `subscription-expiry.php` (root)

Run daily via crontab on the server, e.g.:

```
15 2 * * * php /path/to/pcqaapi/subscription-expiry.php >> /var/log/sub-expiry.log 2>&1
```

Each run:
1. Marks lapsed subscriptions expired: `status='active' AND end_at <= NOW()` → `expired`.
2. Downgrades users who **have** subscription rows but no longer have an active one: `membership='paid'` → `free`. Paid users with **no** subscription rows (manual grants) are left untouched.

The script is idempotent — re-running it is a no-op. `user/profile` already treats a lapsed subscription as absent (it only returns rows with `end_at > NOW()`), so access disappears at expiry time even before the cron downgrades the flag; the cron simply cleans up the stored state.
