# COD to Prepaid Feature - Technical Specification

## Overview

Enhanced COD flow that enables conversion of Cash on Delivery orders to Prepaid orders via WhatsApp interaction, providing stores with better payment security and potential discount offerings.

## Feature Flow

```
Admin Enables Config → BOT API Called → COD Order Placed → Campaign Triggered → 
WhatsApp Message → Customer Reply → MSG91 BOT → Store API Called → Order Updated
```

## Settings Configuration UI

### Location: WooCommerce > MSG91 Settings > COD to Prepaid Section

### Settings Fields:

1. **Enable COD to Prepaid Flow** (Toggle)
   - Master switch for entire feature
   - When OFF: All other options disabled/hidden
   - When ON: Triggers BOT API call to register store

2. **COD Confirmation** (Toggle)
   - Enables order confirmation via WhatsApp
   - Customer can confirm/cancel COD orders

3. **COD to Prepaid Conversion** (Toggle)
   - Enables conversion flow with payment links
   - Shows discount/incentive messages

4. **Message Expiry** (Number Input)
   - Time in minutes for message validity
   - Default: 1440 (24 hours)
   - Range: 30-2880 minutes

### Settings API Integration
When settings are saved:
```php
// Call MSG91 BOT API to register/update store configuration
POST https://bot.msg91.com/api/store/configure
{
    "store_url": "https://store.com",
    "store_name": "Store Name",
    "cod_confirmation_enabled": true,
    "cod_to_prepaid_enabled": true,
    "message_expiry_minutes": 1440,
    "api_endpoints": {
        "cancel_order": "/wp-json/msg91-woocommerce/v1/cancel-order",
        "get_conversion_message": "/wp-json/msg91-woocommerce/v1/conversion-message",
        "update_payment": "/wp-json/msg91-woocommerce/v1/update-payment",
        "get_customer_details": "/wp-json/msg91-woocommerce/v1/customer-details"
    },
    "auth_token": "store_global_token"
}
```

## Required API Endpoints

### 1. Cancel Order API
**Endpoint:** `POST /wp-json/msg91-woocommerce/v1/cancel-order`

**Purpose:** Cancel COD order based on customer response

**Request:**
```json
{
    "order_id": 12345,
    "customer_phone": "+919876543210",
    "reason": "customer_cancelled",
    "timestamp": 1643723400
}
```

**Response:**
```json
{
    "success": true,
    "message": "Order cancelled successfully",
    "order_id": 12345,
    "new_status": "cancelled"
}
```

### 2. Get Conversion Message API
**Endpoint:** `GET /wp-json/msg91-woocommerce/v1/conversion-message`

**Purpose:** Get store-specific message for COD to Prepaid conversion

**Request:**
```json
{
    "order_id": 12345,
    "customer_phone": "+919876543210"
}
```

**Response:**
```json
{
    "success": true,
    "message": "Convert your COD order to Prepaid and get 5% discount! Pay now: https://pay.store.com/order/12345",
    "discount_percentage": 5,
    "payment_link": "https://pay.store.com/order/12345",
    "expires_at": "2024-01-01T15:30:00Z"
}
```

### 3. Update Payment API
**Endpoint:** `POST /wp-json/msg91-woocommerce/v1/update-payment`

**Purpose:** Convert COD order to Prepaid and mark as paid

**Request:**
```json
{
    "order_id": 12345,
    "customer_phone": "+919876543210",
    "payment_method": "prepaid",
    "transaction_id": "txn_abc123",
    "amount_paid": 1425.00,
    "discount_applied": 75.00,
    "timestamp": 1643723400
}
```

**Response:**
```json
{
    "success": true,
    "message": "Payment updated successfully",
    "order_id": 12345,
    "old_payment_method": "cod",
    "new_payment_method": "prepaid",
    "payment_status": "paid",
    "discount_applied": 75.00
}
```

### 4. Get Customer Details API
**Endpoint:** `GET /wp-json/msg91-woocommerce/v1/customer-details`

**Purpose:** Get customer information and order history (Future use)

**Request:**
```json
{
    "customer_phone": "+919876543210",
    "include_orders": true,
    "order_limit": 10
}
```

**Response:**
```json
{
    "success": true,
    "customer": {
        "id": 123,
        "name": "John Doe",
        "email": "john@example.com",
        "phone": "+919876543210",
        "total_orders": 5,
        "total_spent": 7500.00
    },
    "recent_orders": [
        {
            "id": 12345,
            "status": "completed",
            "total": 1500.00,
            "date": "2024-01-01T10:00:00Z"
        }
    ]
}
```

## Authentication & Security

### Global Token Authentication
- Single token for all endpoints: `Bearer {GLOBAL_TOKEN}`
- Token generated on plugin activation
- Same token used for all store APIs

### Security Measures
- **Timestamp Verification:** 5-minute window for request validity
- **Phone Verification:** Match customer phone with order
- **Order Validation:** Ensure order exists and is COD
- **Expiry Check:** Validate message hasn't expired
- **Rate Limiting:** Prevent abuse (WordPress default)

## Database Schema Changes

### New Options Table Entries
```php
'msg91_woocommerce_cod_to_prepaid_enabled' => false
'msg91_woocommerce_cod_confirmation_enabled' => false  
'msg91_woocommerce_cod_conversion_enabled' => false
'msg91_woocommerce_message_expiry_minutes' => 1440
'msg91_woocommerce_conversion_discount_percent' => 5
'msg91_woocommerce_conversion_message_template' => 'Convert your COD order...'
```

### Order Meta Fields
```php
'_msg91_cod_message_sent_at' => timestamp
'_msg91_cod_message_expires_at' => timestamp  
'_msg91_cod_conversion_offered' => boolean
'_msg91_cod_converted_to_prepaid' => boolean
'_msg91_cod_discount_applied' => amount
'_msg91_cod_original_total' => amount
```

## Implementation Files

### New/Modified Files:
```
includes/services/CODToPrepaidService.php     # NEW - Main service class
includes/core/class-settings.php             # MODIFY - Add COD settings
includes/views/admin/settings-page.php       # MODIFY - Add settings UI
assets/css/settings.css                      # MODIFY - Settings styling
assets/js/settings.js                        # MODIFY - Settings interactions
```

### Service Class Structure:
```php
class MSG91_WooCommerce_CODToPrepaidService {
    public function register_endpoints()        # Register all 4 endpoints
    public function handle_cancel_order()       # Cancel order logic
    public function handle_conversion_message()  # Get conversion message
    public function handle_update_payment()     # Update payment method
    public function handle_customer_details()   # Get customer info
    public function verify_message_expiry()     # Check message validity
    public function apply_conversion_discount()  # Apply discount logic
}
```

## BOT Integration Points

### Store Registration
When COD to Prepaid is enabled, plugin calls:
```javascript
// MSG91 BOT API
POST /api/store/register
{
    "store_url": "https://store.com",
    "endpoints": {...},
    "settings": {...}
}
```

### Message Flow Handling
BOT receives customer replies and determines action:
- "Yes" → Call conversion message API
- "Pay" → Call update payment API  
- "Cancel" → Call cancel order API
- "Details" → Call customer details API

## Error Handling

### Common Error Responses:
```json
{
    "code": "message_expired",
    "message": "This message has expired",
    "data": {"status": 410}
}

{
    "code": "invalid_order",
    "message": "Order not found or not COD",
    "data": {"status": 404}
}

{
    "code": "phone_mismatch", 
    "message": "Customer phone does not match",
    "data": {"status": 403}
}
```

## Testing Scenarios

1. **Settings Enable/Disable:** Verify BOT API calls
2. **Message Expiry:** Test expired message handling
3. **Order Conversion:** COD to Prepaid flow
4. **Payment Updates:** Transaction processing
5. **Error Cases:** Invalid orders, expired messages
6. **Security:** Token validation, phone verification

## Success Metrics

- **Conversion Rate:** % of COD orders converted to Prepaid
- **Response Time:** API endpoint performance
- **Error Rate:** Failed conversions/cancellations
- **Customer Satisfaction:** Reduced COD abandonment

---

**Implementation Priority:**
1. Settings UI and BOT registration
2. Cancel Order & Conversion Message APIs
3. Update Payment API with discount logic
4. Customer Details API (future enhancement)
5. Comprehensive testing and error handling
