# 📖 Anchor Backend API Documentation

Complete REST API specification and developer reference for the **Anchor Backend** application.

---

## 🌐 General Information

- **Base URL (Local)**: `http://localhost:3000`
- **Content-Type**: `application/json` (API also accepts `multipart/form-data` and `application/x-www-form-urlencoded`)
- **Authentication Scheme**: `Bearer <JWT_TOKEN>` in the HTTP `Authorization` header

---

## 📦 Standard Response Format

All API responses strictly adhere to a unified JSON schema.

### Success Response (`200 OK` / `201 Created`)
```json
{
  "status": "success",
  "code": 200,
  "message": "Operation completed successfully",
  "data": {
    "...": "..."
  }
}
```

### Error Response (`400`, `401`, `409`, `500`)
```json
{
  "status": "error",
  "code": 400,
  "message": "Detailed error description",
  "errors": [
    "field1 is required",
    "field2 is invalid"
  ]
}
```

---

## 📑 Endpoints Summary (100% POST-Only Architecture)

> [!NOTE]
> All endpoints in the Anchor Backend strictly use the **`POST`** HTTP method. `GET`, `PUT`, and `DELETE` methods are not used.

| Method | Endpoint | Auth Required | Description |
| :--- | :--- | :--- | :--- |
| **`POST`** | [`/api/check`](#1-server-health-check) | ❌ No | Verify backend server status |
| **`POST`** | [`/api/auth/signup`](#2-user-signup--registration) | ❌ No | Register a new user account |
| **`POST`** | [`/api/auth/login`](#3-user-login-jwt-authentication) | ❌ No | Authenticate user (supports 2FA challenge / instant code) |
| **`POST`** | [`/api/auth/2fa/verify-login`](#4-2fa-verify-login) | ❌ No | Complete 2FA login with 6-digit Authenticator OTP |
| **`POST`** | [`/api/auth/2fa/setup`](#5-2fa-setup) | 🔐 **Required** | Generate Base32 secret and QR code URI for authenticator |
| **`POST`** | [`/api/auth/2fa/enable`](#6-2fa-enable) | 🔐 **Required** | Verify authenticator code and activate 2FA on account |
| **`POST`** | [`/api/auth/2fa/disable`](#7-2fa-disable) | 🔐 **Required** | Disable 2FA with password or authenticator code |
| **`POST`** | [`/api/auth/refresh`](#8-refresh-token-renew-access-token) | ❌ No | Exchange Refresh token for new Access token |
| **`POST`** | [`/api/auth/logout`](#9-user-logout) | ⚪ Optional | Clear session / invalidate client token |
| **`POST`** | [`/api/auth/forgot-password`](#10-forgot-password) | ❌ No | Generate password reset token |
| **`POST`** | [`/api/auth/verify-reset-token`](#11-verify-reset-token) | ❌ No | Validate reset token before rendering reset form |
| **`POST`** | [`/api/auth/reset-password`](#12-reset-password) | ❌ No | Reset password using reset token |
| **`POST`** | [`/api/auth/send-email-verification`](#13-send-email-verification) | ⚪ Optional | Send 6-digit OTP code to user's email |
| **`POST`** | [`/api/auth/verify-email`](#14-verify-email) | ⚪ Optional | Verify email using 6-digit OTP code |
| **`POST`** | [`/api/auth/send-phone-verification`](#15-send-phone-verification) | ⚪ Optional | Send 6-digit OTP code to user's phone |
| **`POST`** | [`/api/auth/verify-phone`](#16-verify-phone) | ⚪ Optional | Verify phone number using 6-digit OTP code |
| **`POST`** | [`/api/departments`](#17-get-departments-list) | ❌ No | Get list of support departments (Tech, Billing, Sales, Abuse) |
| **`POST`** | [`/api/tickets/create`](#18-create-support-ticket) | 🔐 **Required** | Create a support ticket with department, priority, and file uploads |
| **`POST`** | [`/api/tickets/list`](#19-list-user-tickets) | 🔐 **Required** | List user's tickets with status & department filters in JSON body |
| **`POST`** | [`/api/tickets/detail`](#20-get-ticket-details--history) | 🔐 **Required** | Get full ticket thread with messages & attachments by `id` or `ticket_id` |
| **`POST`** | [`/api/tickets/reply`](#21-reply-to-ticket) | 🔐 **Required** | Reply to ticket thread with optional file attachments |
| **`POST`** | [`/api/tickets/status`](#22-update-ticket-status) | 🔐 **Required** | Update ticket status (e.g. Close ticket) |
| **`POST`** | [`/api/user/checkUserByEmail`](#23-check-user-by-email) | ❌ No | Check if an email is registered / available |
| **`POST`** | [`/api/admin/auth/login`](#24-admin-and-staff-login) | ❌ No | Dedicated Admin & Supporter login authentication |
| **`POST`** | [`/api/admin/permissions`](#25-list-system-permissions) | 👑 **Staff/Admin** | List all granular system permissions |
| **`POST`** | [`/api/admin/staff/list`](#26-list-staff-members) | 👑 **Staff/Admin** | List staff/supporters with assigned permissions |
| **`POST`** | [`/api/admin/staff/create`](#27-create-supporter-account) | 👑 **Admin Only** | Create a new supporter account with assigned permissions |
| **`POST`** | [`/api/admin/staff/detail`](#28-get-staff-details) | 👑 **Staff/Admin** | Get staff member details and permissions |
| **`POST`** | [`/api/admin/staff/update`](#29-update-staff-details) | 👑 **Admin Only** | Update supporter profile, status, or password |
| **`POST`** | [`/api/admin/staff/permissions`](#30-update-supporter-permissions) | 👑 **Admin Only** | Modify assigned permissions for a supporter |
| **`POST`** | [`/api/admin/staff/delete`](#31-delete-supporter-account) | 👑 **Admin Only** | Delete a supporter staff account |
| **`POST`** | [`/api/admin/clients/list`](#32-list-client-accounts) | 🛡️ **`clients.view`** | List client accounts with search & pagination |
| **`POST`** | [`/api/admin/clients/detail`](#33-get-client-details) | 🛡️ **`clients.view`** | Get client profile and ticket history |

---

## 1. Server Health Check

Check whether the backend application is online and responsive.

- **URL**: `/api/check`
- **Method**: `POST`
- **Authentication**: None

### Success Response (`200 OK`):
```json
{
  "status": "success",
  "code": 200,
  "message": "Check API is working"
}
```

### cURL Example:
```bash
curl -X GET http://localhost:3000/api/check
```

---

## 2. User Signup / Registration

Registers a new user account in the database. Validates required fields, checks for duplicate emails, and hashes the password using SHA-256 before storing.

- **URL**: `/api/auth/signup`
- **Method**: `POST`
- **Authentication**: None
- **Headers**: `Content-Type: application/json`

### 📥 Request Parameters

| Parameter | Type | Required? | Description | Constraints |
| :--- | :--- | :--- | :--- | :--- |
| `first_name` | `String` | ✅ **Required** | User's first name | Non-empty |
| `last_name` | `String` | ✅ **Required** | User's last name | Non-empty |
| `email` | `String` | ✅ **Required** | User's email address | Valid email format (e.g. `user@example.com`) |
| `password` | `String` | ✅ **Required** | User's password | Minimum 6 characters |
| `phone_number` | `String` | ⚪ *Optional* | Contact phone number | Defaults to `""` |
| `company_name` | `String` | ⚪ *Optional* | Billing company name | Defaults to `""` |
| `street_address` | `String` | ⚪ *Optional* | Primary street address | Defaults to `""` |
| `street_address_2`| `String` | ⚪ *Optional* | Apartment, suite, unit | Defaults to `""` |
| `city` | `String` | ⚪ *Optional* | City | Defaults to `""` |
| `state` | `String` | ⚪ *Optional* | State / Province / Region | Defaults to `""` |
| `postcode` | `String` | ⚪ *Optional* | Postal / ZIP code | Defaults to `""` |

### 📤 Request Body Example:
```json
{
  "first_name": "Shubham",
  "last_name": "Sharma",
  "email": "shubham@example.com",
  "password": "SecurePassword123",
  "phone_number": "+919876543210",
  "company_name": "HeroWeby Tech",
  "street_address": "123 Tech Park Road",
  "street_address_2": "Suite 4B",
  "city": "Mumbai",
  "state": "Maharashtra",
  "postcode": "400001"
}
```

### 📥 Success Response (`201 Created`):
```json
{
  "status": "success",
  "code": 201,
  "message": "User registered successfully",
  "data": {
    "user_id": 1,
    "first_name": "Shubham",
    "last_name": "Sharma",
    "email": "shubham@example.com"
  }
}
```

### ❌ Error Responses:

- **Missing Required Fields (`400 Bad Request`)**:
  ```json
  {
    "status": "error",
    "code": 400,
    "message": "Missing required fields: first_name, email",
    "errors": ["first_name", "email"]
  }
  ```

- **Invalid Email Format (`400 Bad Request`)**:
  ```json
  {
    "status": "error",
    "code": 400,
    "message": "Invalid email address format"
  }
  ```

- **Short Password (`400 Bad Request`)**:
  ```json
  {
    "status": "error",
    "code": 400,
    "message": "Password must be at least 6 characters long"
  }
  ```

- **Email Already Exists (`409 Conflict`)**:
  ```json
  {
    "status": "error",
    "code": 409,
    "message": "An account with this email already exists"
  }
  ```

### cURL Example:
```bash
curl -X POST http://localhost:3000/api/auth/signup \
  -H "Content-Type: application/json" \
  -d '{
    "first_name": "Shubham",
    "last_name": "Sharma",
    "email": "shubham@example.com",
    "password": "SecurePassword123",
    "phone_number": "+919876543210",
    "company_name": "HeroWeby Tech",
    "street_address": "123 Tech Park Road",
    "city": "Mumbai",
    "state": "Maharashtra",
    "postcode": "400001"
  }'
```

---

## 3. User Login (JWT Authentication)

Authenticates user credentials. If 2FA is disabled on the account, issues signed Access and Refresh JWT tokens immediately. If 2FA is enabled, returns a 2FA challenge with a temporary session token (`temp_token`).

- **URL**: `/api/auth/login`
- **Method**: `POST`
- **Authentication**: None
- **Headers**: `Content-Type: application/json`

### 📥 Request Parameters

| Parameter | Type | Required? | Description |
| :--- | :--- | :--- | :--- |
| `email` | `String` | ✅ **Required** | The registered user's email |
| `password` | `String` | ✅ **Required** | The user's account password |
| `two_factor_code` | `String` | ⚪ *Optional* | 6-digit Authenticator code (if submitting all-in-one) |

### 📤 Request Body Example:
```json
{
  "email": "shubham@example.com",
  "password": "SecurePassword123"
}
```

### 📥 Success Response — Normal Login (2FA Disabled) (`200 OK`):
```json
{
  "status": "success",
  "code": 200,
  "message": "Login successful",
  "data": {
    "token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
    "refresh_token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
    "expires_in": 86400,
    "token_type": "Bearer",
    "user": {
      "id": 1,
      "first_name": "Shubham",
      "last_name": "Sharma",
      "email": "shubham@example.com",
      "phone_number": "+919876543210",
      "company_name": "HeroWeby Tech",
      "street_address": "123 Tech Park Road",
      "city": "Mumbai",
      "state": "Maharashtra",
      "postcode": "400001",
      "two_factor_enabled": 0,
      "is_email_verified": 1,
      "is_phone_verified": 1
    }
  }
}
```

### 📥 Success Response — 2FA Challenge Required (`200 OK`):
Returned when `two_factor_enabled = 1` and `two_factor_code` was not provided in the initial login payload.
```json
{
  "status": "success",
  "code": 200,
  "message": "Two-factor authentication code required",
  "data": {
    "requires_2fa": 1,
    "temp_token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
    "email": "shubham@example.com"
  }
}
```

### ❌ Error Responses:

- **Invalid Credentials (`401 Unauthorized`)**:
  ```json
  {
    "status": "error",
    "code": 401,
    "message": "Invalid email or password"
  }
  ```

- **Invalid 2FA Code (`401 Unauthorized`)**:
  ```json
  {
    "status": "error",
    "code": 401,
    "message": "Invalid 6-digit authenticator code"
  }
  ```

### cURL Example:
```bash
curl -X POST http://localhost:3000/api/auth/login \
  -H "Content-Type: application/json" \
  -d '{
    "email": "shubham@example.com",
    "password": "SecurePassword123"
  }'
```

---

## 4. 2FA Verify Login

Completes the 2FA login by verifying the 6-digit TOTP code generated by the user's authenticator app (Google Authenticator, Microsoft Authenticator, Authy).

- **URL**: `/api/auth/2fa/verify-login`
- **Method**: `POST`
- **Authentication**: None (Requires `temp_token` from Step 1)
- **Headers**: `Content-Type: application/json`

### 📥 Request Parameters

| Parameter | Type | Required? | Description |
| :--- | :--- | :--- | :--- |
| `temp_token` | `String` | ✅ **Required** | The temporary 2FA token received from `/api/auth/login` |
| `code` | `String` | ✅ **Required** | The 6-digit code from user's Authenticator app |

### 📤 Request Body Example:
```json
{
  "temp_token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
  "code": "481920"
}
```

### 📥 Success Response (`200 OK`):
```json
{
  "status": "success",
  "code": 200,
  "message": "Two-factor authentication verified successfully. Login complete.",
  "data": {
    "token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
    "refresh_token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
    "expires_in": 86400,
    "token_type": "Bearer",
    "user": {
      "id": 1,
      "first_name": "Shubham",
      "last_name": "Sharma",
      "email": "shubham@example.com",
      "two_factor_enabled": 1,
      "is_email_verified": 1,
      "is_phone_verified": 1
    }
  }
}
```

### ❌ Error Responses:
- **Invalid Authenticator Code (`401 Unauthorized`)**:
  ```json
  {
    "status": "error",
    "code": 401,
    "message": "Invalid 6-digit authenticator code. Please check your authenticator app and system clock."
  }
  ```
- **Expired 2FA Session (`401 Unauthorized`)**:
  ```json
  {
    "status": "error",
    "code": 401,
    "message": "Invalid or expired 2FA session. Please log in again."
  }
  ```

### cURL Example:
```bash
curl -X POST http://localhost:3000/api/auth/2fa/verify-login \
  -H "Content-Type: application/json" \
  -d '{
    "temp_token": "<TEMP_TOKEN_FROM_LOGIN>",
    "code": "481920"
  }'
```

---

## 5. 2FA Setup

Generates a new Base32 TOTP secret key and standard `otpauth://` QR Code URI for Google Authenticator or Microsoft Authenticator.

- **URL**: `/api/auth/2fa/setup`
- **Method**: `POST`
- **Authentication**: 🔐 **Required** (`Bearer <JWT_TOKEN>`)
- **Headers**: `Content-Type: application/json`, `Authorization: Bearer <TOKEN>`

### 📥 Success Response (`200 OK`):
```json
{
  "status": "success",
  "code": 200,
  "message": "2FA secret generated successfully. Scan the QR code or enter secret in your authenticator app.",
  "data": {
    "secret": "JBSWY3DPEHPK3PXP",
    "otpauth_uri": "otpauth://totp/AnchorPanel:shubham%40example.com?secret=JBSWY3DPEHPK3PXP&issuer=AnchorPanel&algorithm=SHA1&digits=6&period=30",
    "two_factor_enabled": 0
  }
}
```

### cURL Example:
```bash
curl -X POST http://localhost:3000/api/auth/2fa/setup \
  -H "Authorization: Bearer <YOUR_ACCESS_TOKEN>"
```

---

## 6. 2FA Enable

Verifies the initial 6-digit code produced by the user's authenticator app to confirm setup, and activates 2FA on the account (`two_factor_enabled = 1`).

- **URL**: `/api/auth/2fa/enable`
- **Method**: `POST`
- **Authentication**: 🔐 **Required** (`Bearer <JWT_TOKEN>`)
- **Headers**: `Content-Type: application/json`, `Authorization: Bearer <TOKEN>`

### 📥 Request Parameters

| Parameter | Type | Required? | Description |
| :--- | :--- | :--- | :--- |
| `secret` | `String` | ✅ **Required** | The Base32 secret key from `/api/auth/2fa/setup` |
| `code` | `String` | ✅ **Required** | The 6-digit verification code from the authenticator app |

### 📤 Request Body Example:
```json
{
  "secret": "JBSWY3DPEHPK3PXP",
  "code": "481920"
}
```

### 📥 Success Response (`200 OK`):
```json
{
  "status": "success",
  "code": 200,
  "message": "Two-factor authentication has been successfully enabled for your account.",
  "data": {
    "two_factor_enabled": 1
  }
}
```

### cURL Example:
```bash
curl -X POST http://localhost:3000/api/auth/2fa/enable \
  -H "Authorization: Bearer <YOUR_ACCESS_TOKEN>" \
  -H "Content-Type: application/json" \
  -d '{
    "secret": "JBSWY3DPEHPK3PXP",
    "code": "481920"
  }'
```

---

## 7. 2FA Disable

Disables Two-Factor Authentication for the authenticated user's account after confirming either the current password or a valid 6-digit authenticator code.

- **URL**: `/api/auth/2fa/disable`
- **Method**: `POST`
- **Authentication**: 🔐 **Required** (`Bearer <JWT_TOKEN>`)
- **Headers**: `Content-Type: application/json`, `Authorization: Bearer <TOKEN>`

### 📥 Request Parameters

| Parameter | Type | Required? | Description |
| :--- | :--- | :--- | :--- |
| `password` | `String` | ⚪ *Optional* | The user's account password (required if `code` is omitted) |
| `code` | `String` | ⚪ *Optional* | 6-digit Authenticator code (required if `password` is omitted) |

### 📤 Request Body Example:
```json
{
  "password": "SecurePassword123"
}
```

### 📥 Success Response (`200 OK`):
```json
{
  "status": "success",
  "code": 200,
  "message": "Two-factor authentication has been disabled for your account.",
  "data": {
    "two_factor_enabled": 0
  }
}
```

### cURL Example:
```bash
curl -X POST http://localhost:3000/api/auth/2fa/disable \
  -H "Authorization: Bearer <YOUR_ACCESS_TOKEN>" \
  -H "Content-Type: application/json" \
  -d '{"password":"SecurePassword123"}'
```

---

## 8. Refresh Token (Renew Access Token)

Exchanges a valid refresh token for a newly issued access token and refresh token without requiring the user to enter credentials again.

- **URL**: `/api/auth/refresh`
- **Method**: `POST`
- **Authentication**: None
- **Headers**: `Content-Type: application/json`

### 📥 Request Parameters

| Parameter | Type | Required? | Description |
| :--- | :--- | :--- | :--- |
| `refresh_token` | `String` | ✅ **Required** | The refresh token received during login |

### 📤 Request Body Example:
```json
{
  "refresh_token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..."
}
```

### 📥 Success Response (`200 OK`):
```json
{
  "status": "success",
  "code": 200,
  "message": "Token refreshed successfully",
  "data": {
    "token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
    "refresh_token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
    "expires_in": 86400,
    "token_type": "Bearer"
  }
}
```

### ❌ Error Responses:

- **Invalid or Expired Refresh Token (`401 Unauthorized`)**:
  ```json
  {
    "status": "error",
    "code": 401,
    "message": "Invalid or expired refresh token"
  }
  ```

- **Missing Parameter (`400 Bad Request`)**:
  ```json
  {
    "status": "error",
    "code": 400,
    "message": "Missing refresh_token parameter"
  }
  ```

### cURL Example:
```bash
curl -X POST http://localhost:3000/api/auth/refresh \
  -H "Content-Type: application/json" \
  -d '{"refresh_token":"<YOUR_REFRESH_TOKEN>"}'
```

---

## 9. User Logout

Logs the user out of the application.

- **URL**: `/api/auth/logout`
- **Method**: `POST`
- **Headers (Optional)**: `Authorization: Bearer <JWT_TOKEN>`

### 📥 Success Response (`200 OK`):
```json
{
  "status": "success",
  "code": 200,
  "message": "Goodbye, Shubham! Successfully logged out"
}
```

### cURL Example:
```bash
curl -X POST http://localhost:3000/api/auth/logout \
  -H "Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..."
```

---

## 10. Forgot Password (Request Confirmation Link via Email)

Sends an identity confirmation email containing a custom password reset link to the user's registered email address. The link contains a secure, 1-hour signed JWT token.

- **URL**: `/api/auth/forgot-password` *(also supports alias `/api/auth/forget-password`)*
- **Method**: `POST`
- **Authentication**: None
- **Headers**: `Content-Type: application/json`

### 📥 Request Parameters

| Parameter | Type | Required? | Description |
| :--- | :--- | :--- | :--- |
| `email` | `String` | ✅ **Required** | The user's registered email address |
| `redirect_url` | `String` | ⚪ *Optional* | Custom frontend reset URL (e.g. `https://myfrontend.com/reset-password`). If omitted, uses `frontend_reset_url` from config. |

### 📤 Request Body Example:
```json
{
  "email": "shubham@example.com"
}
```

### 📥 Success Response (`200 OK`):
```json
{
  "status": "success",
  "code": 200,
  "message": "Password reset confirmation link has been sent to your registered email address",
  "data": {
    "email": "shubham@example.com",
    "reset_token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
    "reset_link": "http://localhost:5173/reset-password?token=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...&email=shubham%40example.com",
    "expires_in": 3600
  }
}
```

### ❌ Error Responses:

- **Email Not Found (`404 Not Found`)**:
  ```json
  {
    "status": "error",
    "code": 404,
    "message": "No account found with this email address"
  }
  ```

- **Missing/Invalid Email (`400 Bad Request`)**:
  ```json
  {
    "status": "error",
    "code": 400,
    "message": "Invalid email address format"
  }
  ```

### cURL Example:
```bash
curl -X POST http://localhost:3000/api/auth/forgot-password \
  -H "Content-Type: application/json" \
  -d '{"email":"shubham@example.com"}'
```

---

## 11. Verify Password Reset Token

Allows the frontend to validate the reset token from the custom email link before displaying the new password input form to the user.

- **URL**: `/api/auth/verify-reset-token`
- **Method**: `GET` or `POST`
- **Authentication**: None
- **Query Parameter (or JSON Body)**: `token=<RESET_TOKEN>`

### 📥 Request Example:
```bash
curl -X GET "http://localhost:3000/api/auth/verify-reset-token?token=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..."
```

### 📥 Success Response (`200 OK`):
```json
{
  "status": "success",
  "code": 200,
  "message": "Password reset token is valid",
  "data": {
    "valid": 1,
    "user_id": 1,
    "email": "shubham@example.com",
    "first_name": "Shubham"
  }
}
```

### ❌ Error Responses:

- **Invalid or Expired Token (`401 Unauthorized`)**:
  ```json
  {
    "status": "error",
    "code": 401,
    "message": "Invalid or expired password reset token"
  }
  ```

- **Token Already Used (`401 Unauthorized`)**:
  ```json
  {
    "status": "error",
    "code": 401,
    "message": "This password reset token has already been used. Please request a new one."
  }
  ```

---

## 12. Reset Password (Set New Password)

Sets a new password for the user using the validated reset token received from their email. Automatically invalidates the reset token after use and revokes active refresh tokens.

- **URL**: `/api/auth/reset-password`
- **Method**: `POST`
- **Authentication**: None
- **Headers**: `Content-Type: application/json`

### 📥 Request Parameters

| Parameter | Type | Required? | Description |
| :--- | :--- | :--- | :--- |
| `token` | `String` | ✅ **Required** | The password reset token from email link |
| `new_password` | `String` | ✅ **Required** | The new password (min 6 characters) |

### 📤 Request Body Example:
```json
{
  "token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
  "new_password": "MyNewSecurePassword456"
}
```

### 📥 Success Response (`200 OK`):
```json
{
  "status": "success",
  "code": 200,
  "message": "Password has been successfully reset. You can now log in with your new password."
}
```

### ❌ Error Responses:

- **Invalid / Expired / Reused Token (`401 Unauthorized`)**:
  ```json
  {
    "status": "error",
    "code": 401,
    "message": "Invalid or expired password reset token"
  }
  ```

- **Short Password (`400 Bad Request`)**:
  ```json
  {
    "status": "error",
    "code": 400,
    "message": "New password must be at least 6 characters long"
  }
  ```

### cURL Example:
```bash
curl -X POST http://localhost:3000/api/auth/reset-password \
  -H "Content-Type: application/json" \
  -d '{
    "token": "<YOUR_RESET_TOKEN>",
    "new_password": "MyNewSecurePassword456"
  }'
```

---

## 13. Send Email Verification

Generates and sends a 6-digit verification OTP to the user's registered email address (valid for 15 minutes).

- **URL**: `/api/auth/send-email-verification`
- **Method**: `POST`
- **Authentication**: Optional (supports `Bearer <token>` or passing `email` in body)
- **Headers**: `Content-Type: application/json`

### 📥 Request Parameters:
```json
{
  "email": "shubham@example.com"
}
```

### 📥 Success Response (`200 OK`):
```json
{
  "status": "success",
  "code": 200,
  "message": "Verification code sent to email successfully",
  "data": {
    "email": "shubham@example.com",
    "expires_in": 900,
    "code": "105396"
  }
}
```

### cURL Example:
```bash
curl -X POST http://localhost:3000/api/auth/send-email-verification \
  -H "Content-Type: application/json" \
  -d '{"email":"shubham@example.com"}'
```

---

## 14. Verify Email

Submits the 6-digit OTP code to verify and confirm the user's email address.

- **URL**: `/api/auth/verify-email`
- **Method**: `POST`
- **Authentication**: Optional
- **Headers**: `Content-Type: application/json`

### 📥 Request Parameters:
```json
{
  "email": "shubham@example.com",
  "code": "105396"
}
```

### 📥 Success Response (`200 OK`):
```json
{
  "status": "success",
  "code": 200,
  "message": "Email verified successfully",
  "data": {
    "user_id": 1,
    "email": "shubham@example.com",
    "is_email_verified": 1
  }
}
```

### cURL Example:
```bash
curl -X POST http://localhost:3000/api/auth/verify-email \
  -H "Content-Type: application/json" \
  -d '{"email":"shubham@example.com","code":"105396"}'
```

---

## 15. Send Phone Verification

Generates and sends a 6-digit verification OTP to the user's registered phone number (valid for 15 minutes).

- **URL**: `/api/auth/send-phone-verification`
- **Method**: `POST`
- **Authentication**: Optional
- **Headers**: `Content-Type: application/json`

### 📥 Request Parameters:
```json
{
  "phone_number": "9876543210"
}
```

### 📥 Success Response (`200 OK`):
```json
{
  "status": "success",
  "code": 200,
  "message": "Verification code sent to phone successfully",
  "data": {
    "phone_number": "9876543210",
    "expires_in": 900,
    "code": "246644"
  }
}
```

### cURL Example:
```bash
curl -X POST http://localhost:3000/api/auth/send-phone-verification \
  -H "Content-Type: application/json" \
  -d '{"phone_number":"9876543210"}'
```

---

## 16. Verify Phone

Submits the 6-digit OTP code to verify and confirm the user's phone number.

- **URL**: `/api/auth/verify-phone`
- **Method**: `POST`
- **Authentication**: Optional
- **Headers**: `Content-Type: application/json`

### 📥 Request Parameters:
```json
{
  "phone_number": "9876543210",
  "code": "246644"
}
```

### 📥 Success Response (`200 OK`):
```json
{
  "status": "success",
  "code": 200,
  "message": "Phone number verified successfully",
  "data": {
    "user_id": 1,
    "phone_number": "9876543210",
    "is_phone_verified": 1
  }
}
```

### cURL Example:
```bash
curl -X POST http://localhost:3000/api/auth/verify-phone \
  -H "Content-Type: application/json" \
  -d '{"phone_number":"9876543210","code":"246644"}'
```

---

## 17. Get Departments List

Retrieves all active support departments (e.g. Technical Support, Billing, Sales, Abuse) with their IDs and metadata.

- **URL**: `/api/departments` (or `/api/departments/list`)
- **Method**: `POST`
- **Authentication**: None
- **Headers**: `Content-Type: application/json`

### 📥 Success Response (`200 OK`):
```json
{
  "status": "success",
  "code": 200,
  "message": "Departments retrieved successfully",
  "data": {
    "count": 4,
    "departments": [
      {
        "id": 1,
        "deptid": 1,
        "name": "Technical Support",
        "description": "Help with technical issues and server configurations",
        "is_active": 1
      },
      {
        "id": 2,
        "deptid": 4,
        "name": "Billing Department",
        "description": "Invoices, payments, upgrades and account billing",
        "is_active": 1
      },
      {
        "id": 3,
        "deptid": 5,
        "name": "Sales & Pre Sales Department",
        "description": "Pre-sales inquiries, product details, custom plans",
        "is_active": 1
      },
      {
        "id": 4,
        "deptid": 6,
        "name": "Abuse Department",
        "description": "Reports of abuse, DMCA, and network policy violations",
        "is_active": 1
      }
    ]
  }
}
```

### cURL Example:
```bash
curl -X POST http://localhost:3000/api/departments
```

---

## 18. Create Support Ticket

Creates a new support ticket under a chosen department with subject, detailed message, priority level, and optional file attachments (Images, Videos, PDFs, Documents).

- **URL**: `/api/tickets/create` (or `/api/tickets`)
- **Method**: `POST`
- **Authentication**: `Bearer <token>` in Authorization Header
- **Headers**: `Content-Type: multipart/form-data` *(or `application/json` without files)*

### 📥 Form Data Parameters:

| Parameter | Type | Required? | Description |
| :--- | :--- | :--- | :--- |
| `department_id` or `deptid` | `Integer` | ✅ **Required** | Department ID (`1` = Tech, `4` = Billing, `5` = Sales, `6` = Abuse) |
| `subject` | `String` | ✅ **Required** | Short summary / subject of the ticket |
| `message` | `String` | ✅ **Required** | Detailed description / concern |
| `priority` | `String` | ⚪ Optional | Priority: `Low`, `Medium`, `High`, `Critical` *(Default: `Medium`)* |
| `attachments` | `File(s)` | ⚪ Optional | Upload one or multiple files (PNG, JPG, PDF, MP4, etc.) |

### 📥 Success Response (`201 Created`):
```json
{
  "status": "success",
  "code": 201,
  "message": "Ticket created successfully",
  "data": {
    "ticket_id": 1,
    "ticket_number": "TIC-524525",
    "department": {
      "id": 1,
      "deptid": 1,
      "name": "Technical Support"
    },
    "subject": "Server error on uploading large files",
    "priority": "High",
    "status": "Open",
    "message": "Hello Support, whenever I upload a file larger than 5MB...",
    "attachments": [
      {
        "id": 1,
        "file_name": "error_log.txt",
        "file_path": "/uploads/tickets/tic_1_1787573908_9316.txt",
        "file_size": 10240,
        "file_type": "text/plain"
      }
    ],
    "created_at": "Mon Aug 24 17:48:28 2026"
  }
}
```

### cURL Example (with File Upload):
```bash
curl -X POST http://localhost:3000/api/tickets/create \
  -H "Authorization: Bearer <ACCESS_TOKEN>" \
  -F "deptid=1" \
  -F "subject=Server error on uploading large files" \
  -F "message=Hello Support, please see attached screenshot and PDF error report." \
  -F "priority=High" \
  -F "attachments=@/path/to/screenshot.png" \
  -F "attachments=@/path/to/error_report.pdf"
```

---

## 19. List User Tickets

Retrieves all support tickets generated by the authenticated user with status and department filter options.

- **URL**: `/api/tickets/list` (or `/api/tickets`)
- **Method**: `POST`
- **Authentication**: `Bearer <token>` in Authorization Header
- **Headers**: `Content-Type: application/json`
- **Request Body (Optional Filters)**:
```json
{
  "status": "Open",
  "department_id": 1
}
```

### 📥 Success Response (`200 OK`):
```json
{
  "status": "success",
  "code": 200,
  "message": "Tickets retrieved successfully",
  "data": {
    "count": 1,
    "tickets": [
      {
        "id": 1,
        "ticket_number": "TIC-524525",
        "department_name": "Technical Support",
        "department_deptid": 1,
        "subject": "Server error on uploading large files",
        "priority": "High",
        "status": "Open",
        "message_count": 1,
        "attachment_count": 1,
        "created_at": "2026-08-24 17:48:28",
        "updated_at": "2026-08-24 17:48:28"
      }
    ]
  }
}
```

### cURL Example:
```bash
curl -X POST http://localhost:3000/api/tickets/list \
  -H "Authorization: Bearer <ACCESS_TOKEN>" \
  -H "Content-Type: application/json" \
  -d '{"status":"Open"}'
```

---

## 20. Get Ticket Details & History

Retrieves the complete conversation thread and attached files for a specific ticket.

- **URL**: `/api/tickets/detail` (or `/api/tickets/:id` / `/api/tickets/:id/detail`)
- **Method**: `POST`
- **Authentication**: `Bearer <token>` in Authorization Header
- **Headers**: `Content-Type: application/json`
- **Request Body**:
```json
{
  "id": 1
}
```
*(or pass `"ticket_id": "TIC-524525"`)*

### 📥 Success Response (`200 OK`):
```json
{
  "status": "success",
  "code": 200,
  "message": "Ticket details retrieved successfully",
  "data": {
    "ticket": {
      "id": 1,
      "ticket_number": "TIC-524525",
      "department_name": "Technical Support",
      "subject": "Server error on uploading large files",
      "priority": "High",
      "status": "Open",
      "created_at": "2026-08-24 17:48:28",
      "updated_at": "2026-08-24 17:48:28"
    },
    "messages": [
      {
        "id": 1,
        "sender_type": "customer",
        "first_name": "Shubham",
        "last_name": "Sharma",
        "message": "Hello Support, whenever I upload a file larger than 5MB...",
        "created_at": "2026-08-24 17:48:28",
        "attachments": [
          {
            "id": 1,
            "file_name": "error_log.txt",
            "file_path": "/uploads/tickets/tic_1_1787573908_9316.txt",
            "file_size": 10240,
            "file_type": "text/plain"
          }
        ]
      }
    ]
  }
}
```

### cURL Example:
```bash
curl -X POST http://localhost:3000/api/tickets/detail \
  -H "Authorization: Bearer <ACCESS_TOKEN>" \
  -H "Content-Type: application/json" \
  -d '{"id": 1}'
```

---

## 21. Reply to Ticket

Adds a customer reply message to an existing ticket conversation with optional file uploads. Automatically updates the ticket status to `Customer-Reply`.

- **URL**: `/api/tickets/reply` (or `/api/tickets/:id/reply`)
- **Method**: `POST`
- **Authentication**: `Bearer <token>` in Authorization Header
- **Headers**: `Content-Type: multipart/form-data` *(or `application/json`)*

### 📥 Form Data / Body Parameters:
- `id` / `ticket_id` (`Integer` or `String`): The ticket ID or Ticket Number
- `message` (`String`, **Required**): The reply text
- `attachments` (`File(s)`, *Optional*): Additional images, videos, or PDFs

### 📥 Success Response (`201 Created`):
```json
{
  "status": "success",
  "code": 201,
  "message": "Reply submitted successfully",
  "data": {
    "message_id": 2,
    "ticket_id": 1,
    "message": "Here is additional screenshot showing the network tab.",
    "status": "Customer-Reply",
    "attachments": [
      {
        "id": 2,
        "file_name": "screenshot.png",
        "file_path": "/uploads/tickets/tic_1_reply_1787573909_4821.png",
        "file_size": 254890,
        "file_type": "image/png"
      }
    ]
  }
}
```

### cURL Example:
```bash
curl -X POST http://localhost:3000/api/tickets/reply \
  -H "Authorization: Bearer <ACCESS_TOKEN>" \
  -F "ticket_id=1" \
  -F "message=Here is additional screenshot." \
  -F "attachments=@/path/to/screenshot.png"
```

---

## 22. Update Ticket Status

Updates the status of a ticket (e.g. closing an open ticket).

- **URL**: `/api/tickets/status` (or `/api/tickets/:id/status`)
- **Method**: `POST`
- **Authentication**: `Bearer <token>` in Authorization Header
- **Headers**: `Content-Type: application/json`

### 📥 Request Body:
```json
{
  "id": 1,
  "status": "Closed"
}
```
*Allowed statuses: `Open`, `In Progress`, `Answered`, `Customer-Reply`, `Closed`*

### 📥 Success Response (`200 OK`):
```json
{
  "status": "success",
  "code": 200,
  "message": "Ticket status updated to 'Closed' successfully",
  "data": {
    "ticket_id": 1,
    "status": "Closed"
  }
}
```

### cURL Example:
```bash
curl -X POST http://localhost:3000/api/tickets/status \
  -H "Authorization: Bearer <ACCESS_TOKEN>" \
  -H "Content-Type: application/json" \
  -d '{"id": 1, "status":"Closed"}'
```

---

## 23. Check User By Email

Checks if an email address is already registered or available in the system. Useful for real-time validation in signup and registration forms.

- **URL**: `/api/user/checkUserByEmail` (or `/api/user/check-by-email`)
- **Method**: `POST`
- **Authentication**: None
- **Headers**: `Content-Type: application/json`

### 📥 Request Parameters

| Parameter | Type | Required? | Description |
| :--- | :--- | :--- | :--- |
| `email` | `String` | ✅ **Required** | Email address to check |

### 📤 Request Body Example (POST):
```json
{
  "email": "shubham@example.com"
}
```

### 📥 Response: User Found (`200 OK`):
```json
{
  "status": "success",
  "code": 200,
  "message": "User found",
  "data": {
    "exists": true,
    "user_id": 1,
    "email": "shubham@example.com",
    "first_name": "Shubham",
    "last_name": "Sharma"
  }
}
```

### 📥 Response: User Not Found / Available (`200 OK`):
```json
{
  "status": "success",
  "code": 200,
  "message": "User not found",
  "data": {
    "exists": false,
    "email": "available_user@example.com"
  }
}
```

### ❌ Error Responses:

- **Missing Email Parameter (`400 Bad Request`)**:
  ```json
  {
    "status": "error",
    "code": 400,
    "message": "Missing email parameter"
  }
  ```

- **Invalid Email Format (`400 Bad Request`)**:
  ```json
  {
    "status": "error",
    "code": 400,
    "message": "Invalid email address format"
  }
  ```

### cURL Examples:

**Via POST body:**
```bash
curl -X POST http://localhost:3000/api/user/checkUserByEmail \
  -H "Content-Type: application/json" \
  -d '{"email":"shubham@example.com"}'
```

**Via GET query param:**
```bash
curl -X GET "http://localhost:3000/api/user/check-by-email?email=shubham@example.com"
```

---

## 👑 Role-Based Access Control (RBAC) Endpoints

### RBAC Overview & Permissions Matrix
| Role | Table | Access Level | Description |
| :--- | :--- | :--- | :--- |
| **`admin`** | `staff` | **Full Access (`*`)** | Superuser with complete access to all data, staff management, and custom supporter permission assignments. |
| **`supporter`** | `staff` | **Dynamic Permissions** | Staff accounts created by Admin. Can only perform actions explicitly granted by the Admin (e.g. `clients.view`, `tickets.reply`). |
| **`client`** | `clients` | **Standard Customer** | Default customer role stored in dedicated `clients` table. Has fixed access to their own profile and tickets. |

---

## 23. Admin and Staff Login

Dedicated login endpoint for Admin and Supporter staff members. Authenticates directly against the `staff` table.

- **URL**: `/api/admin/auth/login` (or `/api/admin/login`)
- **Method**: `POST`
- **Authentication**: None
- **Content-Type**: `application/json`

### Request Body:
```json
{
  "email": "admin@anchor.com",
  "password": "Password123!",
  "two_factor_code": "123456"
}
```

### Success Response (`200 OK`):
```json
{
  "status": "success",
  "message": "Staff login successful",
  "data": {
    "token": "eyJhbGciOi...",
    "refresh_token": "eyJhbGciOi...",
    "expires_in": 86400,
    "token_type": "Bearer",
    "user": {
      "id": 1,
      "first_name": "Admin",
      "last_name": "User",
      "email": "admin@anchor.com",
      "role": "admin",
      "user_type": "staff",
      "is_active": 1,
      "permissions": ["*"],
      "phone_number": "+1234567890",
      "two_factor_enabled": 0
    }
  }
}
```

---

## 25. List System Permissions

Retrieves all granular permissions available in the system catalog, grouped by category. Useful for building Admin staff-permission checkboxes.

- **URL**: `/api/admin/permissions`
- **Method**: `POST`
- **Authentication**: 🔐 **Required** (Role: `admin` or staff with `staff.view` / `staff.manage`)

### Success Response (`200 OK`):
```json
{
  "status": "success",
  "message": "Permissions retrieved successfully",
  "data": {
    "count": 12,
    "permissions": [
      {
        "id": 1,
        "slug": "clients.view",
        "name": "View Clients",
        "description": "View client list and client profiles",
        "category": "Clients"
      },
      {
        "id": 5,
        "slug": "tickets.reply",
        "name": "Reply to Tickets",
        "description": "Post staff replies on customer tickets",
        "category": "Tickets"
      }
    ],
    "by_category": {
      "Clients": [
        { "slug": "clients.view", "name": "View Clients" },
        { "slug": "clients.create", "name": "Create Clients" },
        { "slug": "clients.edit", "name": "Edit Clients" },
        { "slug": "clients.delete", "name": "Delete Clients" }
      ],
      "Tickets": [
        { "slug": "tickets.view_all", "name": "View All Tickets" },
        { "slug": "tickets.reply", "name": "Reply to Tickets" },
        { "slug": "tickets.edit_status", "name": "Manage Ticket Status" },
        { "slug": "tickets.delete", "name": "Delete Tickets" }
      ],
      "Staff": [
        { "slug": "staff.view", "name": "View Staff" },
        { "slug": "staff.manage", "name": "Manage Staff" }
      ]
    }
  }
}
```

---

## 26. List Staff Members

Lists all staff members (`admin` and `supporter`) along with their active permissions.

- **URL**: `/api/admin/staff/list` (or `/api/admin/staff`)
- **Method**: `POST`
- **Authentication**: 🔐 **Required** (Role: `admin` or staff with `staff.view` / `staff.manage`)

### Success Response (`200 OK`):
```json
{
  "status": "success",
  "message": "Staff members retrieved successfully",
  "data": {
    "count": 2,
    "staff": [
      {
        "id": 1,
        "first_name": "Admin",
        "last_name": "User",
        "email": "admin@anchor.com",
        "role": "admin",
        "is_active": 1,
        "permissions": ["*"]
      },
      {
        "id": 2,
        "first_name": "Alex",
        "last_name": "Support",
        "email": "alex@anchor.com",
        "role": "supporter",
        "is_active": 1,
        "permissions": [
          "clients.view",
          "tickets.view_all",
          "tickets.reply"
        ]
      }
    ]
  }
}
```

---

## 27. Create Supporter Account

Allows an Admin to create a new `supporter` staff account and assign initial permissions.

- **URL**: `/api/admin/staff/create` (or `/api/admin/staff`)
- **Method**: `POST`
- **Authentication**: 🔐 **Required** (Role: `admin` only)
- **Content-Type**: `application/json`

### Request Body:
```json
{
  "first_name": "Alex",
  "last_name": "Support",
  "email": "alex@anchor.com",
  "password": "Password123!",
  "phone_number": "+1234567890",
  "permissions": [
    "clients.view",
    "tickets.view_all",
    "tickets.reply",
    "tickets.edit_status"
  ]
}
```

### Success Response (`201 Created`):
```json
{
  "status": "success",
  "message": "Supporter account created successfully",
  "data": {
    "user_id": 2,
    "first_name": "Alex",
    "last_name": "Support",
    "email": "alex@anchor.com",
    "role": "supporter",
    "is_active": 1,
    "permissions": [
      "clients.view",
      "tickets.edit_status",
      "tickets.reply",
      "tickets.view_all"
    ]
  }
}
```

---

## 28. Get Staff Details

Retrieves details and permissions for a specific staff member by ID.

- **URL**: `/api/admin/staff/detail` (or `/api/admin/staff/:id` / `/api/admin/staff/:id/detail`)
- **Method**: `POST`
- **Authentication**: 🔐 **Required** (Role: `admin` or staff with `staff.view`)
- **Headers**: `Content-Type: application/json`
- **Request Body**:
```json
{
  "id": 2
}
```

### Success Response (`200 OK`):
```json
{
  "status": "success",
  "message": "Staff details retrieved successfully",
  "data": {
    "staff": {
      "id": 2,
      "first_name": "Alex",
      "last_name": "Support",
      "email": "alex@anchor.com",
      "phone_number": "+1234567890",
      "role": "supporter",
      "is_active": 1,
      "permissions": [
        "clients.view",
        "tickets.reply"
      ]
    }
  }
}
```

---

## 29. Update Staff Details

Allows an Admin to update a supporter's profile information, status (`is_active: 0/1`), or reset password.

- **URL**: `/api/admin/staff/update` (or `/api/admin/staff/:id/update`)
- **Method**: `POST`
- **Authentication**: 🔐 **Required** (Role: `admin` only)
- **Content-Type**: `application/json`

### Request Body:
```json
{
  "id": 2,
  "first_name": "Alex",
  "last_name": "Senior Support",
  "phone_number": "+1987654321",
  "is_active": 1,
  "password": "NewSecretPassword123!"
}
```

### Success Response (`200 OK`):
```json
{
  "status": "success",
  "message": "Staff member updated successfully",
  "data": {
    "staff": {
      "id": 2,
      "first_name": "Alex",
      "last_name": "Senior Support",
      "email": "alex@anchor.com",
      "role": "supporter",
      "is_active": 1,
      "permissions": [
        "clients.view",
        "tickets.reply"
      ]
    }
  }
}
```

---

## 30. Update Supporter Permissions

Allows an Admin to dynamically modify the granular permissions assigned to a supporter.

- **URL**: `/api/admin/staff/permissions` (or `/api/admin/staff/:id/permissions`)
- **Method**: `POST`
- **Authentication**: 🔐 **Required** (Role: `admin` only)
- **Content-Type**: `application/json`

### Request Body:
```json
{
  "id": 2,
  "permissions": [
    "clients.view",
    "tickets.view_all",
    "tickets.reply"
  ]
}
```

### Success Response (`200 OK`):
```json
{
  "status": "success",
  "message": "Permissions updated successfully for supporter: Alex Support",
  "data": {
    "user_id": "2",
    "email": "alex@anchor.com",
    "role": "supporter",
    "permissions": [
      "clients.view",
      "tickets.reply",
      "tickets.view_all"
    ]
  }
}
```

---

## 31. Delete Supporter Account

Permanently deletes a supporter staff account. Cannot delete Admin accounts.

- **URL**: `/api/admin/staff/delete` (or `/api/admin/staff/:id/delete`)
- **Method**: `POST`
- **Authentication**: 🔐 **Required** (Role: `admin` only)
- **Content-Type**: `application/json`

### Request Body:
```json
{
  "id": 2
}
```

### Success Response (`200 OK`):
```json
{
  "status": "success",
  "message": "Supporter account (alex@anchor.com) deleted successfully",
  "data": {
    "deleted_id": 2,
    "email": "alex@anchor.com"
  }
}
```

---

## 32. List Client Accounts

Lists registered client/customer accounts with optional search and pagination.

- **URL**: `/api/admin/clients/list` (or `/api/admin/clients`)
- **Method**: `POST`
- **Authentication**: 🔐 **Required** (Role: `admin` OR supporter with `clients.view` permission)
- **Request Body (Optional Filters)**:
```json
{
  "search": "john",
  "page": 1,
  "limit": 20
}
```

### Success Response (`200 OK`):
```json
{
  "status": "success",
  "message": "Clients retrieved successfully",
  "data": {
    "count": 1,
    "total": 45,
    "page": 1,
    "limit": 20,
    "clients": [
      {
        "id": 10,
        "first_name": "John",
        "last_name": "Doe",
        "email": "client@example.com",
        "company_name": "Acme Corp",
        "phone_number": "+1234567890",
        "role": "client",
        "is_active": 1,
        "is_email_verified": 1,
        "is_phone_verified": 0,
        "created_at": "2026-03-01 10:00:00"
      }
    ]
  }
}
```

### Access Denied Response (`403 Forbidden`):
```json
{
  "status": "error",
  "message": "Access denied. You do not have permission to view clients.",
  "code": 403
}
```

---

## 33. Get Client Details

Retrieves full profile details and recent support tickets for a specific client account.

- **URL**: `/api/admin/clients/detail` (or `/api/admin/clients/:id`)
- **Method**: `POST`
- **Authentication**: 🔐 **Required** (Role: `admin` OR supporter with `clients.view` permission)
- **Headers**: `Content-Type: application/json`
- **Request Body**:
```json
{
  "id": 10
}
```

### Success Response (`200 OK`):
```json
{
  "status": "success",
  "message": "Client details retrieved successfully",
  "data": {
    "client": {
      "id": 10,
      "first_name": "John",
      "last_name": "Doe",
      "email": "client@example.com",
      "company_name": "Acme Corp",
      "street_address": "123 Main St",
      "city": "New York",
      "state": "NY",
      "postcode": "10001",
      "role": "client",
      "is_active": 1,
      "is_email_verified": 1,
      "is_phone_verified": 0
    },
    "tickets": [
      {
        "id": 5,
        "ticket_number": "TIC-482910",
        "subject": "Need help with billing invoice",
        "status": "Open",
        "priority": "High",
        "created_at": "2026-03-01 12:30:00"
      }
    ]
  }
}
```

---

## 🔒 Authenticated Request Header Guide

To make authenticated requests to future protected endpoints, pass the JWT token in the `Authorization` header:

```http
Authorization: Bearer <YOUR_JWT_TOKEN>
```

### JavaScript / Fetch Example:
```javascript
const response = await fetch('http://localhost:3000/api/auth/logout', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
    'Authorization': `Bearer ${token}`
  }
});

const data = await response.json();
console.log(data);
```

### Axios Example:
```javascript
import axios from 'axios';

const api = axios.create({
  baseURL: 'http://localhost:3000',
  headers: {
    'Authorization': `Bearer ${token}`
  }
});

const res = await api.post('/api/auth/logout');
```

---

## 📊 HTTP Status Codes Reference

| Code | Status | Usage in Anchor Backend |
| :--- | :--- | :--- |
| `200` | **OK** | Request succeeded (e.g. login, health check, logout) |
| `201` | **Created** | New resource created (e.g. user signup) |
| `400` | **Bad Request** | Missing parameters, invalid email regex, password < 6 chars |
| `401` | **Unauthorized** | Wrong password, user not found during login |
| `409` | **Conflict** | Email address is already registered |
| `500` | **Internal Server Error** | Database connection failure or unhandled exception |
