# Extra Charges Retrieval in Sale Details

## 📋 Overview

This guide explains how discount and extra charges data is retrieved and displayed when viewing sale details in the receipts system.

## 🔧 Implementation Components

### **1. Database Structure**

The system uses these tables to store discount and charges data:

#### **Sales Table Columns (Added)**
```sql
-- In {branch_code}_sales table
discount_type VARCHAR(20) DEFAULT NULL,     -- 'percentage' or 'amount'
discount_value DECIMAL(10,2) DEFAULT 0,     -- Discount value
delivery_charge DECIMAL(10,2) DEFAULT 0,    -- Delivery charge amount
other_charge DECIMAL(10,2) DEFAULT 0        -- Other miscellaneous charge
```

#### **Extra Charges Tables**
```sql
-- Items Extra table: {branch_code}_items_extra
extra_id INT PRIMARY KEY AUTO_INCREMENT,
extra_name VARCHAR(255) NOT NULL,
extra_price DECIMAL(10,2) NOT NULL,
is_active TINYINT(1) DEFAULT 1

-- Sale Extra Charges junction table: {branch_code}_sale_extra_charges  
sale_id INT NOT NULL,
extra_id INT NOT NULL,
quantity INT NOT NULL DEFAULT 1,
unit_price DECIMAL(10,2) NOT NULL
```

### **2. Backend Data Retrieval**

#### **A. Sales Handler Enhancement (`pos/sales_handler.php`)**
The `get_sale` case now retrieves:
- Basic sale information
- Sale items
- **NEW:** Extra charges with details

```php
// Get extra charges if they exist
$extra_charges = [];
try {
    $sale_extra_charges_table = getBranchTable('sale_extra_charges');
    $items_extra_table = getBranchTable('items_extra');
    
    $extra_charges_query = "
        SELECT sec.*, ie.extra_name, ie.extra_price
        FROM $sale_extra_charges_table sec
        JOIN $items_extra_table ie ON sec.extra_id = ie.extra_id
        WHERE sec.sale_id = ?
    ";
    
    $stmt = executeQuery($pdo, $extra_charges_query, [$sale_id]);
    $extra_charges = $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (Exception $e) {
    // Table might not exist yet, continue without extra charges
}
```

#### **B. Response Structure**
```json
{
    "success": true,
    "data": {
        "sale": {
            "sale_id": 123,
            "total": 150.00,
            "discount_type": "percentage",
            "discount_value": 10,
            "delivery_charge": 25.00,
            "other_charge": 5.00,
            // ... other sale fields
        },
        "items": [
            // Sale items array
        ],
        "extra_charges": [
            {
                "sale_id": 123,
                "extra_id": 1,
                "quantity": 2,
                "unit_price": 5.00,
                "extra_name": "Gravy",
                "extra_price": 5.00
            }
        ]
    }
}
```

### **3. Frontend Display Enhancement**

#### **A. Sale Modal Updates (`pos/sale_modal.php`)**
The sale details modal now shows:
1. **Items table** (existing functionality)
2. **NEW:** Detailed breakdown section with:
   - Subtotal
   - Discount (if applied)
   - Delivery charge (if applied)
   - Other charges (if applied)
   - Individual extra charges
   - Grand total

#### **B. Display Logic**
```javascript
// Extract data from response
const sale = result.data.sale;
const items = result.data.items;
const extraCharges = result.data.extra_charges || [];

// Calculate subtotal from items
let subtotal = items.reduce((sum, item) => {
    return sum + (parseFloat(item.price) * parseFloat(item.quantity));
}, 0);

// Display breakdown
if (sale.discount_type && sale.discount_value && parseFloat(sale.discount_value) > 0) {
    // Show discount
}

if (sale.delivery_charge && parseFloat(sale.delivery_charge) > 0) {
    // Show delivery charge
}

if (extraCharges && extraCharges.length > 0) {
    extraCharges.forEach(charge => {
        // Show each extra charge with quantity
    });
}
```

## 🎯 Receipt Display Structure

When viewing a sale with discounts and extra charges, the receipt displays:

```
SALE DETAILS - #123
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

ITEMS:
┌─────────────────────────────────────────────────────────────────────────────┐
│ Item Name          │ Qty │ Price  │ Total   │
├────────────────────┼─────┼────────┼─────────┤
│ Chicken Meal       │ 2   │ ₱45.00 │ ₱90.00  │
│ Rice               │ 1   │ ₱15.00 │ ₱15.00  │
└─────────────────────────────────────────────────────────────────────────────┘

CALCULATION BREAKDOWN:
┌─────────────────────────────────────────────────────────────────────────────┐
│ Subtotal:                                                    ₱105.00 │
│ Discount (10%):                                     -₱10.50 │
│ Delivery Charge:                                     +₱25.00 │
│ Gravy (2x):                                         +₱10.00 │
│ Meal Box (1x):                                      +₱15.00 │
│ Other Charge:                                        +₱5.00 │
├─────────────────────────────────────────────────────────────────────────────┤
│ GRAND TOTAL:                                                 ₱149.50 │
└─────────────────────────────────────────────────────────────────────────────┘
```

## 🚀 Benefits

### **1. Complete Transaction Transparency**
- Shows exactly how the final total was calculated
- Clearly separates base items from add-ons and charges
- Helps with customer inquiries and dispute resolution

### **2. Accurate Financial Reporting**
- Proper tracking of discount amounts
- Separate accounting for delivery and service charges
- Detailed extra item sales tracking

### **3. Audit Trail Support**
- All transaction components are preserved
- Historical data remains intact even if extra items are modified
- Supports compliance and accounting requirements

## 🔍 Testing the Implementation

### **Manual Testing Steps:**

1. **Create a Sale with Extras:**
   - Go to POS → Items
   - Add items to cart
   - Click "Cart Details"
   - Add discount (e.g., 10% off)
   - Add delivery charge (e.g., ₱25.00)
   - Add extra charges (e.g., 2x Gravy)
   - Complete the sale

2. **View Sale Details:**
   - Go to POS → Receipts
   - Find the sale in the list
   - Click "View" to see sale details
   - Verify all charges are displayed correctly

3. **Verify Data Integrity:**
   - Check that subtotal + charges - discount = grand total
   - Confirm extra charges show correct quantity and pricing
   - Ensure all components are clearly labeled

### **Database Verification:**
```sql
-- Check sale record
SELECT * FROM m001_sales WHERE sale_id = [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 = [SALE_ID];
```

## 🛠️ Troubleshooting

### **Common Issues:**

1. **Extra charges not displaying:**
   - Check if tables exist: `m001_sale_extra_charges`, `m001_items_extra`
   - Verify foreign key relationships are intact
   - Check browser console for JavaScript errors

2. **Discount not showing:**
   - Verify `discount_type` and `discount_value` columns exist in sales table
   - Check if values are properly saved during sale creation

3. **Incorrect totals:**
   - Verify that `save_sale.php` is correctly calculating and storing the total
   - Check for rounding issues in JavaScript calculations

## 📈 Future Enhancements

- **Tax calculations** integration
- **Multiple discount types** (bulk, loyalty, etc.)
- **Conditional charges** (free delivery over certain amount)
- **Charge categories** for better reporting
- **Customer-specific pricing** rules

---

**✅ Implementation Status: Complete**
- ✅ Database structure updated
- ✅ Backend retrieval implemented  
- ✅ Frontend display enhanced
- ✅ Error handling included
- ✅ Backward compatibility maintained 