# FCM Push Notification Migration Plan

## 1. Database Schema
- **New Table: `user_fcm_tokens`**
  - Stores mapping between `user_id` and multiple device tokens.
  - Columns: `id`, `user_id`, `device_token` (unique index), `platform`, `last_seen`.
- **Modify Table: `notifications`**
  - Add `fcm_sent_at` (DATETIME, default NULL) to track push status separately from `delivered` (polling status).

## 2. Backend (PHP)
### A. Token Registration
- Update `html/early_access/api/notifications.php` to handle `POST` action `register_token`.
- Upsert tokens into `user_fcm_tokens`.

### B. Global Generator Script (`html/early_access/api/cron/generate_notifications.php`)
- Refactor existing reminder generation logic to run for all active users.
- Intended to run daily via cron.

### C. FCM Sender Script (`html/early_access/api/cron/fcm_sender.php`)
- **JWT Implementation**: Raw PHP implementation using `openssl_sign` to generate Google OAuth2 tokens (no Composer dependencies).
- **Process**:
  1. Fetch notifications where `notify_at <= NOW()` and `fcm_sent_at IS NULL`.
  2. For each, retrieve all associated `device_tokens`.
  3. Send via FCM HTTP v1 API using CURL.
  4. Update `fcm_sent_at`.
  5. Remove stale tokens if FCM returns 404/410.

## 3. Mobile (Flutter)
### Update `notification_service.dart`
- **Token Lifecycle**:
  - Request permissions on app start.
  - Fetch FCM token and sync with backend on login/initialization.
  - Listen for `onTokenRefresh` to keep backend in sync.
- **Service Integration**:
  - Ensure the token registration API call includes proper authentication (API Key/Session).

## 4. Cron Configuration
- `fcm_sender.php`: Every 10 minutes.
- `generate_notifications.php`: Once per day.

---
**Verification Plan**:
1. Manually trigger `register_token` from the app.
2. Insert a dummy notification into the DB.
3. Run `fcm_sender.php` manually and verify push receipt.
