# OTT Platform — REST API Documentation

**Base URL:** `https://ott.prashanth.qzz.io/api/v1`
**Auth:** API Key (header) **+** Laravel Sanctum (Bearer token)
**Content-Type:** `application/json` (or `multipart/form-data` for file uploads)

---

## 0. API Key (Required for all API access)

Every request to the API must include a valid **API key**, except requests that already carry a Sanctum Bearer token (logged-in users bypass the key check). This keeps the API closed to the public — only apps you issue a key to can call it.

### How to send the key
Send it in the `X-API-KEY` header (or the `Authorization` header):

```
X-API-KEY: UzH315UMs3e2R0VWDRYKpUup9sQnlIjJ4DuPilj5
```

### Manage keys in the admin panel
1. Log in to `https://ott.prashanth.qzz.io/admin`.
2. Go to **System → API Keys**.
3. Click **New API Key**, give it a name (e.g. "Flutter App"), and save.
4. The full key is shown **once** in a notification — copy it immediately. It is stored hashed and cannot be retrieved again.
5. Toggle **Active** off to revoke a key at any time.

### Errors
| Scenario | Response |
|----------|----------|
| No key / empty header | `401` → `Missing API key. Provide it via the X-API-KEY header.` |
| Invalid or inactive key | `401` → `Invalid or inactive API key.` |

### Example
```bash
curl https://ott.prashanth.qzz.io/api/v1/movies \
  -H "X-API-KEY: UzH315UMs3e2R0VWDRYKpUup9sQnlIjJ4DuPilj5"
```

---

## 1. Response Envelope

Every response follows a consistent JSON shape.

### Success (single / collection)
```json
{
  "success": true,
  "message": "Success",
  "data": { }
}
```

### Success (paginated)
```json
{
  "success": true,
  "message": "Success",
  "data": [ { }, { } ],
  "meta": {
    "current_page": 1,
    "per_page": 15,
    "total": 42,
    "last_page": 3,
    "from": 1,
    "to": 15
  },
  "links": {
    "first": "https://.../api/v1/movies?page=1",
    "last": "https://.../api/v1/movies?page=3",
    "prev": null,
    "next": "https://.../api/v1/movies?page=2"
  }
}
```

### Error
```json
{
  "success": false,
  "message": "Invalid credentials or account is not active.",
  "errors": null
}
```

### HTTP Status Codes
| Code | Meaning |
|------|---------|
| 200 | OK |
| 201 | Created (register, submit payment) |
| 401 | Unauthenticated (missing/invalid token) |
| 403 | Forbidden (e.g. rental required to play or read) |
| 404 | Not found |
| 422 | Validation error (field errors returned in `errors`) |
| 500 | Server error |

---

## 2. Authentication

All authenticated routes require the header:
```
Authorization: Bearer <token>
```

### POST `/auth/register`
**Public.** Create account, returns user + token.

| Field | Type | Rules |
|-------|------|-------|
| name | string | required, max 255 |
| mobile | string | nullable, max 20 |
| email | string | required, email, unique |
| password | string | required, min 8, confirmed (`password_confirmation`) |
| profile_image | file | nullable, image, max 5 MB |

```bash
curl -X POST https://ott.prashanth.qzz.io/api/v1/auth/register \
  -H "Content-Type: application/json" \
  -d '{"name":"John","email":"john@example.com","password":"secret123","password_confirmation":"secret123"}'
```

**Response 201**
```json
{
  "success": true,
  "message": "Registration successful.",
  "data": {
    "user": { "id": 3, "name": "John", "email": "john@example.com", "mobile": null, "profile_image": null, "status": "active", "roles": ["user"], "created_at": "2026-07-17T..." },
    "token": "1|abc...xyz",
    "token_type": "Bearer"
  }
}
```

### POST `/auth/login`
**Public.**
```bash
curl -X POST https://ott.prashanth.qzz.io/api/v1/auth/login \
  -H "Content-Type: application/json" \
  -d '{"email":"john@example.com","password":"secret123"}'
```
**Response 200** → `{ user, token, token_type }` (same shape as register).
**Response 401** → `Invalid credentials or account is not active.`

### POST `/auth/logout`
**Auth.** Revokes current token. **Response 200** → `Logged out successfully.`

### GET `/auth/profile`
**Auth.** Returns the `UserResource` of the current user.

### PUT `/auth/profile`
**Auth.** Update profile.

| Field | Type | Rules |
|-------|------|-------|
| name | string | sometimes required, max 255 |
| mobile | string | nullable, max 20 |
| email | string | sometimes required, email, unique (ignores self) |
| profile_image | file | nullable, image, max 5 MB |

### POST `/auth/change-password`
**Auth.**

| Field | Type | Rules |
|-------|------|-------|
| current_password | string | required |
| password | string | required, min 8, confirmed |

**Response 422** if current password wrong → `Current password is incorrect.`

### POST `/auth/forgot-password`
**Public.** Sends a 6-digit OTP to the user's email. OTP expires in 10 minutes.
Body: `{ "email": "john@example.com" }`.
**Response 202** → `{ success: true, message: "Password reset OTP sent to your email.", data: { email, otp_expires_in_minutes: 10 } }`

### POST `/auth/reset-password`
**Public.** Validates the OTP and resets the password.
Body: `{ "email": "john@example.com", "token": "123456", "password": "newSecret123", "password_confirmation": "newSecret123" }`.
**Response 200** → `Password reset successfully.`

---

## 3. Policies (Public)

Legal and content policies managed by the admin. The mobile app can fetch all active public policies or a single policy by slug.

### GET `/policies`
**Public.** Returns all active public policies, ordered by `type` then `title`.

**PolicyResource**
```json
{
  "id": 1,
  "title": "Terms of Service",
  "slug": "terms-of-service",
  "type": "terms",
  "content": "<p>Full HTML or plain text content here...</p>",
  "is_public": true,
  "created_at": "2026-07-26T...",
  "updated_at": "2026-07-27T..."
}
```

**Response** → `PolicyResource[]` (non-paginated array).

### GET `/policies/{slug}`
**Public.** Returns a single active public policy by slug. **Response 404** if not found or not public.

Example: `GET /policies/privacy-policy`

---

## 4. Movies & Catalog (Public browsing)

### GET `/movies`
List/paginate movies with filters (query params):

| Param | Type | Notes |
|-------|------|-------|
| search | string | matches title/description |
| category_id | int | exists:categories |
| access_type | `free`\|`rental` | |
| genre | string | |
| language | string | |
| featured | bool | |
| trending | bool | |
| sort_by | `title`\|`created_at`\|`release_date`\|`duration` | |
| sort_dir | `asc`\|`desc` | |
| per_page | int | 1–100, default 15 |

**Response** → paginated `MovieResource[]`.

### GET `/movies/free`
Paginated free movies.

### GET `/movies/rental`
Paginated rental movies.

### GET `/movies/featured`
Paginated featured movies.

### GET `/movies/trending`
Paginated trending movies.

### GET `/movies/categories`
All categories. **Response** → `CategoryResource[]` (no pagination).

### GET `/movies/{id}`
Single movie. **Response 404** if not found.

**MovieResource shape**
```json
{
  "id": 1,
  "title": "Demo Movie",
  "slug": "demo-movie",
  "description": "…",
  "thumbnail": "https://…/storage/movies/thumb.jpg",
  "banner": "https://…/storage/movies/banner.jpg",
  "trailer_url": "https://…",
  "video_url": "https://…",
  "genre": "Action",
  "language": "English",
  "duration": 120,
  "release_date": "2024-01-01",
  "featured": false,
  "trending": false,
  "access_type": "free",          // "free" | "rental"
  "rental_price": "49.00",
  "rental_duration": 48,          // hours
  "status": "active",
  "category": { "id": 1, "name": "Action", "slug": "action", "image": "…", "status": "active" },
  "created_at": "2026-07-17T…"
}
```

> **Note:** The `slug` field is now auto-generated from `title` in the admin panel and can be manually edited. It is unique and used for SEO-friendly URLs.

---

## 5. E-Books & Catalog (Public browsing)

E-books use the same **free / rental** access model as movies. Reading is powered by PDF files uploaded from the admin panel. Use `POST /ebooks/{id}/read` to retrieve authorized PDF access.

### GET `/ebooks`
List/paginate e-books with filters (query params):

| Param | Type | Notes |
|-------|------|-------|
| search | string | matches title / author / genre / language / description |
| category_id | int | exists:categories |
| access_type | `free`\|`rental` | |
| genre | string | |
| language | string | |
| featured | bool | |
| trending | bool | |
| sort_by | `title`\|`created_at`\|`published_date`\|`pages` | |
| sort_dir | `asc`\|`desc` | |
| per_page | int | 1–100, default 15 |

**Response** → paginated `EbookResource[]`.

### GET `/ebooks/free`
Paginated free e-books.

### GET `/ebooks/rental`
Paginated rental e-books.

### GET `/ebooks/featured`
Paginated featured e-books.

### GET `/ebooks/trending`
Paginated trending e-books.

### GET `/ebooks/{id}`
Single e-book metadata. **Response 404** if not found.

**EbookResource shape**
```json
{
  "id": 1,
  "title": "The Sample Book",
  "slug": "the-sample-book",
  "description": "…",
  "thumbnail": "https://…/cors-storage/ebooks/thumbnails/….jpg",
  "file_url": "https://…/cors-storage/ebooks/pdfs/….pdf",
  "pdf_url": "https://…/cors-storage/ebooks/pdfs/….pdf",
  "author": "Jane Doe",
  "genre": "Fiction",
  "language": "English",
  "pages": 240,
  "published_date": "2024-06-01",
  "featured": false,
  "trending": false,
  "access_type": "free",
  "rental_price": "29.00",
  "rental_duration": 48,
  "status": "active",
  "category": { "id": 1, "name": "Fiction", "slug": "fiction", "image": "…", "status": "active" },
  "created_at": "2026-08-14T…"
}
```

> **Note:** Thumbnails and PDF files are served via `cors-storage/` with proper CORS and MIME headers for mobile PDF readers.

---

## 6. Playback & Reading (Auth)

### POST `/movies/{id}/play`
**Auth.** Authorize movie playback.

- **Free movie + logged in** → 200, returns stream URL + signed link.
- **Rental movie without active rental** → 403 → `You need to rent this movie before watching.`
- **Guest** → 401.

**Response 200**
```json
{
  "success": true,
  "message": "Playback authorized.",
  "data": {
    "movie_id": 1,
    "stream_url": "https://ott.prashanth.qzz.io/stream/movie/1?signature=…&expires=…",
    "expires_at": "2026-07-17T…"
  }
}
```

### POST `/ebooks/{id}/read`
**Auth.** Authorize reading and return the e-book PDF URL.

- **Free e-book + logged in** → 200, returns `pdf_url` / `file_url`.
- **Rental e-book without active rental** → 403 → `You need to rent this e-book before reading.`
- **Expired rental** → 403 → `Your rental for this e-book has expired.`
- **Inactive / missing** → 403 / 404.
- **Guest** → 401.

**Response 200**
```json
{
  "success": true,
  "message": "Reading authorized.",
  "data": {
    "ebook_id": 1,
    "title": "The Sample Book",
    "author": "Jane Doe",
    "access_type": "free",
    "pdf_url": "https://ott.prashanth.qzz.io/cors-storage/ebooks/pdfs/sample.pdf",
    "file_url": "https://ott.prashanth.qzz.io/cors-storage/ebooks/pdfs/sample.pdf",
    "rental": null
  }
}
```

For a rental e-book with a valid rental, `rental` is:
```json
{
  "start_time": "2026-08-14T10:00:00.000000Z",
  "end_time": "2026-08-16T10:00:00.000000Z"
}
```

---

## 7. Payments (Auth)

The active payment gateway is controlled by the admin. Only **one** gateway can be active at a time:
- **QR Code** (manual UPI payment) — requires admin approval after screenshot/UTR submission
- **PhonePe** — auto-approved, no admin approval needed

### GET `/qr/active`
**Auth.** Returns the single active QR payment config. **Response 404** if QR is not active.

**QrPaymentResource**
```json
{ "id": 1, "merchant_name": "OTT", "upi_id": "ott@upi", "qr_image": "https://…/storage/qr/…png", "is_active": true }
```

### GET `/phonepe/active`
**Auth.** Returns the single active PhonePe payment config. **Response 404** if PhonePe is not active.

### POST `/payment/submit`
**Auth.** Submit a payment using the active gateway.

| Field | Type | Rules |
|-------|------|-------|
| movie_id | int | required without `ebook_id`, exists:movies, cannot be sent with `ebook_id` |
| ebook_id | int | required without `movie_id`, exists:ebooks, cannot be sent with `movie_id` |
| amount | numeric | required, min 0 |
| qr_payment_id | int | required when QR is active |
| utr_number | string | required when QR is active, max 100 |
| screenshot | file | required when QR is active, image, max 10 MB |

Send **either** `movie_id` **or** `ebook_id`, never both. Approval creates a rental for that movie or e-book using its `rental_duration` (hours, default 48).

**Behavior:**
- **QR active:** Creates a `pending` payment. Admin must approve to create rental.
- **PhonePe active:** Creates an `approved` payment and automatically creates the rental. No admin approval needed.

**Response 201** → `PaymentResource`.

### GET `/payment/history`
**Auth.** Paginated payments of the current user.

### GET `/payment/status/{id}`
**Auth.** Single payment by id (must belong to user). **Response 404** if not found.

**PaymentResource**
```json
{
  "id": 5,
  "user": { "id": 3, "name": "John", "email": "john@example.com" },
  "movie": { "id": 1, "title": "Demo Movie" },
  "ebook": null,
  "qr_payment": { "id": 1, "upi_id": "ott@upi" },
  "phonepe_payment": { "id": 1, "merchant_id": "MERCHANT123" },
  "gateway_type": "qr",
  "phonepe_transaction_id": null,
  "amount": "49.00",
  "utr_number": "UTR123",
  "screenshot": "https://…/storage/payments/…png",
  "status": "pending",     // pending | approved | rejected
  "remarks": null,
  "approved_by": null,
  "approved_at": null,
  "created_at": "2026-07-17T…"
}
```

For an e-book payment, `movie` is `null` and `ebook` is the `EbookResource`. The same applies to rentals.

---

## 8. Rentals (Auth)

### GET `/rentals/my`
**Auth.** Paginated rental history of the current user.

### GET `/rentals/active`
**Auth.** List of currently active rentals (non-paginated).

**RentalResource**
```json
{
  "id": 2,
  "user": { "id": 3, "name": "John" },
  "movie": { "id": 1, "title": "Demo Movie" },
  "ebook": null,
  "payment": { "id": 5, "status": "approved" },
  "status": "active",       // active | expired
  "start_time": "2026-07-17T…",
  "end_time": "2026-07-19T…",
  "created_at": "2026-07-17T…"
}
```

For an e-book rental, `movie` is `null` and `ebook` is the `EbookResource`. (Flutter / Android / iOS)

1. **Register / Login** → store the returned `token`.
2. Attach `Authorization: Bearer <token>` to all authenticated calls.
3. **Browse movies** `/movies`, `/movies/free`, `/movies/categories` (no auth needed).
4. **Browse e-books** `/ebooks`, `/ebooks/free`, `/ebooks/rental` (no auth needed). Catalog payloads do **not** include book text.
5. **Fetch policies** `/policies` (no auth needed) to display Terms, Privacy, etc.
6. To watch a **free** movie: `POST /movies/{id}/play` → open `stream_url` in a video player.
7. To read a **free** e-book: `POST /ebooks/{id}/read` → render `data.content` in a reader.
8. To watch a **rental** movie or read a **rental** e-book:
   - `GET /qr/active` or `GET /phonepe/active` → determine active gateway.
   - **QR flow:** `POST /payment/submit` with `movie_id` **or** `ebook_id` (plus UTR + screenshot), then poll `GET /payment/status/{id}` until `status == approved`.
   - **PhonePe flow:** `POST /payment/submit` with `movie_id` **or** `ebook_id` → instantly approved, rental created.
   - `GET /rentals/active` confirms the active rental.
   - Movie: `POST /movies/{id}/play` → stream.
   - E-book: `POST /ebooks/{id}/read` → content.

---

## 10. Rate Limiting
Authenticated + guest requests are throttled to **60 requests/minute** per user (or per IP for guests). Exceeding returns `429 Too Many Requests`.

---

## 11. Watchlist (Auth)

### GET `/watchlist`
**Auth.** Paginated list of movies the user saved. **Response** → paginated `WatchlistResource[]`.

**WatchlistResource**
```json
{ "id": 1, "movie": { ...MovieResource }, "created_at": "2026-07-19T…" }
```

### POST `/watchlist`
**Auth.** Add a movie to the watchlist.

| Field | Type | Rules |
|-------|------|-------|
| movie_id | int | required, exists:movies |

**Response 201** → `WatchlistResource`. If already present, returns the existing entry (no duplicate).

### GET `/watchlist/check/{movieId}`
**Auth.** Whether a movie is in the user's watchlist.
```json
{ "success": true, "data": { "in_watchlist": true } }
```

### DELETE `/watchlist/{movieId}`
**Auth.** Remove a movie from the watchlist. **Response 404** if not present.

---

## 12. Watch Progress & Continue Watching (Auth)

The mobile app reports playback progress so the admin panel can compute **watch hours** and the app can show **Continue Watching**.

### POST `/watch/progress`
**Auth.** Report or update playback position for the current user.

| Field | Type | Rules |
|-------|------|-------|
| movie_id | int | required, exists:movies |
| position_seconds | int | nullable, min 0 |
| duration_seconds | int | nullable, min 0 |
| watched_seconds | int | nullable, min 0 |
| completed | bool | nullable |

**Behavior:** upserts a per-user/movie record, only ever increasing `watched_seconds`, and rolls the totals up into the movie's `watch_seconds_total` and `views_count` counters (used by Movies Analytics). **Response 200** → `WatchProgressResource`.

**WatchProgressResource**
```json
{
  "id": 1,
  "movie": { ...MovieResource },
  "position_seconds": 540,
  "duration_seconds": 7200,
  "watched_seconds": 540,
  "progress_percent": 7.5,
  "completed": false,
  "updated_at": "2026-07-19T…"
}
```

### GET `/watch/continue`
**Auth.** Movies the user has partially watched but not finished (Continue Watching shelf). **Response** → `WatchProgressResource[]` (non-paginated, max 20).

### GET `/watch/history`
**Auth.** Full paginated watch history for the user.

---

## 13. Ads & Ad Analytics

### GET `/ads/serve`
**Public.** Fetch ads to display in the mobile app.

| Param | Type | Notes |
|-------|------|-------|
| placement | `all`\|`home`\|`movie_detail`\|`preroll` | default `all` |
| type | `video`\|`poster` | optional filter |

Only **active** ads whose schedule (`starts_at`/`ends_at`) is currently valid are returned, ordered by `priority` desc. **Response** → `AdResource[]`.

**AdResource**
```json
{
  "id": 1,
  "name": "Summer Promo",
  "type": "video",                 // "video" | "poster"
  "media": "https://…/storage/ads/…mp4",
  "target_url": "https://…",
  "placement": "preroll",
  "duration_seconds": 15,
  "is_active": true,
  "priority": 10,
  "starts_at": null,
  "ends_at": null,
  "views_count": 1234,
  "created_at": "2026-07-19T…"
}
```

### POST `/ads/view`
**Auth.** Record an ad impression for analytics.

| Field | Type | Rules |
|-------|------|-------|
| ad_id | int | required, exists:ads |
| placement | string | nullable, one of placements |
| movie_id | int | nullable, exists:movies |
| device | string | nullable, e.g. `android`/`ios`/`web` |

**Response 200** → `View recorded.` The admin **Ad Analytics** page aggregates `views_count` per ad.

---

## 14. Movies Analytics (Auth)

Admin-facing aggregates (also surfaced in the **Movies Analytics** admin page).

### GET `/analytics/movies`
Summary: total watch hours, total views, total movies, avg watch hours/movie.

### GET `/analytics/movies/top-hours?limit=10`
Top movies by total **watch hours** (aggregated watched seconds).

### GET `/analytics/movies/most-viewed?limit=10`
Most viewed movies (by distinct viewers / `views_count`).

### GET `/analytics/movies/top-viewing?limit=10`
Top viewing movies with `watch_hours`, `views_count`, and `completion_rate` (%).

### GET `/analytics/movies/watch-trend?days=30`
Watch hours per day for charts: `{ "labels": [...], "values": [...] }`.

---

## 16. Android TV Authentication & Device Pairing

Allows Android TV apps to sign in without typing passwords on the TV by displaying a QR code and 6-character user code for mobile approval.

Full guide and code examples available in [TV_INTEGRATION_GUIDE.md](file:///Volumes/ssd/nadsouza/admin/docs/TV_INTEGRATION_GUIDE.md).

### POST `/tv/auth/initiate`
**Public (X-API-KEY).** Initiates a TV login session.
- **Request Body:** `{ "device_name": "Living Room Sony TV", "device_model": "KD-55X80K", "device_os": "Android TV 12" }`
- **Response 200:** Returns `device_code`, `user_code`, `qr_payload`, `deep_link`, `expires_in` (600s), and `interval` (4s).

### POST `/tv/auth/poll`
**Public (X-API-KEY).** Polled periodically by the TV app.
- **Request Body:** `{ "device_code": "..." }`
- **Response 200:** Returns `status` (`pending`, `approved`, `expired`, `denied`). When `approved`, includes `token` (Sanctum Bearer token) and `user` object.

### GET `/tv/auth/verify?code=ABC123`
**Auth (Bearer token).** Called by mobile app to preview TV details before approving.
- **Response 200:** Returns TV `device_name`, `device_model`, `device_os`, `ip_address`, and `expires_in`.

### POST `/tv/auth/authorize`
**Auth (Bearer token).** Called by mobile app to authorize the TV login.
- **Request Body:** `{ "user_code": "ABC123", "device_name": "Living Room TV (optional)" }`
- **Response 200:** Marks TV session as approved and generates the TV Bearer token.

### POST `/tv/auth/deny`
**Auth (Bearer token).** Called by mobile app to reject the TV connection request.
- **Request Body:** `{ "user_code": "ABC123" }`

### GET `/tv/devices`
**Auth (Bearer token).** Lists all connected TV devices for the logged-in user.

### DELETE `/tv/devices/{id}`
**Auth (Bearer token).** Disconnects a TV device and immediately revokes its auth token.

---

## 17. Admin Panel — New Sections

| Section | Group | Purpose |
|---------|-------|---------|
| **E-Books** | Content | CRUD for e-books: thumbnail, PDF file upload, author, free/rental price and duration |
| **White Label** | Settings | Panel branding (logo, colors, fonts, layout, footer, custom CSS) |
| **Payment Gateways** | Payments | Manage QR Code and PhonePe gateways. Only one can be active at a time. Enabling one disables the other. |
| **Policies** | Settings | CRUD for legal/content policies (Terms, Privacy, Refund, Content, Custom) with slug, status, and public visibility |
| **Movies Analytics** | Analytics | Watch-hours overview, 30-day trend, most-viewed & top-viewing movie tables |
| **Ad Management** | Advertising | CRUD for video & poster ads (media upload, placement, schedule, priority) |
| **Ad Analytics** | Advertising | Per-ad view counts + 30-day ad-views trend |
| **Watchlist** | Content | Read-only view of every user's saved movies |
| Movie table | Content | Now shows **Slug**, **Views**, and **Watch Hours** columns per movie. Slugs are auto-generated from title and editable. |
| Payment / Rental tables | Payments / Rentals | Show **Movie** and **E-Book** columns. PhonePe payments are auto-approved; QR payments require admin approval. |

The mobile app consumes `/ebooks`, `/ebooks/{id}/read`, `/ads/serve`, `/watch/progress`, `/watch/continue`, `/watchlist`, `/analytics/*`, `/qr/active`, `/phonepe/active`, and `/tv/*` to determine the active payment method and power the rest of the experience.

