# Modern MessageBox System - Complete Guide

## Overview
A beautiful, branded message box system that replaces standard JavaScript `alert()`, `confirm()`, and `prompt()` dialogs across all modules (Sales, Purchase, Items, Reports, etc.).

## Features
✅ **Branded Interface** - Shows your store name, location, and logo
✅ **Multiple Types** - Success, Error, Warning, Info, Confirm
✅ **Async/Await Support** - Modern JavaScript promise-based API
✅ **Keyboard Shortcuts** - Enter to confirm, Escape to cancel
✅ **Mobile Responsive** - Works perfectly on all screen sizes
✅ **Focus Management** - Returns focus to the original element after closing
✅ **Global Access** - Works in ALL modules without code duplication

---

## Installation

### Step 1: Add CSS to Your Page Header
```html
<link rel="stylesheet" href="../css/modern-messagebox.css">
<!-- OR if you're in the root directory -->
<link rel="stylesheet" href="css/modern-messagebox.css">
```

### Step 2: Add JavaScript Before Closing Body Tag
```html
<script src="../js/modern-messagebox.js"></script>
<!-- OR if you're in the root directory -->
<script src="js/modern-messagebox.js"></script>
```

### Step 3: Make Sure Font Awesome is Loaded
```html
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css">
```

---

## Basic Usage

### 1. Simple Alert
Replace `alert()` with modern styled alerts:

```javascript
// Old way
alert('Item added successfully!');

// New way - Info alert (default)
await MsgBox.alert('Item added successfully!');

// With type
await MsgBox.alert('Item added successfully!', 'success');
await MsgBox.alert('Something went wrong!', 'error');
await MsgBox.alert('Please check your input!', 'warning');
await MsgBox.alert('Your session will expire soon.', 'info');
```

### 2. Confirmation Dialog
Replace `confirm()` with modern confirmations:

```javascript
// Old way
if (confirm('Are you sure you want to delete this item?')) {
    // Delete item
}

// New way - Basic
if (await MsgBox.confirm('Are you sure you want to delete this item?')) {
    // Delete item
}

// New way - With custom buttons
const result = await MsgBox.confirm('Clear the cart?', {
    confirmText: 'Yes, Clear',
    cancelText: 'No, Keep',
    type: 'warning'
});

if (result) {
    clearCart();
}

// New way - Danger mode (red confirm button)
if (await MsgBox.confirm('Delete this customer?', { dangerMode: true })) {
    deleteCustomer();
}
```

### 3. Prompt Dialog
Replace `prompt()` with modern input dialogs:

```javascript
// Old way
const quantity = prompt('Enter quantity:', '1');

// New way
const quantity = await MsgBox.prompt('Enter quantity:', '1', 'Enter a number');

if (quantity !== null) {
    // User entered something
    console.log('Quantity:', quantity);
} else {
    // User cancelled
}
```

### 4. Shorthand Methods

```javascript
// Success message
await MsgBox.success('Item saved successfully!');

// Error message
await MsgBox.error('Failed to save item. Please try again.');

// Warning message
await MsgBox.warning('Low stock alert!');

// Delete confirmation (shorthand with danger mode)
if (await MsgBox.confirmDelete('Delete this supplier?')) {
    // Delete supplier
}
```

---

## Advanced Usage

### Custom Buttons and Styling
```javascript
const result = await MsgBox.custom({
    type: 'warning',
    message: 'Choose an action:',
    buttons: [
        { text: 'Cancel', style: 'secondary', action: 'cancel' },
        { text: 'Save Draft', style: 'warning', action: 'draft' },
        { text: 'Publish', style: 'success', action: 'publish' }
    ]
});

if (result.action === 'draft') {
    saveDraft();
} else if (result.action === 'publish') {
    publishItem();
}
```

### With Loading State
```javascript
const result = await MsgBox.custom({
    type: 'info',
    message: 'Processing your request...',
    buttons: [
        { text: 'Please Wait...', style: 'primary', action: 'ok', loading: true, disabled: true }
    ]
});
```

---

## Complete Examples for Each Module

### Sales Module Example
```javascript
// In Sales/index.php or Sales/products.php

// Before adding item to cart
const qty = await MsgBox.prompt('Enter quantity:', '1', 'Qty');
if (qty && qty > 0) {
    addToCart(productId, qty);
    await MsgBox.success('Added to cart!');
}

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

// On successful sale
await MsgBox.success('Sale completed successfully!\nInvoice #' + invoiceNo);
```

### Purchase Module Example
```javascript
// In Purchase/index.php or Purchase/products.php

// Before selecting supplier
if (!supplierId) {
    await MsgBox.error('Please select a supplier first!');
    return;
}

// Confirm bill deletion
if (await MsgBox.confirmDelete('Delete this purchase bill?\n\nThis cannot be undone!')) {
    deleteBill(billId);
}

// Low stock warning
await MsgBox.warning('Stock is running low!\nCurrent: ' + currentStock);
```

### Items Module Example
```javascript
// In items/item-management.php

// Confirm item deletion
if (await MsgBox.confirmDelete()) {
    deleteItem(itemId);
}

// Validation error
await MsgBox.error('Please fill all required fields!');

// Success after save
await MsgBox.success('Item saved successfully!');
```

### Reports Module Example
```javascript
// In any report file

// No data found
if (reportData.length === 0) {
    await MsgBox.warning('No data found for the selected date range.');
    return;
}

// Export confirmation
if (await MsgBox.confirm('Export report to Excel?')) {
    exportToExcel();
}

// Error loading report
await MsgBox.error('Failed to load report data.\nPlease try again.');
```

---

## Migration Guide

### Replace Old Alerts
```javascript
// BEFORE
alert('Please select a customer');

// AFTER
await MsgBox.alert('Please select a customer', 'warning');
```

### Replace Old Confirms
```javascript
// BEFORE
if (confirm('Delete item?')) {
    deleteItem();
}

// AFTER
if (await MsgBox.confirm('Delete item?')) {
    deleteItem();
}
```

### Replace Old Prompts
```javascript
// BEFORE
const discount = prompt('Enter discount %:', '0');

// AFTER
const discount = await MsgBox.prompt('Enter discount %:', '0', 'Discount');
```

---

## Customization Options

### Message Box Types
- `success` - Green header, check icon
- `error` - Red header, exclamation icon
- `warning` - Pink/orange header, warning icon
- `info` - Blue header, info icon
- `confirm` - Purple header, question icon
- `default` - Purple header, bell icon

### Button Styles
- `primary` - Purple gradient
- `success` - Green gradient
- `danger` - Red gradient
- `warning` - Pink gradient
- `secondary` - Gray

### Confirm Options
```javascript
{
    type: 'confirm',           // Message type
    confirmText: 'Yes',        // Confirm button text
    cancelText: 'No',          // Cancel button text
    confirmStyle: 'success',   // Confirm button style
    cancelStyle: 'secondary',  // Cancel button style
    dangerMode: false          // true = red confirm button
}
```

---

## Keyboard Shortcuts
- **Enter** - Confirms/submits (clicks primary button)
- **Escape** - Cancels and closes the dialog
- **Tab** - Navigate between buttons

---

## Pre-loading for Faster Display
To make the first message box appear instantly:

```javascript
// Call this when page loads
$(document).ready(function() {
    MsgBox.preload();
});
```

The system already auto-preloads store information on page load!

---

## Browser Compatibility
✅ Chrome, Firefox, Safari, Edge (Modern)
✅ Mobile browsers (iOS Safari, Chrome Mobile)
✅ IE11 (with polyfills for Promise)

---

## File Structure
```
UZRS-inventory/
├── css/
│   └── modern-messagebox.css      ← Global CSS
├── js/
│   └── modern-messagebox.js       ← Global JS
├── api/
│   └── get-store-info.php         ← Global API
├── Sales/
│   ├── index.php                  ← Use MsgBox here
│   └── products.php               ← Use MsgBox here
├── Purchase/
│   ├── index.php                  ← Use MsgBox here
│   └── products.php               ← Use MsgBox here
└── items/
    └── item-management.php        ← Use MsgBox here
```

---

## Troubleshooting

### MessageBox doesn't show
1. Check CSS is loaded: `<link href="../css/modern-messagebox.css">`
2. Check JS is loaded: `<script src="../js/modern-messagebox.js">`
3. Check Font Awesome is loaded
4. Open browser console for errors

### Store name shows "Store"
1. Check `api/get-store-info.php` is accessible
2. Verify database table `tblstore_settings` exists
3. Check user is logged in (session active)

### Buttons don't work
1. Make sure to use `await` before `MsgBox.confirm()`
2. Function must be `async`
3. Check browser console for JavaScript errors

---

## API Reference

### MsgBox.alert(message, type)
- **message**: String - Text to display
- **type**: String - 'success', 'error', 'warning', 'info', 'default'
- **Returns**: Promise

### MsgBox.confirm(message, options)
- **message**: String - Question to ask
- **options**: Object - Customization options
- **Returns**: Promise<boolean>

### MsgBox.prompt(message, defaultValue, placeholder)
- **message**: String - Prompt text
- **defaultValue**: String - Default input value
- **placeholder**: String - Input placeholder
- **Returns**: Promise<string|null>

### MsgBox.success(message)
- Shorthand for `alert(message, 'success')`

### MsgBox.error(message)
- Shorthand for `alert(message, 'error')`

### MsgBox.warning(message)
- Shorthand for `alert(message, 'warning')`

### MsgBox.confirmDelete(message)
- Shorthand for dangerous confirms with red button

### MsgBox.custom(options)
- Full control over message box appearance and buttons

### MsgBox.preload()
- Pre-load store information for instant display

---

## Support
For issues or questions, check:
1. Browser console for errors
2. Network tab for API failures
3. This documentation for usage examples

Happy coding! 🚀
