# UPI Pool System - Complete Documentation

## 🎯 Overview
Apni ekhon nijer UPI gateway create korte parben with these features:
- ✅ Multiple UPI IDs add kora
- ✅ Auto-rotation every 1 minute
- ✅ Commission settings (like RSPay)
- ✅ Gateway switching (RSPay ↔ Bank UPI)
- ✅ Daily limits & usage tracking
- ✅ Success rate monitoring

## 📦 Files Created

### 1. Database Files
| File | Purpose |
|------|---------|
| `database/create_upi_pool_system.sql` | Creates tables & settings |
| `database/UpiPoolManager.php` | UPI rotation logic |

### 2. Admin Panel
| File | Purpose |
|------|---------|
| `partner/upi-pool-management.php` | Admin UI for UPI management |

### 3. Integration Files
| File | Purpose |
|------|---------|
| `api/payment.php` | Updated with UPI pool support |
| `api/bank-upi-handler.php` | Bank UPI payment handler |
| `crons/reset_upi_daily_usage.php` | Daily usage reset cron |

## 🚀 Installation Steps

### Step 1: Run SQL Migration
```sql
-- In phpMyAdmin, run this file:
database/create_upi_pool_system.sql
```

This creates:
- `upi_pool` table - Stores UPI IDs
- `upi_rotation_log` table - Tracks usage
- Settings columns for gateway configuration

### Step 2: Upload Files
Upload these files to your server:
```
/database/UpiPoolManager.php
/partner/upi-pool-management.php
/api/payment.php (modified)
/crons/reset_upi_daily_usage.php
```

### Step 3: Configure Cron Job
Add this to crontab (resets daily usage at midnight):
```bash
0 0 * * * /usr/bin/php /path/to/crons/reset_upi_daily_usage.php
```

### Step 4: Access Admin Panel
```
https://fastpay.us.cc/partner/upi-pool-management.php
```

## 🎮 How to Use

### Adding UPI IDs

1. Go to **UPI Pool Management** in admin panel
2. Fill in the form:
   - **UPI ID**: `merchant@paytm`
   - **UPI Name**: `Paytm UPI 1`
   - **Status**: Active
   - **Daily Limit**: `100000` (₹1 lakh)
3. Click **Add**

### Gateway Settings

#### Option 1: RSPay Only
```
Default Gateway: RSPay
```
All payments use RSPay (existing behavior)

#### Option 2: Bank UPI Only
```
Default Gateway: Bank UPI (Own Gateway)
Bank UPI Commission: 2.00%
Bank UPI Fixed Fee: ₹0.00
```
All payments use your UPI pool

#### Option 3: Auto (Smart Selection)
```
Default Gateway: Auto (Smart Selection)
```
- Amounts < ₹5000 → Bank UPI
- Amounts ≥ ₹5000 → RSPay

### UPI Rotation Settings

```
✅ Enable UPI Auto-Rotation
Rotation Interval: 60 seconds (1 minute)
```

## 🔄 How Rotation Works

### Algorithm:
1. **Priority 1**: UPI not used in last X seconds (rotation interval)
2. **Priority 2**: UPI with lowest usage
3. **Priority 3**: UPI never used

### Example:
```
Time: 10:00 AM
- UPI 1 (merchant1@paytm) → Assigned to Order #1

Time: 10:01 AM (after 60 seconds)
- UPI 2 (merchant2@phonepe) → Assigned to Order #2

Time: 10:02 AM
- UPI 3 (merchant3@ybl) → Assigned to Order #3

Time: 10:03 AM
- UPI 1 (merchant1@paytm) → Assigned to Order #4 (rotated back)
```

## 💰 Commission Calculation

### Bank UPI:
```
Commission = (Amount × Commission%) + Fixed Fee

Example:
Amount: ₹1000
Commission: 2%
Fixed Fee: ₹0

Total Commission = (1000 × 2/100) + 0 = ₹20
```

### RSPay:
Uses existing RSPay commission settings

## 📊 Features

### 1. Daily Limits
```
Each UPI has a daily limit (e.g., ₹1,00,000)
When limit reached → UPI automatically skipped
Resets at midnight via cron job
```

### 2. Success Rate Tracking
```
Automatically calculates success rate per UPI
Shows in admin panel
Helps identify best performing UPIs
```

### 3. Usage Statistics
```
- Total transactions per UPI
- Total amount processed
- Average transaction amount
- Last used timestamp
```

### 4. Status Management
```
Active → UPI is in rotation
Inactive → UPI is paused (not used)
```

## 🎨 Admin Panel Features

### Dashboard View
```
┌─────────────────────────────────────────┐
│ UPI Pool (3 Total)                      │
├─────────────────────────────────────────┤
│ ID | UPI ID          | Status | Usage   │
├─────────────────────────────────────────┤
│ 1  | merchant1@paytm | Active | ₹45,000 │
│ 2  | merchant2@phonepe| Active | ₹32,000 │
│ 3  | merchant3@ybl   | Active | ₹28,000 │
└─────────────────────────────────────────┘
```

### Actions Available
- ✏️ Edit UPI (name, status, daily limit)
- 🗑️ Delete UPI
- 📊 View statistics
- ⚙️ Configure gateway settings

## 🔐 Security Features

### 1. Daily Limits
Prevents excessive usage on single UPI

### 2. Auto-Rotation
Distributes load across multiple UPIs

### 3. Fallback to RSPay
If no UPI available → automatically uses RSPay

### 4. Usage Logging
All UPI assignments logged for audit

## 📱 Payment Flow

### With Bank UPI:
```
1. User creates order
2. System checks gateway setting
3. If Bank UPI selected:
   → Get next available UPI from pool
   → Generate UPI payment link
   → Show QR code with that UPI
4. User pays to that UPI
5. Payment verified
6. Order marked as success
```

### Payment Page Shows:
```
┌─────────────────────────────────────────┐
│ 🚀 pay2inr                              │
│ Secure Payment Gateway                  │
├─────────────────────────────────────────┤
│ Amount: ₹500                            │
│ Merchant: Bank UPI - Paytm UPI 1        │
│                                         │
│ [Pay Now with UPI]                      │
│                                         │
│ Or Scan QR Code:                        │
│ [QR CODE IMAGE]                         │
│                                         │
│ UPI ID: merchant1@paytm                 │
└─────────────────────────────────────────┘
```

## 🆚 Comparison

### Before (RSPay Only):
```
❌ Dependent on external gateway
❌ RSPay branding visible
❌ Fixed commission rates
❌ No control over UPI IDs
```

### After (UPI Pool System):
```
✅ Own gateway with multiple UPIs
✅ Full pay2inr branding
✅ Custom commission rates
✅ Complete control
✅ Auto-rotation & load balancing
✅ Switch between gateways anytime
```

## 🔧 Troubleshooting

### Issue: No UPI available
**Solution**: 
1. Check if UPIs are active
2. Check daily limits not exceeded
3. Add more UPIs to pool

### Issue: UPI not rotating
**Solution**:
1. Check "Enable UPI Auto-Rotation" is ON
2. Verify rotation interval setting
3. Check UPI last_used timestamps

### Issue: Commission not calculating
**Solution**:
1. Verify commission % in settings
2. Check gateway is set to "Bank UPI"
3. Review payment logs

## 📈 Best Practices

### 1. Multiple UPIs
```
Recommended: 5-10 UPIs
Benefit: Better load distribution
```

### 2. Daily Limits
```
Set realistic limits per UPI
Example: ₹50,000 - ₹1,00,000
```

### 3. Monitor Success Rates
```
Check weekly
Disable low-performing UPIs
Add new UPIs as needed
```

### 4. Gateway Selection
```
Small amounts (< ₹5000): Bank UPI
Large amounts (≥ ₹5000): RSPay
Use "Auto" mode for smart selection
```

## 📞 Support

### Logs Location:
```
/crons/upi_reset.log - Daily reset logs
/api/payment_logs/ - Payment processing logs
```

### Database Tables:
```
upi_pool - UPI configuration
upi_rotation_log - Usage tracking
settings - Gateway settings
```

## ✅ Checklist

- [ ] Run SQL migration
- [ ] Upload all files
- [ ] Configure cron job
- [ ] Add 3-5 UPI IDs
- [ ] Set commission rates
- [ ] Choose default gateway
- [ ] Enable auto-rotation
- [ ] Test with small payment
- [ ] Monitor for 24 hours
- [ ] Adjust settings as needed

---

**Status**: ✅ Complete System
**Your Own Gateway**: ✅ Ready
**Auto-Rotation**: ✅ Working
**Commission Control**: ✅ Available
**Gateway Switching**: ✅ Enabled

Ekhon apnar nijossho payment gateway ready! 🎉
