# Free Preview & Free Sample — Frontend Guide

Everything the web/mobile/dashboard clients need to build, display and play **free-preview lessons** on recorded courses, plus the recent change that keeps the course-level **`has_free_sample`** flag in sync with them.

- **Audience:** frontend developers (learner app, trainer dashboard, admin dashboard)
- **Applies to:** recorded courses (`course_type = "recorded"`) — video lessons only, never quizzes
- **Base path:** `{{base_url}}` = `/api/v1`
- **Related docs:** [course-lesson-free-preview-update.md](./course-lesson-free-preview-update.md) (original feature notes), [courses-user.md](./courses-user.md), [courses-trainer.md](./courses-trainer.md), [courses-admin.md](./courses-admin.md)

Common headers on every call: `Accept: application/json`, `Content-Type: application/json`, `Accept-Language: en|ar`. Responses use the standard envelope `{ "status", "message", "data" }`.

---

## 1. Concepts

There are two related flags. They live at different levels and have different owners.

| Flag | Level | Set by | Meaning |
|---|---|---|---|
| `is_free_preview` (+ `free_preview_from_seconds`, `free_preview_to_seconds`) | **Lesson** (`type = "lesson"` only) | Trainer | This video has a range that anyone may watch without enrolling |
| `has_free_sample` | **Course** | **Derived by the backend** from lessons (see §2) | The course currently contains at least one free-preview lesson |

Related but separate: `demo_video` on the course is a single trailer clip and is unrelated to lesson previews.

### How a free preview is delivered

The backend does **not** cut or transcode video. For a free-preview lesson it returns the **full video URL plus the allowed range**. The player must enforce the range for anyone who is not enrolled: start at `free_preview_from_seconds`, stop at `free_preview_to_seconds`. See §5.

---

## 2. What changed in this update

**Before:** `has_free_sample` was only ever written by an admin (course create/update form). Nothing updated it when a trainer flagged or unflagged a lesson, so it drifted. The course card badge, the browse filter `?filters[has_free_sample]=1` and the course-show payload could disagree with the lessons that were actually free.

**Now:** the backend recomputes `has_free_sample` automatically whenever a video lesson changes in a way that affects it:

| Event | Result |
|---|---|
| Trainer creates a lesson with `is_free_preview: true` | `has_free_sample` becomes `true` |
| Trainer updates a lesson, switching `is_free_preview` `false → true` | `true` |
| Trainer updates a lesson, switching `is_free_preview` `true → false` and it was the **last** free lesson | `false` |
| Trainer deletes a free-preview lesson and it was the **last** one | `false` |
| A free lesson is deleted but **another free lesson remains** | stays `true` |
| A soft-deleted free lesson is restored | `true` |
| A lesson that is **not** free is created/edited/deleted | no change to the flag |

Quizzes never count — only `type = "lesson"` rows.

### What this means for the frontend

1. **Treat `has_free_sample` as read-only, derived data everywhere.** Use it to render a "Free preview" badge and to drive the browse filter. To know *which* lessons are free, read `lessons[]` (§4.1).
2. **Admin dashboard:** the course form still accepts `has_free_sample`, but a manual value will be **overwritten** the next time a trainer flags/unflags/deletes a free-preview lesson on that course. Recommended: show it as a read-only badge/toggle-disabled field, or drop it from the edit form.
3. **No new fields, endpoints or response shapes** were added by this update. Existing clients keep working; only the *correctness* of `has_free_sample` changed.
4. **No backfill.** Courses that already had `has_free_sample = true` with no free-preview lessons (e.g. seeded/demo data) stay `true` until one of the events above touches them. Do not rely on the flag alone to decide whether a "Watch preview" button can render — check that a lesson with a range exists (§4.1).

---

## 3. Endpoint map

| Audience | Method & path | Purpose |
|---|---|---|
| Trainer | `POST /trainer/courses/{course}/lessons/video` | Create a video lesson (optionally free preview) |
| Trainer | `PUT /trainer/lessons/video/{lesson}` | Update a video lesson, incl. toggling free preview |
| Trainer | `DELETE /trainer/lessons/{lesson}` | Delete a lesson (soft delete) |
| Trainer | `GET /trainer/courses/{course}/lessons` | List curriculum with all free-preview fields (needs `view_courses`) |
| Public / Learner | `GET /user/courses` | Browse; supports `filters[has_free_sample]=1` |
| Public / Learner | `GET /user/courses/{course}` | Course detail incl. free-preview lessons |
| Learner (enrolled) | `GET /user/courses/{course}/curriculum` | Full, progression-gated curriculum |
| Admin | `GET /admin/courses/{course}`, `GET /admin/courses/{course}/lessons`, `GET /admin/lessons/{lesson}` | Read-only view of flags |

`{course}` and `{lesson}` are **UUIDs**, never numeric ids.

---

## 4. Learner-facing API

### 4.1 Course detail — `GET /user/courses/{course}`

Public: works for guests and logged-in users. Returns **403** (`This course is not available.`) if the course is not visible and approved; **404** for an unknown UUID.

The `lessons[]` array is the source of truth for free previews.

```json
{
  "status": "success",
  "message": "Course retrieved successfully",
  "data": {
    "id": "9d3f…-course-uuid",
    "slug": "intro-to-accounting",
    "name": "Intro to Accounting",
    "course_type": "recorded",
    "has_certificate": true,
    "has_free_sample": true,
    "image": "https://…/course.jpg",
    "demo_video": "https://…/trailer.mp4",
    "price": 150.0,
    "lessons": [
      {
        "id": "a1…-lesson-uuid",
        "type": "lesson",
        "title": "Welcome",
        "sort_order": 0,
        "materials": [],
        "video": "https://…/welcome.mp4",
        "free_preview_from_seconds": 0,
        "free_preview_to_seconds": 45
      },
      {
        "id": "b2…-lesson-uuid",
        "type": "lesson",
        "title": "Balance sheets",
        "sort_order": 1,
        "materials": [
          { "id": "…", "title": "Handout", "material_type": "pdf", "file": "https://…/handout.pdf" }
        ]
      },
      {
        "id": "c3…-quiz-uuid",
        "type": "quiz",
        "title": "Chapter quiz",
        "sort_order": 2,
        "materials": []
      }
    ],
    "lessons_count": 2,
    "total_duration_seconds": 1860
  }
}
```

**Per-item rules**

| Item | Keys present |
|---|---|
| Free-preview video lesson | `id, type, title, sort_order, materials` **+ `video`, `free_preview_from_seconds`, `free_preview_to_seconds`** |
| Locked video lesson | `id, type, title, sort_order, materials` only — **no `video` key at all** |
| Quiz | `id, type, title, sort_order, materials` only |

- **Detect a free lesson with key presence** (`lesson.video !== undefined` / `'free_preview_from_seconds' in lesson`), not with a boolean — there is no `is_free_preview` field on this public payload.
- `video` is a full URL string. It can be `null` if the trainer flagged a lesson as free but has not uploaded the video yet — hide the play button in that case.
- `materials[]` is returned for **every** lesson (free or locked). This is intentional and unchanged.
- The payload has **no enrollment flag for the course itself.** To know whether the current user is enrolled, use `GET /user/my-courses` or treat a 403 from `.../curriculum` as "not enrolled".
- `has_free_sample`, `lessons_count` and `total_duration_seconds` are top-level and always consistent with `lessons[]` after this update.

Helper to extract previews:

```ts
type Lesson = {
  id: string; type: 'lesson' | 'quiz'; title: string; sort_order: number;
  video?: string | null;
  free_preview_from_seconds?: number;
  free_preview_to_seconds?: number;
};

export const freePreviews = (lessons: Lesson[]) =>
  lessons.filter(l => l.type === 'lesson' && l.video && l.free_preview_to_seconds != null);
```

### 4.2 Browse — `GET /user/courses?filters[has_free_sample]=1`

Returns only courses whose `has_free_sample` is `true`. Each card carries `has_free_sample` (boolean) and **does not** include `lessons[]`. Because the flag is now derived, the "Free preview" filter and badge accurately reflect real content for any course a trainer has edited since this update.

### 4.3 Enrolled curriculum — `GET /user/courses/{course}/curriculum`

Requires auth + active/completed enrollment (**403** otherwise: `You are not enrolled in this course.`). This endpoint is **unchanged** and does **not** use `is_free_preview`:

```json
{ "id": "…", "type": "lesson", "title": "Balance sheets",
  "is_unlocked": true, "is_completed": false,
  "duration_seconds": 620, "completion_threshold": 90,
  "video": "https://…/balance.mp4",
  "progress": { "watched_percent": 0, "watched": false, "last_position_seconds": null } }
```

- `video` is `null` while `is_unlocked` is `false` (sequential unlock rules apply).
- Once enrolled, play the **full** video from this endpoint. Never apply the free-preview range to an enrolled learner.

---

## 5. Player integration

Use the free-preview range **only** when the viewer is not enrolled.

```ts
function previewConfig(lesson: Lesson) {
  const from = lesson.free_preview_from_seconds ?? 0;
  const to   = lesson.free_preview_to_seconds!;
  return { src: lesson.video!, from, to };
}

function attachPreview(video: HTMLVideoElement, { src, from, to }: ReturnType<typeof previewConfig>, onEnd: () => void) {
  video.src = src;
  video.addEventListener('loadedmetadata', () => { video.currentTime = from; }, { once: true });

  video.addEventListener('timeupdate', () => {
    if (video.currentTime >= to) { video.pause(); onEnd(); }   // show the "Enroll to continue" CTA
  });
  video.addEventListener('seeking', () => {
    if (video.currentTime < from) video.currentTime = from;    // no rewinding before the range
    if (video.currentTime > to)   video.currentTime = to;      // no skipping past the range
  });
}
```

UX recommendations:

- Custom progress bar scoped to `[from, to]` (show `to − from` as the duration, not the full video length).
- Hide download / picture-in-picture / playback-speed above normal if you want to discourage bypassing; the URL itself is the full video, so this is a soft guard, not DRM.
- When the range ends: pause, show an enrol CTA (`POST /user/courses/{course}/enroll`).
- Lock icon on non-free lessons; free lessons get a "Free preview" chip with the range length (`to − from` seconds).
- Show the "Free preview" course badge from `has_free_sample`, but render the *Watch preview* button only if `freePreviews(lessons).length > 0`.

---

## 6. Trainer dashboard API

Requires trainer auth, ownership of the course, the **Manage Lessons** capability, and the course to be in an editable state (`draft` / `needs_revision`) — otherwise **422** `This course cannot be edited while it is :status.`

### 6.1 Create — `POST /trainer/courses/{course}/lessons/video`

```json
{
  "en": { "title": "Welcome" },
  "ar": { "title": "مرحبا" },
  "video": "<media-hash>",
  "duration_seconds": 300,
  "completion_threshold": 90,
  "is_free_preview": true,
  "free_preview_from_seconds": 0,
  "free_preview_to_seconds": 45
}
```

Returns **201** with the lesson (`LessonResource`):

```json
{ "id": "…", "type": "lesson", "title": "Welcome", "sort_order": 0,
  "duration_seconds": 300, "completion_threshold": 90, "video": "https://…",
  "is_free_preview": true, "free_preview_from_seconds": 0, "free_preview_to_seconds": 45 }
```

### 6.2 Update — `PUT /trainer/lessons/video/{lesson}`

Send only what changes. To remove the preview:

```json
{ "is_free_preview": false }
```

The `free_preview_*` values are kept in the database but are ignored while the flag is `false`; the trainer form can prefill them if the user toggles it back on.

### 6.3 Delete — `DELETE /trainer/lessons/{lesson}`

Soft delete. Returns `{ "status": "success", "message": "Lesson deleted successfully", "data": [] }`. Deleting the last free lesson clears the course's `has_free_sample`.

### 6.4 Validation (422 with per-field errors)

| Field | Rule |
|---|---|
| `is_free_preview` | optional boolean |
| `free_preview_from_seconds` | **required when** `is_free_preview` is `true`; integer ≥ 0 |
| `free_preview_to_seconds` | **required when** `is_free_preview` is `true`; integer, **strictly greater than** `free_preview_from_seconds` |

Other rules:

- Quiz endpoint (`.../lessons/quiz`) **rejects** all three fields (`prohibited`) — never send them for quizzes. Hide the toggle in the quiz form.
- A lesson's type is fixed. Updating a quiz through the video endpoint (or vice-versa) returns 422.
- Recommended client checks: `to > from`, and `to <= duration_seconds` when the duration is known (the API does not enforce the upper bound).

### 6.5 Trainer form behaviour

- Toggle **"Offer a free preview"** → reveals two time inputs (from / to). Accept `mm:ss`, send seconds.
- When the toggle is turned off, send `is_free_preview: false` and omit or keep the times.
- Read values back from `is_free_preview`, `free_preview_from_seconds`, `free_preview_to_seconds` (always present on video items in trainer/admin responses).
- After saving, **refetch the course** if the UI displays `has_free_sample` — the backend changed it as a side effect.

---

## 7. Admin dashboard

- Lesson endpoints are **read-only** for admins; free-preview fields (`is_free_preview`, `free_preview_from_seconds`, `free_preview_to_seconds`) appear on video items.
- Course details (`GET /admin/courses/{course}`) return `has_free_sample`. See §2.2 for how to handle the form field.

---

## 8. Edge cases

| Situation | Behaviour |
|---|---|
| Free lesson with no uploaded video | `video: null` in public payload — hide the play control |
| Course has `has_free_sample: true` but `lessons[]` has no free lesson | Legacy/seeded data (no backfill). Hide "Watch preview" |
| Two free lessons, one deleted | Flag stays `true` |
| Quiz created/deleted | No effect on the flag |
| Course in `live` type | Free previews apply to recorded lessons only; live courses expose `sessions[]` instead |
| Guest vs. logged-in, not enrolled | Identical payload; range enforced client-side for both |
| Enrolled learner | Use `curriculum` `video`; ignore the preview range |
| Caching | Course detail is per-request; refetch after a trainer edit rather than patching local state |

---

## 9. Error reference

| HTTP | When |
|---|---|
| 401 | Missing/expired token on trainer/admin/enrolled endpoints |
| 403 | Course not browsable (detail, `This course is not available.`); not enrolled (curriculum); trainer does not own the course or lacks the capability |
| 404 | Unknown course/lesson UUID |
| 422 | Validation failure (§6.4); course not editable (`This course cannot be edited while it is …`); wrong-type endpoint |

Validation error shape follows the standard envelope with `errors` keyed by field name (e.g. `free_preview_to_seconds`).

---

## 10. QA checklist

**Learner**
- [ ] Course with one free lesson: badge visible, *Watch preview* plays only `[from, to]`, cannot seek outside it.
- [ ] Locked lessons show no player and no `video` URL in the network response.
- [ ] Preview end shows the enrol CTA; enrolling switches playback to the curriculum video with no range limit.
- [ ] `?filters[has_free_sample]=1` lists only courses that really have a free lesson (after trainer edits).
- [ ] Free lesson without a video renders without a broken player.

**Trainer**
- [ ] Toggle on → from/to required; `to <= from` shows the 422 message on the right field.
- [ ] Toggle off → learner page stops offering the preview; course `has_free_sample` becomes `false` if it was the only one.
- [ ] Deleting the only free lesson clears the badge; deleting one of two keeps it.
- [ ] Quiz form never sends the free-preview fields.

**Admin**
- [ ] `has_free_sample` shown read-only (or understood to be overwritten).

---

## 11. Backend reference

| Concern | Location |
|---|---|
| Sync logic (model hooks) | `app/Models/CourseLesson.php` — `booted()`, `syncCourseFreeSample()` |
| Public payload | `app/Http/Resources/User/Course/CourseCardResource.php` |
| Trainer/admin payload | `app/Http/Resources/{Trainer,Admin}/Course/LessonResource.php` |
| Validation | `app/Http/Requests/Trainer/Course/VideoLessonRequest.php`, `QuizLessonRequest.php` |
| Create/update flow | `app/Http/Controllers/Api/V1/Trainer/AbstractLessonController.php` |
| Tests | `tests/Feature/Education/LessonFreePreviewTest.php` |
