# PWA Push Notifications - Setup Guide

This guide explains how to set up Progressive Web App (PWA) push notifications for your order management system. Users will receive real-time notifications when new orders arrive, even when the browser is closed.

## What Are PWA Push Notifications?

PWA push notifications work like mobile app notifications, but for web browsers:

- **Real-time alerts** when new orders arrive
- **Work even when browser is closed** (on desktop)
- **No app installation** required (it's a web app)
- **Cross-platform** (works on Chrome, Firefox, Edge, etc.)
- **Optional** (users can enable/disable)

## How It Works

1. User visits your site
2. Browser asks "Allow notifications?"
3. User clicks "Allow"
4. System registers their device
5. New order arrives → push notification sent
6. User clicks notification → opens order details

## Requirements

- **HTTPS required** (PWA only works on secure connections)
- **Supported browsers:** Chrome, Firefox, Edge, Opera, Safari (iOS 16.4+)
- **Laravel 11** with Pusher Beams or similar service
- **Service Worker** (included in the code)

## Installation Steps

### 1. Install Laravel WebPush Package

The system uses Laravel's notification system with web push support:

```bash
composer require laravel-notification-channels/webpush
```

### 2. Generate VAPID Keys

VAPID keys are used to secure push notifications. Generate them:

```bash
php artisan webpush:vapid
```

This creates two keys and adds them to your `.env` file:

```env
VAPID_PUBLIC_KEY=BG1hDJr...
VAPID_PRIVATE_KEY=vgYT3...
```

**Important:** Keep these keys secret. Don't commit them to version control.

### 3. Run Database Migration

Create the push subscriptions table:

```bash
php artisan migrate
```

This creates a `push_subscriptions` table to store user device registrations.

### 4. Configure App Settings

Update your `.env` file:

```env
# App settings (must be HTTPS in production)
APP_URL=https://yourdomain.com

# PWA Settings
PWA_NAME="Multistore System"
PWA_SHORT_NAME="Multistore"
PWA_THEME_COLOR="#1a202c"
PWA_BACKGROUND_COLOR="#ffffff"
```

### 5. Deploy Service Worker

The service worker file is already included at `public/serviceworker.js`. Make sure it's accessible:

Test by visiting: `https://yourdomain.com/serviceworker.js`

You should see the service worker JavaScript code.

### 6. Update Icons

PWA requires icons for different device sizes. Place these in `public/icons/`:

- `icon-72x72.png`
- `icon-96x96.png`
- `icon-128x128.png`
- `icon-144x144.png`
- `icon-152x152.png`
- `icon-192x192.png`
- `icon-384x384.png`
- `icon-512x512.png`

You can generate these from a single logo using online tools like [RealFaviconGenerator](https://realfavicongenerator.net/).

### 7. Clear Caches

After making changes:

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

## Testing on Localhost

Testing PWA features on localhost requires special setup since PWA needs HTTPS.

### Option 1: Use ngrok (Easiest)

1. Install [ngrok](https://ngrok.com/)
2. Start your local server: `php artisan serve`
3. Start ngrok: `ngrok http 8000`
4. Use the HTTPS URL ngrok provides

### Option 2: Local HTTPS Certificate

See [Local PWA Testing Guide](testing.md) for detailed instructions on setting up local HTTPS.

## Enabling Notifications (User Side)

Once set up, users can enable notifications:

1. Visit the site (must be HTTPS)
2. Browser shows "Allow notifications?" prompt
3. Click "Allow"
4. Notification permission granted
5. User's device is registered

Alternatively, users can enable notifications from the settings page or a dedicated toggle button.

## Sending Test Notification

Test if notifications work:

```bash
php artisan tinker
```

```php
$user = App\Models\User::find(1); // Replace with your user ID
$order = App\Models\Order::first();

$user->notify(new App\Notifications\OrderCreatedNotification($order));
```

You should receive a notification on your device.

## Notification Types

The system sends notifications for:

1. **New Order Created**
   - Title: "New Order Received"
   - Body: "Order #12345 from Customer Name"
   - Click action: Opens order details

2. **Order Status Changed**
   - Title: "Order Status Updated"
   - Body: "Order #12345 is now Processing"
   - Click action: Opens order details

3. **Tracking Number Generated**
   - Title: "Order Shipped"
   - Body: "Order #12345 tracking: POS1234567"
   - Click action: Opens order details

## Who Gets Notifications?

The system determines who receives notifications based on roles:

**Seller:**
- Gets notifications for their own orders only
- Orders they created via checkout/sales pages

**Manager:**
- Gets notifications for their team's orders
- Can be configured per manager

**Admin:**
- Gets notifications for all orders (optional)
- Can be disabled in user settings

## Customizing Notifications

### Notification Content

Edit `app/Notifications/OrderCreatedNotification.php`:

```php
public function toWebPush($notifiable)
{
    return (new WebPushMessage)
        ->title('New Order!')  // Customize title
        ->body('Order from ' . $this->order->customer_name)  // Customize body
        ->icon('/icons/icon-192x192.png')  // App icon
        ->badge('/icons/badge-72x72.png')  // Badge icon
        ->data(['order_id' => $this->order->id])  // Custom data
        ->action('View Order', 'view_order');  // Action button
}
```

### Notification Sound

Add sound to notifications (edit `public/serviceworker.js`):

```javascript
self.addEventListener('push', function(event) {
    const options = {
        body: data.body,
        icon: '/icons/icon-192x192.png',
        badge: '/icons/badge-72x72.png',
        vibrate: [200, 100, 200],  // Vibration pattern
        sound: '/sounds/notification.mp3',  // Add sound
        data: data.data
    };

    event.waitUntil(
        self.registration.showNotification(data.title, options)
    );
});
```

## Browser Support

| Browser | Desktop | Mobile | Notes |
|---------|---------|--------|-------|
| Chrome | ✅ | ✅ | Full support |
| Firefox | ✅ | ✅ | Full support |
| Edge | ✅ | ✅ | Full support |
| Safari | ✅ (macOS 13+) | ✅ (iOS 16.4+) | Recent versions only |
| Opera | ✅ | ✅ | Based on Chrome |

**Note:** iOS Safari only supports PWA push since iOS 16.4 (March 2023).

## Production Deployment

When deploying to production:

1. **Ensure HTTPS** is properly configured
2. **Update APP_URL** in `.env` to your production domain
3. **Clear all caches** after deployment
4. **Test notifications** before announcing to users
5. **Monitor logs** for any push notification errors

## Troubleshooting

**Notifications not showing:**
- Check [Troubleshooting Guide](troubleshooting.md)

**Permission denied:**
- User must manually reset permission in browser settings

**Service worker not registering:**
- Check browser console for errors
- Verify `serviceworker.js` is accessible
- Must be served over HTTPS

## Security Considerations

1. **VAPID keys are private** - Don't share or commit them
2. **HTTPS is required** - No exceptions for production
3. **User consent required** - Never force-enable notifications
4. **Respect user preferences** - Provide easy opt-out

## Next Steps

- [Testing Guide](testing.md) - Test notifications locally
- [Troubleshooting](troubleshooting.md) - Fix common issues

---

**Last updated:** 2025-11-21
