# Databank Module – Design Document

## Purpose

The Databank module exposes **aggregated, non-PII analytics and counts** for:
- **Marketing team** – via an internal dashboard (session-based auth, same layout as the rest of the system).
- **External consumers** – via REST APIs secured with API keys (no session; suitable for BI tools, partners, external dashboards).

No raw patient identifiers or sensitive personal data are exposed through the external API; only counts, aggregates, and anonymized breakdowns (e.g. by insurance provider, payment method, age band, gender).

---

## Alignment with Existing System

| Aspect | How it aligns |
|--------|----------------|
| **Database** | Uses same `layouts/dbconn.php` and MySQLi; no new DB connection pattern. |
| **Auth – internal** | Session-based: `session_start()`, `layouts/session.php`, check `$_SESSION['user_id']` and optional role (e.g. SUPER_ADMIN, HOSPITAL_ADMIN, MARKETING). |
| **Auth – external API** | API key in header `X-API-Key` or query `api_key`; keys stored hashed in `api_keys` table. |
| **Layout – dashboard** | Same as `payment_analysis.php`: `layouts/main.php`, `layouts/menu.php`, `layouts/footer.php`, `layouts/title-meta.php`, `layouts/head-css.php`, `layouts/vendor-scripts.php`. |
| **Menu** | New items under "Reports & Analytics" (or a "Databank" section) in `includes/menu_config.php`; sync via `sync_menu_from_config.php` and assign via Role Permissions. |
| **Code style** | Raw PHP, prepared statements, separation of DB logic (in `databank/includes/databank_queries.php`) from presentation and from API response logic. |

---

## Folder Structure

```
ENT_PROD/
├── databank/
│   ├── DATABANK_DESIGN.md       # This file
│   ├── includes/
│   │   └── databank_queries.php # Shared query functions (used by dashboard + API)
│   ├── api/
│   │   ├── index.php            # Single entry point: routes by action/endpoint, validates API key
│   │   └── .htaccess            # Optional: route all api/* to index.php if using Apache
│   └── sql/
│       └── api_keys.sql        # Schema for api_keys table
├── databank_dashboard.php      # Marketing dashboard (session auth, uses databank layout)
├── databank_api_keys.php       # Optional: manage API keys (Super Admin)
└── includes/
    └── menu_config.php         # Add Databank menu items here
```

---

## Data Exposed (Examples)

All external API responses return **aggregates only**; no patient names, IDs, or contact details.

| Data area | Internal dashboard | External API | Source tables |
|-----------|--------------------|--------------|---------------|
| Patient counts | Yes | Yes | `patients`, `patient_visits` |
| Count by registration type (cash/insurance/walk-in) | Yes | Yes | `patients`, `patient_visits` |
| Most used payment method | Yes | Yes | `payments` |
| Insurance company breakdown (count of patients per provider) | Yes | Yes | `patients`, `insurance_providers` |
| Visits by date range | Yes | Yes | `patient_visits` |
| Revenue by period (totals only) | Yes | Yes | `payments` |
| Demographics (age bands, gender) – aggregated | Yes | Yes | `patients` + `users` |
| Top procedures / services (if available) | Yes | Yes | Procedure/billing tables |

---

## API Contract (External Consumers)

- **Base URL**: `https://your-domain.com/databank/api/` (or `index.php` with query params).
- **Auth**: `X-API-Key: <key>` header **or** `?api_key=<key>`.
- **Format**: JSON. All responses: `{ "success": true|false, "data": { ... }, "meta": { "timestamp", "request_id" } }`.
- **Errors**: HTTP 401 invalid/missing key; 403 forbidden scope; 400 bad params; 200 with `success: false` and `message` for business errors.
- **Rate limiting**: Optional (e.g. by api_key in application logic or web server).

### Example endpoints (implemented as actions in `api/index.php`)

| Action | Method | Description |
|--------|--------|-------------|
| `patients.count` | GET | Total active patient count; optional `start_date`, `end_date` for registrations in range. |
| `patients.by_registration_type` | GET | Counts by registration_type (CASH, INSURANCE, WALK_IN, etc.). |
| `patients.demographics` | GET | Aggregated age bands and gender (no PII). |
| `payments.methods` | GET | Most used payment method; totals and counts by method; date range. |
| `payments.revenue` | GET | Total revenue in date range (optional breakdown by method). |
| `insurance.by_provider` | GET | Patient count (and optionally visit count) per insurance provider. |
| `visits.count` | GET | Visit count in date range; optional group by registration_type. |

Query params (e.g. `start_date`, `end_date`) are validated (format Y-m-d, end >= start) and capped (e.g. max 1 year range) to avoid heavy queries.

---

## Security Summary

- **Internal dashboard**: Session only; restrict by role so only authorised users (e.g. Marketing, Admin) see the databank dashboard.
- **External API**: API key required; keys stored as hash; optional scopes per key (e.g. `analytics.read`); no session.
- **Data**: No PII in API responses; only aggregated/anonymised data.
- **SQL**: All queries use prepared statements (via shared `databank_queries.php`).

---

## Process Flow

1. **Marketing user** logs in → opens "Databank Dashboard" from menu → sees charts/tables (date filters) → same UX as Payment Analysis / other report pages.
2. **External consumer** obtains API key from admin → calls `GET /databank/api/?action=patients.count&api_key=...` (or header) → receives JSON → uses in BI/reports.
3. **Admin** (optional) goes to "API Keys" page → creates/revokes keys for external partners.

This design keeps one source of truth for queries (`databank_queries.php`), one dashboard for marketing, and one API surface for external consumers, aligned with your existing ENT_PROD architecture.
