You are an expert Senior Full-Stack Architect and HealthTech Engineer working on "Meduvo Health," a multi-tenant Collaborative Care Model (CoCM) platform. SYSTEM OVERVIEW: - Backend/Admin: Laravel 12, MySQL (InnoDB), multi-tenant (tenant_id scoping on all clinic-owned tables, enforced via a global Eloquent scope + middleware — not separate databases per tenant). - Auth: Laravel Sanctum (token-based, SPA + mobile clients). Do not use Passport unless a task explicitly calls for a third-party OAuth2 authorization server. - Provider App: Flutter (mobile/tablet), Riverpod for state management. - Patient App: Flutter (mobile), Riverpod for state management. - Kiosk/Tablet: Optimized Web/Blade layout (or Flutter Tablet wrapper) using locked-down tokens. - Transport: REST (versioned, /api/v1/...) for CRUD; Laravel Reverb (WebSockets) only for: (a) BHCM registry live updates, (b) push-style in-app notifications, (c) call-invite signaling and warm handoffs. Video/audio media itself goes over Daily.co (has a standard BAA available) or Agora — not over Reverb. DOMAIN RULES (do not violate): - Triad workflow: PCP leads care; BHCM coordinates care and owns metrics tracking; Psychiatric Consultant is a data-driven advisor to the BHCM/PCP only — never build any feature giving the psychiatric consultant direct patient messaging, calls, or patient-visible actions. - Time tracking must be granular, per-activity, immutable once submitted (corrections create a new adjustment record referencing the original, never an in-place edit). - Billing code logic must be DATA-DRIVEN, not hardcoded. CPT/HCPCS thresholds (99492, 99493, 99494, G2214) change over time and vary by payer/FQHC status. Store them in a versioned `billing_rule_sets` table with an `effective_date` and `payer_type`, and have the engine look up the active rule set rather than branching on hardcoded minute values. Treat the exact numeric thresholds as PLACEHOLDER/CONFIGURABLE data to be confirmed by a compliance/coding reviewer — flag this clearly wherever the seed data is created. - All PHI-bearing tables need audit logging: who read/wrote what, when. Audit log table is append-only (no UPDATE/DELETE grants at the DB user level for that table). NON-FUNCTIONAL REQUIREMENTS: - Encrypt PHI columns at rest where feasible (Laravel's encrypted casts) in addition to full-disk/DB encryption; TLS everywhere in transit. - Every endpoint enforces RBAC (SuperAdmin, ClinicAdmin, PCP, BHCM, Psychiatrist, Patient) AND tenant scoping — a request must never be able to read another clinic's data even with a valid token for a different tenant. - Provide PHPUnit feature tests for RBAC/tenant-isolation and for the billing rule engine specifically — these are the two highest-liability areas in the system. - No placeholder/mock logic — all code must run against real migrations. PHASE 1 — Backend Schema, Auth, and Core API (Split into 1A/1B/1C) Phase 1A — Schema & Multi-Tenancy Foundation [Paste SHARED CONTEXT from above] TASK: Design and generate Laravel 12 migrations, models, and factories for the following, with full foreign keys, indices, and enum/lookup constraints: 1. `tenants` (clinics) — Add a `status` enum (pending_review, approved, suspended), an `operational_timezone` string, and administration fields for `approved_at` and `approved_by_user_id` to enforce the platform manual-activation gate. 2. `users` — role (super_admin, clinic_admin, pcp, bhcm, psychiatrist, patient), tenant_id (nullable for super_admin), status (active/invited/suspended), standard Sanctum fields, and a boolean `is_online` presence flag for real-time routing. 3. `patient_profiles` — linked to exactly one PCP and one assigned BHCM (foreign keys to users, role-constrained). Contains core demographic fields, enrollment_date, encrypted diagnosis_codes, a `co_cm_status` enum (prospect, active, declined, discharged), an encrypted text field for `decline_reason`, and a `session_state` JSON column to track onboarding progress/drop-off recovery steps. 4. `patient_sdoh_records` — linked to patient_profiles and tenant_id, storing encrypted social determinants of health markers (housing stability, food security, transportation barriers). 5. `patient_assessment_responses` — linked to patients, containing foreign key relations to `assessment_templates` or templates framework, an `answers` JSON column, `total_score`, and a critical `has_safety_risk` boolean flag. 6. `co_cm_consents` — linked to patient_profiles, tenant_id, and witnessing provider_id. Must store an encrypted signature image byte vector stream/blob, the explicit `consent_version` string, and an immutable device timestamp. 7. `emergency_safety_alerts` — id, tenant_id, patient_profile_id, assessment_response_id, `triggered_at`, `acknowledged_at` (nullable), and `acknowledged_by_user_id` (foreign key to users) to log exactly who defused a self-harm flag and when. 8. `care_encounters` — a lightweight session record framework that links patient_profiles and tenant_id to aggregate physical clinical notes, encounter milestones, or diagnostic sessions. 9. `time_tracking_logs` — started_at, ended_at, duration_minutes (generated/stored), activity_type (enum: direct_call, indirect_charting, psychiatric_caseload_review, registry_review, other), patient_id, provider_id, tenant_id, submitted_at, a nullable `care_encounter_id` link, and a nullable `superseded_by_id` self-reference for adjustments. 10. `care_goals` — tenant_id, patient_profile_id, created_by_user_id (must be role-validated as BHCM), goal statement + action steps (encrypted), target_date, achieved_at (nullable). 11. `audit_logs` — id, tenant_id, user_id (nullable), action (create/read/update/delete/export), auditable_type, auditable_id, old_values (json, encrypted), new_values (json, encrypted), ip_address, user_agent, created_at. (Include explicit append-only comments). 12. `billing_rule_sets` and `billing_rule_codes` — versioned lookup tables holding CPT/HCPCS code, min_minutes, max_minutes, payer_type, effective_start, effective_end. Include `allow_partial_month_grace`. 13. `billing_periods` — monthly rows aggregating total minutes, resolved codes, active status string, and a nullable foreign key `applied_rule_set_id` linking back to the matching `billing_rule_sets` row. 14. `psychiatric_recommendations` — psychiatrist → BHCM/PCP records with status (pending/approved/deferred), an encrypted `deferral_reason` text field (populated if deferred), and a boolean `escalation_triggered` flag. Enforce database level/foreign constraints that prevent direct patient-facing thread mapping. 15. `ehr_sync_queue` — id, tenant_id, patient_profile_id, standard HL7/FHIR hook event payload structure (json), sync_status (pending, synced, failed), and error_log (text) for external data exports. CORE TENANT SCOPE ARCHITECTURE: Implement the tenant isolation layer as a global Eloquent scope via a `BelongsToTenant` trait that hooks into Eloquent's `creating` and `booting` events to automatically append `tenant_id` based on user context. Enforce via middleware/trait constraints that if a tenant's status is NOT 'approved', any read/write operation on PHI tables must throw a strict Authorization/Compliance exception. Deliverables: migration files, Eloquent models with relationships, model factories, and a short README section explaining tenant status isolation, self-harm logging, and key-management caveats. Phase 1B — Auth, RBAC, and API Skeleton [Paste SHARED CONTEXT from above] TASK: Assuming the Phase 1A schema exists, implement: 1. Sanctum-based auth: registration (invite-only via an `invitations` table tracking email, role, tenant_id, token_hash, expires_at, and accepted_at), login, token issuance, and password reset. Configure Sanctum token lifetimes to expire after a strict period of inactivity (HIPAA compliance), writing an audit log whenever an admin revokes a staff token. 2. Platform Activation Gate Middleware: Enforce an application middleware that blocks any user belonging to a clinic with a 'pending_review' status from reading/writing patient records, allowing only SuperAdmin actions on the tenant account. 3. Mid-Assessment Intercept & Self-Harm Alert Endpoint: Build an endpoint `/api/v1/assessments/stream-answer` that receives question-by-question responses from the kiosk. If a critical suicide/self-harm item is flagged positive, the backend must instantly: (a) Write a row to `emergency_safety_alerts`. (b) Return a JSON response code instructing the frontend to halt/interrupt the routine survey. (c) Broadcast an urgent event via Laravel Reverb to the active providers in that tenant workspace. 4. BHM Presence & Availability Endpoint: Build an API route `/api/v1/referrals/check-availability` used during in-room discussion. The controller looks up the assigned BHM's `is_online` status and caseload capacity to return a routing decision matrix (Direct WebRTC Call vs Calendar Scheduling). 5. In-Clinic Tablet Handoff Endpoint (`/api/v1/device/handover`): Allows staff to generate a temporary, short-lived screening token for a specific patient, exposing only the intake/assessment questionnaire space while locking out all provider directories, clinical histories, or other tenants. 6. Patient Decline Endpoint: Process payloads where a patient declines CoCM enrollment, writing the status as 'declined', logging the encrypted text `decline_reason`, and dispatching a soft follow-up task due in 30 days. 7. A versioned API route file (`routes/api_v1.php`) with resource controllers for users, patient_profiles, and time_tracking_logs—including the explicit correction/adjustment endpoint for time logs, and the `session_state` update endpoint to recover dropped patient onboarding journeys. 8. Feature tests proving: (a) cross-tenant isolation, (b) self-harm intercept returns a hard-stop flag, (c) unapproved clinics cannot query patients, (d) validation preventing overlapping provider activity logs, and (e) validation preventing tablet handover tokens from accessing provider resources. Deliverables: controllers, policies, middleware, route file, and the feature test suite. Phase 1C — CMS Billing Rule Engine [Paste SHARED CONTEXT from above] TASK: Build the billing rule engine as a standalone, testable service class (`App\Services\Billing\CocmRuleEngine`), NOT inline controller logic. Requirements: 1. Aggregate `time_tracking_logs` into total minutes for a calendar month determined by the tenant’s operational timezone stored on the `tenants` table, protecting against UTC boundary rollovers. 2. Concurrent/Overlapping Window Rejection Engine (Fraud Prevention): At write time, reject any `time_tracking_logs` entry whose `[started_at, ended_at)` interval overlaps with an existing logged block for *the same provider across any patient*, OR *the same patient across any provider* (preventing concurrent double-billing). Throw a strict database-level validation exception. 3. Wrap the aggregation-and-write steps in a `lockForUpdate()` transaction to prevent race conditions with concurrent logs or recompute jobs. 4. Dynamically look up the ACTIVE `billing_rule_sets` row based on the patient’s payer_type and effective_date range. Compute base codes + add-on units without hardcoding thresholds. 5. Handle transition-month anomalies: implement evaluation logic checking the `allow_partial_month_grace` flag if a patient is enrolled near the end of a billing cycle (e.g., less than 3 days remaining). 6. Persist the output onto `billing_periods`, writing the matching row reference directly into `applied_rule_set_id` alongside compiled breakdown details. Protect records flagged as "submitted to payer" from being overwritten unless an explicit override is passed. 7. Unit tests covering: exact threshold boundaries, multiple add-on units, rule-set version changes mid-month, timezone boundary handling, partial-month grace logic, overlapping provider window rejections, and cross-provider patient double-booking blocks. Deliverables: service class, supporting DTOs/value objects, an Artisan command for manual recomputations, and a dedicated PHPUnit billing engine test suite. PHASE 2 — Admin Web Portal [Paste SHARED CONTEXT from above] TASK: Build a desktop-optimized admin portal using Laravel Blade + Tailwind CSS. Modules: 1. SuperAdmin Practice Activation & Compliance Hub: - A dedicated, restricted view for SuperAdmins to manage the 'tenants' pipeline. - Includes verification checkboxes for BAA (Business Associate Agreement) execution and eSign compliance documents. - Action button to flip clinic status from 'pending_review' to 'approved', which dynamically opens access to PHI tables across the application. - Features a high-contrast persistent visual banner whenever a SuperAdmin is interacting inside a specific clinic's tenant workspace to completely minimize cross-tenant data entry errors. 2. Clinic & Provider Onboarding Module: - ClinicAdmin view to invite clinical users by role and explicitly assign each patient's PCP + BHCM pairing (enforcing the one-PCP / one-BHCM rule). 3. Real-Time Emergency Alert Monitor (Sticky Widget): - A high-visibility, global dashboard widget that listens to Laravel Reverb for real-time `emergency_safety_alerts` (triggered by positive kiosk self-harm responses). - Displays a red flashing critical alert status with the patient's room location/provider details. - Requires an explicit click on an "Acknowledge Alert" button, which opens a confirmation modal forcing the logged-in staff member to confirm physical intervention, recording their User ID and timestamp to resolve the backend emergency table entry. 4. Traffic-Light Billing Dashboard: - Displays per-patient current-month minute totals read directly from the Phase 1C engine's output. - Statuses are color-coded dynamically (Green: base threshold met, Amber: within the configurable "approaching threshold" band width managed from the rule set, Red: unbillable with a days-remaining-in-month countdown). - Include a drill-down showing the exact log entries and care encounter pointers contributing to the total for audit defensibility. 5. Billing Rule Settings & Threshold Band Configuration: - A dedicated UI interface for clinical and billing admins to view/modify active rule versions and adjust the "approaching threshold" amber band widths. - CRITICAL RULE: Changing any parameter or band width here must NEVER edit an already-effective rule set in place. It must create a new dated rule-set entry with versioning, consistent with the Phase 1C engine approach. - Every single modification or rule version change here must be audit-logged automatically. 6. In-Room Decline & Soft Follow-Up Tracker: - A dedicated tracking grid for patients who completed an assessment but transitioned to a 'declined' status during the PCP in-room discussion. - Displays the encrypted `decline_reason` and tracks the 30-day soft follow-up countdown task, preventing these prospective accounts from falling out of care tracking. 7. Immutable Audit Trail Module: - Read-only, filterable, and exportable (CSV) log viewer over the audit log table (filters by provider, patient, date range, and action type). No delete/edit UI layouts anywhere. - Enforce that executing the CSV download stream implicitly writes an "export" action to the `audit_logs` table before streaming the file, as exporting PHI is a high-liability event. Deliverables: routes, controllers, Blade views with Tailwind components, and a comprehensive access-matrix table (role × module × permission) in the README. PHASE 3 — Flutter Provider App [Paste SHARED CONTEXT from above] TASK: Build the multi-role Flutter Provider app using Riverpod for state management, consuming the Phase 1 API + Laravel Reverb WebSockets. The UI must adapt dynamically based on the authenticated user's role (PCP, BHCM, or Psychiatric Consultant). Features: 1. BHM Presence & Capacity Toggle: - Provide a persistent profile/status toggle switch in the application shell that updates the backend user table's `is_online` presence flag. - Displays a real-time badge showing the provider's current active caseload count vs. maximum configured capacity limits. 2. BHCM Registry Dashboard & Automatic Escalation Indicators: - Caseload tracking grid sorted by an automated, multi-factor risk stratification score. Compute risk as a function of: (a) Latest assessment score changes via an expected `/api/v1/assessments/delta` payload. (b) Missing-milestone flags (e.g., no contact, charting, or clinical review logged in 30+ days). - Automatically injects a prominent, high-visibility "Needs Psychiatric Review" flag for any patient whose symptom metrics show zero improvement or negative deltas after 60 continuous days of care tracking, or who trigger critical medication warning flags. Make these risk-weight thresholds dynamically configurable. 3. Live 3-Way Warm Handoff Signaling Hub: - When a PCP triggers a 'Start Live Collaborative Call' via the in-room dashboard during a patient referral, a high-priority WebSocket signaling event is broadcasted via Reverb. - If the assigned BHM is active (`is_online`), a full-screen incoming warm-handoff interrupt overlay appears on the BHM's device with audible alert pinging. - Tapping "Join Session" instantly wires the BHM into the WebRTC media pipeline (Daily.co or Agora) alongside the PCP and patient before the patient leaves the exam room. 4. Background Session Timer & Local Storage Strategy: - Starts automatically when a provider opens a patient chart view or care encounter screen, and pauses/stops on a 2-minute idle timeout (no touch, scroll, or input events). - Track active sessions using absolute system clock timestamps across `AppLifecycleState` transitions to ensure stability if suspended by iOS/Android background rules. - For continuous tracking on locked devices, leverage a proper native Android foreground service with its required persistent notification. - Offline Synchronization: If connectivity drops, completed session log entries must be encrypted in local storage using AES-256 (Hive/SQLCipher) keyed from the device hardware keystore before network retry loops begin. 5. PCP Approval & Deferral Queue: - Interactive list of pending `psychiatric_recommendations`. Providers can tap to approve, or select to "defer/dismiss". - Selecting "Defer Recommendation" forces the provider to complete a structured text area tracking the exact clinical `deferral_reason`. This payload is encrypted and posted to the API, updating state dynamically across the ecosystem via Reverb. Deliverables: Flutter project directory framework, Riverpod state providers/notifiers, WebRTC signaling integration layers, and offline secure cache modules. PHASE 4 — Flutter Patient App [Paste SHARED CONTEXT from above] TASK: Build the Flutter Patient app using Riverpod for state management, consuming the Phase 1 API, explicitly architected to support both offsite remote usage and locked In-Clinic Tablet Kiosk mode. Features: 1. Locked In-Clinic Kiosk Handover Mode: - When initialized via a staff member's short-lived handover token (`/api/v1/device/handover`), the app completely strips out native navigation rails, settings, profile configurations, and historical logs, locking into an absolute screening view. - Displays an Identity Confirmation Overlay showing the target patient's first name and partial DOB mask, backed by a prominent "Get Staff Assistance" exit mechanism. 2. Real-Time Answer Streaming & Emergency Interrupt UI: - The assessment wizard must bind to a debounced onChange listener that posts responses question-by-question to the backend `/api/v1/assessments/stream-answer` path rather than waiting for full end-of-survey submission. - If a response payload triggers the backend `has_safety_risk` validation flag (positive self-harm indicator), the application must immediately interrupt the workflow, block the back/next buttons, clear active state memories, and force-render an un-dismissible, compassionate "Please Wait — Clinical Staff Notified" full-screen emergency lockdown screen. 3. Dynamic Forms Renderer: - Builds PHQ-9, GAD-7, and custom screening questionnaires dynamically using JSON metadata payloads pulled from the backend template API. - Includes support for native local push notification triggers when scheduled tracking assessments become due. 4. Structured eConsent Signature Pad: - A legally binding electronic signature capture panel embedded within a dedicated terms scroll box layout matching the `co_cm_consents` schema. - Enforces that the "Agree & Consent" submit button remains disabled until the user scrolls to the bottom of the disclosure text. Captures signature image byte vector streams, consent structure version identifiers, and an immutable device timestamp. 5. Secure Telehealth Client & Care Portal: - Single-tap WebRTC client interface that automatically fires when an incoming room signal is received via WebSockets. No interface elements allowed for initiating unauthorized outbound patient-to-psychiatrist calling paths, strictly preserving the Triad rule. - Local caching of active care goals and text logs uses an encrypted storage architecture (Hive AES-256) bound strictly to the device's secure hardware keychain elements (iOS Keychain / Android Keystore). Secure chat messaging routes text channels exclusively to the assigned BHCM using versioned REST polling for delivery layered with Reverb for instant UI updates. Deliverables: Flutter kiosk-capable structural layout templates, custom-drawn signature component controls, question-streaming notifier states, and WebRTC layout managers. PHASE 5 — In-Clinic Kiosk Terminal (Web/Tablet Onboarding) [Paste SHARED CONTEXT from above] TASK: Build the standalone In-Clinic Kiosk Terminal view layer. This interface serves exclusively as a dedicated waiting-room layout deployed on clinic hardware, relying on the Phase 1B `/api/v1/device/handover` token rules. Features: 1. Hardened Handover Mode UI — A full-screen, highly simplified user interface layout with zero standard app bars, navigation drawers, or generic settings routes. Escaping the wizard back to any diagnostic screen or other client data spaces must be blocked at both the system route level and through structural frontend error catching. 2. Dynamic Screening Assessment Engine — Consumes the `/api/v1/assessments/templates` schema. Dynamically render structural question components (e.g., PHQ-9 or GAD-7 sliders/radios) with large, high-contrast touch targets suitable for elderly or physically impaired clinical patients. Bound to the step-by-step answer streaming endpoint for real-time safety tracking. 3. Social Determinants of Health (SDOH) Intake Wizard — Multi-step screen paths allowing patients to securely record current status markers across predefined categories: - Housing stability checklist - Food insecurity markers - Local transportation barrier toggles Encrypt the generated payload lines immediately prior to transmission over TLS into the `patient_sdoh_records` table. 4. Active Drop-Off Recovery Monitor — Implement an automated state tracker on the form wizard. On every step change or after a 45-second input pause, fire an asynchronous background patch log to the `/api/v1/patient/session_state` endpoint containing current progress metrics and partial inputs. If a patient walks away or leaves the tablet, the registry updates instantly so clinic staff can clear or reclaim the active station. 5. Session Autoclose Cleaners — When the final form step is submitted, write the clinical entries to the backend, wipe the local device memory states/tokens cleanly, and present a generic, neutral "Thank you, please return the terminal to clinic staff" splash screen. Deliverables: Kiosk router rules, dedicated dynamic questionnaire layouts, an SDOH form state wizard, and background checkpoint triggers for recovery states.