# Design notes: why the billing system is built this way

These are the decisions behind the code and the reasoning for each, so you can challenge or change them.

## 1. One ISP per installation (multi-tenancy was dropped)
**Decision:** each ISP runs its own copy of the application and its own database. The first version was multi-tenant (a `tenant_id` column on every table, one subdomain per ISP). It was removed when the project's focus moved from selling a hosted platform to building the billing system itself.
**Why:** every query, index, callback and cron job had to carry and check a tenant, which is a standing risk (one missed filter leaks another ISP's data) and a tax on every new feature. A single-ISP code base is simpler to reason about, needs no wildcard DNS or wildcard certificate, and is easier to back up, move and debug. Isolation between ISPs is now the strongest possible one: separate servers or databases.
**Trade-off:** updating many ISPs means updating each installation (`git pull` and `php bin/migrate.php`). If a hosted multi-ISP product is wanted again, it is cleaner to build it as a separate layer that provisions installations than to put `tenant_id` back into every table.
**Migration:** `bin/convert_to_single.php` converts a multi-tenant database (keeping one ISP) and records the schema version; see docs/INSTALL.md.

## 2. MikroTik integration: RouterOS API, not RADIUS (yet)
**Decision:** talk to each router over the API (port 8728/8729) to create PPP secrets and hotspot users, and to kick active sessions.
**Why:** zero extra infrastructure; the ISP only needs an API user. RADIUS scales better (no push, routers ask us) but needs FreeRADIUS plus a sync layer. The `Billing` class is the only place that knows about routers, so RADIUS can be added later without touching the UI.
**Risk:** the server must reach the router. Use a VPN (WireGuard/OpenVPN) per router and give the API user a minimal policy group (`api, read, write, ppp, test`).

## 3. M-Pesa: STK Push and Paybill with the ISP's own credentials
**Decision:** each ISP stores its own shortcode, key, secret and passkey (encrypted with libsodium). Money goes straight to the ISP's own till/paybill; the platform never holds funds.
**Why:** avoids you becoming a payment aggregator (regulatory and reconciliation burden) and lets each ISP use its own paybill.
**Callback security:** Daraja callbacks are unauthenticated, so the URL carries a random secret token (`?k=`). We also: match on `CheckoutRequestID`, check the paid amount against the plan price, enforce a unique `mpesa_receipt`, and lock the payment row (`FOR UPDATE` plus `fulfilled` flag), so a retried or forged callback cannot extend service twice.
**Resilience:** if the router is offline when the callback arrives, the payment stays `success, fulfilled=0` and `cron/expire.php` retries. Customers never lose money.

## 4. Billing model
**Decision:** a customer has one plan and an `expires_at`. Payment adds the plan duration on top of the remaining time (early renewal does not waste days). Cron sets `expired` and disables the router account once per minute.
**Why:** simple, predictable, and the router is the enforcement point. Hotspot users get `limit-uptime` equal to the time they paid for, so the router cuts them off even if cron is late.

## 5. Roles and permissions (admin can change them)
**Decision:** permissions are a fixed list in code (`Auth::PERMISSIONS`); roles are rows in the database; the admin ticks permissions per role in **Staff & roles**. Defaults: Admin (everything), Technician (view customers, register installations, view routers, no money access), Cashier (payments and manual payments).
**Why:** permissions are code-defined because each one guards specific code; roles are data-defined because every ISP organises staff differently. Each page checks one permission, and sensitive actions re-check on POST, not only in the menu.
**Technician flow:** technicians register a customer on site; the account is created **disabled** on the router and switches on after the first payment (STK or cashier). This stops unpaid installs getting free service.

## 6. Security choices
PDO prepared statements everywhere, `password_hash`, CSRF token on every POST, session id regeneration on login, secrets encrypted at rest (`app_key` lives only in the git-ignored `config.php`), audit log of sensitive actions, basic rate limit on STK prompts per phone, output escaped with `e()`.

## 7. What is deliberately not built yet
Customer self-service portal for PPPoE (the `/api/stk.php` endpoint already accepts `account=<username>`), SMS reminders, super-admin panel, Static IP/queue plans, RADIUS, reports/exports, migrations tool, automated tests. Each is a clean add-on branch.
