# Subscription Tiers API Documentation

## Overview
This API provides daily, weekly, and monthly subscription plans with manual payment verification.

**Base URL:** `https://your-domain.com/api`

---

## Public Endpoints (No Auth Required)

### 1. Get All Subscription Plans
```
GET /subscription-plans
```

**Response:**
```json
{
  "success": true,
  "plans": [
    {
      "id": 1,
      "name": "Daily Plan",
      "slug": "daily",
      "description": "Access all premium features for 1 day",
      "price": "5.00",
      "duration_days": 1,
      "duration_type": "daily",
      "features": ["Full access to VIP picks", "Daily predictions", "24/7 support"],
      "is_active": true,
      "sort_order": 1
    },
    {
      "id": 2,
      "name": "Weekly Plan",
      "slug": "weekly",
      "description": "Access all premium features for 7 days",
      "price": "25.00",
      "duration_days": 7,
      "duration_type": "weekly",
      "features": ["Full access to VIP picks", "Weekly predictions", "24/7 support", "Priority notifications"],
      "is_active": true,
      "sort_order": 2
    },
    {
      "id": 3,
      "name": "Monthly Plan",
      "slug": "monthly",
      "description": "Access all premium features for 30 days",
      "price": "75.00",
      "duration_days": 30,
      "duration_type": "monthly",
      "features": ["Full access to VIP picks", "Monthly predictions", "24/7 support", "Priority notifications", "Exclusive tips"],
      "is_active": true,
      "sort_order": 3
    }
  ]
}
```

### 2. Get Single Plan by Slug
```
GET /subscription-plans/{slug}
```

**Example:** `GET /subscription-plans/weekly`

**Response:**
```json
{
  "success": true,
  "plan": {
    "id": 2,
    "name": "Weekly Plan",
    "slug": "weekly",
    "description": "Access all premium features for 7 days",
    "price": "25.00",
    "duration_days": 7,
    "duration_type": "weekly",
    "features": ["Full access to VIP picks", "Weekly predictions", "24/7 support", "Priority notifications"],
    "is_active": true
  }
}
```

---

## Paystack Payment Endpoint

### Verify Paystack Payment
```
POST /subscription-plans/verify-payment
```

**Request Body:**
```json
{
  "reference": "PAYSTACK_REFERENCE_123",
  "plan_id": 2,
  "country": "ghana"
}
```

**Response (Success):**
```json
{
  "status": "success",
  "message": "Subscription activated successfully",
  "subscription": {
    "id": 5,
    "user_id": 12,
    "subscription_plan_id": 2,
    "starts_at": "2025-12-22T09:00:00.000000Z",
    "expires_at": "2025-12-29T09:00:00.000000Z",
    "status": "active",
    "amount_paid": "25.00",
    "payment_method": "paystack",
    "payment_reference": "PAYSTACK_REFERENCE_123",
    "plan": {
      "id": 2,
      "name": "Weekly Plan"
    }
  }
}
```

**Note:** If user already has active subscription, it extends the existing one instead of creating new.

---

## User Endpoints (Auth Required)

**Headers Required:**
```
Authorization: Bearer {token}
Content-Type: application/json
```

### 3. Get My Subscription Status
```
GET /my-subscription
```

**Response (No Active Subscription):**
```json
{
  "success": true,
  "has_active_subscription": false,
  "active_subscription": null,
  "history": []
}
```

**Response (With Active Subscription):**
```json
{
  "success": true,
  "has_active_subscription": true,
  "active_subscription": {
    "id": 5,
    "plan": {
      "id": 2,
      "name": "Weekly Plan",
      "slug": "weekly",
      "price": "25.00",
      "duration_days": 7
    },
    "starts_at": "2025-12-22T09:00:00.000000Z",
    "expires_at": "2025-12-29T09:00:00.000000Z",
    "days_remaining": 6,
    "status": "active"
  },
  "history": [
    {
      "id": 5,
      "subscription_plan_id": 2,
      "starts_at": "2025-12-22T09:00:00.000000Z",
      "expires_at": "2025-12-29T09:00:00.000000Z",
      "status": "active",
      "amount_paid": "25.00",
      "payment_method": "manual",
      "created_at": "2025-12-22T09:00:00.000000Z",
      "plan": {
        "id": 2,
        "name": "Weekly Plan",
        "slug": "weekly"
      }
    }
  ]
}
```

### 4. Request/Subscribe to a Plan
```
POST /subscribe
```

**Request Body:**
```json
{
  "plan_id": 2,
  "payment_reference": "PAY-12345" // optional
}
```

**Response (Success):**
```json
{
  "success": true,
  "message": "Subscription request submitted successfully",
  "subscription": {
    "id": 6,
    "user_id": 12,
    "subscription_plan_id": 2,
    "starts_at": "2025-12-22T10:00:00.000000Z",
    "expires_at": "2025-12-29T10:00:00.000000Z",
    "status": "active",
    "amount_paid": "25.00",
    "payment_method": "pending",
    "plan": {
      "id": 2,
      "name": "Weekly Plan"
    }
  }
}
```

**Response (Already Subscribed):**
```json
{
  "error": "You already have an active subscription",
  "current_subscription": { ... }
}
```

### 5. Check Subscription Access
```
GET /check-subscription-access
```

**Response:**
```json
{
  "has_access": true
}
```
or
```json
{
  "has_access": false
}
```

---

## Admin Endpoints (Auth + Admin Role Required)

**Headers Required:**
```
Authorization: Bearer {admin_token}
Content-Type: application/json
```

### 6. Get All Plans (Including Inactive)
```
GET /admin/subscription-plans
```

### 7. Create New Plan
```
POST /admin/subscription-plans
```

**Request Body:**
```json
{
  "name": "Weekend Special",
  "description": "Special weekend access",
  "price": 15.00,
  "duration_days": 3,
  "duration_type": "daily",
  "features": ["VIP picks", "Weekend predictions"],
  "is_active": true,
  "sort_order": 4
}
```

### 8. Update Plan
```
PUT /admin/subscription-plans/{id}
```

**Request Body:** (any field can be updated)
```json
{
  "price": 20.00,
  "is_active": false
}
```

### 9. Delete Plan
```
DELETE /admin/subscription-plans/{id}
```

**Note:** Cannot delete plans with active subscriptions.

### 10. Get All User Subscriptions
```
GET /admin/user-subscriptions?status=all&page=1&limit=20
```

**Query Parameters:**
- `status`: `all`, `active`, `expired`, `expiring_soon`
- `page`: Page number (default: 1)
- `limit`: Items per page (default: 20)

**Response:**
```json
{
  "success": true,
  "subscriptions": [
    {
      "id": 5,
      "user_id": 12,
      "subscription_plan_id": 2,
      "starts_at": "2025-12-22T09:00:00.000000Z",
      "expires_at": "2025-12-29T09:00:00.000000Z",
      "status": "active",
      "amount_paid": "25.00",
      "payment_method": "manual",
      "user": {
        "id": 12,
        "name": "John Doe",
        "email": "john@example.com"
      },
      "plan": {
        "id": 2,
        "name": "Weekly Plan"
      },
      "activated_by": {
        "id": 1,
        "name": "Admin"
      }
    }
  ],
  "pagination": {
    "page": 1,
    "limit": 20,
    "total": 45,
    "pages": 3
  }
}
```

### 11. Get Subscription Stats (Dashboard)
```
GET /admin/user-subscriptions/stats
```

**Response:**
```json
{
  "success": true,
  "stats": {
    "total_active": 25,
    "total_expired": 150,
    "expiring_soon": 3,
    "revenue_this_month": "1250.00",
    "by_plan": [
      { "plan": "Daily Plan", "active_subscriptions": 5 },
      { "plan": "Weekly Plan", "active_subscriptions": 12 },
      { "plan": "Monthly Plan", "active_subscriptions": 8 }
    ]
  }
}
```

### 12. Get User's Subscription History
```
GET /admin/user-subscriptions/user/{userId}
```

**Response:**
```json
{
  "success": true,
  "user": {
    "id": 12,
    "name": "John Doe",
    "email": "john@example.com"
  },
  "has_active_subscription": true,
  "active_subscription": { ... },
  "all_subscriptions": [ ... ]
}
```

### 13. Activate Subscription for User (Manual Payment Verified)
```
POST /admin/user-subscriptions/activate
```

**Request Body:**
```json
{
  "user_id": 12,
  "plan_id": 2,
  "payment_method": "momo",
  "payment_reference": "MOMO-12345",
  "admin_notes": "Payment verified via screenshot"
}
```

**Response:**
```json
{
  "success": true,
  "message": "Subscription activated successfully",
  "subscription": { ... }
}
```

**Note:** If user already has active subscription, it extends instead of creating new.

### 14. Extend Subscription
```
POST /admin/user-subscriptions/{id}/extend
```

**Request Body:**
```json
{
  "days": 7,
  "admin_notes": "Extended as compensation"
}
```

### 15. Cancel Subscription
```
POST /admin/user-subscriptions/{id}/cancel
```

**Request Body:**
```json
{
  "admin_notes": "Refund requested"
}
```

---

## Frontend Implementation Guide

### Subscription Flow (Paystack - Recommended)

```
1. User views plans → GET /subscription-plans
2. User selects plan → Initialize Paystack payment popup
3. User completes payment → Paystack returns reference
4. Frontend calls → POST /subscription-plans/verify-payment { reference, plan_id, country }
5. Backend verifies with Paystack → Subscription activated automatically
6. User has access → GET /check-subscription-access returns true
```

### Subscription Flow (Manual Payment)

```
1. User views plans → GET /subscription-plans
2. User selects plan → Show payment instructions (MoMo number, bank details)
3. User pays externally → Gets reference/receipt
4. User submits → POST /subscribe with payment_reference
5. Admin sees pending → GET /admin/user-subscriptions?status=all
6. Admin verifies payment → POST /admin/user-subscriptions/activate
7. User now has access → GET /check-subscription-access returns true
```

### Checking Access in Frontend

```javascript
// Check if user can access premium content
async function checkPremiumAccess() {
  const response = await fetch('/api/check-subscription-access', {
    headers: { 'Authorization': `Bearer ${token}` }
  });
  const data = await response.json();
  return data.has_access;
}

// Use it
if (await checkPremiumAccess()) {
  // Show premium content
} else {
  // Show subscription prompt
}
```

### Displaying Subscription Status

```javascript
async function getMySubscription() {
  const response = await fetch('/api/my-subscription', {
    headers: { 'Authorization': `Bearer ${token}` }
  });
  const data = await response.json();
  
  if (data.has_active_subscription) {
    const sub = data.active_subscription;
    console.log(`Plan: ${sub.plan.name}`);
    console.log(`Expires: ${sub.expires_at}`);
    console.log(`Days remaining: ${sub.days_remaining}`);
  } else {
    console.log('No active subscription');
  }
}
```

### Admin: Activating a Subscription

```javascript
async function activateUserSubscription(userId, planId, paymentRef) {
  const response = await fetch('/api/admin/user-subscriptions/activate', {
    method: 'POST',
    headers: {
      'Authorization': `Bearer ${adminToken}`,
      'Content-Type': 'application/json'
    },
    body: JSON.stringify({
      user_id: userId,
      plan_id: planId,
      payment_method: 'manual',
      payment_reference: paymentRef,
      admin_notes: 'Payment verified'
    })
  });
  return await response.json();
}
```

---

## Tier Games API (Like VIP/VVIP Games)

Games are organized into **groups** with booking codes, just like VIP games.

### User Endpoints (Auth Required)

#### Get My Tier Games
```
GET /my-tier-games
```

**Response:**
```json
{
  "success": true,
  "subscription": {
    "plan": "Weekly Plan",
    "expires_at": "2026-01-08T09:00:00.000000Z",
    "days_remaining": 6
  },
  "groups": [
    {
      "id": 1,
      "subscription_plan_id": 2,
      "price": null,
      "status": "won",
      "sporty_booking": "ABC123",
      "msport_booking": "DEF456",
      "betway_booking": "GHI789",
      "onex_booking": "JKL012",
      "selling": true,
      "created_at": "2026-01-01T10:00:00.000000Z",
      "games": [
        {
          "id": 1,
          "date_time": "2026-01-01T15:00:00.000000Z",
          "home_team": "Arsenal",
          "away_team": "Chelsea",
          "league": "Premier League",
          "option": "Over 2.5",
          "odds": "1.85",
          "status": "won"
        }
      ]
    }
  ]
}
```

#### Get Single Game Group
```
GET /my-tier-games/{groupId}
```

---

### Admin Endpoints (Auth + Admin Required)

#### List All Game Groups
```
GET /admin/tier-games?plan_id=2
```

**Query Parameters:**
- `plan_id` - Filter by subscription plan (1=Daily, 2=Weekly, 3=Monthly)

#### Get Groups by Date Range
```
GET /admin/tier-games/plan/{planId}?start_date=2026-01-01&end_date=2026-01-07
```

#### Get Single Group
```
GET /admin/tier-games/{id}
```

#### Create Game Group with Games
```
POST /admin/tier-games
```

**Request Body:**
```json
{
  "subscription_plan_id": 2,
  "selling": true,
  "sporty_booking": "ABC123",
  "msport_booking": "DEF456",
  "betway_booking": "GHI789",
  "onex_booking": "JKL012",
  "games": [
    {
      "date_time": "2026-01-02 15:00:00",
      "home_team": "Arsenal",
      "away_team": "Chelsea",
      "league": "Premier League",
      "option": "Over 2.5",
      "odds": 1.85
    },
    {
      "date_time": "2026-01-02 17:30:00",
      "home_team": "Barcelona",
      "away_team": "Real Madrid",
      "league": "La Liga",
      "option": "BTTS",
      "odds": 1.75
    }
  ]
}
```

**Response:**
```json
{
  "group": {
    "id": 5,
    "subscription_plan_id": 2,
    "sporty_booking": "ABC123",
    "msport_booking": "DEF456",
    "betway_booking": "GHI789",
    "onex_booking": "JKL012",
    "selling": true
  },
  "games": [...]
}
```

#### Update Game Group
```
PUT /admin/tier-games/{id}
```

**Request Body:** (same structure as create, all fields optional)

#### Update Group Status
```
POST /admin/tier-games/{id}/status
```

**Request Body:**
```json
{
  "status": "won"
}
```
Status options: `pending`, `won`, `lost`

#### Delete Game Group
```
DELETE /admin/tier-games/{id}
```

#### Transfer Group to Different Tier
```
POST /admin/tier-games/{id}/transfer
```

**Request Body:**
```json
{
  "target_plan_id": 3
}
```

Moves the entire game group (with all games and booking codes) to another tier.

#### Duplicate Group to Selected Tiers
```
POST /admin/tier-games/{id}/duplicate
```

**Request Body:**
```json
{
  "target_plan_ids": [1, 3]
}
```

Creates copies of the game group in the specified tiers.

#### Duplicate Group to ALL Tiers
```
POST /admin/tier-games/{id}/duplicate-all
```

Creates copies of the game group in all other active tiers.

#### Get Tier Games Stats
```
GET /admin/tier-games/stats
```

**Response:**
```json
{
  "success": true,
  "stats": [
    {
      "plan": "Daily Plan",
      "plan_id": 1,
      "total_groups": 10,
      "won": 7,
      "lost": 2,
      "pending": 1,
      "win_rate": "77.8%"
    },
    {
      "plan": "Weekly Plan",
      "plan_id": 2,
      "total_groups": 15,
      "won": 12,
      "lost": 2,
      "pending": 1,
      "win_rate": "85.7%"
    }
  ]
}
```

---

## Error Responses

All errors follow this format:
```json
{
  "error": "Error message here"
}
```

**Common HTTP Status Codes:**
- `200` - Success
- `201` - Created
- `400` - Bad request / Validation error
- `401` - Unauthorized (no token)
- `403` - Forbidden (not admin)
- `404` - Not found
- `500` - Server error

---

## Notes

1. **Prices** are returned as strings with 2 decimal places
2. **Dates** are in ISO 8601 format (UTC timezone)
3. **features** is an array of strings
4. **duration_type** is one of: `daily`, `weekly`, `monthly`
5. When a subscription expires, status automatically changes to `expired`
6. Expiry reminders are sent 24 hours before expiration (via cron job)
