# Nexera Africa - Pi Payment System Testing Guide

## 🧪 Testing Overview

This guide helps you test and debug the Pi payment system at every stage.

---

## 1️⃣ Setup Testing Environment

### Prerequisites
- Pi Developer Account (free at https://pi.network)
- Pi Browser (download from https://www.pi.network/browser)
- Postman or cURL for API testing

### Create Test App
1. Go to https://develop.pi
2. Sign up / Login
3. Create new app
4. Name: "Nexera Africa Test"
5. Type: "Web App"
6. Sandbox mode: **ON** (for testing)
7. Copy your test **API Key**

---

## 2️⃣ Backend API Testing

### Test 1: Database Connection

**Command:**
```bash
php -r "
include 'config/db.php';
if (isset(\$db)) {
    echo 'Database: OK\n';
    \$result = \$db->query('SELECT 1');
    echo 'Query: OK\n';
} else {
    echo 'Database: FAILED\n';
}
"
```

**Expected Output:**
```
Database: OK
Query: OK
```

---

### Test 2: API Endpoint - Create Order

**Using cURL:**
```bash
curl -X POST http://localhost/api/pi_payment.php?action=create \
  -H "Content-Type: application/json" \
  -d '{
    "amount": 0.00314,
    "memo": "Test Purchase",
    "metadata": {"listing_id": 1, "test": true}
  }'
```

**Using Postman:**
1. Method: POST
2. URL: `http://localhost/api/pi_payment.php?action=create`
3. Headers: `Content-Type: application/json`
4. Body (JSON):
```json
{
  "amount": 0.00314,
  "memo": "Test Purchase",
  "metadata": {"listing_id": 1, "test": true}
}
```

**Expected Response:**
```json
{
  "status": "success",
  "orderId": "NEXERA-xxxxxx",
  "amount": 0.00314,
  "memo": "Test Purchase"
}
```

**Troubleshooting:**
- ❌ 500 error: Check PHP error logs
- ❌ Database error: Verify credentials in `config/db.php`
- ❌ Table missing: Run `PI_DATABASE_SCHEMA.sql`

---

### Test 3: Database Table Creation

**Check if table exists:**
```bash
mysql -u root -p -e "DESC nexora_db.pi_payments;"
```

**Expected Output:**
```
+------------+----------+------+-----+-----------+---+
| Field      | Type     | Null | Key | Default   | + |
+------------+----------+------+-----+-----------+---+
| id         | int      | NO   | PRI | NULL      | + |
| order_id   | varchar  | NO   | UNI | NULL      | + |
| payment_id | varchar  | YES  |     | NULL      | + |
| txid       | varchar  | YES  |     | NULL      | + |
| status     | enum     | NO   |     | initial   | + |
| metadata   | json     | YES  |     | NULL      | + |
| created_at | datetime | NO   |     | CURRENT_T | + |
| updated_at | datetime | NO   |     | CURRENT_T | + |
+------------+----------+------+-----+-----------+---+
```

---

### Test 4: Verify Table Contains Payment Records

**Query:**
```sql
SELECT * FROM pi_payments ORDER BY created_at DESC LIMIT 5;
```

**Expected Output:**
```
| id | order_id      | payment_id | txid | status      | metadata | created_at |
|----|---------------|-----------|------|-------------|----------|-----------|
| 1  | NEXERA-12345  | NULL      | NULL | initialized | {...}    | 2024-06-13|
```

---

## 3️⃣ Frontend Testing

### Test 5: Pi SDK Loading

**In Browser Console (F12):**
```javascript
// Check if Pi SDK is loaded
console.log(Pi);

// Should output Pi SDK object
// Pi.init() should be available
```

**Expected Output:**
```
Object { init: ƒ, auth: {...}, createPayment: ƒ, ... }
```

**If Pi is undefined:**
- ❌ SDK script not loading: Check network tab
- ❌ HTTPS required: Ensure site is HTTPS
- ❌ In Pi Browser: Must be in Pi Browser, not regular browser

---

### Test 6: Pi SDK Initialization

**In Browser Console:**
```javascript
Pi.init({ version: "2.0", sandbox: true });
console.log("Pi SDK initialized");
```

**Expected Output:**
```
Pi SDK initialized
```

---

### Test 7: Standalone Checkout Page

1. Open `checkout.html` in **Pi Browser ONLY**
   ```
   https://nexeraafrica.com/checkout.html
   ```

2. You should see:
   - [ ] Title "Nexera Africa - Checkout"
   - [ ] Purple connect button "Connect Pi Wallet"
   - [ ] Status message area

3. Click "Connect Pi Wallet"
   - [ ] Pi authentication dialog appears
   - [ ] After auth: username displays
   - [ ] "Complete Payment" button becomes active

4. Click "Complete Payment with Pi"
   - [ ] Payment processing message shows
   - [ ] Pi Wallet overlay appears
   - [ ] Can see payment confirmation

---

### Test 8: Listing Purchase Page

1. Create a test listing
   - Title: "Test Product"
   - Price: 0.00314 Pi
   - Status: Approved

2. Open purchase page:
   ```
   https://nexeraafrica.com/payment.php?id=1
   ```

3. You should see:
   - [ ] Listing details (title, category, description)
   - [ ] Amount display: "0.00314 Pi"
   - [ ] "Pay with Pi Wallet" button
   - [ ] Status message area

4. Click "Pay with Pi Wallet"
   - [ ] Status: "Creating order..."
   - [ ] Then: "Opening Pi Wallet..."
   - [ ] Pi authentication if needed
   - [ ] Pi Wallet payment overlay

---

## 4️⃣ Debugging Issues

### Issue: "Pi is not defined"

**Solution:**
```javascript
// Check SDK is loaded
if (typeof Pi === 'undefined') {
    console.log('SDK not loaded yet. Waiting...');
    // Wait and retry
    setTimeout(() => {
        Pi.init({ version: "2.0", sandbox: true });
    }, 1000);
}
```

### Issue: "HTTPS required" Error

**Solution:**
```bash
# Verify SSL certificate
openssl s_client -connect nexeraafrica.com:443 -tls1_2

# Certificate should be valid and not expired
```

### Issue: "Authentication Failed"

**Debugging:**
```javascript
// In console during authentication
Pi.authenticate(
    ['username', 'payments'],
    function(auth) {
        console.log('Auth success:', auth);
    }
)
.catch(e => console.error('Auth error:', e));
```

### Issue: "Payment Stuck at Approval"

**Check:**
1. Network tab → Look for `/api/pi_payment.php?action=approve` request
2. Response should be:
   ```json
   {"status": "success", "paymentId": "..."}
   ```
3. If 500 error:
   - Check PHP error log
   - Verify API Key is correct
   - Check MySQL is running

---

### Issue: Database Not Saving Orders

**Debug Script:**
```php
<?php
// test_db.php
include 'config/db.php';

try {
    // Test insert
    $stmt = $db->prepare(
        "INSERT INTO pi_payments (order_id, status, metadata) 
         VALUES (?, 'initialized', ?)"
    );
    $result = $stmt->execute([
        'TEST-' . time(),
        json_encode(['test' => true])
    ]);
    
    echo $result ? "Insert: OK\n" : "Insert: FAILED\n";
    
    // Test query
    $rows = $db->query("SELECT COUNT(*) as count FROM pi_payments")->fetch();
    echo "Total records: " . $rows['count'] . "\n";
    
} catch (Exception $e) {
    echo "Error: " . $e->getMessage() . "\n";
}
?>
```

**Run:**
```bash
php test_db.php
```

---

## 5️⃣ Network Debugging

### Check Request/Response Flow

**In Browser DevTools → Network Tab:**

1. **Create Order Request**
   ```
   POST /api/pi_payment.php?action=create
   Status: 200 ✓
   Response: {"status":"success","orderId":"NEXERA-...","amount":0.00314}
   ```

2. **Approve Request**
   ```
   POST /api/pi_payment.php?action=approve
   Status: 200 ✓
   Response: {"status":"success","paymentId":"..."}
   ```

3. **Complete Request**
   ```
   POST /api/pi_payment.php?action=complete
   Status: 200 ✓
   Response: {"status":"success","txid":"..."}
   ```

### Monitor with cURL

```bash
# Watch all requests in real-time
curl -v -X POST https://nexeraafrica.com/api/pi_payment.php?action=create \
  -H "Content-Type: application/json" \
  -d '{"amount":0.00314,"memo":"Test"}'
```

Look for:
- `HTTP/2 200` (success)
- Proper JSON response
- `Content-Type: application/json` header

---

## 6️⃣ Complete Payment Flow Test

### Full End-to-End Test

**Prerequisites:**
- [ ] Database table created
- [ ] Api/pi_payment.php accessible at https
- [ ] checkout.html loads without errors
- [ ] Pi SDK loading (check console)

**Steps:**
1. Open checkout.html in Pi Browser
2. Connect wallet
3. See payment screen
4. Complete payment
5. Check database:
   ```sql
   SELECT * FROM pi_payments ORDER BY created_at DESC LIMIT 1;
   ```
6. Verify order has:
   - [ ] `status = 'completed'`
   - [ ] `txid` not null
   - [ ] `metadata` contains listing_id

---

## 7️⃣ Performance Testing

### Load Test

```bash
# Test API under load
for i in {1..100}; do
  curl -X POST https://nexeraafrica.com/api/pi_payment.php?action=create \
    -H "Content-Type: application/json" \
    -d '{"amount":0.00314,"memo":"Load test '$i'"}' &
done
wait

# Check results
mysql -u root -p -e "SELECT COUNT(*) as total FROM nexora_db.pi_payments;"
```

---

## 8️⃣ Monitoring & Logging

### Enable Debug Logging

**In `api/pi_payment.php` add:**
```php
error_log('Payment action: ' . $_GET['action'] . ' at ' . date('Y-m-d H:i:s'));
```

**View logs:**
```bash
tail -f /var/log/php-fpm.log
tail -f /var/log/apache2/error.log
tail -f /var/log/mysql/error.log
```

---

## ✅ Final Checklist

- [ ] API endpoint responds with proper JSON
- [ ] Database table exists and is empty
- [ ] checkout.html loads without errors
- [ ] Pi SDK initializes successfully
- [ ] Can authenticate with Pi Wallet
- [ ] Payment flow completes without errors
- [ ] Order is recorded in database
- [ ] Status changes from 'initialized' to 'completed'
- [ ] TXID is saved in database
- [ ] No console errors during entire flow

---

## 🚀 Ready for Production When:

✅ All tests pass
✅ No console errors
✅ Database saving all payments
✅ Payment completes in < 30 seconds
✅ Tested on multiple devices
✅ HTTPS working perfectly
✅ Backup/restore tested
✅ Monitoring logs configured
