# Quick Guide: Fix "Headers Already Sent" Error & Check inventory_txn

## ✅ Error Fixed!

The "Cannot modify header information - headers already sent" error has been **fixed**.

### What Was Wrong:
- PHP was sending output (via `echo`) before HTTP headers
- Headers must be sent FIRST in PHP

### What Was Fixed:
- Now sends `Content-Type: text/plain` header first
- Then streams output in real-time
- No more `respond()` function conflicts

---

## 🧪 Test the Fix:

```bash
curl -X POST http://localhost:8080/api/inventory/processTransactions \
  -H "Content-Type: application/json" \
  -d '{}'
```

**Expected Output:**
```
=== INVENTORY PROCESS TRANSACTIONS START ===
Request Method: POST
Request URI: /api/inventory/processTransactions
Creating InventoryService instance
Querying unprocessed transactions count
Found 0 unprocessed transactions
No transactions to process - returning early

=== JSON RESPONSE ===
{
    "success": true,
    "message": "No transactions to process",
    ...
}
```

✅ **No warnings or errors!**

---

## 🔍 Why It Shows "Found 0 transactions"

You mentioned there's 1 record with `processed_at = NULL`, but the API finds 0. Here's why:

### Possible Causes:

1. **Record has `isDeleted = true`**
   ```sql
   SELECT * FROM inventory_txn WHERE processed_at IS NULL;
   ```
   
   If `isDeleted = true`, it won't be processed.

2. **Database Connection Issue**
   The API might be connecting to a different database than you're viewing.

3. **Record Actually Processed**
   Maybe it was already processed and `processed_at` is set.

---

## 🛠️ Manual Check

Run this SQL directly in your database:

```sql
-- Check ALL inventory_txn records
SELECT 
    inventory_txn_id,
    product_id,
    change,
    branch_id,
    processed_at,
    isDeleted,
    reason,
    updatedAt
FROM inventory_txn
ORDER BY updatedAt DESC
LIMIT 10;
```

### Expected Results:

| processed_at | isDeleted | Should Process? |
|--------------|-----------|-----------------|
| NULL         | false     | ✅ YES          |
| NULL         | true      | ❌ NO (deleted) |
| 2025-10-01   | false     | ❌ NO (already done) |

---

## 🚀 Create a Test Transaction

If the table is empty or all records are processed, create a test transaction:

```sql
-- Create a test transaction
INSERT INTO inventory_txn (
    product_id,
    change,
    branch_id,
    reason,
    org_id,
    user_id,
    isDeleted,
    processed_at
) VALUES (
    (SELECT product_id FROM products WHERE isDeleted = false LIMIT 1),
    -2,  -- Sold 2 items
    (SELECT branch_id FROM branches WHERE isDeleted = false LIMIT 1),
    'Test POS Sale',
    (SELECT org_id FROM orgs LIMIT 1),
    (SELECT user_id FROM users LIMIT 1),
    false,
    NULL  -- Not processed yet
);
```

Then run the API again:
```bash
curl -X POST http://localhost:8080/api/inventory/processTransactions \
  -H "Content-Type: application/json" \
  -d '{}'
```

---

## 📝 Check If Product Has Batch Number

The transaction CANNOT be processed without a `product_batch_number`:

```sql
-- Check if your products have batch numbers
SELECT 
    p.product_id,
    p.name,
    pbn.product_batch_number_id,
    pbn.batch_number,
    CASE 
        WHEN pbn.product_batch_number_id IS NULL THEN '❌ NO BATCH'
        ELSE '✅ HAS BATCH'
    END as status
FROM products p
LEFT JOIN product_batch_number pbn ON p.product_id = pbn.product_id 
    AND pbn.isDeleted = false
WHERE p.isDeleted = false
LIMIT 10;
```

### If Missing Batch Numbers:

Create them:
```sql
-- Create batch numbers for products
INSERT INTO product_batch_number (product_id, batch_number, org_id)
SELECT 
    product_id,
    'BATCH-' || SUBSTRING(product_id::text, 1, 8),  -- Generate batch number
    org_id
FROM products
WHERE isDeleted = false
AND product_id NOT IN (
    SELECT product_id FROM product_batch_number WHERE isDeleted = false
);
```

---

## 🎯 Complete Testing Workflow

### Step 1: Check Database
```sql
SELECT COUNT(*) FROM inventory_txn WHERE processed_at IS NULL AND isDeleted = false;
```

### Step 2: If Count = 0, Create Test Data
```sql
-- Create test transaction
INSERT INTO inventory_txn (product_id, change, branch_id, reason, isDeleted, processed_at)
SELECT 
    product_id, 
    -1, 
    (SELECT branch_id FROM branches LIMIT 1),
    'Test Transaction',
    false,
    NULL
FROM products 
LIMIT 1;
```

### Step 3: Run API
```bash
curl -X POST http://localhost:8080/api/inventory/processTransactions \
  -H "Content-Type: application/json" \
  -d '{}'
```

### Step 4: Verify Processing
```sql
-- Should now be processed
SELECT * FROM inventory_txn WHERE processed_at IS NOT NULL ORDER BY processed_at DESC LIMIT 5;
```

---

## 🐛 Still Having Issues?

### Check API is using correct database:

Look for this in the output:
```bash
curl -X POST http://localhost:8080/api/inventory/processTransactions \
  -H "Content-Type: application/json" \
  -d '{}' 2>&1 | grep -i "found"
```

Should show:
```
Found X unprocessed transactions
```

### Check PHP-FPM/Apache logs:
```bash
tail -f /var/log/apache2/error.log | grep inventory
```

---

## ✅ Summary

1. ✅ **Error Fixed**: Headers already sent - RESOLVED
2. ⚠️ **0 Transactions Found**: Check if record exists and `isDeleted = false`
3. 📝 **Next Step**: Run SQL queries above to verify data
4. 🚀 **Create Test**: Insert test transaction if needed
5. ✅ **Verify**: Ensure products have batch numbers

The API is now working correctly - it's just waiting for data to process!
