# ⚡ Quick Start Guide - Week 8: Test Scheduling & Notifications

Get the scheduling and notifications system up and running in 5 minutes!

## 🚀 Step-by-Step Setup

### 1. Run Migrations (1 minute)

```bash
cd /home/user/pathshalaa_api
php artisan migrate
```

Expected output:
```
✓ Created jobs table
✓ Created failed_jobs table
✓ Created job_batches table
✓ Created scheduled_notifications table
✓ Added scheduling fields to testseries table
```

### 2. Configure Environment (1 minute)

Edit `.env` file:

```bash
nano .env
```

Add/update these lines:

```env
# Queue (already set to database)
QUEUE_CONNECTION=database

# Email (use your Gmail or SMTP)
MAIL_MAILER=smtp
MAIL_HOST=smtp.gmail.com
MAIL_PORT=587
MAIL_USERNAME=your-email@gmail.com
MAIL_PASSWORD=your-app-password
MAIL_ENCRYPTION=tls
MAIL_FROM_ADDRESS=support@pathshalaa.in
MAIL_FROM_NAME="Pathshalaa"

# App URL (for email links)
APP_URL=https://pathshalaa.in
```

**Note:** For Gmail, create an app-specific password at https://myaccount.google.com/apppasswords

### 3. Start Queue Worker (30 seconds)

**Development:**
```bash
php artisan queue:work --tries=3
```

Keep this terminal running!

**Production (with Supervisor):**
```bash
sudo cp supervisor/pathshalaa-worker.conf /etc/supervisor/conf.d/
sudo supervisorctl reread
sudo supervisorctl update
sudo supervisorctl start pathshalaa-worker:*
```

### 4. Add Routes (1 minute)

Edit `routes/api.php`:

```php
use App\Http\Controllers\Api\Teacher\TestSeriesController;
use App\Http\Controllers\Api\Admin\QueueMonitoringController;

// Teacher routes
Route::middleware(['auth:sanctum', 'role:teacher'])->prefix('v2/tutor')->group(function () {
    Route::put('test-series/{id}/schedule', [TestSeriesController::class, 'updateSchedule']);
    Route::post('test-series/{id}/cancel', [TestSeriesController::class, 'cancelTest']);
    Route::get('test-series/scheduled', [TestSeriesController::class, 'getScheduledTests']);
});

// Admin routes
Route::middleware(['auth:sanctum', 'role:admin'])->prefix('v2/admin/queue')->group(function () {
    Route::get('stats', [QueueMonitoringController::class, 'getQueueStats']);
    Route::get('failed-jobs', [QueueMonitoringController::class, 'getFailedJobs']);
    Route::post('failed-jobs/{id}/retry', [QueueMonitoringController::class, 'retryFailedJob']);
    Route::delete('failed-jobs/{id}', [QueueMonitoringController::class, 'deleteFailedJob']);
    Route::delete('failed-jobs', [QueueMonitoringController::class, 'clearFailedJobs']);
    Route::get('scheduled-notifications', [QueueMonitoringController::class, 'getScheduledNotifications']);
});
```

### 5. Test It! (1 minute)

**Option A: Using cURL**

```bash
# Create a test with schedule (replace YOUR_TOKEN and adjust date)
curl -X POST http://localhost:8000/api/v2/tutor/test-series/auto-generate \
  -H "Authorization: Bearer YOUR_TEACHER_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "test_series_name": "Quick Test",
    "class_id": 1,
    "subject_ids": [10],
    "topic_ids": [101],
    "question_count": 10,
    "per_question_marks": 1,
    "total_time": 30,
    "use_ai_generation": false,
    "consent_given": false,
    "scheduled_at": "2025-01-20 10:00:00",
    "auto_publish_results": true
  }'
```

**Option B: Using Postman**

1. Import collection: `postman/Week_8_Test_Scheduling_Notifications.postman_collection.json`
2. Set variables: `base_url`, `teacher_token`, `admin_token`
3. Run "Create Test with Schedule" request

### 6. Verify It's Working (1 minute)

**Check scheduled notifications:**
```bash
# In MySQL/DB client
SELECT * FROM scheduled_notifications ORDER BY id DESC LIMIT 5;
```

Expected result: You should see 4 notifications for your test:
- test_scheduled (immediate)
- 24h_reminder
- 1h_reminder
- test_live

**Check queue jobs:**
```bash
# In MySQL/DB client
SELECT queue, COUNT(*) as count FROM jobs GROUP BY queue;
```

Expected result: Jobs queued for future execution.

**Check worker logs:**
```bash
tail -f storage/logs/worker.log
```

---

## ✅ Verification Checklist

- [ ] Migrations ran successfully
- [ ] `.env` configured with email settings
- [ ] Queue worker is running
- [ ] Routes added to `routes/api.php`
- [ ] Test created with schedule via API
- [ ] Scheduled notifications exist in database
- [ ] Jobs queued in `jobs` table
- [ ] Worker processing jobs (check logs)

---

## 🎯 Quick Test Scenarios

### Scenario 1: Schedule a Test for Tomorrow

```json
POST /api/v2/tutor/test-series/auto-generate
{
  "scheduled_at": "2025-01-15 14:00:00",
  "auto_publish_results": true
}
```

Result:
- ✅ Immediate notification sent
- ✅ 24h reminder scheduled for tomorrow 14:00
- ✅ 1h reminder scheduled for tomorrow 13:00
- ✅ "Test Live" notification scheduled for tomorrow 14:00

### Scenario 2: Reschedule a Test

```json
PUT /api/v2/tutor/test-series/{id}/schedule
{
  "scheduled_at": "2025-01-16 10:00:00"
}
```

Result:
- ✅ Old notifications cancelled
- ✅ New notifications scheduled
- ✅ Students notified of reschedule

### Scenario 3: Cancel a Test

```json
POST /api/v2/tutor/test-series/{id}/cancel
```

Result:
- ✅ All notifications cancelled
- ✅ Students notified of cancellation
- ✅ Test marked as cancelled

---

## 🐛 Common Issues & Fixes

### Issue: Queue not processing

**Fix:**
```bash
# Check if queue worker is running
ps aux | grep "queue:work"

# If not running, start it
php artisan queue:work --tries=3
```

### Issue: Emails not sending

**Fix:**
```bash
# Test SMTP connection
php artisan tinker
```
```php
Mail::raw('Test', fn($m) => $m->to('test@example.com')->subject('Test'));
```

Check for errors. Common causes:
- Wrong email credentials in `.env`
- Gmail blocking (use app-specific password)
- SMTP port blocked by firewall

### Issue: Notifications not appearing

**Fix:**
```bash
# Check scheduled_notifications table
SELECT * FROM scheduled_notifications WHERE test_series_id = YOUR_TEST_ID;

# Check if jobs are queued
SELECT * FROM jobs LIMIT 10;

# Check failed jobs
SELECT * FROM failed_jobs ORDER BY failed_at DESC LIMIT 5;
```

### Issue: "Class not found" errors

**Fix:**
```bash
# Clear and regenerate autoload
composer dump-autoload

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

---

## 📊 Monitoring Commands

```bash
# View queue stats
curl http://localhost:8000/api/v2/admin/queue/stats \
  -H "Authorization: Bearer YOUR_ADMIN_TOKEN"

# View scheduled tests
curl http://localhost:8000/api/v2/tutor/test-series/scheduled \
  -H "Authorization: Bearer YOUR_TEACHER_TOKEN"

# Check failed jobs
php artisan queue:failed

# Retry failed jobs
php artisan queue:retry all

# View worker logs
tail -f storage/logs/worker.log
```

---

## 🎉 Success!

If you've completed all steps, you now have:
- ✅ Tests can be scheduled with notifications
- ✅ Multi-channel notifications (Push + Email + Database)
- ✅ Queue-based async processing
- ✅ Schedule management (update/cancel)
- ✅ Admin monitoring dashboard

**Need help?** Check the full documentation in `WEEK_8_SCHEDULING_NOTIFICATIONS.md`

---

## 📞 Next Steps

1. **Test email templates** - Send yourself test emails
2. **Configure Firebase** - Ensure FCM is working for push notifications
3. **Set up Supervisor** - For production queue workers
4. **Monitor queues** - Use admin endpoints to track performance
5. **Customize templates** - Edit Blade templates in `resources/views/emails/`

**Happy scheduling! 🚀**
