# Quick Setup: Adding Payment History to Your App

## Step 1: Component Already Created ✅
- File: `Frontend Predict AI/frontend/src/components/PaymentHistory.js`
- CSS: `Frontend Predict AI/frontend/src/components/PaymentHistory.css`
- Backend endpoints already exist

## Step 2: Add Route to Your Router

Find your main routing file (likely `App.js`, `Routes.js`, or `index.js` in your router config) and add:

```javascript
import PaymentHistory from './components/PaymentHistory';

// Add this route to your Router
<Route path="/invoices" element={<PaymentHistory />} />
```

Or if using react-router-dom with a navigation component:

```javascript
import { BrowserRouter, Routes, Route, Link } from 'react-router-dom';
import PaymentHistory from './components/PaymentHistory';

function App() {
  return (
    <BrowserRouter>
      <nav>
        {/* Your existing navigation */}
        <Link to="/invoices">My Invoices</Link>
      </nav>
      <Routes>
        {/* Your existing routes */}
        <Route path="/invoices" element={<PaymentHistory />} />
      </Routes>
    </BrowserRouter>
  );
}
```

## Step 3: Add Link in Navigation/User Menu

Add a link to the Payment History page in your main navigation:

```javascript
// In your header/navigation component
<li>
  <Link to="/invoices" className="nav-link">
    📊 Invoices
  </Link>
</li>
```

Or in a user profile dropdown:

```javascript
<Link to="/invoices">
  📊 Payment History & Invoices
</Link>
```

## Step 4: Test the Integration

1. **Start your frontend**: `npm start` in `Frontend Predict AI/frontend/`
2. **Ensure backend is running**: `node app_sortingtype.js` in `Predict Backend/`
3. **Navigate to the page**: Visit `http://localhost:3000/invoices` (or your frontend URL)
4. **Make a test payment** and check if it appears in the history

## Step 5: Verify Backend Endpoint

Run this command to test the payment history endpoint:

```powershell
cd 'Predict Backend'
$body = @{} | ConvertTo-Json
$response = Invoke-RestMethod -Uri 'http://localhost:5000/api/payments/history/test-user-id' -Method Get -ErrorAction Stop
$response | ConvertTo-Json
```

Expected response:
```json
{
  "success": true,
  "payments": [ ... ],
  "count": 5,
  "total": 500
}
```

## Features Included

✅ View all payments with date, amount, status  
✅ Filter by payment status (Completed, Pending, Failed)  
✅ Sort by date or amount  
✅ Download invoices as PDF  
✅ See payment method (M-Pesa or Card)  
✅ View totals and statistics  
✅ Mobile responsive design  
✅ Color-coded status badges  

## Customization Examples

### Change Colors in CSS
Edit `PaymentHistory.css`:
```css
.payment-history-header {
  border-bottom: 2px solid #YOUR_COLOR;
}
```

### Change Currency (from KES to other)
Edit `PaymentHistory.js`, find all `KES` strings and replace:
```javascript
// Change this:
doc.text(`KES ${payment.amount || 0}`, ...);
// To this:
doc.text(`USD ${(payment.amount * 0.0077).toFixed(2)}`, ...);
```

### Add Email Invoice Feature
Add this function to `PaymentHistory.js`:
```javascript
const emailInvoice = async (payment) => {
  try {
    await axios.post('http://localhost:5000/api/payments/email-invoice', {
      paymentId: payment.reference,
      email: user.email
    });
    alert('Invoice sent to ' + user.email);
  } catch (err) {
    alert('Failed to send invoice');
  }
};
```

### Add to User Profile Page
```javascript
import PaymentHistory from '../PaymentHistory';

function UserProfile() {
  const [tab, setTab] = useState('profile');
  
  return (
    <div>
      <button onClick={() => setTab('profile')}>Profile</button>
      <button onClick={() => setTab('payments')}>Payments</button>
      
      {tab === 'profile' && <UserProfileForm />}
      {tab === 'payments' && <PaymentHistory />}
    </div>
  );
}
```

## Troubleshooting

### "No payments found" but I made payments
- Check that Firebase has the payments stored (look in Firebase Console)
- Verify the `userId` in payments matches the logged-in user's `uid`
- Check browser console for fetch errors

### PDF download not working
- Ensure `jspdf` is installed: `npm install jspdf`
- Check if JavaScript console shows any errors
- Make sure enough memory is available

### Backend endpoint 404
- Restart backend: `node app_sortingtype.js`
- Verify the route is mounted in `app_sortingtype.js`
- Check backend console for any errors

### Styling looks broken
- Ensure `PaymentHistory.css` is in same directory as `PaymentHistory.js`
- Check for CSS import: `import './PaymentHistory.css';`
- Clear browser cache (Ctrl+Shift+Delete or Cmd+Shift+Delete)

## Next Steps

1. ✅ Add the component to your app routing
2. ✅ Add navigation link
3. ✅ Test with a payment
4. ✅ Customize styling to match your brand
5. Consider adding:
   - Email invoice receipts
   - Refund requests
   - Invoice notes/descriptions
   - Export to CSV/Excel
   - Recurring payment setup

## Files Reference

| File | Purpose |
|------|---------|
| `PaymentHistory.js` | Main React component |
| `PaymentHistory.css` | Styling and responsive design |
| `routes/payments.js` | Backend API endpoints |
| `.env` | Stripe and M-Pesa credentials |

## Support

For issues or questions:
1. Check the console for error messages
2. Review `INVOICES_AND_PAYMENTS_GUIDE.md` for detailed documentation
3. Verify all environment variables are set
4. Ensure both frontend and backend are running
