# Subscription API Documentation

## Base URL
```
/subscription
```

---

## Staff / App Endpoints

### Get Subscription Status
Check the current subscription status of a company.

**POST** `/subscription/status`

**Request Body:**
```json
{
  "reg_id": 1
}
```

**Response (Success):**
```json
{
  "status": "success",
  "data": {
    "reg_id": 1,
    "company_name": "ABC Finance",
    "plan": {
      "id": 1,
      "name": "Annual Plan",
      "price": 5000.00
    },
    "subscription_amount": 5000.00,
    "subscription_valid_until": "2027-07-14",
    "subscription_status": "active",
    "subscription_start_date": "2026-07-14",
    "is_active": true,
    "remaining_days": 365,
    "show_warning": false
  }
}
```

**Response Fields:**
| Field | Description |
|---|---|
| `is_active` | `true` if subscription is not expired |
| `remaining_days` | Days left until expiry |
| `show_warning` | `true` if 30 days or less remaining, or expired |
| `subscription_amount` | Custom amount set for this company |

> **Staff Action:** If `show_warning` is `true`, display a banner/alert to the user. No access is blocked.

---

### Get Plan Details
Get the active subscription plan details.

**POST** `/subscription/plan`

**Response:**
```json
{
  "status": "success",
  "data": {
    "id": 1,
    "name": "Annual Plan",
    "slug": "annual-plan",
    "description": "One year subscription plan",
    "price": 5000.00,
    "billing_interval": "yearly",
    "is_active": true
  }
}
```

---

### Get Payment History
View all past payments for a company.

**POST** `/subscription/history`

**Request Body:**
```json
{
  "reg_id": 1
}
```

**Response:**
```json
{
  "status": "success",
  "count": 2,
  "data": [
    {
      "id": 2,
      "reg_id": 1,
      "plan_id": 1,
      "amount": 5000.00,
      "razorpay_order_id": "order_ABC123",
      "razorpay_payment_id": "pay_XYZ789",
      "payment_method": "razorpay",
      "status": "completed",
      "paid_by": null,
      "valid_from": "2026-07-14",
      "valid_until": "2027-07-14",
      "notes": null,
      "created_at": "2026-07-14T10:30:00.000Z",
      "plan": {
        "id": 1,
        "name": "Annual Plan",
        "slug": "annual-plan",
        "price": 5000.00
      }
    },
    {
      "id": 1,
      "reg_id": 1,
      "plan_id": 1,
      "amount": 4000.00,
      "razorpay_order_id": null,
      "razorpay_payment_id": null,
      "payment_method": "manual",
      "status": "completed",
      "paid_by": "Super Admin",
      "valid_from": "2025-07-14",
      "valid_until": "2026-07-14",
      "notes": "Initial subscription",
      "created_at": "2025-07-14T10:30:00.000Z",
      "plan": {
        "id": 1,
        "name": "Annual Plan",
        "slug": "annual-plan",
        "price": 5000.00
      }
    }
  ]
}
```

---

### Online Payment (Razorpay)

#### Step 1: Create Order

**POST** `/subscription/create-order`

**Request Body:**
```json
{
  "reg_id": 1,
  "plan_id": 1,
  "amount": 5000
}
```

> `amount` is optional. If not provided, uses the company's `subscription_amount` or falls back to plan price.

**Response:**
```json
{
  "status": "success",
  "data": {
    "order_id": "order_ABC123",
    "amount": 500000,
    "currency": "INR",
    "key": "rzp_test_xxx",
    "plan_id": 1,
    "plan_name": "Annual Plan",
    "history_id": 1
  }
}
```

> `amount` in response is in **paise** (₹5000 = 500000 paise). Use `key` to initialize Razorpay client.

#### Step 2: Verify Payment

**POST** `/subscription/verify`

**Request Body:**
```json
{
  "reg_id": 1,
  "razorpay_order_id": "order_ABC123",
  "razorpay_payment_id": "pay_XYZ789",
  "razorpay_signature": "abc123..."
}
```

**Response (Success):**
```json
{
  "status": "success",
  "message": "Payment verified and subscription activated",
  "data": {
    "plan_id": 1,
    "amount": 5000.00,
    "valid_from": "2026-07-14",
    "valid_until": "2027-07-14"
  }
}
```

**Response (Signature Failed):**
```json
{
  "status": "error",
  "message": "Signature verification failed"
}
```

---

## Admin Endpoints

> All admin endpoints require JWT token in `Authorization: Bearer <token>` header.

### View All Company Subscriptions

**GET** `/subscription/admin/all`

**Response:**
```json
{
  "status": "success",
  "count": 3,
  "data": [
    {
      "reg_id": 1,
      "company_name": "ABC Finance",
      "plan": { "id": 1, "name": "Annual Plan" },
      "subscription_amount": 5000.00,
      "subscription_valid_until": "2027-07-14",
      "subscription_status": "active",
      "is_active": true,
      "remaining_days": 365,
      "show_warning": false
    },
    {
      "reg_id": 2,
      "company_name": "XYZ Loans",
      "plan": null,
      "subscription_amount": null,
      "subscription_valid_until": null,
      "subscription_status": "active",
      "is_active": false,
      "remaining_days": 0,
      "show_warning": true
    }
  ]
}
```

---

### Create Plan

**POST** `/subscription/admin/create-plan`

**Request Body:**
```json
{
  "name": "Annual Plan",
  "slug": "annual-plan",
  "description": "One year subscription plan",
  "price": 5000
}
```

> `slug` is auto-generated from `name` if not provided.

**Response:**
```json
{
  "status": "success",
  "message": "Plan created",
  "data": {
    "id": 1,
    "name": "Annual Plan",
    "slug": "annual-plan",
    "price": 5000.00,
    "billing_interval": "yearly",
    "is_active": true
  }
}
```

---

### Update Plan Price

**POST** `/subscription/admin/update-plan`

**Request Body:**
```json
{
  "plan_id": 1,
  "price": 7500,
  "name": "Annual Plan Pro",
  "description": "Updated plan description"
}
```

> All fields except `plan_id` are optional. Only send what you want to change.

**Response:**
```json
{
  "status": "success",
  "message": "Plan updated",
  "data": {
    "id": 1,
    "name": "Annual Plan Pro",
    "slug": "annual-plan",
    "price": 7500.00,
    "billing_interval": "yearly",
    "is_active": true
  }
}
```

---

### Manually Assign Subscription

Assign or renew a subscription without online payment.

**POST** `/subscription/admin/assign`

**Request Body:**
```json
{
  "reg_id": 1,
  "amount": 5000,
  "paid_by": "Super Admin",
  "valid_from": "2026-07-14",
  "notes": "Renewal for next year"
```

**Response:**
```json
{
  "status": "success",
  "message": "Subscription assigned successfully",
  "data": {
    "reg_id": 1,
    "amount": 5000,
    "valid_from": "2026-07-14",
    "valid_until": "2027-07-14"
  }
}
```

> If `valid_from` is not provided, today's date is used. Subscription is always set for 365 days.

---

### View Payment History by Company

**GET** `/subscription/admin/history/:reg_id`

**Response:** Same format as `/subscription/history` above.

---

## Subscription Status Flow

```
                  ┌──────────────┐
                  │   No Plan    │
                  │  assigned    │
                  └──────┬───────┘
                         │
          Admin assigns / User pays
                         │
                         ▼
                  ┌──────────────┐
                  │    Active    │ ← 365 days from payment
                  │  is_active   │
                  └──────┬───────┘
                         │
                    30 days left
                         │
                         ▼
                  ┌──────────────┐
                  │   Warning    │ ← show_warning = true
                  │   Banner     │
                  └──────┬───────┘
                         │
                   365 days pass
                         │
                         ▼
                  ┌──────────────┐
                  │   Expired    │ ← is_active = false
                  │  Warning     │    show_warning = true
                  └──────────────┘
                  (No login block, just warning)
```

---

## Mobile App Integration

### Show Subscription Banner
```javascript
const response = await fetch('/subscription/status', {
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify({ reg_id: companyId })
});
const { data } = await response.json();

if (data.show_warning) {
  if (data.is_active) {
    // Show: "Your subscription expires in X days"
    showExpiryBanner(`Expires in ${data.remaining_days} days`);
  } else {
    // Show: "Your subscription has expired"
    showExpiredBanner();
  }
}
```

### Razorpay Checkout
```javascript
const { data } = await createOrder({ reg_id, plan_id });

const options = {
  key: data.key,
  amount: data.amount,
  currency: data.currency,
  order_id: data.order_id,
  handler: async (response) => {
    await verifyPayment({
      reg_id,
      razorpay_order_id: response.razorpay_order_id,
      razorpay_payment_id: response.razorpay_payment_id,
      razorpay_signature: response.razorpay_signature
    });
  }
};

const rzp = new Razorpay(options);
rzp.open();
```

---

## Database Tables

### `subscription_plan`
| Column | Type | Description |
|---|---|---|
| `id` | INT PK | Plan ID |
| `name` | VARCHAR(100) | Plan name |
| `slug` | VARCHAR(50) | Unique URL slug |
| `description` | TEXT | Plan description |
| `price` | DECIMAL(10,2) | Base yearly price |
| `billing_interval` | VARCHAR(50) | Always `yearly` |
| `is_active` | BOOLEAN | Active/inactive |

### `subscription_history`
| Column | Type | Description |
|---|---|---|
| `id` | INT PK | Record ID |
| `reg_id` | INT FK | Reference to registration |
| `plan_id` | INT FK | Reference to subscription_plan |
| `amount` | DECIMAL(10,2) | Amount paid |
| `razorpay_order_id` | VARCHAR(100) | Razorpay order ID |
| `razorpay_payment_id` | VARCHAR(100) | Razorpay payment ID |
| `razorpay_signature` | VARCHAR(255) | Razorpay HMAC signature |
| `payment_method` | VARCHAR(50) | `razorpay` or `manual` |
| `status` | VARCHAR(50) | `created`, `completed`, `failed` |
| `paid_by` | VARCHAR(100) | Admin name (for manual) |
| `valid_from` | DATE | Subscription start date |
| `valid_until` | DATE | Subscription end date |
| `notes` | TEXT | Remarks |

### `registration` (added columns)
| Column | Type | Description |
|---|---|---|
| `plan_id` | INT FK | Active subscription plan |
| `subscription_valid_until` | DATE | Expiry date |
| `subscription_status` | VARCHAR(50) | `active`, `expired`, `trial` |
| `subscription_amount` | DECIMAL(10,2) | Custom amount for this company |
| `subscription_start_date` | DATE | Current subscription start |
