# Local PWA Testing Guide (multistore.test)

Quick guide to test PWA push notifications on your local development environment.

## ✅ Installation Complete!

The following has been set up for you:

1. ✅ laravel-notification-channels/webpush package installed
2. ✅ Database migrations run (push_subscriptions table created)
3. ✅ VAPID keys generated and saved to .env
4. ✅ Service worker registered in base.blade.php
5. ✅ Notification subscription button added to dashboard
6. ✅ PWA routes configured

## 🚀 Quick Test (5 Minutes)

### Step 1: Start Your Server

Make sure Apache/Nginx is running and visit:
```
http://multistore.test
```

**Note**: Service workers work on localhost without HTTPS, but for production you'll need HTTPS.

### Step 2: Add Temporary Icons (Optional)

For testing purposes, you can skip icons. The app will work but show broken icon images.

**Quick fix**: Download a placeholder:
1. Visit: https://via.placeholder.com/192x192/4F46E5/FFFFFF?text=MT
2. Save as `public/icons/icon-192.png`
3. Copy to: `public/icons/icon-72.png`

Or see: `public/icons/SETUP_ICONS.txt` for detailed instructions.

### Step 3: Login to Dashboard

1. Login to your account
2. You should see "Enable Notifications" button in the top right of the dashboard
3. If you don't see it, check browser console for errors

### Step 4: Enable Notifications

1. Click "Enable Notifications" button
2. Browser will ask for permission - click "Allow"
3. Button should change to "Notifications Enabled" (green)
4. Check browser console - should see: `[PWA] Subscription successful`

### Step 5: Verify Service Worker

Open Chrome DevTools:
- Press `F12`
- Go to **Application** tab
- Click **Service Workers** (left sidebar)
- You should see `service-worker.js` - Status: activated and running

### Step 6: Check Manifest

Still in Application tab:
- Click **Manifest** (left sidebar)
- Should show:
  - Name: "Multistore Order Management"
  - Short name: "Multistore"
  - Icons (may show broken if not added yet)
  - Theme color: #4F46E5

### Step 7: Verify Subscription Saved

Check database:
```bash
php artisan tinker
```

Then run:
```php
$user = App\Models\User::find(YOUR_USER_ID);
$user->pushSubscriptions()->count(); // Should return 1
$user->pushSubscriptions()->first(); // View subscription details
```

Or via MySQL:
```bash
mysql -u root -e "SELECT * FROM multistore.push_subscriptions;"
```

### Step 8: Test Notification (Create Order)

**Option A: Via Tinker (Quickest)**
```bash
php artisan tinker
```

Then:
```php
$user = App\Models\User::find(YOUR_USER_ID);

$order = new App\Models\Order([
    'order_number' => 'TEST-' . time(),
    'total' => 150.00,
    'currency' => 'RM',
    'status' => 'pending',
    'created_by' => $user->id,
    'is_manual' => true,
    'billing' => [
        'first_name' => 'Test',
        'last_name' => 'Customer',
        'phone' => '0123456789'
    ],
    'shipping' => [
        'first_name' => 'Test',
        'last_name' => 'Customer',
        'address_1' => '123 Test St',
        'city' => 'KL',
        'postcode' => '50000',
        'country' => 'MY'
    ],
    'line_items' => []
]);

$order->save();
```

**Option B: Via Checkout Form**
1. Go to your checkout page
2. Create a real test order
3. Complete the order

**Option C: Via Sales Page**
1. Create a sales page
2. Submit an order through it

### Step 9: Verify Notification

After creating the order, you should:

1. **See browser notification** appear (top-right or system tray)
   - Title: "💰 Kaching! Order #TEST-xxxxx"
   - Body: "RM150.00 • Test Customer • Checkout Form"

2. **Hear sound** (if you added sound files)
   - Default: kaching.mp3
   - High value (>RM500): big-win.mp3

3. **Check logs**:
```bash
tail -f storage/logs/laravel.log | grep -i "notification\|push"
```

Should see:
```
[INFO] PWA push notification queued
[INFO] PWA push notification sent
```

### Step 10: Click Notification

Click the notification - should:
1. Focus/open the multistore.test window
2. Navigate to the order details page

## 🔍 Troubleshooting

### Notification Button Not Showing

**Check 1**: Browser console errors
```javascript
// Open console (F12 > Console tab)
// Look for errors related to service worker or push
```

**Check 2**: Service worker registered
```javascript
navigator.serviceWorker.getRegistration().then(reg => console.log(reg));
```

**Check 3**: Alpine.js loaded
- The button uses Alpine.js (x-data)
- Make sure Alpine is included in your app.js

### Service Worker Not Registering

**Fix 1**: Clear browser cache
- Chrome: DevTools > Application > Storage > Clear site data

**Fix 2**: Check service-worker.js is accessible
- Visit: `http://multistore.test/service-worker.js`
- Should show JavaScript code, not 404

**Fix 3**: Check console for errors
```
[PWA] ServiceWorker registration failed: [error]
```

### VAPID Key Error

If you see `VAPID_PUBLIC_KEY not found`:

1. Check `.env` file:
```bash
grep VAPID .env
```

2. If missing, regenerate:
```bash
php artisan webpush:vapid
```

3. Clear config cache:
```bash
php artisan config:clear
```

### Notification Permission Denied

If user denied permission:
1. Click padlock icon in address bar
2. Site Settings > Notifications > Allow
3. Refresh page
4. Try subscribing again

### No Notification Appears

**Check 1**: User has subscription
```php
php artisan tinker
User::find(YOUR_ID)->pushSubscriptions()->count(); // Should be > 0
```

**Check 2**: Order created with created_by
```php
App\Models\Order::latest()->first()->created_by; // Should be your user ID
```

**Check 3**: Logs for errors
```bash
tail -f storage/logs/laravel.log
```

**Check 4**: Browser allows notifications
- Check browser settings
- Check Do Not Disturb is off (Windows/Mac)

### Icons Not Loading

Temporary fix: Icons are optional for testing

Permanent fix: See `public/icons/SETUP_ICONS.txt`

### Sounds Not Playing

Temporary: Notifications work without sounds

Permanent: See `public/sounds/SETUP_SOUNDS.txt`

## 📊 Testing Checklist

- [ ] Service worker registered successfully
- [ ] Manifest.json loads without errors
- [ ] "Enable Notifications" button appears on dashboard
- [ ] Clicked "Enable Notifications" and allowed permission
- [ ] Subscription saved to database
- [ ] Created test order via tinker
- [ ] Browser notification appeared
- [ ] Notification title shows order number
- [ ] Clicking notification navigates to order
- [ ] Logs show "PWA push notification sent"

## 🎯 What's Working Now

Even without icons and sounds, you can test:
- ✅ Service worker registration
- ✅ Push subscription
- ✅ Notification delivery
- ✅ Notification click handling
- ✅ Role-based notifications
- ✅ Order observer triggers
- ✅ Database logging

## 📝 Next Steps

1. **Add Icons**: Follow `public/icons/SETUP_ICONS.txt`
2. **Add Sounds**: Follow `public/sounds/SETUP_SOUNDS.txt`
3. **Test Different Roles**:
   - Create seller account - should see own orders
   - Create manager account - should see team orders
   - Admin - sees all orders

4. **Test High-Value Orders**:
   - Create order with total >= RM500
   - Should see 🎉 emoji in notification
   - Will use big-win.mp3 sound (when added)

5. **Test on Mobile**:
   - Access multistore.test from phone (same network)
   - Enable notifications
   - Test order creation

6. **Production Deployment**:
   - See `PWA_IMPLEMENTATION_GUIDE.md` for full deployment steps
   - Remember: Production needs HTTPS

## 💡 Pro Tips

1. **Keep DevTools Open**: Application tab shows real-time service worker updates
2. **Check Network Tab**: See push subscription API calls
3. **Use Incognito**: Test fresh installation experience
4. **Multiple Browsers**: Test on Chrome, Edge, Firefox
5. **Clear Data**: Between tests, clear application data in DevTools

## 🆘 Still Having Issues?

1. Check Laravel logs: `storage/logs/laravel.log`
2. Check browser console (F12 > Console)
3. Verify database: `SELECT * FROM push_subscriptions;`
4. Test VAPID keys: `php artisan tinker` → `config('webpush.vapid.public_key')`
5. Review `PWA_IMPLEMENTATION_GUIDE.md` for detailed troubleshooting

## 📚 Resources

- [Service Worker API](https://developer.mozilla.org/en-US/docs/Web/API/Service_Worker_API)
- [Push API](https://developer.mozilla.org/en-US/docs/Web/API/Push_API)
- [Laravel WebPush Package](https://github.com/laravel-notification-channels/webpush)
- [Chrome DevTools Application Panel](https://developer.chrome.com/docs/devtools/progressive-web-apps/)

Happy testing! 🚀
