1.  **Analyze Existing Code:**
    *   Carefully review the current implementations of `notifications.php` (at `@/finance_manager/notifications.php`) and `notification_service.dart` (at `@/mysportmanager-shared/lib/services/notification_service.dart`) to understand their existing functionality related to notifications and token management (if any). This will inform the modifications needed for FCM integration.

2.  **Update `notifications.php` (Backend - Finance Manager):**
    *   **Schema Update (Database):** Determine the data structure required to store FCM device tokens.  Consider the following fields: `user_id`, `device_token`, `platform` (e.g., 'android', 'ios', 'web'). Modify the database table schema (likely `users` or a dedicated `devices` table) to include these fields. Consider data type limitations (e.g. VARCHAR length). Back up data before changes.
    *   **API Endpoint Modification:**  Modify `notifications.php` to include an API endpoint that accepts `user_id` and `device_token` parameters via POST.  This endpoint will be responsible for storing (or updating) the device token in the database. Implement input validation and sanitization to prevent SQL injection and other security vulnerabilities. Handle cases where the token already exists for the user and update it accordingly. Use prepared statements for database interaction. Consider adding logging for debugging.
    *   **Error Handling:** Implement robust error handling within the API endpoint. Return appropriate HTTP status codes and error messages to the client (the mobile app) in case of failures (e.g., invalid parameters, database errors).

3.  **Create `fcm_sender.php` (Backend - Cron Job):**
    *   **File Creation:** Create a new PHP file named `fcm_sender.php`.
    *   **Configuration:** Define necessary configuration variables at the beginning of the file, including:
        *   FCM Server Key:  The API key for your Firebase project.  Store this securely (e.g., in an environment variable or a separate configuration file that is not committed to version control).
        *   Database Connection Details:  Credentials for connecting to the database where device tokens are stored.
    *   **Database Query:** Write a database query to retrieve relevant device tokens based on the notification criteria (e.g., all tokens, tokens for specific users, tokens for users matching certain criteria). Consider pagination or limiting the number of tokens retrieved at once to prevent memory issues if you have a large number of users.
    *   **FCM API Call:** Implement the logic to send FCM messages using the retrieved device tokens. This will involve making a POST request to the FCM API endpoint (`https://fcm.googleapis.com/fcm/send`).  Construct the JSON payload according to the FCM API documentation, including the `to` (device token), `notification` (title, body), and `data` (custom data) fields. Handle different FCM message types (notification vs data messages).
    *   **Error Handling (FCM):** Implement error handling for the FCM API calls. Check the HTTP status code of the response and parse the JSON response to identify any errors. Log errors appropriately. Implement retry logic for transient errors (e.g., network issues). Implement exponential backoff to prevent overwhelming FCM servers.
    *   **Token Management (FCM):** Handle FCM registration token invalidation errors (e.g., `NotRegistered`, `InvalidRegistration`). If a token is invalid, remove it from the database to prevent future sending attempts.
    *   **Logging:** Implement comprehensive logging throughout the script.  Log successful sends, errors, and any other relevant information for debugging and monitoring purposes.
    *   **Cron Job Setup:** Configure a cron job to execute `fcm_sender.php` at the desired interval (e.g., every minute, every hour).  Ensure that the cron job has the necessary permissions to access the database and the FCM API key.
    *   **Security Considerations:** Ensure this script does not expose any sensitive information if accessed via a web browser. It should only be executed via CLI.

4.  **Update `notification_service.dart` (Frontend - Shared Library):**
    *   **Token Registration:** Modify `notification_service.dart` to register the device token with FCM when the app is initialized or when the user logs in.  Use the `FirebaseMessaging` plugin to retrieve the FCM token.
    *   **Token Persistence:** Persist the FCM token locally (e.g., using shared preferences) to avoid retrieving it every time the app starts.
    *   **Token Refresh Handling:**  Listen for FCM token refresh events (using `FirebaseMessaging.onTokenRefresh`) and update the token in the database whenever it changes.
    *   **API Call (Backend):** Implement a function to send the FCM token and the user ID to the `notifications.php` endpoint via a POST request.  Use a suitable HTTP client library (e.g., `http` package).
    *   **Error Handling (Frontend):** Handle errors during token registration and sending the token to the backend. Display appropriate error messages to the user. Implement retry logic for transient errors.
    *   **Platform Detection:**  Implement platform-specific logic to handle differences between Android and iOS. Specifically, handle the need for iOS to request notification permissions.
    *   **Background Message Handling**: Review how background messages are currently handled. Ensure compatibility with the new FCM setup.

5.  **Testing and Deployment:**
    *   **Unit Testing:** Write unit tests for `fcm_sender.php` and `notification_service.dart` to ensure that they are functioning correctly. Pay particular attention to error handling and edge cases.
    *   **Integration Testing:** Perform integration testing to ensure that the entire notification pipeline is working correctly, from the mobile app to the FCM service to the recipient device.
    *   **Staging Environment:** Deploy the updated code to a staging environment for thorough testing before deploying to production.
    *   **Monitoring:** Set up monitoring to track the performance of the notification system. Monitor the number of notifications sent, the delivery rate, and any errors that occur.
    *   **Rollout:** Implement a phased rollout of the changes to production to minimize the risk of disruption.
    *   **Documentation:** Update documentation to reflect the changes to the notification system.
6. **Security Review:** Conduct a thorough security review of the entire notification system to identify and address any potential vulnerabilities. Pay particular attention to the storage and handling of FCM tokens and the security of the API endpoints.
7. **Bug Reporting:** Use `/mnt/ssd_data/bugs.md` to track any encountered bugs during the development process.
