# Notification System - Quick Start Guide

## 🚀 Getting Started in 3 Steps

### Step 1: Set Up Environment

If you don't have a `.env` file yet:

```bash
# Copy the example file
cp .env.example .env

# Generate application key
php artisan key:generate
```

Make sure your `.env` has these settings:

```env
QUEUE_CONNECTION=database

MAIL_MAILER=smtp
MAIL_HOST=smtp.yandex.com
MAIL_PORT=587
MAIL_USERNAME=noreply@apper.com.tr
MAIL_PASSWORD=cchwvkreuwlwyzbb
MAIL_ENCRYPTION=tls
MAIL_FROM_ADDRESS=noreply@apper.com.tr
MAIL_FROM_NAME="Görev Bildirimi"
```

### Step 2: Run Migrations

```bash
php artisan migrate
```

This creates:
- `notifications` table - Stores all notifications
- `jobs` table - Queue system for emails
- Other pending migrations

### Step 3: Start Queue Worker

Open a **new terminal** and run:

```bash
php artisan queue:work --tries=3 --timeout=90
```

**Keep this running** while testing!

---

## 🧪 Testing the System

### Option 1: Use the Test Command

```bash
php artisan test:notifications --email=your-email@example.com
```

This will send 3 test notifications to verify everything works.

### Option 2: Manual Testing

1. **Login as User A** (task creator)
2. Create a new task
3. **Assign it to User B**
4. Check User B's email → Should receive "Yeni Görev Atandı" notification

5. **Login as User B** (assignee)
6. Complete the task or add a note
7. Check User A's email → Should receive "Görev Güncellendi" notification

---

## 📊 Monitoring

### Check Database Notifications

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

-- Count notifications per user
SELECT notifiable_id, COUNT(*) as count 
FROM notifications 
GROUP BY notifiable_id;
```

### Check Queue Status

```bash
# View failed jobs
php artisan queue:failed

# Retry all failed jobs
php artisan queue:retry all

# Clear failed jobs
php artisan queue:flush
```

### View Logs

```bash
# Real-time log monitoring
tail -f storage/logs/laravel.log

# Or on Windows PowerShell
Get-Content storage/logs/laravel.log -Wait -Tail 50
```

---

## 🔔 When Notifications Are Sent

| Action | Who Gets Notified | Notification Type |
|--------|------------------|-------------------|
| Assign task to user | Assigned user | TaskAssigned |
| Unassign/reassign user | Previous assignee | TaskUpdated (status_changed) |
| Complete task | Task creator | TaskUpdated (completed) |
| AI complete task | Task creator | TaskUpdated (completed) |
| Add note to task | Task creator | TaskUpdated (note_added) |
| Update task note | Task creator | TaskUpdated (details_updated) |
| Assign company | Task creator | TaskUpdated (details_updated) |
| Change task color | Task creator | TaskUpdated (details_updated) |

**Note:** Notifications are only sent when the actor is different from the recipient (you won't notify yourself).

---

## 🎨 Email Customization

To customize email templates, edit these files:

- `app/Notifications/TaskAssigned.php` - Assignment email template
- `app/Notifications/TaskUpdated.php` - Update email template

You can modify:
- Subject lines
- Greeting messages
- Email body content
- Action button text/URL
- Closing messages

---

## ⚙️ Advanced Configuration

### Add Notification Preferences

Want users to control which notifications they receive?

1. Add columns to users table:
```bash
php artisan make:migration add_notification_preferences_to_users_table
```

2. Migration content:
```php
Schema::table('users', function (Blueprint $table) {
    $table->boolean('email_on_task_assigned')->default(true);
    $table->boolean('email_on_task_updated')->default(true);
});
```

3. Check preferences before sending:
```php
if ($user->email_on_task_assigned) {
    $user->notify(new TaskAssigned($task, auth()->user()->name));
}
```

### Production Queue Setup

For production, use Supervisor instead of manual queue worker:

```bash
# Install Supervisor
sudo apt-get install supervisor

# Create config
sudo nano /etc/supervisor/conf.d/laravel-worker.conf
```

Config content:
```ini
[program:laravel-worker]
process_name=%(program_name)s_%(process_num)02d
command=php /path/to/planner.apper/artisan queue:work database --sleep=3 --tries=3 --max-time=3600
autostart=true
autorestart=true
stopwaitsecs=3600
numprocs=8
redirect_stderr=true
stdout_logfile=/path/to/planner.apper/storage/logs/worker.log
```

Then:
```bash
sudo supervisorctl reread
sudo supervisorctl update
sudo supervisorctl start laravel-worker:*
```

---

## ❓ Troubleshooting

### Emails Not Being Sent

1. **Check if queue worker is running:**
   ```bash
   ps aux | grep queue:work
   ```

2. **Check for failed jobs:**
   ```bash
   php artisan queue:failed
   ```

3. **Check mail configuration:**
   ```bash
   php artisan tinker
   >>> config('mail.mailers.smtp.host')
   >>> config('mail.from.address')
   ```

4. **Test SMTP connection:**
   ```bash
   telnet smtp.yandex.com 587
   ```

### Notifications Not Appearing in Database

1. **Verify migrations ran:**
   ```bash
   php artisan migrate:status
   ```

2. **Check notifications table exists:**
   ```sql
   SHOW TABLES LIKE 'notifications';
   ```

### Queue Worker Stops

Restart it:
```bash
php artisan queue:restart
php artisan queue:work --tries=3 --timeout=90
```

---

## 📚 Additional Resources

- Laravel Notifications: https://laravel.com/docs/notifications
- Laravel Queues: https://laravel.com/docs/queues
- Laravel Mail: https://laravel.com/docs/mail

---

## ✅ Checklist

Before going live, verify:

- [ ] `.env` file configured with correct settings
- [ ] Migrations completed successfully
- [ ] Queue worker running (or Supervisor configured)
- [ ] Test notifications received in email
- [ ] Database notifications being stored
- [ ] No errors in `storage/logs/laravel.log`
- [ ] SMTP credentials working (check Yandex app password)

---

**Need help?** Check `NOTIFICATION_SYSTEM_SETUP.md` for detailed documentation.
