# Post-Payment Redirect to Invoice Feature

## Overview

This feature automatically redirects users to the **prediction-details** page showing their **invoice** immediately after a successful payment (both M-Pesa and Card payments).

## What Changed

### Updated Components

#### 1. **PaymentModal.js** (Frontend)
- Added `useNavigate` hook from react-router-dom
- Accepts `prediction` prop (optional, but required for redirect)
- On successful M-Pesa payment:
  - Polls payment status
  - On completion, navigates to `/prediction-details` with:
    - `prediction`: The prediction object
    - `fromPayment`: `true` (indicates payment just completed)
    - `showInvoice`: `true` (tells Invoice component to show invoice)
    - `paymentReference`: The payment reference ID
- On successful Card payment:
  - Extracts payment intent ID
  - Redirects to same location as M-Pesa

**Key Code Changes:**
```javascript
navigate('/prediction-details', {
  state: {
    prediction: prediction,
    fromPayment: true,
    paymentReference: reference,
    showInvoice: true
  }
});
```

#### 2. **PredictionDetails.js** (Frontend)
- Extracts `fromPayment`, `showInvoice`, and `paymentReference` from location state
- Displays a green success banner when `fromPayment && showInvoice` are true
- Shows invoice below the banner
- Invoice component remains unchanged and handles all display logic

**Success Banner:**
```
✓ Payment successful! Your invoice is below.
```

#### 3. **PredictionItemWithPayment.js** (Frontend)
- Added `useNavigate` hook
- Builds `prediction` object from component props
- CardForm now accepts `prediction` and `navigate` props
- M-Pesa payment polling now redirects on completion
- Card payment success handler now redirects

**Redirect Flow:**
```
User clicks "Pay with M-Pesa" or "Pay with Card"
  ↓
Payment processes (M-Pesa STK / Stripe)
  ↓
Payment status: completed
  ↓
navigate('/prediction-details', { state: { prediction, fromPayment: true, ... } })
  ↓
PredictionDetails.js renders with success banner + invoice
```

#### 4. **PaymentHistory.js** (Frontend)
- Added `useNavigate` hook
- New `viewInvoice()` function that builds prediction object from payment data
- "View" button now calls `viewInvoice()` to navigate to prediction-details
- Shows invoice view for historical payments (completed status)

**Usage:**
- User clicks "View" button on a completed payment in history
- Navigates to prediction-details showing invoice with payment data

### Backend
- **No changes required** - existing endpoints continue to work
- Payment endpoints return the same data structure

## User Flow

### Flow 1: Make a New Payment → View Invoice

```
1. User browses predictions
2. Clicks "Buy Prediction" / "Pay Now" button
3. Opens PaymentModal
4. Selects payment method (M-Pesa or Card)
5. Completes payment
6. ✨ Automatically redirected to prediction-details
7. Sees success banner: "✓ Payment successful!"
8. Views full invoice with:
   - Prediction details
   - Payment info (amount, date, reference)
   - SMS bet code (if available)
```

### Flow 2: View Historical Payment → View Invoice

```
1. User navigates to Invoices page
2. Sees table of past payments
3. Clicks "View" button on completed payment
4. ✨ Navigates to prediction-details
5. Views invoice with payment data
```

## Component Props & State

### PaymentModal
```javascript
<PaymentModal
  isOpen={boolean}              // Modal visibility
  onClose={function}            // Close handler
  amount={number}               // Payment amount in KES
  onSuccess={function}          // Callback on success
  prediction={object}           // NEW: Prediction to display after payment
  // prediction shape: { 
  //   predictionId, predictionName, predictiontype, 
  //   numGames, totalOdds, selectedOdds, price 
  // }
/>
```

### PredictionDetails Location State
```javascript
location.state = {
  prediction: {
    predictionId: string,
    predictionName: string,
    // ... other prediction fields
  },
  fromPayment: boolean,        // NEW
  showInvoice: boolean,        // NEW
  paymentReference: string,    // NEW
  paymentData: object          // NEW (full payment record)
}
```

## Styling

### Success Banner
The green success banner is styled inline in `PredictionDetails.js`:
- Background: Light green (#e6ffed)
- Border: 2px solid green (#2ecc71)
- Text color: Dark green (#055a20)
- Font size: 1.05rem
- Font weight: 500
- Padding: 15px
- Margin bottom: 20px

To customize, edit `PredictionDetails.js` lines ~14-26

## Testing the Feature

### Test M-Pesa Payment → Redirect

```bash
# 1. Navigate to a prediction page
# 2. Click "Buy Prediction"
# 3. Select M-Pesa
# 4. Enter phone: 254712345678
# 5. Confirm payment in terminal/sandbox
# ✓ Should redirect to /prediction-details with success banner
```

### Test Card Payment → Redirect

```bash
# 1. Navigate to a prediction page
# 2. Click "Buy Prediction"
# 3. Select Card
# 4. Enter test card: 4242 4242 4242 4242
# 5. Confirm payment
# ✓ Should redirect to /prediction-details with success banner
```

### Test View Invoice from History

```bash
# 1. Navigate to /invoices
# 2. Click "View" on a completed payment
# ✓ Should navigate to /prediction-details with invoice
```

## Environment Variables Required

No new environment variables are needed. Existing ones work:
- `REACT_APP_STRIPE_PUBLISHABLE_KEY`
- `REACT_APP_BACKEND_URL` (if used)

## Troubleshooting

### Issue: Redirect not happening
**Solution:**
1. Check browser console for errors
2. Verify `prediction` prop is being passed to PaymentModal
3. Check that `/prediction-details` route exists in App.js
4. Verify `useNavigate()` is imported from `react-router-dom`

### Issue: Success banner not showing
**Solution:**
1. Verify `fromPayment` is `true` in location state
2. Verify `showInvoice` is `true` in location state
3. Check PredictionDetails.js has the updated code (lines ~14-26)

### Issue: Invoice not displaying
**Solution:**
1. Check that `Invoice` component is working correctly
2. Verify payment data is being passed correctly
3. Check browser console for any fetch errors

### Issue: Payment data not showing in invoice
**Solution:**
1. Verify payment record was created in Firebase
2. Check that payment reference was passed to Invoice component
3. Ensure prediction object has all required fields

## Future Enhancements

1. **Email Receipt**: Send invoice to user's email automatically
2. **SMS Confirmation**: Send payment confirmation via SMS
3. **Print Invoice**: Add print functionality to invoice
4. **Share Invoice**: Add share to email/WhatsApp features
5. **Invoice Status**: Show real-time payment status
6. **Recurring Payments**: Set up automatic recurring payments
7. **Payment History Export**: Export all invoices as CSV/PDF

## Code Files Modified

| File | Changes |
|------|---------|
| PaymentModal.js | Added navigation, redirect on payment completion |
| PredictionDetails.js | Added success banner, display payment state |
| PredictionItemWithPayment.js | Added navigation logic, pass prediction to payment |
| PaymentHistory.js | Added view invoice navigation |

## File Locations

- `Frontend Predict AI/frontend/src/components/PaymentModal.js`
- `Frontend Predict AI/frontend/src/components/PredictionDetails.js`
- `Frontend Predict AI/frontend/src/components/Events/EventList/EventItem/PredictionItemWithPayment.js`
- `Frontend Predict AI/frontend/src/components/PaymentHistory.js`

## Integration Points

### Frontend Routes
- `/prediction-details` - Existing route, now receives payment state
- `/invoices` - Shows payment history, links to invoice view

### Backend API Endpoints (Unchanged)
- `POST /api/stkpush` - M-Pesa payment initiation
- `GET /api/payments/status/:reference` - Payment status polling
- `POST /api/payments/create-card-payment` - Card payment
- `GET /api/payments/history/:userId` - Payment history

## Performance Considerations

- Redirect delay: 1500ms (allows user to see success message)
- No additional API calls required
- Navigation happens client-side only
- Invoice component renders existing state without refetch

## Security Notes

- Payment reference is stored in URL state (not stored in browser storage)
- User must be authenticated to access prediction-details
- Invoice data comes from existing Firebase payment records
- No sensitive payment data is exposed in navigation

## Support

For issues or questions:
1. Check this guide's troubleshooting section
2. Review console errors
3. Check Firebase payment records
4. Verify route configuration in App.js
