# PWA Setup Checklist

Complete this checklist to enable full PWA functionality for the Inventory Counter app.

## ✅ Pre-Setup Requirements

- [ ] MySQL/MariaDB running
- [ ] PHP 7.4+ installed
- [ ] Node.js and npm installed (for generating VAPID keys)
- [ ] App accessible over HTTPS (or localhost for testing)

## ✅ Step 1: Database Migration

### Windows
```bash
setup-pwa-schema.bat
```

### macOS/Linux
```bash
bash setup-pwa-schema.sh
```

Or manually:
```bash
mysql -u root -p invcount < database/pwa-schema.sql
```

This creates these tables:
- `notifications` - User notifications
- `push_subscriptions` - Push subscription endpoints
- `sync_logs` - Offline operation tracking
- `offline_settings` - User offline preferences

## ✅ Step 2: Generate VAPID Keys (for Push Notifications)

### Install web-push globally
```bash
npm install -g web-push
```

### Generate VAPID keys
```bash
web-push generate-vapid-keys
```

Output will be:
```
Public Key: BIx... (very long string)
Private Key: RxP... (very long string)
```

**Save these keys safely!**

## ✅ Step 3: Configure VAPID Keys

Add to `config/config.php`:

```php
// Push Notifications Configuration
define('VAPID_PUBLIC_KEY', 'BIx...'); // Your public key
define('VAPID_PRIVATE_KEY', 'RxP...'); // Your private key
```

Or store in database settings:

```php
$settings = new Settings();
$settings->set('push_vapid_public_key', 'YOUR_PUBLIC_KEY');
$settings->set('push_vapid_private_key', 'YOUR_PRIVATE_KEY');
```

## ✅ Step 4: Verify Manifest Configuration

Check `manifest.json`:

```json
{
  "name": "Inventory Counter",
  "short_name": "InvCounter",
  "start_url": "/invcount/login.php",
  "scope": "/invcount/",
  "display": "standalone",
  // ... other fields
}
```

**Key fields to verify:**
- ✅ `name` - Non-empty
- ✅ `start_url` - Valid URL
- ✅ `scope` - Matches your app path
- ✅ `display` - Set to "standalone"
- ✅ `icons` - At least 192×192 and 512×512

## ✅ Step 5: Verify Service Worker is Loaded

### In Browser DevTools:

1. Press **F12** to open Developer Tools
2. Go to **Application** tab
3. Check **Service Workers** section
4. You should see:
   - ✅ Service Worker registered for `/invcount/`
   - ✅ Status: `activated and running`

### In Console:

Should see messages like:
```
[PWA] Initializing PWA Helper...
[PWA] Registering Service Worker...
[PWA] Service Worker registered successfully
[PWA] PWA Helper initialized
```

## ✅ Step 6: Verify App Shell Caching

### In Browser DevTools:

1. Go to **Application** → **Cache Storage**
2. You should see caches:
   - `inv-cache-v1` (main app shell)
   - `inv-runtime-v1` (runtime cache)
   - `inv-images-v1` (image cache)
   - `inv-api-v1` (API responses)

### Test offline:

1. Go to **Application** → **Service Workers**
2. Check the **Offline** checkbox
3. Refresh the page
4. App should still load with cached assets

## ✅ Step 7: Test Offline Data Sync

### Simulate Offline:

1. Open DevTools → **Application** → **Service Workers**
2. Check **Offline** checkbox
3. Submit a count or create data
4. Data should be saved to IndexedDB

### Go Back Online:

1. Uncheck **Offline** checkbox
2. Watch console for sync messages:
   ```
   [SyncManager] Starting sync...
   [SyncManager] Syncing 5 counts...
   [SyncManager] Count sync completed
   ```
3. Check database - data should be synced

### Verify IndexedDB:

1. DevTools → **Application** → **IndexedDB**
2. Expand `InvCounterDB`
3. You should see these stores:
   - `counts` - Offline count records
   - `assignments` - Cached assignments
   - `reports` - Cached reports
   - `pending_syncs` - Operations to sync
   - `user_data` - User-specific data

## ✅ Step 8: Test Notifications

### Request Permission:

1. Reload page
2. Browser may ask for notification permission
3. Click **Allow**

### Check Subscription:

1. Open console and run:
   ```javascript
   await pwaHelper.subscribeToPushNotifications()
   ```
2. Should see: `[PWA] Subscribed to push notifications`

### Verify in Database:

```sql
SELECT * FROM push_subscriptions WHERE user_id = YOUR_USER_ID;
```

Should show the subscription endpoint.

### Send Test Notification:

```php
<?php
require_once 'includes/init.php';

$db = new Database();
$userId = 1; // Your user ID

// Create notification
$db->execute(
    "INSERT INTO notifications (user_id, title, message, type) VALUES (?, ?, ?, ?)",
    [$userId, 'Test Notification', 'This is a test', 'info']
);

// In-app notification will show on page refresh
echo "Notification created!";
```

## ✅ Step 9: Verify All APIs are Accessible

Test each API endpoint:

### Via Browser Console:

```javascript
// Test sync API
fetch('/invcount/api/sync-counts', {
  method: 'POST',
  headers: {'Content-Type': 'application/json'},
  body: JSON.stringify({counts: []})
}).then(r => r.json()).then(console.log)

// Test get assignments
fetch('/invcount/api/get-assignments')
  .then(r => r.json()).then(console.log)

// Test get reports
fetch('/invcount/api/get-reports')
  .then(r => r.json()).then(console.log)

// Test notifications
fetch('/invcount/api/get-notifications')
  .then(r => r.json()).then(console.log)

// Test VAPID key
fetch('/invcount/api/get-vapid-key')
  .then(r => r.json()).then(console.log)
```

All should return 200 status with valid JSON.

## ✅ Step 10: Test Install Prompt

### On Supported Browsers (Chrome, Edge, etc.):

1. Reload app in browser
2. Browser should show install prompt (in URL bar or menu)
3. Click **Install** / **Add to Home Screen**
4. App should install with icon and start_url

### Verify Installation:

- App opens in standalone mode (no browser chrome)
- App icon appears on home screen / app drawer
- App can be launched like native app

## ✅ Step 11: Enable Background Sync Features

### Periodic Sync (browser console):

```javascript
await pwaHelper.setupPeriodicBackgroundSync()
```

This will:
- Sync counts every 12 hours
- Check for notifications every 30 minutes

### Verify Registration:

```javascript
const reg = await navigator.serviceWorker.ready;
const tags = await reg.periodicSync.getTags();
console.log('Periodic sync tags:', tags);
// Should show: ['periodic-sync-counts', 'periodic-check-notifications']
```

## ✅ Step 12: Verify All Features

### Checklist:

```javascript
// In browser console
const status = pwaHelper.getInstallationStatus();
console.log('Installation Status:', status);

// Should show:
// {
//   isInstalled: true,
//   isOnline: true,
//   swReady: true,
//   notificationsEnabled: true,
//   canInstall: false (after install)
// }

// Sync status
console.log('Sync Status:', syncManager.getSyncStatus());
// Should show:
// {
//   isOnline: true,
//   syncInProgress: false,
//   databaseReady: true
// }

// Notification status
console.log('Notification Status:', notificationHandler.getStatus());
// Should show:
// {
//   serviceWorkerReady: true,
//   subscriptionReady: true,
//   pollingActive: false,
//   permissionStatus: 'granted'
// }
```

## ✅ Troubleshooting

### Service Worker Not Installing

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

### Offline Not Working

1. Check manifest MIME type: `Content-Type: application/manifest+json`
2. Verify Service Worker scope: `/invcount/`
3. Check browser DevTools → Application → Service Workers
4. Ensure all cache files exist (manifest, CSS, JS)

### Notifications Not Showing

1. Check browser notification permission
2. Verify Service Worker is "activated"
3. Test push subscription: `await pwaHelper.subscribeToPushNotifications()`
4. Check `push_subscriptions` table

### Sync Not Working

1. Verify IndexedDB exists in DevTools
2. Check API endpoints in browser Network tab
3. Review console for errors (filter `[SW]` and `[SyncManager]`)
4. Ensure user is authenticated

## 📝 Next Steps

After setup:

1. **Document offline workflows** - Guide users on offline-first features
2. **Add offline UI indicators** - Show sync status, online/offline state
3. **Implement conflict resolution** - Handle concurrent edits
4. **Monitor sync logs** - Regular DB cleanup of old sync records
5. **User education** - Train users on offline features
6. **Performance monitoring** - Track cache sizes and sync times

## 🔗 Documentation Files

- `PWA_IMPLEMENTATION.md` - Complete technical guide
- `manifest.json` - App manifest configuration
- `assets/js/service-worker.js` - Service Worker logic
- `assets/js/pwa-helper.js` - PWA initialization
- `assets/js/sync-manager.js` - Offline sync management
- `assets/js/notification-handler.js` - Notification handling
- `api/*.php` - API endpoints for PWA features

## 📞 Support

For issues or questions:

1. Check console for error messages (F12 → Console)
2. Review `PWA_IMPLEMENTATION.md` for detailed documentation
3. Check browser DevTools for Service Worker status
4. Review MySQL `sync_logs` table for sync errors
5. Test APIs manually from browser console

---

**Setup Complete!** Your Inventory Counter app is now a full Progressive Web App with offline capabilities. 🎉
