# Modern MessageBox Implementation Examples

## Quick Integration for Each Module

### 1. Sales Module (Sales/index.php)

#### Add to Header Section
```html
<!-- Add before closing </head> tag -->
<link rel="stylesheet" href="../css/modern-messagebox.css">
```

#### Add to Footer Section
```html
<!-- Add before closing </body> tag -->
<script src="../js/modern-messagebox.js"></script>
```

#### Replace Existing Alerts
```javascript
// OLD CODE:
if (confirm('Are you sure you want to clear the cart?')) {
    clearCart();
}

// NEW CODE:
if (await MsgBox.confirm('Clear entire cart?', {
    confirmText: 'Yes, Clear',
    cancelText: 'No',
    type: 'warning'
})) {
    clearCart();
}
```

---

### 2. Purchase Module (Purchase/index.php)

#### Add to Header Section
```html
<!-- Add before closing </head> tag -->
<link rel="stylesheet" href="../css/modern-messagebox.css">
```

#### Add to Footer Section
```html
<!-- Add before closing </body> tag -->
<script src="../js/modern-messagebox.js"></script>
```

#### Replace Existing Alerts
```javascript
// OLD CODE:
alert('Please select a supplier first');

// NEW CODE:
await MsgBox.alert('Please select a supplier first', 'warning');
```

---

### 3. Items Module (items/item-management.php)

#### Add to Header Section
```html
<!-- Add before closing </head> tag -->
<link rel="stylesheet" href="../css/modern-messagebox.css">
```

#### Add to Footer Section
```html
<!-- Add before closing </body> tag -->
<script src="../js/modern-messagebox.js"></script>
```

#### Replace Existing Alerts
```javascript
// OLD CODE:
if (confirm('Delete this item?')) {
    deleteItem();
}

// NEW CODE:
if (await MsgBox.confirmDelete('Delete this item?')) {
    deleteItem();
}
```

---

### 4. Reports Module (Any Report File)

#### Add to Header Section
```html
<!-- Add before closing </head> tag -->
<link rel="stylesheet" href="../css/modern-messagebox.css">
```

#### Add to Footer Section
```html
<!-- Add before closing </body> tag -->
<script src="../js/modern-messagebox.js"></script>
```

#### Replace Existing Alerts
```javascript
// OLD CODE:
alert('Please select both start and end dates');

// NEW CODE:
await MsgBox.alert('Please select both start and end dates', 'warning');
```

---

## Common Patterns by Use Case

### Validation Errors
```javascript
// Empty field
if (!customerName) {
    await MsgBox.error('Please enter customer name!');
    return;
}

// Invalid value
if (quantity <= 0) {
    await MsgBox.warning('Quantity must be greater than 0!');
    return;
}

// Date range
if (startDate > endDate) {
    await MsgBox.warning('Start date must be before end date!');
    return;
}
```

### Success Messages
```javascript
// Save success
await MsgBox.success('✓ Item saved successfully!');

// Sale complete
await MsgBox.success('✓ Sale completed!\nInvoice #' + invoiceNo);

// Record updated
await MsgBox.success('✓ Customer updated successfully!');
```

### Delete Confirmations
```javascript
// Simple delete
if (await MsgBox.confirmDelete()) {
    deleteRecord();
}

// Delete with details
if (await MsgBox.confirmDelete('Delete "' + itemName + '"?\n\nThis cannot be undone!')) {
    deleteItem(itemId);
}
```

### User Input
```javascript
// Get quantity
const qty = await MsgBox.prompt('Enter quantity:', '1', 'Qty');
if (qty && qty > 0) {
    addToCart(qty);
}

// Get discount
const discount = await MsgBox.prompt('Enter discount %:', '0', '0-100');
if (discount !== null) {
    applyDiscount(discount);
}

// Get customer name
const name = await MsgBox.prompt('Enter customer name:', '', 'Full name');
if (name) {
    saveCustomer(name);
}
```

### Complex Confirmations
```javascript
// Before clearing cart
if (await MsgBox.confirm('Clear cart and start new sale?', {
    confirmText: 'Yes, Start New',
    cancelText: 'No, Keep',
    type: 'warning'
})) {
    clearCart();
    newSale();
}

// Before printing
if (await MsgBox.confirm('Print invoice?', {
    confirmText: 'Print',
    cancelText: 'Cancel',
    type: 'info'
})) {
    printInvoice();
}
```

---

## Migration Checklist

### Phase 1: Add Files (5 minutes)
- [x] Copy `js/modern-messagebox.js` to main js folder
- [x] Copy `css/modern-messagebox.css` to main css folder
- [x] Copy `api/get-store-info.php` to main api folder

### Phase 2: Test Installation (5 minutes)
- [ ] Open `test-messagebox.php` in browser
- [ ] Test all message types work correctly
- [ ] Verify store name appears correctly

### Phase 3: Integrate Into Modules (Per Module)
For each module (Sales, Purchase, Items, Reports):

1. **Add CSS Link** (in `<head>`)
   ```html
   <link rel="stylesheet" href="../css/modern-messagebox.css">
   ```

2. **Add JS Script** (before `</body>`)
   ```html
   <script src="../js/modern-messagebox.js"></script>
   ```

3. **Update JavaScript Functions**
   - Replace `alert()` with `await MsgBox.alert()`
   - Replace `confirm()` with `await MsgBox.confirm()`
   - Replace `prompt()` with `await MsgBox.prompt()`
   - Add `async` keyword to functions using MsgBox

4. **Test Each Page**
   - Test all alerts work
   - Test all confirms work
   - Test all prompts work
   - Test keyboard shortcuts (Enter, Escape)

---

## Search & Replace Guide

### Using VS Code Find & Replace

#### Replace alert() calls
**Find (Regex):**
```
alert\(['"](.+?)['"]\)
```

**Replace:**
```
await MsgBox.alert('$1', 'info')
```

#### Replace confirm() calls
**Find (Regex):**
```
if \(confirm\(['"](.+?)['"]\)\)
```

**Replace:**
```
if (await MsgBox.confirm('$1'))
```

#### Replace prompt() calls
**Find (Regex):**
```
prompt\(['"](.+?)['"],\s*['"](.*?)['"]\)
```

**Replace:**
```
await MsgBox.prompt('$1', '$2')
```

⚠️ **Important:** After using find & replace, manually add `async` keyword to the function definitions!

---

## Performance Tips

1. **Pre-load Store Info**
   ```javascript
   $(document).ready(function() {
       MsgBox.preload(); // Loads store info in background
   });
   ```

2. **Cache Results**
   ```javascript
   // Bad: Loading every time
   async function deleteItem() {
       if (await MsgBox.confirmDelete()) {
           // ...
       }
   }
   
   // Good: Single confirmation
   const confirmed = await MsgBox.confirmDelete();
   if (confirmed) {
       for (let item of items) {
           deleteItem(item);
       }
   }
   ```

3. **Batch Operations**
   ```javascript
   // Show single message for batch operation
   const result = await MsgBox.confirm('Delete ' + count + ' items?', {
       dangerMode: true
   });
   ```

---

## Troubleshooting

### Issue: "MsgBox is not defined"
**Solution:** Make sure JS file is loaded:
```html
<script src="../js/modern-messagebox.js"></script>
```

### Issue: MessageBox doesn't appear
**Solution:** Check CSS is loaded:
```html
<link rel="stylesheet" href="../css/modern-messagebox.css">
```

### Issue: Icons don't show
**Solution:** Add Font Awesome:
```html
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css">
```

### Issue: Store name shows "Store"
**Solution:** Check database connection and `tblstore_settings` table exists

### Issue: Buttons don't work
**Solution:** Make sure function is `async`:
```javascript
// Wrong
function deleteItem() {
    if (await MsgBox.confirm(...)) // Error!
}

// Correct
async function deleteItem() {
    if (await MsgBox.confirm(...)) // Works!
}
```

---

## Module-Specific Notes

### Sales Module
- Use `MsgBox.success()` after successful sale
- Use `MsgBox.confirm()` before clearing cart
- Use `MsgBox.prompt()` for custom quantities
- Use `MsgBox.warning()` for stock alerts

### Purchase Module
- Use `MsgBox.alert()` to show supplier selection error
- Use `MsgBox.confirm()` before deleting bills
- Use `MsgBox.success()` after bill saved
- Use `MsgBox.error()` for validation errors

### Items Module
- Use `MsgBox.confirmDelete()` before deleting items
- Use `MsgBox.success()` after saving
- Use `MsgBox.error()` for duplicate items
- Use `MsgBox.warning()` for stock warnings

### Reports Module
- Use `MsgBox.warning()` for date range errors
- Use `MsgBox.info()` for no data found
- Use `MsgBox.confirm()` before exporting
- Use `MsgBox.error()` for loading errors

---

## Support & Documentation

- **Full Guide:** `MODERN_MESSAGEBOX_GUIDE.md`
- **Test Page:** `test-messagebox.php`
- **API Reference:** See main documentation

---

Last Updated: November 6, 2025
