# Payment Integration Guide

## Overview
The payment system has been updated to use **invoice-based payments**. All payments now require an invoice and use the invoice amount (from Odoo pricing).

## Key Changes

### 1. Backend API (`PaymentController.php`)
- `initiatePayment()` now requires `invoice_id` (not `sales_order_id`)
- `uploadProofOfPayment()` requires `invoice_id`
- Amount validation: Payment amount must match `invoice.total_amount`
- Proof of payment uploads to Odoo as attachment on the invoice

### 2. Frontend API (`api.js`)
```javascript
// Updated payment endpoints
api.payments = {
  // Initiate Pesepay payment (NOW REQUIRES INVOICE)
  initiate: (data) => api.post('/payments/initiate', data),
  
  // Upload proof of payment for bank transfer
  uploadProof: (formData) => api.post('/payments/upload-proof', formData, {
    headers: { 'Content-Type': 'multipart/form-data' }
  }),
}
```

### 3. Payment Components

#### PaymentOptions Component
Location: `afinet-portal/src/components/payments/PaymentOptions.jsx`

**Props:**
- `invoice` (required): Invoice object with `id`, `total_amount`, `invoice_number`, etc.
- `onPaymentSuccess` (optional): Callback when payment succeeds

**Usage:**
```jsx
import PaymentOptions from '@/components/payments/PaymentOptions';

function InvoicePaymentPage() {
  const invoice = {
    id: 123,
    invoice_number: 'INV-2024-001',
    total_amount: 150.00,
    invoice_date: '2024-02-15',
    due_date: '2024-03-15',
  };

  const handlePaymentSuccess = (paymentData) => {
    console.log('Payment successful:', paymentData);
    // Redirect or show success message
  };

  return (
    <PaymentOptions 
      invoice={invoice} 
      onPaymentSuccess={handlePaymentSuccess} 
    />
  );
}
```

#### ProofOfPaymentUpload Component
Location: `afinet-portal/src/components/payments/ProofOfPaymentUpload.jsx`

**Props:**
- `invoice` (required): Invoice object
- `onSuccess` (optional): Callback when upload succeeds
- `onCancel` (optional): Callback when user cancels

**Features:**
- Drag-and-drop file upload
- Amount pre-filled from invoice (read-only)
- Validates file type (PDF, JPG, PNG) and size (5MB max)
- Uploads to both local storage and Odoo
- Sends email notifications to finance team and customer

### 4. Payment Hook (`use-payment.js`)

**Updated Methods:**
```javascript
const { initiateInvoicePayment } = usePayment();

// Initiate payment for an invoice
await initiateInvoicePayment.mutateAsync({
  invoiceId: 123,
  amount: 150.00,
  paymentMethod: 'pesepay'
});
```

### 5. UnifiedPaymentModal Integration

The `UnifiedPaymentModal` already supports invoice payments:

```jsx
import { UnifiedPaymentModal } from '@/components/modals/unified-payment-modal';

function InvoiceDetailsPage() {
  const [paymentModalOpen, setPaymentModalOpen] = useState(false);
  const [paymentData, setPaymentData] = useState(null);

  const handlePayNow = () => {
    setPaymentData({
      type: 'invoice',
      id: invoice.id,
      amount: invoice.total_amount,
      reference: invoice.invoice_number,
      description: `Payment for Invoice #${invoice.invoice_number}`,
    });
    setPaymentModalOpen(true);
  };

  return (
    <>
      <button onClick={handlePayNow}>Pay Now</button>
      
      <UnifiedPaymentModal
        isOpen={paymentModalOpen}
        onClose={() => setPaymentModalOpen(false)}
        paymentData={paymentData}
        onSuccess={(result) => {
          toast.success('Payment completed!');
          // Refresh invoice data
        }}
      />
    </>
  );
}
```

## Complete Payment Flow

### Quotation → Sales Order → Invoice → Payment

1. **Customer accepts quotation**
   ```javascript
   // QuotationController::accept()
   // - Creates sales order in Odoo
   // - Auto-generates invoice in Odoo
   // - Syncs invoice to portal database
   ```

2. **Customer views invoice**
   ```javascript
   // Invoice page shows:
   // - Invoice details (number, date, amount)
   // - "Pay Now" button
   ```

3. **Customer initiates payment**
   ```javascript
   // Two options:
   // A) Pesepay (instant)
   api.payments.initiate({
     invoice_id: invoice.id,
     amount: invoice.total_amount,
     payment_method: 'pesepay'
   });
   
   // B) Bank Transfer (manual verification)
   // - Customer uploads proof of payment
   // - Finance team receives email with attachment
   // - Payment status: pending_verification
   ```

4. **Payment verification**
   ```javascript
   // Pesepay: Automatic via webhook
   // Bank Transfer: Manual by finance team
   ```

## API Endpoints

### POST /api/payments/initiate
**Request:**
```json
{
  "invoice_id": 123,
  "amount": 150.00,
  "payment_method": "pesepay"
}
```

**Response:**
```json
{
  "success": true,
  "data": {
    "payment_id": 456,
    "redirect_url": "https://pesepay.com/...",
    "invoice": {
      "id": 123,
      "invoice_number": "INV-2024-001",
      "amount": 150.00
    }
  }
}
```

### POST /api/payments/upload-proof
**Request (FormData):**
```
invoice_id: 123
amount: 150.00
payment_reference: "TXN123456"
payment_date: "2024-02-15"
proof_file: [File]
notes: "Optional notes"
```

**Response:**
```json
{
  "success": true,
  "message": "Proof of payment uploaded successfully...",
  "data": {
    "payment_id": 456,
    "status": "pending_verification",
    "odoo_attachment_id": 99720
  }
}
```

## Email Notifications

### Finance Team Email
- **To:** NOC@afinet.africa
- **Subject:** New Proof of Payment - Invoice #INV-2024-001
- **Attachments:** Proof of payment file
- **Content:** Customer details, invoice info, payment reference

### Customer Confirmation Email
- **To:** customer@example.com
- **Subject:** Payment Received - Invoice #INV-2024-001
- **Content:** Payment confirmation, verification timeline (24 hours)

## Database Schema

### payments table
```sql
- payment_reference (string)
- customer_id (foreign key)
- invoice_id (foreign key) -- PRIMARY LINK
- sales_order_id (foreign key) -- SECONDARY REFERENCE
- quotation_id (foreign key) -- TERTIARY REFERENCE
- amount (decimal)
- payment_method (enum: pesepay, bank_transfer)
- status (enum: pending, completed, failed, pending_verification)
- gateway_response (json) -- includes odoo_attachment_id for bank transfers
```

## Important Notes

1. **Amount is read-only**: The payment amount comes from `invoice.total_amount` and cannot be changed by the user
2. **Invoice required**: All payments must have an associated invoice
3. **Odoo integration**: Proof of payment files are uploaded to Odoo and attached to the invoice
4. **Email notifications**: Both finance team and customer receive emails for bank transfer payments
5. **Verification time**: Bank transfer payments are verified within 24 hours

## Testing

### Test Pesepay Payment
```javascript
// In test mode, payments auto-complete
const response = await api.payments.initiate({
  invoice_id: 123,
  amount: 150.00,
  payment_method: 'pesepay'
});
// Check response.data.test_mode === true
```

### Test Bank Transfer
```javascript
// Upload proof of payment
const formData = new FormData();
formData.append('invoice_id', 123);
formData.append('amount', 150.00);
formData.append('payment_reference', 'TEST-TXN-123');
formData.append('payment_date', '2024-02-15');
formData.append('proof_file', file);

const response = await api.payments.uploadProof(formData);
// Check emails sent to NOC@afinet.africa and customer
```

## Migration Notes

If you have existing code using the old flow:
- Replace `sales_order_id` with `invoice_id`
- Ensure invoice is generated before payment
- Update amount source from quotation to invoice
- Update payment components to use new props
