# Firebase Admin SDK - Quick Commands Reference

## Installation

```bash
# Install Firebase Admin SDK package
composer require kreait/firebase-php

# Clear cache after installation
php artisan config:clear
composer dump-autoload
```

## Testing Commands

### 1. Test Firebase Connection

```bash
php artisan tinker
```

```php
>>> app(\App\Services\FirebaseServiceV1::class)->messaging();
// Should return Firebase Messaging object without errors
```

### 2. Test Topic Subscription

```bash
php artisan tinker
```

```php
>>> $service = app(\App\Services\FirebaseServiceV1::class);
>>> $result = $service->subscribeToTopic('test_token_123', 'test-topic');
>>> dd($result);
// Expected: ['success' => true, 'message' => 'Successfully subscribed to topic']
```

### 3. Send Test Notification to Topic

```bash
php artisan tinker
```

```php
>>> $service = app(\App\Services\FirebaseServiceV1::class);
>>> $result = $service->sendToTopic(
...     'test-topic',
...     'Hello Firebase!',
...     'Testing Firebase Admin SDK',
...     ['type' => 'test']
... );
>>> dd($result);
```

### 4. Check Environment Configuration

```bash
php artisan tinker
```

```php
>>> env('FIREBASE_CREDENTIALS');
// Should return: storage/app/firebase/disruptdemo-firebase-adminsdk-fbsvc-5d1bff0c1f.json

>>> config('firebase.credentials.file');
// Should return full path to JSON file

>>> file_exists(config('firebase.credentials.file'));
// Should return: true
```

### 5. Validate FCM Token

```bash
php artisan tinker
```

```php
>>> $service = app(\App\Services\FirebaseServiceV1::class);
>>> $isValid = $service->validateToken('your_fcm_token_here');
>>> dd($isValid);
// Returns: true or false
```

### 6. Send to Multiple Tokens

```bash
php artisan tinker
```

```php
>>> $service = app(\App\Services\FirebaseServiceV1::class);
>>> $tokens = ['token1', 'token2', 'token3'];
>>> $result = $service->sendMulticast(
...     $tokens,
...     'Bulk Test',
...     'Testing multicast send',
...     ['batch' => 'test']
... );
>>> dd($result);
```

## Database Queries

### Check FCM Tokens

```sql
-- View all FCM tokens
SELECT * FROM fcm_tokens;

-- View tokens for specific topic
SELECT * FROM fcm_tokens WHERE topic LIKE 'program-%';

-- Count subscribers per topic
SELECT topic, COUNT(*) as subscribers
FROM fcm_tokens
WHERE subscribed_at IS NOT NULL
GROUP BY topic;

-- View recent subscriptions
SELECT * FROM fcm_tokens
ORDER BY subscribed_at DESC
LIMIT 10;
```

## Log Monitoring

### Real-time Log Watching

```bash
# Watch all Firebase-related logs
tail -f storage/logs/laravel.log | grep -i firebase

# Watch notification logs
tail -f storage/logs/laravel.log | grep -i "notification sent"

# Watch subscription logs
tail -f storage/logs/laravel.log | grep -i "subscribed to topic"
```

### View Recent Errors

```bash
# Last 50 lines with Firebase errors
tail -50 storage/logs/laravel.log | grep -i "firebase.*error"

# View full error context
grep -A 5 -B 5 "Firebase initialization error" storage/logs/laravel.log
```

## File Verification

### Check Service Account File

```bash
# Windows PowerShell
Test-Path "storage\app\firebase\disruptdemo-firebase-adminsdk-fbsvc-5d1bff0c1f.json"

# Or view file details
Get-Item "storage\app\firebase\disruptdemo-firebase-adminsdk-fbsvc-5d1bff0c1f.json"
```

### Verify JSON File Content

```bash
# Check if JSON is valid (PowerShell)
Get-Content "storage\app\firebase\disruptdemo-firebase-adminsdk-fbsvc-5d1bff0c1f.json" | ConvertFrom-Json
```

## Common Issue Fixes

### Clear All Caches

```bash
php artisan config:clear
php artisan cache:clear
php artisan route:clear
php artisan view:clear
composer dump-autoload
```

### Reinstall Firebase Package

```bash
composer remove kreait/firebase-php
composer require kreait/firebase-php
composer dump-autoload
```

### Check PHP Extensions

```bash
php -m | grep -E 'json|openssl|mbstring'
# All three should be listed
```

## Production Deployment

### Before Deploying

```bash
# Test locally first
php artisan tinker
>>> app(\App\Services\FirebaseServiceV1::class)->messaging();

# Clear and cache config
php artisan config:cache
php artisan route:cache
```

### On Production Server

```bash
# Upload service account JSON
# Ensure file permissions: 644
chmod 644 storage/app/firebase/*.json

# Verify file exists
ls -la storage/app/firebase/

# Test connection
php artisan tinker
>>> app(\App\Services\FirebaseServiceV1::class)->messaging();
```

## Quick Test Workflow

### Complete Test Sequence

```bash
# 1. Check file exists
Test-Path "storage\app\firebase\disruptdemo-firebase-adminsdk-fbsvc-5d1bff0c1f.json"

# 2. Verify environment
php artisan tinker
>>> env('FIREBASE_CREDENTIALS')

# 3. Test connection
>>> app(\App\Services\FirebaseServiceV1::class)->messaging()

# 4. Test subscription
>>> $service = app(\App\Services\FirebaseServiceV1::class);
>>> $service->subscribeToTopic('test_token', 'test-topic')

# 5. Test notification
>>> $service->sendToTopic('test-topic', 'Test', 'It works!')

# 6. Check logs
tail -f storage/logs/laravel.log
```

## Useful Snippets

### Get All Subscribed Topics for User

```php
$userId = 1;
$tokens = \App\Models\FcmToken::where('user_id', $userId)
    ->whereNotNull('subscribed_at')
    ->get();

foreach ($tokens as $token) {
    echo "Topic: {$token->topic}\n";
}
```

### Send Notification to All Program Subscribers

```php
$programId = 123;
$topic = "program-{$programId}";

$service = app(\App\Services\FirebaseServiceV1::class);
$result = $service->sendToTopic(
    $topic,
    'New Episode Available!',
    'Check out the latest content',
    ['program_id' => $programId]
);

dd($result);
```

### Bulk Subscribe Users to Topic

```php
$tokens = ['token1', 'token2', 'token3'];
$topic = 'important-updates';

$service = app(\App\Services\FirebaseServiceV1::class);

foreach ($tokens as $token) {
    $result = $service->subscribeToTopic($token, $topic);
    echo "Token: " . substr($token, 0, 20) . "... - " .
         ($result['success'] ? 'Success' : 'Failed') . "\n";
}
```

## Environment Variables Checklist

```env
# Required
FIREBASE_CREDENTIALS=storage/app/firebase/disruptdemo-firebase-adminsdk-fbsvc-5d1bff0c1f.json

# Optional
FIREBASE_PROJECT_ID=disruptdemo

# Legacy (if needed)
FCM_SERVER_KEY=your_legacy_key
```

## Package Dependencies

```json
{
  "require": {
    "kreait/firebase-php": "^7.0"
  }
}
```

## Support & Documentation

- **Firebase Admin SDK**: https://firebase.google.com/docs/admin/setup
- **kreait/firebase-php**: https://firebase-php.readthedocs.io/
- **FCM Migration**: https://firebase.google.com/docs/cloud-messaging/migrate-v1
