# Push Notification System - Quick Start Guide

## ✅ What Has Been Implemented

A complete push notification system has been created for the Disrupt Radio platform with the following components:

### 1. Database Schema ✅

- **push_subscriptions** - Device tokens and subscription management
- **notification_preferences** - User content subscription tracking
- **notification_logs** - Notification history and delivery status

### 2. Backend Components ✅

- **Models**: PushSubscription, NotificationPreference, NotificationLog
- **Service**: PushNotificationService (handles all notification logic)
- **Controller**: PushNotificationController (API endpoints)
- **Event**: NewContentPublished
- **Listener**: SendContentNotification (queued job)
- **Helper Functions**: notifyNewEpisode(), notifyNewProgram(), notifyNewPodcast(), notifyLiveShow()

### 3. API Endpoints ✅

All routes created under `/notifications/*`:

- Subscribe/unsubscribe devices
- Subscribe to specific content (programs/podcasts)
- Get/update user preferences
- Check subscription status

### 4. Frontend Components ✅

- **Service Worker** (`/public/service-worker.js`) - Handles push events
- **Push Manager** (`/public/js/push-notifications.js`) - Manages subscriptions
- **Notification Bell** (`/public/js/notification-bell.js`) - UI component
- **Styles** (`/public/css/push-notifications.css`) - Complete styling
- **Settings Page** (`/resources/views/front/notification-settings.blade.php`)

### 5. UI Integration ✅

- Bell icons added to program cards (Flagship & Specialist)
- Bell icons added to podcast cards
- Modal for requesting permission
- Toast notifications for feedback
- Settings page for managing preferences

---

## 🚀 Quick Setup (5 Steps)

### Step 1: Install Dependencies

```bash
composer require minishlink/web-push
composer dump-autoload
```

### Step 2: Run Database Migrations

```bash
php artisan migrate
```

### Step 3: Generate VAPID Keys

**Option A - Using Online Tool:**
Visit: https://web-push-codelab.glitch.me/ and generate VAPID keys

**Option B - Using PHP:**

```php
<?php
require 'vendor/autoload.php';
use Minishlink\WebPush\VAPID;
$keys = VAPID::createVapidKeys();
echo "Public: " . $keys['publicKey'] . "\n";
echo "Private: " . $keys['privateKey'] . "\n";
```

### Step 4: Update .env File

```env
# Add these lines to your .env file
VAPID_PUBLIC_KEY=your_generated_public_key_here
VAPID_PRIVATE_KEY=your_generated_private_key_here

# For mobile apps (optional)
FCM_SERVER_KEY=your_fcm_server_key_here

# Queue configuration (recommended)
QUEUE_CONNECTION=database
```

### Step 5: Clear Cache & Test

```bash
php artisan config:cache
php artisan queue:table
php artisan migrate
php artisan queue:work
```

---

## 🎯 How to Use

### For Developers - Trigger Notifications

**When creating new content:**

```php
// In your Audio/Episode Controller
$episode = Audio::create($data);
notifyNewEpisode($episode);

// In your Program Controller
$program = Program::create($data);
notifyNewProgram($program);

// In your Podcast Controller
$podcast = Album::create($data);
notifyNewPodcast($podcast);

// When going live
notifyLiveShow($program);
```

### For Users - Subscribe to Content

1. Click the bell icon on any program or podcast
2. Click "Allow" in the permission modal
3. Bell icon turns solid (notifications enabled)
4. Click again to unsubscribe

### For Users - Manage Settings

Visit: `https://yoursite.com/notification-settings`

---

## 📱 Mobile App Support (Android/iOS)

The backend is ready for mobile apps using Firebase Cloud Messaging (FCM).

**Mobile App Implementation:**

1. Get FCM Server Key from Firebase Console
2. Add to `.env`: `FCM_SERVER_KEY=your_key`
3. From your mobile app, send device token:

```javascript
// API Call from mobile app
POST /notifications/subscribe
{
  "device_token": "fcm_device_token_here",
  "device_type": "android" // or "ios"
}
```

4. Handle notifications in your app with deep linking based on `type` and `id` in payload

---

## 🧪 Testing

### Test Web Push Notifications:

1. Open your site in Chrome/Firefox
2. Open DevTools Console
3. Run:

```javascript
// Request permission
await window.pushNotificationManager.requestPermission();

// Subscribe to a program (ID 1)
await window.pushNotificationManager.toggleContentSubscription("program", 1);
```

4. From backend, trigger a test:

```php
use App\Services\PushNotificationService;

$service = app(PushNotificationService::class);
$service->notifySubscribers('program', 1, 'Test', 'Testing notifications!', url('/'));
```

---

## 📋 Integration Checklist

Use this checklist to integrate notifications into your existing content controllers:

### Audio/Episode Controller

- [ ] Add `notifyNewEpisode($audio)` after creating new episode
- [ ] Add notification when unpublished episode is published

### Program Controller

- [ ] Add `notifyNewProgram($program)` after creating new program
- [ ] Add `notifyLiveShow($program)` when starting live broadcast

### Podcast Controller

- [ ] Add `notifyNewPodcast($podcast)` after creating new podcast
- [ ] Add notification when adding new episode to podcast series

### Scheduled Tasks (optional)

- [ ] Add cron job to check upcoming live shows
- [ ] Add cleanup job for old notification logs

---

## 🎨 UI Customization

All styles are in `/public/css/push-notifications.css`

**Key CSS classes:**

- `.notification-bell-btn` - Bell button styling
- `.notification-modal` - Permission modal
- `.notification-toast` - Toast notifications
- `.notification-bell-compact` - Smaller bell for cards

**Colors match your brand:**

- Primary: `#DA0238` (red gradient)
- Background: Dark theme with transparency
- Hover effects and animations included

---

## 🔧 Troubleshooting

### Notifications not showing?

1. Check VAPID keys are set in `.env`
2. Run `php artisan config:cache`
3. Verify HTTPS (required, except localhost)
4. Check browser permission: Settings > Site Settings > Notifications

### Bell icon not appearing?

1. Check scripts are loaded in layout file
2. Verify `data-notification-bell` attribute is present
3. Check browser console for JavaScript errors
4. Run `initializeNotificationBells()` in console to reinitialize

### Subscription fails?

1. Ensure CSRF token is on page: `<meta name="csrf-token" content="{{ csrf_token() }}">`
2. Check user is authenticated
3. Verify API endpoints are accessible
4. Check network tab for 422/500 errors

---

## 📖 Documentation Files

- `PUSH_NOTIFICATIONS_SETUP.md` - Complete technical documentation
- `NOTIFICATION_INTEGRATION_EXAMPLES.php` - Code examples for integration
- This file - Quick start guide

---

## 🌐 Browser Support

| Browser | Support                 |
| ------- | ----------------------- |
| Chrome  | ✅ Full                 |
| Firefox | ✅ Full                 |
| Safari  | ✅ iOS 16.4+, macOS 13+ |
| Edge    | ✅ Full                 |
| Opera   | ✅ Full                 |
| IE      | ❌ Not supported        |

---

## 🔐 Security Notes

1. **HTTPS Required** - Web Push only works over HTTPS
2. **Keep private keys secret** - Never commit VAPID private key or FCM server key
3. **User consent required** - Always ask permission before subscribing
4. **Easy unsubscribe** - Bell icon provides instant unsubscribe

---

## 📊 Monitoring

Check notification delivery status:

```php
// Get recent notifications
$logs = \App\NotificationLog::where('created_at', '>=', now()->subHours(24))
    ->with('user')
    ->get();

// Get failed notifications
$failed = \App\NotificationLog::failed()->get();

// Get statistics
$stats = [
    'total_sent' => \App\NotificationLog::sent()->count(),
    'total_failed' => \App\NotificationLog::failed()->count(),
    'active_subscriptions' => \App\PushSubscription::where('is_active', true)->count(),
];
```

---

## 🎉 Ready to Go!

Your push notification system is complete and ready to use. Follow the 5-step quick setup above, then start adding notification triggers to your content controllers.

**Support:** Check the example files for implementation patterns and best practices.

**Next Steps:**

1. Complete the 5-step setup
2. Test with a program/podcast
3. Integrate into your existing controllers
4. Monitor and adjust as needed

Good luck! 🚀
