# PWA Quick Reference Card

## 🚀 Quick Start

### 1. Setup Database
```bash
setup-pwa-schema.bat          # Windows
bash setup-pwa-schema.sh      # macOS/Linux
```

### 2. Generate VAPID Keys
```bash
npm install -g web-push
web-push generate-vapid-keys
```

### 3. Add to Config
```php
define('VAPID_PUBLIC_KEY', 'YOUR_KEY_HERE');
define('VAPID_PRIVATE_KEY', 'YOUR_KEY_HERE');
```

### 4. Test
- Open DevTools (F12) → Application
- Check Service Workers (should show "activated and running")
- Go offline and try to use app

---

## 📱 JavaScript API Quick Reference

### PWA Helper
```javascript
// Check if installed
pwaHelper.isInstalled()

// Get status
pwaHelper.getInstallationStatus()
// Returns: {isInstalled, isOnline, swReady, notificationsEnabled, canInstall}

// Prompt install
await pwaHelper.promptInstall()

// Subscribe to push
await pwaHelper.subscribeToPushNotifications()

// Show notification
pwaHelper.showNotification(title, body)

// Trigger sync
await pwaHelper.triggerBackgroundSync()

// Setup periodic sync
await pwaHelper.setupPeriodicBackgroundSync()

// Check online status
if (pwaHelper.isOnline) { /* online */ }
```

### Sync Manager
```javascript
// Save count offline
await syncManager.saveCount({
  item_id: 123,
  quantity: 50,
  notes: 'Notes here'
})

// Get cached assignments
const assignments = await syncManager.getAssignments()

// Get cached reports
const reports = await syncManager.getReports()

// Sync manually
await syncManager.syncPendingOperations()

// Get sync status
syncManager.getSyncStatus()
// Returns: {isOnline, syncInProgress, databaseReady}

// Clear cache
await syncManager.clearCache()
```

### Notification Handler
```javascript
// Request permission
await notificationHandler.ensurePermission()

// Show notification
await notificationHandler.showNotification(title, options)

// Notify events
await notificationHandler.notifyCountSubmitted(itemName, qty)
await notificationHandler.notifyAssignmentUpdate(assignment)
await notificationHandler.notifySyncComplete(count)
await notificationHandler.notifySyncError(error)

// Start polling (fallback)
notificationHandler.setupPeriodicNotifications(5*60*1000)

// Stop polling
notificationHandler.stopPeriodicNotifications()

// Get status
notificationHandler.getStatus()
```

---

## 🔌 PHP API Quick Reference

### Endpoints

```
POST /api/sync-counts
  Request: {counts: [...]}
  Response: {success, synced_ids, synced_count, total_count, errors}

GET /api/get-assignments
  Response: [{id, item_id, item_name, status, ...}]

GET /api/get-reports
  Response: [{id, title, type, status, ...}]

GET /api/get-notifications
  Response: [{id, title, body, icon, tag, requireInteraction, data}]

POST /api/save-push-subscription
  Request: {subscription: {endpoint, keys: {auth, p256dh}}}
  Response: {success, message}

GET /api/get-vapid-key
  Response: {key: 'BIx...'}
```

### Helper Functions

```php
// Send notification
send_notification($userId, $title, $message, $type='info', $options=[])

// Send with push
send_notification($userId, $title, $msg, 'info', ['push' => true])

// Send push notification
send_push_notification($userId, $title, $message, $options=[])

// Notify role
notify_role(ROLE_ADMIN, $title, $message, $type='info')

// Notify multiple users
notify_users([1, 2, 3], $title, $message, $type='info')

// Log sync operation
log_sync($userId, $operation, $table, $recordId, $status='pending', $error=null)

// Get sync status
get_sync_status($userId)
// Returns: {pending, synced, failed, last_sync}

// Check push enabled
has_push_enabled($userId)

// Get offline settings
get_offline_settings($userId)

// Update offline settings
update_offline_settings($userId, [{key => value}])

// PWA status
get_pwa_status()
// Returns: {vapid_configured, database_ready, tables_exist}

// PWA stats
get_pwa_stats()
// Returns: {total_users, users_with_push, pending_syncs, failed_syncs, ...}

// Cleanup
cleanup_sync_logs(30)    // Keep 30 days
cleanup_notifications(30)

// Test
send_test_notification($userId)
```

---

## 📊 Database Quick Reference

### Notifications Table
```sql
SELECT * FROM notifications WHERE user_id = 1 AND read_at IS NULL;
INSERT INTO notifications (user_id, title, message, type) VALUES (1, 'Title', 'Message', 'info');
UPDATE notifications SET read_at = NOW() WHERE id = 1;
```

### Push Subscriptions
```sql
SELECT * FROM push_subscriptions WHERE user_id = 1;
DELETE FROM push_subscriptions WHERE user_id = 1;
```

### Sync Logs
```sql
SELECT * FROM sync_logs WHERE user_id = 1 AND status = 'pending';
SELECT COUNT(*) FROM sync_logs WHERE status = 'failed';
DELETE FROM sync_logs WHERE created_at < DATE_SUB(NOW(), INTERVAL 30 DAY);
```

### Offline Settings
```sql
SELECT * FROM offline_settings WHERE user_id = 1;
UPDATE offline_settings SET auto_sync_enabled = 1 WHERE user_id = 1;
```

---

## 🔍 DevTools Debugging

### Check Service Worker
1. Open DevTools → **Application**
2. Click **Service Workers**
3. Look for `/invcount/` entry
4. Status should show "activated and running"
5. Check "Offline" to test offline mode

### Check Caches
1. **Application** → **Cache Storage**
2. Should see:
   - `inv-cache-v1` (main app)
   - `inv-runtime-v1` (CSS, JS)
   - `inv-images-v1` (images)
   - `inv-api-v1` (API responses)

### Check IndexedDB
1. **Application** → **IndexedDB**
2. Expand `InvCounterDB`
3. Should contain:
   - `counts` (offline count records)
   - `assignments` (cached assignments)
   - `reports` (cached reports)
   - `pending_syncs` (operations to sync)

### Console Debugging
```javascript
// Check console logs
// Look for [PWA], [SyncManager], [SW], [NotificationHandler] prefixes

// Manually trigger sync
await syncManager.syncPendingOperations()

// Check status
console.log(pwaHelper.getInstallationStatus())
console.log(syncManager.getSyncStatus())
console.log(notificationHandler.getStatus())

// Clear everything (dev only)
caches.keys().then(names => 
  Promise.all(names.map(n => caches.delete(n)))
).then(() => location.reload())
```

---

## ⚠️ Common Issues

| Issue | Check | Fix |
|-------|-------|-----|
| SW not installing | HTTPS/localhost, manifest MIME type | Verify in DevTools, check console |
| Offline not working | Cache storage, asset URLs | Check DevTools cache names, verify paths |
| Notifications blocked | Browser settings, permission status | Request permission, check notification settings |
| Push failing | VAPID keys, subscription endpoint | Regenerate keys, check push_subscriptions table |
| Sync not working | IndexedDB, API responses, network | Check DevTools Network tab, review console |

---

## 🎯 Use Cases

### When User Submits Count While Offline
```javascript
// User clicks "Submit Count"
const count = {item_id: 123, quantity: 50};
await syncManager.saveCount(count);
// UI shows "Saved locally, will sync when online"
// When online: automatic background sync
// Server receives count via /api/sync-counts
// Database updated
```

### When New Assignment Arrives
```php
// Admin creates assignment
// Call this in your assignment creation code:
send_notification(
    $userId,
    'New Assignment',
    'You have a new item to count',
    'alert',
    ['push' => true, 'tag' => 'assignment-new']
);
// User sees in-app notification immediately
// If push enabled, native notification shows
```

### When Report is Ready
```php
// Admin generates report
notify_role(
    ROLE_COUNTER,
    'Report Ready',
    'Daily count report is available',
    'success'
);
// All counters notified
// In-app + push notifications sent
```

---

## 🔄 Lifecycle Events

### Service Worker Lifecycle
```
install → waiting → activate → fetch/sync/push
```

### Sync Lifecycle
```
Offline action → IndexedDB save → Online detected → Background sync → API call → DB update
```

### Notification Lifecycle
```
User action → send_notification() → DB insert → Service Worker push → Browser notification → User click
```

---

## 📈 Performance Tips

1. **Limit cache size** - Set max 100MB
2. **Batch operations** - Sync multiple items at once
3. **Cleanup regularly** - Delete old sync logs (30+ days)
4. **Monitor performance** - Check sync_logs table
5. **Test on slow network** - DevTools → Network → Throttle

---

## 🔐 Security Checklist

- [ ] HTTPS enabled (or localhost)
- [ ] VAPID keys generated and stored securely
- [ ] All API endpoints require authentication
- [ ] Input validation on all forms
- [ ] CORS properly configured
- [ ] Database backups enabled
- [ ] Sync logs monitored
- [ ] Old data cleanup scheduled

---

## 📚 Documentation

- **Full Technical Docs:** `PWA_IMPLEMENTATION.md`
- **Setup Instructions:** `PWA_SETUP_CHECKLIST.md`
- **Architecture Overview:** `PWA_SUMMARY.md`
- **This Quick Reference:** `PWA_QUICK_REFERENCE.md`

---

## 💡 Pro Tips

1. **Test offline first** - Use DevTools offline mode before deploying
2. **Monitor sync_logs** - Check for failures: `SELECT * FROM sync_logs WHERE status='failed'`
3. **Use tags for notifications** - Prevents duplicate notifications
4. **Batch sync operations** - Send multiple items in one API call
5. **Set requireInteraction=true** - Only for important alerts
6. **Use push for time-sensitive** - Use in-app for less urgent
7. **Clean up cache regularly** - Prevent storage quota exceeded
8. **Test push notifications** - Use `send_test_notification()` function

---

**Last Updated:** May 17, 2026  
**Version:** 1.0  
**Status:** Production Ready ✅
