# 🔔 PWA Push Notifications - Setup Guide

**Quick guide for setting up PWA push notifications**

---

## 📋 What is PWA Push Notifications?

PWA (Progressive Web App) Push Notifications allow your website to send real-time notifications to users' browsers, even when the website is closed. Users receive instant alerts for new orders with custom sounds and emojis.

### Features
- ✅ Real-time order notifications
- ✅ Custom notification sounds (Kaching!)
- ✅ Custom emojis (💰 for regular orders, 🎉 for high-value orders)
- ✅ Works on desktop & mobile browsers
- ✅ Customizable notification templates
- ✅ Volume control
- ✅ Admin settings UI

---

## 🎯 Requirements

### Browser Support
- ✅ Chrome/Edge (Desktop & Android)
- ✅ Firefox (Desktop & Android)
- ✅ Safari 16.4+ (macOS & iOS)
- ❌ iOS Safari below 16.4 (not supported)

### Server Requirements
- ✅ **HTTPS Required** (SSL certificate)
- ✅ PHP extension: `gmp` (for VAPID keys)
- ✅ Laravel packages installed (webpush)
- ✅ Database tables: `push_subscriptions`, `notifications`

---

## 🔧 Installation Steps

### Step 1: Install PHP GMP Extension

```bash
# Ubuntu/Debian
sudo apt install php8.2-gmp -y

# Restart PHP
sudo systemctl restart php8.2-fpm
# OR for OpenLiteSpeed
sudo systemctl restart lsws
```

Verify:
```bash
php -m | grep gmp
# Should output: gmp
```

### Step 2: Generate VAPID Keys

VAPID (Voluntary Application Server Identification) keys authenticate your server with push services.

```bash
cd /var/www/mamadil.team

# Generate keys
php artisan webpush:vapid

# Output:
# Public key:  BMCKxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
# Private key: RfEhxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
```

**Copy these keys!** You'll need them in the next step.

### Step 3: Configure Environment

Edit `.env` and add VAPID keys:

```bash
nano .env
```

Add these lines:
```env
# PWA Push Notifications
VAPID_PUBLIC_KEY=BMCKxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
VAPID_PRIVATE_KEY=RfEhxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
VAPID_SUBJECT=mailto:admin@mamadil.team
```

**Important:**
- `VAPID_SUBJECT` must be a valid email address
- Replace `admin@mamadil.team` with your actual email
- Keys must not have any line breaks

### Step 4: Run Migrations

```bash
php artisan migrate --force
```

This creates two tables:
- `push_subscriptions` - Stores user notification subscriptions
- `notifications` - Laravel notifications table

Verify tables exist:
```bash
mysql -u username -p database_name -e "SHOW TABLES LIKE '%push%'; SHOW TABLES LIKE '%notif%';"
```

### Step 5: Upload PWA Icon Files

Icons are required for PWA installation and notifications.

**Option A: Use an online generator**

1. Go to https://realfavicongenerator.net/
2. Upload your logo (512x512px square recommended)
3. Configure settings
4. Generate and download icons
5. Upload to `public/icons/` folder

**Option B: Manual creation**

Create these icon files and upload to `public/icons/`:

```
public/icons/icon-72.png     (72x72px)
public/icons/icon-96.png     (96x96px)
public/icons/icon-128.png    (128x128px)
public/icons/icon-144.png    (144x144px)
public/icons/icon-152.png    (152x152px)
public/icons/icon-192.png    (192x192px)
public/icons/icon-384.png    (384x384px)
public/icons/icon-512.png    (512x512px)
```

**Icon Requirements:**
- PNG format
- Square (width = height)
- Transparent background recommended
- Simple, recognizable design

### Step 6: Upload Notification Sound

The default notification sound is `kaching.mp3`.

```bash
# Ensure sound file exists
ls -lh public/sounds/kaching.mp3
```

**Upload your own sound:**
1. Create/find a short sound (1-3 seconds recommended)
2. Save as MP3 format
3. Upload to `public/sounds/kaching.mp3`

**Tips for notification sounds:**
- Short duration (< 3 seconds)
- Clear and distinctive
- Not too loud
- MP3 format for best compatibility

### Step 7: Configure PWA Settings

Edit `config/pwa.php` to customize for your domain:

```bash
nano config/pwa.php
```

Update domain settings:
```php
'domains' => [
    'mamadil.team' => [
        'name' => 'Your App Name',
        'short_name' => 'YourApp',
        'description' => 'Real-time order notifications',
        'theme_color' => '#4F46E5',        // App color
        'background_color' => '#ffffff',   // Background
    ],
    // Add your production domain
    'yoursite.com' => [
        'name' => 'Your Site',
        'short_name' => 'Site',
        'description' => 'Description',
        'theme_color' => '#4F46E5',
        'background_color' => '#ffffff',
    ],
],
```

### Step 8: Clear Caches

```bash
php artisan config:clear
php artisan cache:clear
php artisan view:clear
php artisan route:clear
```

### Step 9: Verify Routes

```bash
php artisan route:list | grep -E "manifest|vapid|push"
```

Should show:
```
GET|HEAD  manifest.json ................. pwa.manifest
GET|HEAD  api/vapid-public-key .......... pwa.vapid
POST      api/push/subscribe ............. pwa.subscribe
DELETE    api/push/unsubscribe ........... pwa.unsubscribe
```

---

## 🧪 Testing

### Test 1: Check HTTPS

PWA requires HTTPS (except localhost).

```bash
curl -I https://yoursite.com
# Should return: HTTP/2 200
```

### Test 2: Check Manifest

Visit: `https://yoursite.com/manifest.json`

Should show JSON like:
```json
{
  "name": "Your App Name",
  "short_name": "YourApp",
  "start_url": "/",
  "display": "standalone",
  "icons": [...]
}
```

### Test 3: Check VAPID Public Key

Visit: `https://yoursite.com/api/vapid-public-key`

Should return your public key.

### Test 4: Enable Notifications

1. Login to your site
2. Go to Dashboard
3. Look for "Enable Notifications" button (top right)
4. Click it
5. Browser will ask for permission - Click "Allow"
6. Button should change to "Notifications Enabled"

**Browser Console (F12):**
```
[PWA] ServiceWorker registration successful
[PWA] Push subscription successful
```

### Test 5: Receive Notification

1. Create a test order (from Orders page)
2. You should immediately receive a notification
3. Notification should include:
   - Sound (kaching.mp3)
   - Emoji (💰 or 🎉)
   - Order number
   - Customer name
   - Total amount

### Test 6: Admin Settings

1. Go to: `https://yoursite.com/settings`
2. Scroll to "PWA Push Notifications" section
3. You should see:
   - Enable/disable checkbox
   - Title template input
   - Body template input
   - Emoji inputs
   - High value threshold
   - Volume slider
   - Preview button
4. Click "Preview Notification"
5. Should receive test notification with sound

---

## 🎨 Customization

### Customize Notification Templates

Go to: **Settings → PWA Push Notifications**

**Title Template:**
```
{emoji} Kaching! Pesanan #{order_number}
```

Available variables:
- `{emoji}` - Regular or high-value emoji
- `{order_number}` - Order ID

**Body Template:**
```
{total} • {customer} • {platform}
```

Available variables:
- `{total}` - Order total (e.g., RM888.00)
- `{customer}` - Customer name
- `{platform}` - Order source (Checkout Form, WooCommerce, etc.)

### Customize Emojis

- **Regular Order Emoji:** 💰 (default)
- **High Value Order Emoji:** 🎉 (default)

Change in Settings page or config:

```php
// app/Models/SystemSetting.php defaults:
'pwa_regular_emoji' => '💰'
'pwa_high_value_emoji' => '🎉'
```

### Customize High Value Threshold

Orders with total >= threshold use high-value emoji.

Default: RM 500

Change in: **Settings → High Value Threshold**

### Customize Sound Volume

Volume: 0-100% (default: 80%)

Change in: **Settings → Notification Sound Volume**

---

## 📁 File Structure

```
multistore/
├── app/
│   ├── Http/Controllers/
│   │   ├── ManifestController.php         # Generates manifest.json
│   │   └── PushSubscriptionController.php # Handles subscriptions
│   ├── Models/
│   │   └── SystemSetting.php             # PWA settings helpers
│   └── Notifications/
│       └── OrderCreatedNotification.php   # Push notification logic
├── config/
│   ├── pwa.php                            # PWA configuration
│   └── webpush.php                        # Web Push settings
├── database/migrations/
│   ├── 2025_11_18_154436_create_push_subscriptions_table.php
│   └── 2025_11_18_163041_create_notifications_table.php
├── public/
│   ├── icons/                             # PWA icons (72-512px)
│   ├── sounds/
│   │   └── kaching.mp3                    # Notification sound
│   └── service-worker.js                  # Service worker script
├── resources/views/
│   ├── components/
│   │   └── pwa-notification-button.blade.php
│   ├── layouts/
│   │   └── base.blade.php                 # Includes PWA setup
│   └── settings/
│       └── index.blade.php                # Admin settings UI
└── routes/
    └── web.php                            # PWA routes
```

---

## 🔍 Troubleshooting

### Issue: "Enable Notifications" button not showing

**Check:**
1. Service worker registered?
   - Open browser console (F12)
   - Look for: `[PWA] ServiceWorker registration successful`

2. User logged in?
   - PWA button only shows for authenticated users

3. HTTPS enabled?
   - Push notifications require HTTPS (except localhost)

**Fix:**
```bash
# Clear view cache
php artisan view:clear

# Hard refresh browser (Ctrl+Shift+R)
```

---

### Issue: "ServiceWorker registration failed"

**Cause:** Usually HTTPS requirement or CORS issue

**Check:**
1. Using HTTPS? (Push requires HTTPS)
2. Service worker accessible?
   ```bash
   curl -I https://yoursite.com/service-worker.js
   ```

**Fix for development (HTTP):**
- Chrome flag: `chrome://flags/#unsafely-treat-insecure-origin-as-secure`
- Add: `http://yoursite.test`
- Relaunch browser

---

### Issue: Notification permission "denied"

**Check:**
- Browser notification permission
- Site settings → Notifications

**Fix:**
1. Open browser settings
2. Find your site
3. Change notifications to "Allow"
4. Refresh page and try again

---

### Issue: No sound playing

**Check:**
1. Sound file exists?
   ```bash
   ls -lh public/sounds/kaching.mp3
   ```

2. Browser console shows sound playing?
   ```
   [PWA] Playing sound: /sounds/kaching.mp3
   [PWA] Sound played successfully
   ```

3. Browser audio not muted?
4. Volume setting in admin settings?

**Fix:**
```bash
# Re-upload sound file
# Check file format is MP3
# Check file size < 1MB
```

---

### Issue: VAPID key errors

**Error:** "VAPID keys not found"

**Fix:**
```bash
# Regenerate VAPID keys
php artisan webpush:vapid

# Update .env
nano .env

# Clear config cache
php artisan config:clear
```

---

### Issue: Notifications not sending

**Check:**
1. Queue worker running?
   ```bash
   sudo supervisorctl status mamadil-worker:*
   ```

2. Database tables exist?
   ```bash
   php artisan migrate:status | grep -E "push_subscriptions|notifications"
   ```

3. Laravel logs for errors?
   ```bash
   tail -100 storage/logs/laravel.log
   ```

**Fix:**
```bash
# Restart queue workers
sudo supervisorctl restart mamadil-worker:*

# Run migrations
php artisan migrate --force

# Clear all caches
php artisan optimize:clear
```

---

## 🔒 Security Notes

### VAPID Keys
- **Never commit to Git**
- Store securely in `.env`
- Backup in secure location
- Regenerating keys = all users must re-subscribe

### Database
- `push_subscriptions` table contains:
  - Endpoint URLs
  - Public keys
  - Auth tokens
- This data is sensitive, protect access

### HTTPS
- PWA requires HTTPS in production
- Self-signed certificates won't work for push
- Use Let's Encrypt for free SSL

---

## 📊 Analytics & Monitoring

### Check Subscription Count

```sql
SELECT COUNT(*) as active_subscriptions FROM push_subscriptions;
```

### Check Notification History

```sql
SELECT * FROM notifications ORDER BY created_at DESC LIMIT 10;
```

### Monitor Push Success Rate

Check Laravel logs:
```bash
tail -f storage/logs/laravel.log | grep -i "push"
```

---

## 🔄 Maintenance

### Regular Tasks

**Weekly:**
- Check subscription count
- Monitor error logs
- Test notifications working

**Monthly:**
- Clean old notifications
  ```sql
  DELETE FROM notifications WHERE created_at < DATE_SUB(NOW(), INTERVAL 90 DAY);
  ```
- Review notification settings
- Update sound files if needed

**As Needed:**
- Add new icon sizes
- Update notification templates
- Adjust volume based on feedback

---

## 📞 Support

### Useful Commands

```bash
# Check VAPID keys
php artisan tinker
>>> config('webpush.vapid.public_key')
>>> exit

# List all push routes
php artisan route:list --name=pwa

# Check queue jobs
php artisan queue:work --once

# Clear everything
php artisan optimize:clear
```

### Debug Mode

Enable detailed logging:
```env
# .env
APP_DEBUG=true
LOG_LEVEL=debug
```

Then check:
```bash
tail -f storage/logs/laravel.log
```

---

## ✅ Quick Checklist

- [ ] HTTPS enabled
- [ ] PHP GMP extension installed
- [ ] VAPID keys generated
- [ ] VAPID keys in .env
- [ ] Migrations ran
- [ ] Icons uploaded (8 sizes)
- [ ] Sound file uploaded
- [ ] PWA config updated
- [ ] Caches cleared
- [ ] Service worker loads
- [ ] Manifest loads
- [ ] Can enable notifications
- [ ] Test order sends notification
- [ ] Sound plays
- [ ] Settings page works

---

## 🎉 Success!

Your PWA push notifications are now set up! Users will receive real-time order notifications with custom sounds and emojis.

**Next Steps:**
- Train users how to enable notifications
- Monitor notification delivery
- Adjust settings based on feedback
- Consider adding more sound variations

---

**Document Version:** 1.0
**Last Updated:** 2025-11-18
**For:** Multistore Management System - PWA Feature
