# Debugging Extra Charges in Sale Details

## 🐛 Issue Identified

**Problem:** Extra charges are not being saved to the database when processing sales.

**Root Cause:** JavaScript `Map` objects in `window.cartCalculations.extraCharges` were not being serialized properly to JSON when sent to `save_sale.php`.

**Symptoms:**
- Sale details in receipts.php not displaying extra charges/discounts 
- Records missing from `m001_sale_extra_charges` table
- Discrepancy between subtotal and grand total

**Example:** Sale #16 shows:
- Subtotal: ₱30.00 (items only)
- Grand Total: ₱37.00 (difference of ₱7.00 not explained)

## 🔍 Debugging Steps Added

### **1. Frontend Console Logging**
Added debug logs in `pos/sale_modal.php`:
```javascript
console.log('Sale data:', sale);
console.log('Extra charges:', extraCharges);
console.log('Sale total:', sale.total, 'Discount type:', sale.discount_type, 'Discount value:', sale.discount_value);
console.log('Delivery charge:', sale.delivery_charge, 'Other charge:', sale.other_charge);
```

### **2. Backend Logging** 
Added debug logs in `pos/sales_handler.php`:
```php
error_log("Final response data for sale ID {$sale_id}:");
error_log("Sale data: " . json_encode($sale));
error_log("Extra charges: " . json_encode($extra_charges));
```

### **3. Unknown Charges Detection**
Added logic to detect and display unexplained differences:
```javascript
// Check for unexplained difference
const expectedTotal = subtotal + totalCharges - totalDiscount;
const actualTotal = parseFloat(sale.total);
const unexplainedDifference = actualTotal - expectedTotal;

// Show unexplained charges/differences if they exist
if (Math.abs(unexplainedDifference) > 0.01) {
    html += `
        <div class="row mb-2 text-warning">
            <div class="col-9 text-end">Unknown Charges:</div>
            <div class="col-3 text-end">${unexplainedDifference >= 0 ? '+' : ''}₱${unexplainedDifference.toFixed(2)}</div>
        </div>`;
}
```

## 📋 Testing Procedure

### **Step 1: Test with Existing Sale**
1. Go to **POS → Receipts**
2. Find Sale #16 and click **View**
3. Open browser **Developer Tools** (F12)
4. Check **Console** tab for debug output
5. Look for the breakdown section showing "Unknown Charges: +₱7.00"

### **Step 2: Test with New Sale**
1. Go to **POS → Items**
2. Add items to cart (e.g., Value Cuts ₱30.00)
3. Click **Cart Details**
4. Add charges:
   - **Discount:** 10% off
   - **Delivery Charge:** ₱25.00
   - **Extra Charges:** 2x Gravy (₱5.00 each)
5. Complete the sale
6. Go to **Receipts** and view the new sale details

### **Step 3: Verify Database Data**
Check if charges are properly stored:
```sql
-- Check sales table
SELECT sale_id, total, discount_type, discount_value, delivery_charge, other_charge 
FROM m001_sales WHERE sale_id = [NEW_SALE_ID];

-- Check extra charges
SELECT sec.*, ie.extra_name, ie.extra_price 
FROM m001_sale_extra_charges sec
JOIN m001_items_extra ie ON sec.extra_id = ie.extra_id
WHERE sec.sale_id = [NEW_SALE_ID];
```

## 🔧 Expected Results

### **For Existing Sale #16:**
- Console should show charge fields as null/0
- Display should show "Unknown Charges: +₱7.00"
- This indicates legacy data without proper charge breakdown

### **For New Sale with Charges:**
- Console should show actual charge values
- Display should show detailed breakdown:
  - Subtotal: [item total]
  - Discount: -[discount amount]
  - Delivery Charge: +[delivery amount]
  - Extra charges: +[individual charges]
  - Grand Total: [final total]

## 🚨 Possible Issues

### **1. Table Missing**
If extra charges tables don't exist:
```bash
# Check if tables exist
mysql -u root -h localhost test -e "SHOW TABLES LIKE '%items_extra%';"
mysql -u root -h localhost test -e "SHOW TABLES LIKE '%sale_extra_charges%';"
```

### **2. Data Not Saving**
If charges aren't being saved during sale creation:
- Check `pos/save_sale.php` for calculation object processing
- Verify form data is being sent correctly from cart modal

### **3. Frontend Not Loading**
If modal doesn't show breakdown:
- Check browser console for JavaScript errors
- Verify `pos/sale_modal.php` is included properly
- Check if Bootstrap styles are loading correctly

## 🛠️ Quick Fixes

### **Fix 1: Clear Browser Cache**
- Hard refresh the page (Ctrl+F5)
- Clear browser cache and cookies

### **Fix 2: Check File Permissions**
- Ensure PHP files are readable by web server
- Check error logs for file access issues

### **Fix 3: Verify Database Connection**
- Check if queries are executing without errors
- Look at PHP error logs for database issues

## 📊 Current Status

✅ **FIXED:**
- **Map Serialization Issue**: Converted `extraCharges` Map to plain object using `Object.fromEntries()`
- **Backend data retrieval**: Enhanced with comprehensive logging
- **Frontend display logic**: Added breakdown section and unknown charges detection
- **Debug logging**: Added both frontend and backend debugging

✅ **Implemented:**
- Backend data retrieval for extra charges
- Frontend display logic for all charge types
- Debug logging for troubleshooting
- Unknown charges detection
- **NEW:** Map to Object conversion for proper JSON serialization

🧪 **Ready for Testing:**
- Browser console output verification
- New sale creation with charges
- Database data integrity check
- Extra charges saving verification

📝 **Testing Steps:**
1. **Create a test sale** with extra charges
2. **Check browser console** for conversion debug output
3. **Verify database records** in `m001_sale_extra_charges`
4. **View sale details** in receipts to see complete breakdown

---

**Note:** The ₱7.00 difference in Sale #16 suggests it was created before our charge system was implemented, or there's missing data that needs investigation. 