# Cannabus Loyalty API Documentation

## Overview
This document describes the REST API endpoints for the Cannabus Loyalty Program. The API allows you to:
1. Process loyalty points when orders are completed
2. Calculate discounts when users apply loyalty points to orders

## Base URL
```
http://localhost/cannabus/api
```
*Update the `baseUrl` variable in Postman collection to match your environment*

---

## Endpoints

### 1. Process Loyalty Points (Order Completed)

**Endpoint:** `POST /api/processLoyaltyPoints`

**Description:** Processes loyalty points when an order is marked as completed. This endpoint automatically:
- Validates the order exists and is completed
- Prevents duplicate processing
- Calculates points based on order price
- Applies reward rules (double points days, VIP promotions, tier bonuses)
- Awards points to customer
- Updates customer tier/level
- Creates loyalty history record

**Request Parameters:**
| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| orderId | string | Yes | Order ID that was completed |

**Request Example:**
```
POST /api/processLoyaltyPoints
Content-Type: application/x-www-form-urlencoded

orderId=order123
```

**Success Response (200 OK):**
```json
{
    "success": true,
    "message": "Loyalty points processed successfully",
    "data": {
        "orderId": "order123",
        "customerId": "customer456",
        "orderTotal": 150.00,
        "points": {
            "earned": 150,
            "basePoints": 150.0,
            "multiplier": 1.0,
            "pointsBefore": 500,
            "pointsAfter": 650,
            "breakdown": [
                {
                    "type": "double_points_day",
                    "multiplier": 2.0,
                    "description": "Double Points Day Bonus"
                }
            ]
        },
        "tier": {
            "oldTier": "silver",
            "newTier": "gold",
            "tierChanged": true
        },
        "birthdayBonusAwarded": false
    }
}
```

**Error Responses:**
- `400 Bad Request` - Missing orderId
- `404 Not Found` - Order not found
- `400 Bad Request` - Order is not completed
- `409 Conflict` - Points already processed for this order

---

### 2. Apply Loyalty Points (Calculate Discount)

**Endpoint:** `POST /api/applyLoyaltyPoints`

**Description:** Calculates discount when user applies loyalty points to an order. This endpoint:
- Fetches user's current loyalty points
- Calculates discount based on points (100 points = $1 by default)
- Applies discount to total amount
- Returns discounted price and updated tier/level after points are applied

**Note:** This is a **calculation endpoint** - it does NOT actually redeem the points. Points are redeemed when the order is completed.

**Request Parameters:**
| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| userId | string | Yes | Customer User ID |
| totalAmount | float | Yes | Order total amount before discount |
| pointsToRedeem | integer | No | Specific number of points to redeem (if not provided, uses all available points) |

**Request Example (Use All Points):**
```
POST /api/applyLoyaltyPoints
Content-Type: application/x-www-form-urlencoded

userId=customer123
totalAmount=150.00
```

**Request Example (Specific Points):**
```
POST /api/applyLoyaltyPoints
Content-Type: application/x-www-form-urlencoded

userId=customer123
totalAmount=150.00
pointsToRedeem=500
```

**Success Response (200 OK):**
```json
{
    "success": true,
    "message": "Loyalty points applied successfully",
    "data": {
        "userId": "customer123",
        "pricing": {
            "originalAmount": 150.00,
            "discountAmount": 5.00,
            "finalAmount": 145.00,
            "pointsRedeemed": 500,
            "pointsPerDollar": 100,
            "discountPercentage": 3.33
        },
        "loyalty": {
            "pointsBefore": 1000,
            "pointsAfter": 500,
            "pointsRedeemed": 500,
            "tierBefore": "gold",
            "tierAfter": "silver",
            "tierChanged": true,
            "maxDiscountAvailable": 10.00,
            "maxPointsAvailable": 1000
        }
    }
}
```

**Error Responses:**
- `400 Bad Request` - Missing userId or totalAmount
- `404 Not Found` - Customer not found
- `400 Bad Request` - User is not a customer
- `200 OK` (with success: false) - Customer has no loyalty points

**No Points Available Response:**
```json
{
    "success": false,
    "message": "Customer has no loyalty points to redeem",
    "data": {
        "currentPoints": 0,
        "currentTier": "bronze",
        "totalAmount": 150.00,
        "discountedAmount": 150.00,
        "discount": 0,
        "pointsRedeemed": 0
    }
}
```

---

## Points Conversion Rate

**Default:** 100 points = $1 discount

The conversion rate can be configured in the loyalty settings. The system uses:
- `pointsForReward` setting (if available)
- Default: 100 points per dollar discount

**Example Calculations:**
- 500 points = $5.00 discount
- 1000 points = $10.00 discount
- 2500 points = $25.00 discount

---

## Customer Tiers

The system supports multiple customer tiers based on total loyalty points:

| Tier | Typical Threshold | Benefits |
|------|------------------|----------|
| Bronze | 0+ points | Standard rewards |
| Silver | 500+ points | 5% bonus points |
| Gold | 1000+ points | 10% bonus points |
| Platinum | 2500+ points | 15% bonus points |

*Thresholds are configurable in the admin panel*

---

## Postman Collection

### Importing the Collection

1. Open Postman
2. Click **Import** button
3. Select the file: `Cannabus_Loyalty_API.postman_collection.json`
4. The collection will be imported with all endpoints and example requests

### Collection Variables

Update these variables in Postman:

| Variable | Default Value | Description |
|----------|---------------|-------------|
| baseUrl | http://localhost/cannabus | Your API base URL |
| orderId | order123 | Sample order ID for testing |
| userId | customer123 | Sample customer ID for testing |
| totalAmount | 150.00 | Sample order amount |
| pointsToRedeem | 500 | Sample points to redeem |

### Using the Collection

1. **Process Loyalty Points**: Use this when an order is completed
   - Update `orderId` variable with actual order ID
   - Send request to process points

2. **Apply Loyalty Points**: Use this to calculate discount before checkout
   - Update `userId` with customer ID
   - Update `totalAmount` with order total
   - Optionally specify `pointsToRedeem` for specific amount

3. **Apply Loyalty Points (Specific Points)**: Same as above but with specific points amount

---

## Integration Examples

### Example 1: Process Points After Order Completion

```php
// In your order completion handler
$orderId = "order123";

// Call API endpoint
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://localhost/cannabus/api/processLoyaltyPoints");
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query(array('orderId' => $orderId)));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);

if ($httpCode == 200) {
    $result = json_decode($response, true);
    if ($result['success']) {
        echo "Points awarded: " . $result['data']['points']['earned'];
    }
}
```

### Example 2: Calculate Discount Before Checkout

```php
// In your checkout page
$userId = "customer123";
$totalAmount = 150.00;

// Call API endpoint
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://localhost/cannabus/api/applyLoyaltyPoints");
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query(array(
    'userId' => $userId,
    'totalAmount' => $totalAmount
)));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

$response = curl_exec($ch);
$result = json_decode($response, true);

if ($result['success']) {
    $finalAmount = $result['data']['pricing']['finalAmount'];
    $discount = $result['data']['pricing']['discountAmount'];
    echo "Original: $" . $totalAmount . "<br>";
    echo "Discount: $" . $discount . "<br>";
    echo "Final: $" . $finalAmount;
}
```

---

## Error Handling

All endpoints return consistent error responses:

```json
{
    "success": false,
    "message": "Error description here"
}
```

Common HTTP Status Codes:
- `200 OK` - Request successful (even if no points available)
- `400 Bad Request` - Invalid parameters
- `404 Not Found` - Resource not found
- `409 Conflict` - Points already processed
- `500 Internal Server Error` - Server error

---

## Testing Checklist

- [ ] Import Postman collection
- [ ] Update baseUrl variable
- [ ] Test Process Loyalty Points with valid order ID
- [ ] Test Process Loyalty Points with invalid order ID
- [ ] Test Apply Loyalty Points with valid customer
- [ ] Test Apply Loyalty Points with customer having no points
- [ ] Test Apply Loyalty Points with specific points amount
- [ ] Verify tier changes are reflected correctly
- [ ] Verify discount calculations are correct

---

## Support

For issues or questions, contact the development team.
