# Processing Fee SMS Timing Fix

## Problem

Processing fee SMS messages were being sent **before** the customer actually paid, causing confusion. The timestamps showed:

- **12:00:50** - Processing fee SMS sent ("Confirmed KES 2,000.00 processing fee **paid**...")
- **12:01:24** - Actual payment received (34 seconds later)

The message incorrectly claimed the fee was "paid" when it was only **requested**.

## Root Cause

In `users/views.py`, the `send_processing_fee_sms()` function was called immediately after initiating the STK push:

```python
# STK push sent to customer's phone
initiate_stk_push(...)

# SMS sent IMMEDIATELY (before payment!)
send_processing_fee_sms(...)  # ❌ WRONG
```

This happened in two places:
1. Line 4127: `request_processing_fee_stk_prereg` (pre-registration)
2. Line 4220: `request_processing_fee_stk` (existing client)

## Solution

### Part 1: Remove Premature SMS Calls
Removed the `send_processing_fee_sms()` calls from both STK push initiation functions in `users/views.py`. Added comments indicating that SMS will be sent by the IPN callback after payment confirmation.

### Part 2: Send SMS After Payment Confirmation
Modified the IPN callback handler in `payments/sasapay_service.py` (line ~400) to:

1. **Detect processing fee payments**: When a borrower is matched but has no active loan, treat it as a processing fee payment
2. **Send appropriate SMS**: Call `send_processing_fee_sms()` instead of sending an error alert
3. **Still log as unknown payment**: Keep the payment in the unknown payments table for admin review/reconciliation

## Result

Now the SMS flow matches the payment flow:

```
Customer receives STK push → Customer enters PIN → Payment confirmed → SMS sent ✓
```

The processing fee SMS is only sent **after** the IPN callback confirms the payment was successful, matching the behavior of regular loan repayment confirmations.

## Files Modified

1. **users/views.py**
   - Line 4127-4136: Removed premature SMS in `request_processing_fee_stk_prereg`
   - Line 4220-4228: Removed premature SMS in `request_processing_fee_stk`

2. **payments/sasapay_service.py**
   - Line ~400: Added processing fee SMS logic to IPN callback handler's "no active loan" branch

## Testing

To verify the fix:
1. Initiate a processing fee STK push for a borrower with no active loan
2. Confirm that NO SMS is sent immediately
3. Complete the payment on the customer's phone
4. Verify the processing fee SMS is sent only after IPN callback confirms payment
5. Check that the payment appears in unknown payments table for admin review
