# Unified Payment System - Quick Start Guide

## 🚀 Quick Integration (5 Minutes)

### Step 1: Import
```javascript
import { useState } from 'react';
import { UnifiedPaymentModal } from '@/components/modals/unified-payment-modal';
import toast from 'react-hot-toast';
```

### Step 2: Add State
```javascript
const [paymentModalOpen, setPaymentModalOpen] = useState(false);
const [paymentData, setPaymentData] = useState(null);
```

### Step 3: Create Handler
```javascript
const handlePayment = (item) => {
  setPaymentData({
    type: 'order', // or 'invoice', 'quotation'
    id: item.id,
    amount: item.amount,
    reference: item.reference,
    description: `Payment for ${item.reference}`,
  });
  setPaymentModalOpen(true);
};
```

### Step 4: Add Button
```javascript
<button onClick={() => handlePayment(item)}>
  Pay Now
</button>
```

### Step 5: Add Modal
```javascript
<UnifiedPaymentModal
  isOpen={paymentModalOpen}
  onClose={() => setPaymentModalOpen(false)}
  paymentData={paymentData}
  onSuccess={() => {
    toast.success('Payment completed!');
    refetch(); // Refresh your data
  }}
  onError={() => toast.error('Payment failed')}
/>
```

## 📋 Payment Data Structure

```javascript
{
  type: 'order' | 'invoice' | 'quotation',  // Required
  id: number,                                 // Required
  amount: number,                             // Required
  reference: string,                          // Required (display)
  description: string,                        // Required (display)
  metadata: {                                 // Optional
    // Any additional data you want to track
    orderNumber: string,
    invoiceNumber: string,
    customField: any,
  }
}
```

## 🎯 Common Use Cases

### Pay an Order
```javascript
setPaymentData({
  type: 'order',
  id: order.id,
  amount: order.total_amount,
  reference: order.order_number,
  description: `Payment for Order #${order.order_number}`,
});
```

### Pay an Invoice
```javascript
setPaymentData({
  type: 'invoice',
  id: invoice.id,
  amount: invoice.amount_due,
  reference: invoice.invoice_number,
  description: `Payment for Invoice #${invoice.invoice_number}`,
});
```

### Pay Multiple Invoices
```javascript
setPaymentData({
  type: 'invoice',
  id: firstInvoice.id,
  amount: totalAmount,
  reference: 'Multiple Invoices',
  description: `Payment for ${count} invoices`,
  metadata: {
    invoiceIds: invoiceIds,
    count: count,
  },
});
```

## 🔧 Advanced Usage

### With Custom Success Handler
```javascript
<UnifiedPaymentModal
  isOpen={paymentModalOpen}
  onClose={() => setPaymentModalOpen(false)}
  paymentData={paymentData}
  onSuccess={(result) => {
    console.log('Payment result:', result);
    toast.success('Payment completed!');
    
    // Custom logic
    if (result.status === 'completed') {
      router.push(`/orders/${paymentData.metadata.orderNumber}`);
    }
    
    refetch();
  }}
  onError={(error) => {
    console.error('Payment error:', error);
    toast.error(`Payment failed: ${error.message}`);
  }}
/>
```

### With Loading State
```javascript
const [isProcessing, setIsProcessing] = useState(false);

<UnifiedPaymentModal
  isOpen={paymentModalOpen}
  onClose={() => !isProcessing && setPaymentModalOpen(false)}
  paymentData={paymentData}
  onSuccess={() => {
    setIsProcessing(false);
    toast.success('Payment completed!');
  }}
  onError={() => {
    setIsProcessing(false);
    toast.error('Payment failed');
  }}
/>
```

## 🎨 Styling

The modal uses your portal's theme automatically:
- Primary color for buttons
- Consistent spacing and typography
- Responsive design
- Accessible components

## 🐛 Troubleshooting

### Modal doesn't open
```javascript
// Check state
console.log('Modal open:', paymentModalOpen);
console.log('Payment data:', paymentData);

// Ensure both are set
setPaymentData({ ... });
setPaymentModalOpen(true);
```

### Payment doesn't initiate
```javascript
// Check payment data structure
console.log('Payment data:', paymentData);

// Ensure all required fields are present
// type, id, amount, reference, description
```

### Success callback not firing
```javascript
// Check if onSuccess is defined
<UnifiedPaymentModal
  onSuccess={(result) => {
    console.log('Success callback fired:', result);
    // Your logic here
  }}
/>
```

## 📚 API Reference

### UnifiedPaymentModal Props

| Prop | Type | Required | Description |
|------|------|----------|-------------|
| `isOpen` | boolean | Yes | Controls modal visibility |
| `onClose` | function | Yes | Called when modal should close |
| `paymentData` | object | Yes | Payment information (see structure above) |
| `onSuccess` | function | No | Called when payment succeeds |
| `onError` | function | No | Called when payment fails |

### Payment Data Object

| Field | Type | Required | Description |
|-------|------|----------|-------------|
| `type` | string | Yes | 'order', 'invoice', or 'quotation' |
| `id` | number | Yes | ID of the item to pay |
| `amount` | number | Yes | Amount to pay |
| `reference` | string | Yes | Reference number for display |
| `description` | string | Yes | Payment description |
| `metadata` | object | No | Additional data |

## 💡 Tips

1. **Always set payment data before opening modal**
   ```javascript
   setPaymentData({ ... });
   setPaymentModalOpen(true);
   ```

2. **Refresh data on success**
   ```javascript
   onSuccess={() => {
     refetch(); // or reload()
   }}
   ```

3. **Handle errors gracefully**
   ```javascript
   onError={(error) => {
     toast.error(error.message || 'Payment failed');
   }}
   ```

4. **Use metadata for tracking**
   ```javascript
   metadata: {
     source: 'checkout',
     campaign: 'promo2024',
   }
   ```

## 🔗 Related Files

- Hook: `/src/hooks/use-payment.js`
- Modal: `/src/components/modals/unified-payment-modal.js`
- Examples: See updated pages in `/src/app/(portal)/`

## ✅ Checklist

Before deploying:
- [ ] Import modal and toast
- [ ] Add state variables
- [ ] Create payment handler
- [ ] Add button with onClick
- [ ] Add modal component
- [ ] Test payment flow
- [ ] Test success callback
- [ ] Test error handling

---

**Need help?** Check the full documentation in `PAYMENT_CONSOLIDATION_FINAL.md`
