# Install on system.eazyradius.co.ke (Ubuntu 22.04 / 24.04, Apache)

Copy-paste version of [`INSTALL.md`](INSTALL.md) with the domain filled in. Run everything as root (`sudo -i`). About 30 minutes.

```
Customers/Admin ──443──▶ Apache ─▶ PHP-FPM ─▶ MariaDB     https://system.eazyradius.co.ke
MikroTik ──UDP 51820──▶ WireGuard hub (10.99.0.1) ──▶ Apache tunnel listener 10.99.0.1:8081
Safaricom ──▶ https://system.eazyradius.co.ke/api/…   (STK + Paybill callbacks)
You ──▶ vpn.eazyradius.co.ke:20010-20012 ──▶ Winbox / WebFig / API of a router (through the tunnel)
```

## 1. DNS (at your registrar or DNS host for eazyradius.co.ke)
Add two records pointing at the same server, then wait until `dig +short system.eazyradius.co.ke` and `dig +short vpn.eazyradius.co.ke` both return your server's IP:

| Type | Name | Value | Used for |
|---|---|---|---|
| A | `system` | the server's public IPv4 | the billing panel and M-Pesa callbacks |
| A | `vpn` | the same IPv4 | routers' WireGuard tunnel and remote access (Winbox / WebFig / API) |

On Cloudflare set both to **DNS only** (grey cloud): WireGuard and Winbox cannot pass through the proxy. Open TCP 80, TCP 443, **UDP 51820** and the remote access range **TCP 20000-60000** (or only your routers' ports) at the cloud firewall.

## 2. Packages
```bash
apt-get update
apt-get install -y apache2 mariadb-server git curl unzip php-fpm php-mysql php-curl php-mbstring php-xml
php -v                                              # 8.1 or newer
php -m | grep -E "pdo_mysql|sodium|curl|mbstring"   # all four listed
a2enmod rewrite ssl headers proxy_fcgi setenvif
a2enconf "$(basename /etc/apache2/conf-available/php*-fpm.conf .conf)"
systemctl restart apache2
```

## 3. Code
```bash
git clone https://github.com/dkaranj/radiuscloud.git /var/www/billing
cd /var/www/billing
```

## 4. Database
```bash
DBPASS=$(openssl rand -base64 18 | tr -d '/+=')
echo "DB password: $DBPASS"                          # write it down, needed in step 5
mysql -e "CREATE DATABASE billing CHARACTER SET utf8mb4;
          CREATE USER 'billing'@'localhost' IDENTIFIED BY '$DBPASS';
          GRANT ALL ON billing.* TO 'billing'@'localhost';"
mysql billing < database/schema.sql
```

## 5. Configuration
```bash
cp config/config.sample.php config/config.php
APPKEY=$(php -r 'echo base64_encode(random_bytes(32));')
echo "app_key: $APPKEY"                              # BACK THIS UP, never change it
nano config/config.php
```
Set these values:

| Key | Value |
|---|---|
| `db` → `dsn` | `mysql:host=127.0.0.1;dbname=billing;charset=utf8mb4` |
| `db` → `user` / `pass` | `billing` / the password from step 4 |
| `app_key` | the key printed above |
| `public_url` | `https://system.eazyradius.co.ke` |
| `timezone` | `Africa/Nairobi` |

```bash
chown root:www-data config/config.php && chmod 640 config/config.php
php bin/migrate.php --baseline
```

## 6. HTTPS certificate
```bash
apt-get install -y certbot
systemctl stop apache2
certbot certonly --standalone -d system.eazyradius.co.ke --deploy-hook "systemctl reload apache2"
systemctl start apache2
```

## 7. Apache site
```bash
cp deploy/apache-app.conf /etc/apache2/sites-available/billing.conf
sed -i 's/billing\.example\.com/system.eazyradius.co.ke/g' /etc/apache2/sites-available/billing.conf
ls /run/php/                       # note the socket name, e.g. php8.3-fpm.sock
grep -n "fpm.sock" /etc/apache2/sites-available/billing.conf   # must match; edit if your PHP version differs
a2dissite 000-default
a2ensite billing
apachectl configtest && systemctl reload apache2
curl -sI https://system.eazyradius.co.ke/ | head -1           # expect 302 or 200
```

## 8. First administrator and cron
```bash
php bin/create_admin.php "Eazy Radius" you@eazyradius.co.ke 'ChooseAStrongPassword'
cp deploy/billing.cron /etc/cron.d/billing
```
Open **https://system.eazyradius.co.ke** and sign in. The business name you entered appears on the login page and hotspot page (change it later in Settings).

## 9. WireGuard hub (routers connect here)
```bash
./deploy/wireguard-hub.sh vpn.eazyradius.co.ke
```
Paste the `'wireguard' => [...]` block it prints into `config/config.php`, replacing the sample block. Then:
```bash
cp deploy/apache-tunnel.conf /etc/apache2/sites-available/billing-tunnel.conf
grep -n "fpm.sock" /etc/apache2/sites-available/billing-tunnel.conf   # same socket name as step 7
a2ensite billing-tunnel
mkdir -p /etc/systemd/system/apache2.service.d
printf '[Unit]\nAfter=wg-quick@wg0.service\nWants=wg-quick@wg0.service\n' > /etc/systemd/system/apache2.service.d/wg.conf
systemctl daemon-reload && apachectl configtest && systemctl restart apache2
ufw allow 80,443/tcp && ufw allow 51820/udp
ufw allow in on wg0 to 10.99.0.1 port 8081 proto tcp
ufw allow 20000:60000/tcp                                    # remote access ports (see step 10)
ufw route allow in on eth0 out on wg0 to 10.99.0.0/16 proto tcp port 80,8291,8728   # replace eth0 with your public interface (ip -br a)
```

### Remote access to routers (Winbox, WebFig, API) through vpn.eazyradius.co.ke
Every WireGuard router automatically gets three public ports on the VPN address. Router id 1 gets `20010` → router port 80 (WebFig), `20011` → 8291 (Winbox), `20012` → 8728 (API); router 2 gets `20020`-`20022`, and so on. `bin/wg_sync.php` (the root cron job) loads the rules within a minute.

- **Routers → Connect router** shows each router's addresses with copy buttons, e.g. Winbox `vpn.eazyradius.co.ke:20011`.
- **Routers → Remote access**: the public ports are open to everyone (there is no IP list). Anyone who knows an address reaches the router's own login screen, so use strong router admin passwords. Switch a service off per router in **Connect router** (for example the API, 8728, if you do not need it from outside).
- Each router can have web, Winbox or API switched off in its Connect dialog.
- Routers get the matching firewall rule in their setup script. A router you set up **before** this feature needs its script run again (Routers → Reconfigure).
- On a server that was set up before this feature: re-run `./deploy/wireguard-hub.sh vpn.eazyradius.co.ke`, then add the two `ufw` lines above.

## 10. Configure in the panel
1. **Settings**: brand, support phone, M-Pesa Daraja credentials (sandbox first).
2. **Paybill**: press **Register URLs with Safaricom**. The URLs will be `https://system.eazyradius.co.ke/api/c2b_confirm.php?k=…` and `…/c2b_validate.php?k=…`.
3. **Routers → Add router (WireGuard)**: paste the one command into the MikroTik, wait for "connected", pick the interfaces, **Save & apply**.
4. **Remote access**: add your IP addresses (see above).
5. **Plans**, then **Messages → Gateway**, **Hotspot page**, **Staff & roles**.

## 11. Verify
```bash
php bin/migrate.php --status           # all "applied"
wg show                                # after adding a router: recent "latest handshake"
tail /var/log/billing-cron.log /var/log/apache2/billing-error.log
```
Reboot once and repeat, to confirm Apache starts after `wg0`.

## Update later
```bash
cd /var/www/billing && git pull --ff-only
mysqldump --single-transaction billing > /root/billing-$(date +%F).sql
php bin/migrate.php && systemctl reload 'php*-fpm'
```

## Back up (daily, off the server)
The database dump, `config/config.php` (holds `app_key`) and `/etc/wireguard/`.

## Locked out?
`php bin/reset_password.php you@eazyradius.co.ke 'NewStrongPass'`

## Device lock and static IPs (stop account sharing)

**Device lock.** Every customer can be locked to one device by its MAC address. Enter it when adding the customer, or press **Device** on the customers page to set it, remove it, or lock to the device that is connected right now. In **Settings → Device lock** you can also lock PPPoE and hotspot customers to the first device they connect with.

| Service | What the router enforces |
|---|---|
| PPPoE | `caller-id` on the PPP secret: only that MAC can dial in |
| Hotspot | `mac-address` on the hotspot user |
| Static IP | a fixed `/ip arp` entry, and the static port answers ARP only for bound devices (`arp=reply-only`) |

One device can belong to one customer only.

**Static IP customers use a single /32.** Enter one address such as `10.10.20.15` (or `10.10.20.15/32`); subnets are refused. For each customer the system creates, on the router:

- a simple queue that limits their speed (created when the customer is added),
- an `/ip address` entry (gateway `/32`, network = the customer's IP) that is **enabled when they pay and disabled when they are unpaid or expired**,
- an ARP entry tying the IP to their MAC.

A customer who shares the IP with another device gets nothing once unpaid, and cannot move the IP to a different device while it is locked.

**Existing routers.** Open the router in **Routers → Reconfigure** once. This removes the old shared `/24` gateway address, sets the static port to `arp=reply-only`, and re-creates every static customer's `/32`, queue and ARP entry. Enter a MAC for each static customer first, otherwise the router will not answer them on that port.

## Router health: leases, hosts and traffic history

On **Router health**, each router has two buttons:

- **DHCP leases & hotspot hosts** reads the router live: every DHCP server with its active lease count, every lease (address, MAC, host name, status, expiry), and every hotspot host (logged in or not). Devices are matched to customers by locked MAC, static IP or hotspot username. Use *Find* to search by IP, MAC or name.
- **Monitor interfaces** (Traffic history) records the interfaces you choose every 10 minutes: bytes downloaded and uploaded, and average speed. View 12 hours, 24 hours, 1 week, 30 days or 90 days, with totals, peaks and a data-used-per-day table. Samples are kept for 400 days. The WAN interface is recorded by default; use **Choose interfaces to monitor** to add more (bridges, uplinks, VLANs).

History needs `cron/monitor.php` running every minute (already part of the install). Run `php bin/migrate.php` after updating.

## Customer profile

Click any customer (in Customers, search results, Accounts, Paybill or Reports) to open their profile. One screen shows the plan, expiry, balance and device lock, with the actions (extend, suspend, change plan, send SMS, device lock, delete) at the top and four tabs:

- **Overview:** service details, recent M-Pesa payments, plan changes.
- **Usage:** data used per day for 30 days (sampled from the router about every 10 minutes while the customer is connected), the data-cap meter, and a **Check now** live session lookup (IP, device MAC, uptime; warns if the device differs from the locked one).
- **Account:** receive money, charge or refund, renew from balance, and the full statement. This replaced the per-customer view on the Accounts page.
- **Messages:** every SMS sent to the customer, with type and delivery status.

The Customers list is now a short overview (name, plan, status, balance). Add a customer with the **Add customer** button. Run `php bin/migrate.php` after updating; usage history starts from that moment.

**Where things are:** open **Routers** and click a router (or **Open**). Its page has three tabs: **Health** (CPU, memory, WAN speed), **Leases & hosts** and **Traffic history**. They no longer appear as separate items in the sidebar.

## More ways to pay (optional)

Settings → **More ways to pay**. M-Pesa (Daraja) stays the default; each extra method is off until you switch it on and save its credentials. When more than one method is on, the hotspot page shows a **Pay with** choice.

- **Airtel Money**: client ID and secret from the Airtel developer portal. The callback is also confirmed with Airtel before a customer is given service.
- **SasaPay**: merchant code, client ID/secret and network code (63902 M-Pesa, 63903 Airtel).
- **KopoKopo**: till number, client ID/secret and API key (the API key signs each result; unsigned results are ignored).
- **Pay to bank**: works on its own, with no SasaPay or KopoKopo. The customer gets an M-Pesa prompt and pays **your bank's paybill** with **your account number** as the reference, so the money goes straight into your bank account. It uses the M-Pesa (Daraja) credentials already saved above. Pick the bank (its paybill is filled in for common banks, but **confirm it with your bank**), enter your account number and save. The account number is sent in full, never shortened. Safaricom must allow your shortcode to pay another paybill; if prompts fail, ask Safaricom to enable it. You can still choose SasaPay or KopoKopo as the collector instead: then the bank details are only recorded and the payout account is set in their dashboard.

Results arrive at `/api/gateway_callback.php` (a secret token is added automatically). Run `php bin/migrate.php` after updating. Test each provider in its sandbox first.

## Smart TVs on the hotspot page

Customers tick **Pay for a Smart TV**, type the TV's MAC address, choose a hotspot package and pay. When the payment lands, the router gets, for that TV:

- an `/ip hotspot ip-binding` of type **bypassed** (the TV is online with no login page),
- a static DHCP lease on `billing-hs-dhcp`, with an address taken from the **top of the hotspot DHCP range** (so it never changes),
- a **simple queue** on that address with the package speed.

When the package expires the binding and queue are disabled, and removing the customer deletes all three. Paying again extends the same TV. A TV shows up in Customers as type `tv` (named after its MAC) and is locked to that MAC. Switch the option off in Settings → Smart TV. It needs the router to have been set up with the wizard, because the hotspot range and DHCP server name come from it. Run `php bin/migrate.php` after updating.

## Email and "Forgot password"

Settings → **Email**: enter an SMTP account (for Gmail: `smtp.gmail.com`, port 587, STARTTLS, your address and a Google **app password**; Zoho, your hosting's mail and SendGrid work the same way), a "send from" address, save, then press **Send test email**. The same account sends router offline/online alerts.

On the sign-in page, **Forgot your password?** asks for the email and mails a 6-digit code (valid 15 minutes, 5 guesses, only its hash is stored). Enter the code and a new password (8+ characters). The page never says whether an email exists; it is limited to 6 requests per hour per address and 3 codes per account every 15 minutes. If email is not set up the page says so, and an administrator can still reset a password under Staff. Outgoing SMTP port 587/465 must be open on the VPS (some providers block port 25 only). Run `php bin/migrate.php` after updating.

## Built-in RADIUS server (no FreeRADIUS)

The billing system includes its own RADIUS server (`bin/radius_server.php`, plain PHP). Routers can log PPPoE and hotspot customers in against it instead of having every account written to them.

**What it does**
- **Login (UDP 1812):** a customer is accepted when the username and password are right, the package has not expired, the account is not suspended, the device matches the device lock (or is learned on first use when that setting is on) and the account is not already online from another device. The reply sets the profile (`Mikrotik-Group`), the speed (`Mikrotik-Rate-Limit`, the slower FUP speed after the data cap) and `Session-Timeout`, so the router drops the customer exactly when the package ends.
- **Accounting (UDP 1813):** sessions, bytes (including 4 GB rollovers), online status and per-customer daily usage come from the router's updates every 5 minutes. The fair-use cap is enforced from these.
- **Disconnect (RFC 5176):** when a package ends, a customer is suspended, or the cap is reached, the router is told to drop the session.
- **Only routers on the WireGuard tunnel** that are switched to RADIUS can talk to it (identified by their tunnel address, each with its own secret). The server listens on the tunnel address only, so nothing is exposed to the internet.
- PAP and CHAP are supported. MS-CHAP is not, and the router script sets the PPPoE servers to `pap,chap`.

**Turn it on**
1. Update (`git pull`, `php bin/migrate.php`) and re-run `deploy/wireguard-hub.sh` as root: it opens UDP 1812/1813 on the tunnel.
2. Install the service: `cp deploy/radius.service /etc/systemd/system/billing-radius.service`, `systemctl daemon-reload`, `systemctl enable --now billing-radius`. Check with `journalctl -u billing-radius -f`.
3. Routers → **Set up / Reconfigure** the router → *How customers log in* → *Built-in RADIUS server*, then apply (this adds the `/radius` entry, turns on RADIUS and accounting for PPP and the hotspot, and lets the server send disconnects).
4. Open Routers → the router → **RADIUS** tab: it shows if the server is running, who is online, and every login attempt with the reason it was refused. Watch it while you test one customer.

Customers are no longer written to a RADIUS router (no PPP secrets or hotspot users); plans still create the profiles. Static IP and Smart TV customers are unaffected. An expired customer is refused at login (they cannot reach the portal over PPPoE), the same as a disabled secret today. Switching a router back to *Accounts written to the router* returns to the old behaviour.

## Something not working? Run the doctor

`sudo php bin/doctor.php` checks, in order: the WireGuard tunnel and each router's handshake, the wg_sync cron, whether Apache answers on `10.99.0.1:8081` with a proper reply, the firewall (ufw and nft) for port 8081 and RADIUS, the RADIUS service and what each RADIUS router has sent, and payments that were paid but not written to a router. Every FAIL line says what to run. Fix the first FAIL and run it again.

- **Router says "failure closing connection" fetching `10.99.0.1:8081`:** the router cannot reach the server through the tunnel, or Apache is not serving the tunnel vhost. The doctor shows which. The usual causes are `deploy/wireguard-hub.sh` not run (or run without the host name), `bin/wg_sync.php` not in cron, the tunnel vhost not enabled, or ufw blocking port 8081 from `wg0`.
- **RADIUS log is empty:** the router never received the RADIUS settings (they arrive with the second script, the one fetched from `10.99.0.1:8081`), or the service is not running. Routers → RADIUS tab shows both.
- **Paid but no user on the router:** Payments shows "Paid, but not on the router yet" with the reason and a Retry button. A router set to RADIUS never gets accounts written to it by design; Routers shows a red warning if RADIUS is on but the service is stopped.

## Reconnect on the hotspot page

The hotspot page has **Already paid? Reconnect**. A customer enters the M-Pesa (or bank) code from their payment message, or the phone number they paid with. The phone number only works from the device that paid (the router passes the MAC to the page); any other device must use the code. Wrong guesses are rate limited. Run `php bin/migrate.php` after updating.

## Loyalty points, MAC address and per-router packages

Run `php bin/migrate.php` after updating (adds the points table).

- **Points:** Settings → **Loyalty points**. Tick the box, set how many shillings make one point (10 means KES 50 earns 5), and optionally pick a **reward package** and how many points it costs. Points are added when a payment is applied to the customer, once per payment, even if the payment is processed again. Free (points) packages earn nothing. On a customer's profile, **Adjust** adds or removes points.
- **On the hotspot page:** the customer sees their points, a progress bar to the reward, and a **Redeem** button when they have enough. The customer is recognised by the phone (device MAC) that paid before, the same way the *Reconnect* box works. After paying they see "You earned N points".
- **MAC address:** the hotspot page shows "Your device: AA:BB:…". Switch it off in Hotspot page → *Show or hide*.
- **Loading screen and transitions:** Hotspot page → **Loading screen & transitions**. Choose the effect (Wi-Fi signal, spreading rings, orbiting dots, sound bars), how long it shows, the text, and how the page appears (fade, rise, zoom, focus from blur). The same screen appears while connecting after a payment. Changes are live immediately. The router's own `login.html` is now a short loading page in the same colours; it is updated when you press **Reconfigure** on the router.
- **Packages per router:** each router's login page sends its id to the portal (`?rt=`), so customers see only the packages of the router they are connected to (and cannot buy another router's package from that page). **Press Reconfigure on every router once** so its login page carries the id. Until then that router shows all hotspot packages.

## Changing your email and password

Click your name at the bottom of the sidebar (**My account**). You can change your name, the email you sign in with, and your password. The current password is always asked for, and wrong guesses count towards the same lockout as signing in. After an email or password change, a notice goes to your old address if email sending is set up. Any staff member can do this for their own account; no extra permission is needed. To reset someone else's, use **Forgot password** on the sign-in page.

## Expenses, profit and the audit log
- **Expenses** (Money → Expenses): record rent, salaries, bandwidth and so on by month. Staff with `accounts.manage` can add or delete; `accounts.view` can look and download CSV.
- **Reports → Profit**: money received minus expenses for any date range, a split by category and the last 12 months with a CSV download.
- **Audit log** (Admin → Audit log, `staff.manage`): who did what and when. Filter by person, kind, text and dates, and download CSV.

## WhatsApp gateway and phone alerts
1. **WhatsApp for customers**: Messages → Gateway → provider *WhatsApp*. Enter the Phone number ID and a permanent access token from Meta (WhatsApp → API setup). Reminders and receipts go out of the 24-hour window, so create a message template once in Meta with a single variable, for example `Account update: {{1}}`, and type its name here. "Free text" mode only works for chats the customer started in the last 24 hours (fine for testing).
2. **Alerts to you**: Settings → Alerts. Add an email, a Telegram bot token and chat id (create a bot with @BotFather, message it, then use your chat id), and/or your WhatsApp number (uses the gateway above). Press *Save and send a test alert* to check each one. Alerts cover failed payments that could not be applied, router offline and similar.

After updating run `git pull && php bin/migrate.php` (adds the expenses table).

## Free WhatsApp on your own server (no Meta account, no per-message cost)
Uses WAHA, an open-source WhatsApp HTTP API, running in Docker on the same VPS and linked to a normal WhatsApp number like WhatsApp Web.
1. `cd /var/www/billing && git pull && php bin/migrate.php`
2. `sudo bash bin/install_whatsapp_server.sh`. It installs Docker if needed, starts WAHA bound to this server only (port 3000 is not exposed to the internet), generates an API key, and saves the address and key in the panel. Safe to run again.
3. In the panel: Messages → Gateway → provider **WhatsApp (free, own server)** → **Check connection**. Scan the QR with the spare phone (WhatsApp → Linked devices → Link a device). It says "Connected" when ready.
4. Save, then send a test message. Tick "Also use it for my admin alerts" to get alerts on WhatsApp too.

Notes: this is not an official WhatsApp service. Use a spare SIM, not your main number. Messages go out a few seconds apart on purpose, because bursts are what get numbers banned; a banned number is replaced by linking another. Keep the phone online occasionally; the link survives server restarts. Logs: `docker logs -f waha`. Update: `cd /opt/waha && docker compose pull && docker compose up -d`. Meta's official API (the other WhatsApp provider) stays available if you prefer it.

## Expired hotspot users are removed from the router
When a hotspot customer's time runs out they are now deleted from the router (not just disabled), and paying again creates a fresh user with a zeroed clock. A renewal also ends the old live session so the customer logs in on the new time. `cron/expire.php` clears leftovers every 15 seconds; to clear them at once run `php bin/cleanup_hotspot.php`. Only users that belong to a customer in this system are touched.

## Vouchers (scratch cards)
For customers who buy from agents or can't pay by M-Pesa on the spot. Menu: **Money → Vouchers** (needs the "Manage plans" permission).
1. `git pull && php bin/migrate.php` (adds the voucher tables).
2. **Card design**: pick Classic, Modern dark or Minimal, then adjust paper (A4 sheets or an 80 mm receipt roll), cards per row, height, colours, title, how-to text and which details show. For full control choose "My own design" and write the card in HTML and CSS using placeholders such as `{code_grouped}`, `{price_line}`, `{plan}`, `{duration}`, `{serial}`, `{valid_until}`, `{brand}`. Only layout tags are kept (no scripts, links or images).
3. **Make cards**: choose a hotspot package, how many (up to 500), the price on the card (defaults to the package price), a batch name (for example the agent), code style and length, an optional prefix and an optional expiry date.
4. **Cards tab**: Print a whole batch or only the cards you tick, download the codes as CSV, or cancel unused cards. Use your browser's print dialog at 100% scale with headers and footers off.
5. **Customers** open the hotspot page, tap *Have a voucher code?*, enter the code and their phone number, and are logged in. Each card works once. A card made for one router only works on that router's page.

The card price is counted as income (Reports → "Vouchers redeemed") when the card is used, not when it is made. Wrong guesses are limited to 15 per 15 minutes per address. Deleting a router also deletes its cards.

## Customer self-service page (/client)
Customers open `https://system.eazyradius.co.ke/client` (`/my` works too) (the hotspot page also links to it), sign in with their phone number, and see: time left, speed, data used this month and over the last 14 days, account balance, Paybill account number and payment history. They can renew by M-Pesa (the same prompt as the hotspot page) or from their balance, and hotspot customers can pick any package on their router.
- **Sign-in:** a 6-digit code sent by SMS or WhatsApp (needs a gateway under Messages → Gateway), or their phone plus account password. Codes work once for 10 minutes; wrong guesses and repeat requests are limited, and the page never reveals whether a number has an account.
- **Settings → Customer self-service page:** turn it on or off and allow or block renewing from it. Share the link on invoices, SMS or your Facebook page.
- Run `git pull && php bin/migrate.php` first (adds the login-code table). Customers who share a phone number see all accounts on that number.

## Automatic backups

Admin → Backups. Every night after the set time (default 02:30) the system makes a compressed copy of the whole database, checks it by reading it back, and keeps it for 14 days (3 to 90, your choice). The three newest copies are never deleted.

Setup on the server (once):

```bash
cd /var/www/billing && git pull
sudo cp deploy/billing.cron /etc/cron.d/billing        # adds the backup line (runs every 15 min, acts once a day)
sudo mkdir -p storage/backups && sudo chown -R www-data:www-data storage
sudo apt install -y mariadb-client                      # only if mysqldump is missing
```

Files are in `/var/www/billing/storage/backups` (closed to the web). Press **Back up now** to test, and `php bin/doctor.php` shows the status.

**Telegram copy (optional):** tick it, choose an encryption password (8+ characters) and save. Telegram needs the bot token and chat id from Settings → Alerts. The file is encrypted before it leaves the server because it holds customer data. Keep the password safe: without it the copy cannot be opened. Limit is 50 MB.

**Restore** (on the server, on purpose):

```bash
cd /var/www/billing/storage/backups
gunzip < billing-YYYYMMDD-HHMMSS.sql.gz | mysql -u DBUSER -p DBNAME
# Telegram copy: decrypt first
php /var/www/billing/bin/backup_decrypt.php billing-....sql.gz.enc restored.sql.gz
```

Also keep a copy of `config/config.php` somewhere safe: it holds the key that unlocks the saved M-Pesa and gateway secrets, and it is not in the backup.

## Missed-payment recovery

Sometimes a customer pays and Safaricom's confirmation never reaches the server. The system now deals with it without a phone call:

- **Asking Safaricom.** An M-Pesa prompt with no result is checked on the customer's own payment screen after 20 seconds, and by a cron every minute (every 15 minutes once it is over 10 minutes old; it gives up after 24 hours). If it was paid, the customer is switched on and the payment is marked *recovered*. If the customer cancelled, it is marked failed with the reason.
- **"I paid but I am still offline".** On the customer page (/client) the customer enters the M-Pesa code from the message. If the payment came from their own registered phone it is applied at once. Otherwise it goes to staff, and nobody can pick up someone else's payment by guessing a code (5 tries an hour).
- **Payments → Payment recovery** (staff): confirm or decline claims, see what was received and which account number the payer typed, and press **Check now** on any prompt still waiting. You get an alert when a claim arrives.
- **Doctor.** `php bin/doctor.php` warns when payments needed recovering (the callback address is probably blocked) and when prompts have waited over 30 minutes.

Update on the server:

```bash
cd /var/www/billing && git pull && php bin/migrate.php
sudo cp deploy/billing.cron /etc/cron.d/billing     # adds the every-minute reconcile line
```

Wrong-account Paybill payments still wait in the Paybill page for assigning, as before.

## FTTH dashboard (ONUs)

Network → ONUs (FTTH) is now a dashboard, not just a list:

- **Fleet health ring** with online share, and counts for *paid up but offline* (customers losing service they paid for), weak signal, marginal signal and ONUs with no customer linked. Click a count to filter the list.
- **Optical signal chart:** received power of every ONU in 2 dBm steps, coloured weak / marginal / good / excellent / too strong.
- **Last check-in bar** and **models** with online ratio.
- **Needs attention:** the most urgent ONUs first (paid but offline, weak, too strong, not seen for a week).
- **Device cards** with a signal ruler, customer and status, last seen, and Open / Refresh / Reboot. Search by serial, model, customer or phone; filter chips; switch to the table view (remembered in your browser).

Link an ONU to a customer by putting its serial number on the customer, as before. No setup or migration is needed.

## Suspend, resume and add days

On a customer's page:

- **Suspend** takes the customer off the network at once: a PPPoE secret or hotspot user is removed from the MikroTik (and the live session dropped); with RADIUS the session is dropped and the login is refused. Static IPs and TVs are blocked instead. The time they have left is **kept**. If the router cannot be reached, they are still suspended in the system and removed from the router automatically within a minute.
- **Resume service** switches them back on until the **same expiry date**. It never adds a period. If no time is left it says so.
- **Add days** gives free time (compensation for an outage, goodwill), on top of what they have left, or from today if none. The reason is written to the audit log. A suspended customer stays suspended until you press Resume. Use *Change plan* or a payment for a paid renewal.
- **Remove days** takes days off the time a customer still has (for a mistake or a duplicate credit). It cannot go past today: to stop service use *Suspend*. The reason is written to the audit log, and if the router cannot be updated nothing is changed.

## Customer page

Customers → click a customer. The top card shows who they are and what matters at a glance:

- **Status and connection** (online now / offline, last seen).
- **Time left** as a ring, with the exact expiry. Green normally, amber in the last fifth of the period, red when expired or suspended.
- **Plan** (with a data-cap bar if the plan has one), **balance** (owes us / credit held) and **last payment**.
- **Quick actions:** *Renew* (from the account balance; if the balance is too low it becomes *Receive payment*), *Add days* (free compensation, with a reason), *Remove days*, *Edit login* (PPPoE: change the username and/or password, with a *Generate* button for a random password; hotspot: password only; the router is updated first and nothing is saved if it refuses; renaming removes the old account so the old login stops working; optionally sent to the customer), *Reset password* (new random password, pushed to the router, optionally sent by SMS, session dropped), *Kick session*, *Suspend / Resume*, *Change plan*, *Send SMS*, *Device lock*.

Tabs underneath: **Overview**, **Usage** (daily data, live session), **Payments** (everything received: M-Pesa, Paybill, cash, vouchers, with receipts, failed attempts, recovered and not-applied flags, totals), **ONU signal** (RX/TX with a dBm ruler, status, model, WiFi names, Refresh / Reboot, and link or change the ONU serial), **Account** (statement, receive money, charges) and **Messages**.

No setup or migration is needed.

## Reboot a router
On the Routers page, open **More ▾** on a router and press **Reboot router**. It asks you to confirm, restarts the MikroTik, and writes the restart to the audit log. The router is offline for about 1 to 2 minutes and customers reconnect by themselves; a "not responding" alert during that time clears on its own. If the router refuses, the API user is missing the `reboot` permission (give its group the `reboot` policy). It needs the *Manage routers* permission.

## Login details for hotspot buyers
Everyone who buys a hotspot package gets one message with their **username, password, the customer portal link**, the plan and when it ends. It is sent once per purchase, a minute at most after the payment.

- **One gateway for everything:** it goes through the gateway chosen under Messages → Gateway, like every other message: WhatsApp (Meta or the free WAHA server) if you chose WhatsApp, SMS if you chose Africa's Talking or another SMS gateway. Nothing is sent if no gateway is set up, and purchases are not affected.
- **Switch it off or change the text:** Messages → Automatic. The text can use `{username}`, `{password}`, `{portal}`, `{plan}`, `{expiry}` and the other placeholders. Over SMS keep it short: the limit is 480 characters (3 SMS).
- **{portal}** is the customer self-service page (`/client/`), where they sign in with the same username and password. If you switch self-service off it becomes the hotspot buy page.
- Hotspot buyers do not get a second "payment received" message: this one already says so.
- The password is part of the message, so staff with access to Messages can see it in the log. Customer passwords are already visible on the customer page.

## WhatsApp inbox and keyword replies
Customers who write to your WhatsApp number show up under **Inbox** (the number on the menu counts conversations waiting for staff). The keyword bot answers what it can; everything else waits for a person. It only works when the chosen gateway (Messages → Gateway) is WhatsApp, either Meta or the free WAHA server: one gateway for everything.

**What the bot answers** (the account is found by the phone number WhatsApp reports, so a customer only ever sees their own):
- `BALANCE` the account balance and the renewal price. `EXPIRY` when the plan ends and how long is left.
- `PASSWORD` the username and password (3 times a day at most, can be switched off). `PAY` sends an M-Pesa prompt for the plan price to the customer's phone (3 an hour at most, can be switched off); with several accounts on one number they send `PAY username`.
- `HELP`, `HI`, `HELLO` the list above. Swahili words work too (`LIPA`, `DENI`, `MUDA`, `NENOSIRI`, `HABARI`).
- Anything else gets one "we have your message" per 6 hours and waits in the Inbox.
- **"I paid but I am offline":** the conversation is tagged *payment question* (filter in the Inbox). The bot first asks Safaricom about the customer's pending prompts and, if one went through, tells them they are connected. If the customer pastes the M-Pesa message, its code becomes a payment claim (Payments → Payment claims) and is applied automatically when the payer's number matches.

**Staff:** open a conversation, type a reply, or pick a saved template. The same conversation is on the customer's page under **Messages**. *Mark as done* hides it until the customer writes again. Replies also appear in the Messages log. New messages appear on the page by themselves every few seconds.

**Setup (once), Messages → Replies:**
- **Free WhatsApp server (WAHA):** press *Turn on replies on the WhatsApp server*. Re-running `sudo bash bin/install_whatsapp_server.sh` does the same and keeps your linked phone.
- **Meta Cloud API:** in developers.facebook.com → WhatsApp → Configuration → Webhook, paste the *Callback URL* and *Verify token* shown on that tab, press *Verify and save* and subscribe to **messages**. Saving the *App secret* makes the panel check Meta's signature. Meta allows plain-text replies for 24 hours after the customer's last message; after that only your approved template can be sent.
- Run `php bin/migrate.php` once (adds the inbox tables).
- Safety: every webhook call must carry the secret in its address, messages seen before are ignored, messages older than 15 minutes are never auto-answered, group chats are ignored, and a number gets at most 20 automatic answers an hour so two bots can never loop.

## Editing plans, live data per session, RADIUS status
- **Edit a plan:** Plans → *Edit* on a row. Name, price, duration, speed, data cap and throttle speed can all be changed. A new price or duration applies to payments from now on; time customers already have is not changed. If the speed changes, the profile on the router is updated (static IP customers' queues too). Customers get the new speed when they reconnect, or tick *reconnect the customers now* (about 10 seconds offline). Type, router and profile name are locked while customers use the plan.
- **Live sessions** now show **Download, Upload and Total** per PPPoE and hotspot customer, with a total row. PPPoE figures come from the router's counters on each customer's connection, so they restart when the customer reconnects.
- **Router → RADIUS tab** starts with a checklist: is the server running, does this router use RADIUS, does it have a tunnel address and secret, has it sent logins and usage updates. *Online now*, *Login attempts* and *Recent sessions* are shown for every router; they stay empty until the router uses RADIUS (a router on local accounts is on Live sessions). Requests the server ignores (an address that is not a RADIUS router, a wrong shared secret) are now listed, so a router that "shows nothing" tells you why.


### Deleting a plan

On **Plans**, each row has **Edit**, **Disable** and **Delete**. Delete is refused while any customer is on the plan (or has it scheduled as their next plan) or unused vouchers still use it; move them or use Disable instead. Past payments keep their history. The speed profile stays on the router.

### Adding a static IP customer

In **Add customer**, choosing a static plan swaps the form: Device MAC, ONU serial and Password are hidden (they only apply to PPPoE and hotspot, which keep them). Instead you pick the **router port** (the list is read live from the MikroTik: bridge, ether2 and so on), the **gateway address**, and the customer's **/32 IP**. **Generate** (or leaving the IP blank) picks a random free address in the gateway's /24. The `/ip address` entry is created on that port switched off, and turns on when the customer pays; it is switched off again when they expire or are suspended. Run `php bin/migrate.php` after updating (adds two columns to customers).

### Load balancing (combine internet links)

On **Routers**, open **More → Load balancing** (or the **Load balancing** tab on a router). Tick the ports that go to your ISPs; a port that is part of a bridge is refused (take it out of the bridge first). For each link say whether it is a **WAN IP** (address/prefix and gateway) or **PPPoE** (username and password from the ISP), and give it a share (higher = carries more traffic). Then pick the type:

- **ECMP**: one default route with all gateways. Simplest; connections are spread over the links and a dead link is skipped (check-gateway=ping).
- **PCC**: mangle rules split customers' connections by weight; every link has its own routing table with the other links as backup. You choose the LAN interface (usually the bridge). Best for links of different speeds.
- **Bonding**: joins the ports into `bond-wan` (802.3ad, balance-xor, balance-rr, active-backup or balance-alb) with ONE WAN IP or PPPoE. Only for cables that go to the same upstream device.

**Show what will be configured** prints the exact RouterOS commands (PPPoE passwords hidden). **Apply** (after ticking the confirmation) sends them. Everything added has the comment `billing-lb`; existing static default routes and DHCP clients on the chosen ports are switched off, and **Remove load balancing** deletes what was added and switches them back on. If the router refuses a step, everything is undone automatically. Run `php bin/migrate.php` after updating (adds `routers.lb_json`).

### Auto-fix for "I paid but I'm offline" and one-tap pay links

**Auto-fix.** When a customer WhatsApps *FIX*, *RECONNECT*, *OFFLINE* or something like "I paid but I am offline", the bot now: asks Safaricom about their open M-Pesa prompts, applies any payment that arrived but was never given as time, checks the account and the router, re-sends the account to the router if it is missing, drops a stale session so they sign in fresh, and replies with a short "here is what we checked" list plus what to do next (restart tips, send PASSWORD, or "the equipment in your area is not answering, you do not need to pay again", which also alerts you). A suspended account is never switched on by it. It runs at most 3 times an hour per customer; anything it cannot solve stays flagged in the Inbox. Staff get the same check from **Customer → Auto-fix connection**. Switch it off under Messages → Replies.

**Pay links.** Reminder, expired and debt messages can include `{paylink}` ("Pay in one tap: link"; `{paylink_url}` is just the link). The link (`/pay/?c=..&s=..`, signed per customer) opens a small mobile page with the plan and amount; one button sends the M-Pesa prompt to the customer's registered number (or another number they type) and shows when it is paid. The default reminder, expired and debt texts include it now; if you saved your own texts, add `{paylink}` where you want it. Turn links off under Messages → Replies. No migration is needed.

### Devices: Ubiquiti radios and the OpenStreetMap

**Network → Devices** lists your access points, station radios, PtP links, switches and other gear, and shows them on an OpenStreetMap. Each marker is green (answering), red (down) or grey (not checked yet); access points and PtP ends have a thick outline. A line joins every station to its access point, coloured by signal (green strong, amber fair, red weak, dashed when either end is down). Click a marker for its details, an *Open web page* link and Edit.

Add a device with its management IP, kind, the access point it connects to, and its position (click the map while the form is open, type the coordinates, or *Use my location* on a phone at the site). You can link a station to a customer by username or phone. Two ways to check a device:
- **With the device login** (airOS username and password, saved encrypted): the system reads signal, noise, CCQ, link rates, distance, frequency, SSID and firmware straight from the radio, and **Reboot** works. The server must be able to reach the device's IP.
- **Without it**: it only checks that the device answers, by pinging it from the MikroTik you choose under *Reached through router* (use this when the radios are on a private network behind the router). With neither, the server tries to connect directly.

`cron/devices.php` (added to `deploy/billing.cron`, every 2 minutes) checks every device. A device is marked down after 2 missed checks, and you get one alert (email / Telegram / WhatsApp as set up) after 3, and one when it is back. Run `php bin/migrate.php` after updating (new `devices` table) and copy the new cron line into `/etc/cron.d/billing`. The map needs the browser to reach cdnjs.cloudflare.com and tile.openstreetmap.org; the list works without it.

#### Static IP customers get their own /30

Each static customer now gets a dedicated /30 block: the router side is the first address and the customer the second, so the IP can only be used once, by that customer (for example router `10.10.0.1/30`, customer `10.10.0.2`; the next customer `10.10.0.5/30` and `10.10.0.6`). Add customer asks for the **address range to pick from** (for example `10.10.0.0/24`; the first and last block are kept free) and the **router port**. **Generate** (or leaving the IP blank) picks a free block; a typed IP must be the second address of a /30 (.2, .6, .10, ...). The router gets `/ip address add address=<router side>/30 interface=<port>` switched off until they pay. Customers added earlier with the shared-gateway /32 method keep working unchanged.

#### Reaching radios through the WireGuard tunnel (Devices)

Radios with private IPs behind a MikroTik need no public IP. On **Devices → Reach radios through the WireGuard tunnel**, type the network each router carries (for example `10.20.0.0/24`) and press **Save and set up**. That does three things:
1. **This server:** `bin/wg_sync.php` (root cron, every minute) adds the network to that router's WireGuard peer (`AllowedIPs`) and installs `ip route replace 10.20.0.0/24 dev wg0`. Routes for removed networks are deleted.
2. **The MikroTik** (through the API, immediately): `/ip firewall filter` forward accept from `wg-billing` to the network (placed first) and `/ip firewall nat` masquerade of the tunnel network towards it, so a radio answers whatever its own gateway is. Both are commented `billing-devnet`; **Apply to router again** re-sends them.
3. **Devices:** a radio whose IP is inside a saved network is attached to that router automatically, and the server polls the radio's airOS page directly through the tunnel (signal, CCQ, rates, distance, reboot).

**Run checks** shows: tunnel handshake, networks saved, router rules, the server's route, and a connection test to a radio IP. Rules: private ranges only (10.x, 172.16-31.x, 192.168.x, 100.64-127.x), /16 to /30, not overlapping the tunnel network or another router's radio network (two routers cannot share a range).

**Open from anywhere (optional, per radio).** Tick it in the device form to open a public port on this server (`forward_start + 5000 + device id`, shown as the "Open from anywhere" link) that forwards straight to the radio's login page through the tunnel. Only use it on radios with strong passwords, and allow the port in the server firewall. Run `php bin/migrate.php` after updating (adds `routers.device_nets`, `routers.devnet_applied`, `devices.remote_access`).

## Devices: access point view, customer radio, auto-fix

- **Access point view**: in Devices click an access point's name (or "View stations" on the map). You see its stations worst signal first, with counts for good, fair, weak (below -75 dBm), down and not checked. **Scan connected stations** asks the AP (airOS `sta.cgi`, needs the AP's saved login) who is associated now, refreshes the signal of stations you already have and lists the ones you have not added, with an Add button that pre-fills name, IP, MAC and the AP.
- **Customer radio**: on a customer's Overview, the Radio card shows the linked station's status, signal, CCQ, access point and last restart, with Check now and Reboot. Link or unlink a radio there (customers.manage).
- **Auto-fix**: when a customer says "I paid but I'm offline" and their account is fine, the linked radio is checked. Not answering: staff are alerted and the customer is told to check power and cable. Answering with a saved login: it is restarted (at most once per 6 hours). Switch off in Messages, Replies, "Check the customer's radio".
- Run `php bin/migrate.php` once (adds `devices.last_reboot_at`).

### Devices: public link not opening, and slow checks
- If a radio's public link (`http://vpn-host:PORT/`) does not open, `bin/wg_sync.php` (root cron) now also adds the `ufw route allow` rule from your public interface to each radio network (ports 80, 443), which ufw otherwise drops. Run `sudo php bin/wg_sync.php` once and check its output; the port itself must be open (`ufw allow 20000:60000/tcp`) and the radio network saved and applied on the Devices page.
- Checks are now parallel (8 at a time) with a 2 s connect timeout, so dead radios no longer hold up the rest.

## Support tickets

- Run `php bin/migrate.php` once (adds the `tickets` and `ticket_events` tables, and gives the Technician role view and manage, the Cashier role view). Other roles get **View support tickets** / **Open, assign and update support tickets** under Staff & roles.
- **Where tickets come from:** a customer sends *FAULT* on WhatsApp, uses **Report a problem** on their customer page (`/my`), staff open one from the Tickets page or a customer's Tickets tab, or the bot opens one automatically when the auto-fix cannot get a paid customer online (offline, router down, radio not answering, or three checks in an hour). A second report of the same kind goes onto the open ticket.
- **Attached automatically:** the customer, their linked radio (status and signal) and their router. The customer's WhatsApp messages while a ticket is open are copied onto its timeline. *TICKET* on WhatsApp shows the status.
- **Staff:** assign (or Take it), change status (Open, Assigned, In progress, Waiting for customer, Resolved, Closed), set priority, write internal notes, or **Send to customer** (WhatsApp, otherwise SMS). Resolving tells the customer. The dashboard shows open and unassigned counts.
- Switches in Messages, Replies: tickets on or off, auto-open on failed auto-fix, tell the customer when resolved.

## Data top-ups and cap messages

- Run `php bin/migrate.php` once (adds `data_topups`, `payments.topup_id`, `customers.extra_cap_mb` and `cap_warned`).
- **Bundles:** Plans page, "Data top-ups" card: name, size in GB, price. A bundle is offered only to customers whose plan has a **data cap and a slower speed after the cap** (plan fields "Data cap" and "Speed after cap"); without the slow-down nothing happens at the cap, so there is nothing to top up.
- **Buying:** the customer's page (`/my`, "Need more data?"), or WhatsApp: *TOPUP* lists the bundles, *TOPUP 2* sends the M-Pesa prompt for bundle 2. When the payment arrives the data is added, a slowed customer is back at full speed straight away (router profile or RADIUS reconnect), and a thank-you message is sent.
- **Limit:** plan cap + bought data. Plan data is used first. When the plan renews, unused bought data stays on the account.
- **Messages:** one at 80% of the limit and one when it is reached, each once per cycle, telling the customer how to buy more. Switch off in Messages, Replies ("Data cap messages").
- **Staff:** the customer's Usage tab shows the total limit and the bought part, and "Add data free" gives data without a payment (audited).

### Data bundles on the hotspot page
When at least one bundle exists and at least one WiFi package has a data cap with a slow-down after it, the hotspot landing page gets a **WiFi packages | Data bundles** switch. The Data bundles tab asks only for the customer's phone number (a WiFi account is named after it), sends the M-Pesa prompt, and on success logs the customer in again so their session restarts at full speed. An expired package is told to renew first. Re-upload nothing: the page is served by the server (`/portal/`), so just `git pull`. The Hotspot page builder preview shows the tab with sample bundles.

## Hotspot page: welcome back

When a phone that has paid before opens the hotspot page, the top of the page shows a "Welcome back" card: the masked number, the time left counting down live, and (for packages with a data cap) a meter of the data used. The **Connect** button logs the phone in with one tap, **Buy data** opens the Data bundles tab, and **Other packages** shows the package list. When the package has ended, the card says so and the last package is pre-selected.

The device is recognised by its MAC address, the same proof the "Already paid? Reconnect" box uses, and the login details are only released by the Connect button for a package that is still active (rate limited). Phones that use a private/randomised Wi-Fi address are not recognised; they keep using the Reconnect box. The data meter follows the usage poll (about every 5 minutes) or RADIUS accounting. No migration is needed; `git pull` is enough.

## PPPoE "Payments are due" page

When a PPPoE package ends, the customer can still dial in, but only to a pay page: a "Payments are due" message where they key in their account number, see the amount and pay with M-Pesa. Everything else stays blocked until the payment arrives, then the session is dropped and the router redials onto the full package.

Turn it on:
1. On every router that serves PPPoE press **Reconfigure** once. This adds the restricted `billing-due` profile, the `billing-due` address-list, the firewall rules (allow DNS and the billing server, drop the rest), a web redirect, and the router's own web proxy on port 8081 (locked to customers who owe).
2. In **Settings** tick "Payments are due page (PPPoE)". Optionally set the speed on the pay page (default 256k/256k).

Notes: phones show their "Sign in to network" sheet because plain http pages are redirected; https sites cannot be redirected, so a customer opening one sees a browser error and should open any http page, or the address `/expired/` on your billing domain (you can put that link in your expiry SMS). Suspended customers are still refused. With RADIUS the router sends the customer into the restricted list at login; with API mode the login stays enabled on the restricted profile. Leave the setting off until the routers have been reconfigured. No migration needed.

## Sign-in page when a hotspot package ends

A phone stays connected to the WiFi when its time runs out, and only shows the "Sign in" page when it notices the network changed. So when a hotspot package ends, the router is also told to drop that phone's hotspot entry, its DHCP lease and, when the phone is on the router's own radio, its WiFi link. The phone reconnects and the sign-in page appears by itself. Phones on a separate access point cannot be disconnected from here, so they notice at their next DHCP renewal: Reconfigure the router once, which sets the hotspot DHCP lease to 10 minutes (it was 1 hour). To turn the drop off, set `hotspot_bounce` to `0` in the settings table.

## Selling by data (Data packages tab)

Update first: `cd /var/www/billing && git pull && php bin/migrate.php` (adds the `cap_action` column to plans).

To create a data package such as "1 GB for KES 50, valid 30 days":

1. Plans → add a hotspot plan on the router.
2. Set the price, the validity in minutes (30 days = 43200) and the speed.
3. Enter the data in GB in the data cap field.
4. Set "When the data runs out" to "End the package".
5. Save.

The portal then shows a "Data packages" tab. If the router also has plans with a cap and slow-down speed, a "Data bundles" tab appears for those top-ups.

- The package ends when the data is used up or the time ends, whichever comes first. The router cuts the user off at the limit (`limit-bytes-total` in API mode, Mikrotik-Total-Limit in RADIUS mode). The panel syncs the usage about every 5 minutes.
- When it ends, the customer gets an SMS with a one-tap M-Pesa pay link (or the portal link if one-tap links are off in Messages).
- Buying another package before the first ends carries the unused data over. Once it has ended, nothing carries over.
- The customer's welcome-back card shows "Buy more data", and "Data finished" when the data is used up.

## Two-step sign-in (WhatsApp code)

Staff can ask for a 6-digit code on WhatsApp after their password. It is off until each person turns it on.

1. Update: `cd /var/www/billing && git pull && php bin/migrate.php`.
2. WhatsApp must be set up first (Messages → Gateway: Meta Cloud API or the free WhatsApp server).
3. Each staff member opens **My account → Two-step sign-in**, types their WhatsApp number and current password, and enters the code they receive. That confirms the number and turns it on.
4. From then on, sign-in is: email and password, then the code (works for 10 minutes, 5 tries, one new code per minute).

Notes:
- If WhatsApp is not working, a person with two-step sign-in on cannot sign in. This is deliberate: skipping the code would defeat it.
- With the Meta Cloud API in template mode the code is sent through your approved template, so the template needs a single text variable.
- To turn it off for someone who cannot get their code: `php bin/disable_2fa.php <email>`.
- To turn it off yourself: My account → Two-step sign-in → Turn off (asks for your password).

## Payment receipts

Every successful payment (M-Pesa, cash or voucher) has a numbered, printable receipt. Nothing to migrate.

- **Staff:** open it from the **Receipt** link in Payments or in a customer's payment history. The page has a "Print or save as PDF" button.
- **Customers:** add `{receipt_url}` to the payment receipt message (Messages → Templates), for example `Received KES {amount}, thank you {name}. Receipt: {receipt_url}`. The link is signed, so it cannot be guessed, and it shows the phone number only in part.
- **Settings → General → Receipts → Design the receipt:** a designer with a live preview.
  - Logo: upload a PNG, JPG or WebP (under 1.5 MB), set its height and put it left or centred.
  - Look: accent colour, font, and paper (A4 or an 80 mm receipt printer).
  - Wording: title, the total line, the stamp (PAID, or empty to hide it), a note under the header and a footer.
  - Business details: address, KRA PIN, VAT rate and receipt number prefix. With a VAT rate above 0 the receipt shows the amount before VAT and the VAT inside the total (prices are treated as VAT-inclusive). Leave it at 0 if you do not charge VAT.
  - Lines to show: business name, support phone, customer, account, phone (partly hidden), what was paid for, how it was paid, M-Pesa code.
  - Changes apply to new and old receipts straight away. "Reset to default" keeps your address and VAT.
- Receipt numbers follow the payment number (for example RCT-000123). They are not gap-free and are not an eTIMS tax invoice.

## Invoices and receipts for other work (CCTV, installations, equipment)

For anything that is not internet service. A client here has no internet account: only a name and contact details. Update first: `cd /var/www/billing && git pull && php bin/migrate.php` (adds the clients and invoice tables).

1. **Finance → Clients:** add a client with a name and a WhatsApp number and/or email.
2. **Finance → Invoices → New invoice:** pick the client (or choose "+ New client" and type the details there), add lines (description, quantity, price), an optional discount, and VAT (none, added on top, or already in the prices). The total updates as you type.
3. **Send it:** open the invoice and press **Send on WhatsApp** or **Send by email**. The client gets a message with a link to a page they can view, print or save as PDF.
4. **Record payments:** cash, M-Pesa, bank or cheque, in full or in parts. Each payment gets its own numbered receipt (RCP-000001), which you can send the same way (**WhatsApp receipt** / **Email receipt**). The invoice moves from unpaid to part paid to paid, and shows overdue after its due date.
5. **Mistakes:** an invoice with no payments can be edited or voided (it keeps its number). A wrong payment is reversed with a reason, which hides its receipt and reopens the balance.

Settings are in **Settings → Design receipts and invoices**: the same logo, colours and paper size as receipts, plus the invoice title, number prefixes, days until due, default VAT, "How to pay" text (Paybill, bank details) and a terms line. The page has a preview you can switch between receipt and invoice.

Invoice payments count as income in Reports (as "Invoices (other services)") and in the Profit tab.

Notes:
- WhatsApp sending needs WhatsApp set up in Messages (with the Meta Cloud API in template mode the message goes through your approved template). Email needs SMTP in Settings → Email. If either is missing the page says so; you can always copy the link and send it yourself.
- Links are signed and cannot be guessed. Receipts show the phone number only in part.
- Invoice and receipt numbers are not gap-free if you change prefixes, and these are not KRA eTIMS tax invoices.


## Quotes, "Pay with M-Pesa" and PDF attachments

After updating: `git pull && php bin/migrate.php`.

**Quotes** (menu: Quotes). Create a quote for any client (new client can be added inline). Add lines, discount and VAT like an invoice, plus a "valid until" date (default from `quote_valid_days`). Send it by email (PDF attached) or WhatsApp link. The client opens the link, sees the quote and presses Accept or Decline; you are notified. You can also record "Client accepted (by phone)". **Convert to invoice** copies lines, discount and VAT into a new invoice (due date from `invoice_due_days`) and marks the quote Invoiced. Expired or declined quotes cannot be accepted; editing a declined quote reopens it. Quote numbers use `quote_prefix` (default QUO-). The title and look come from Receipt designer (Quote preview).

**Pay with M-Pesa on the invoice page.** The client's invoice link shows a "Pay with M-Pesa" box: they confirm the phone number and get an STK prompt for the balance. When paid, the invoice is credited automatically and a receipt is available. Turn it off in Receipt designer ("Pay with M-Pesa button"). Money that arrives for an invoice already paid or closed stays as a normal payment and you are notified. Reports do not double-count these payments. Reversing such a payment only reopens the invoice balance; the M-Pesa money is still in Payments.

**PDF.** Emails for invoices, quotes and receipts carry the PDF as an attachment (needs SMTP set up in Settings). Public pages have a "Download PDF" link (`?pdf=1`). The PDF is a plain text layout using your designer settings and logo; it is not an eTIMS invoice.

## Device lock (MAC control) (Network → Device lock) and usage charts

After updating: `git pull && php bin/migrate.php`. Nothing else to set up; the every-minute monitor does the work.

**Devices per customer.** The monitor (API mode) and RADIUS logins remember each MAC a customer connects from. The customer page, Usage tab, has a "Devices used" table with **Lock to this device** (the existing one-device lock) and **Block**.

**MAC control page.**
- *Find a device*: type part of a MAC or a static IP to see who has it.
- *One device, more than one customer*: the same MAC seen as different customers in the last 45 days (shared password, cloned device, someone who moved). Use **Lock to this customer** to move the lock to the right customer; the previous holder loses it.
- *Static IP given twice*: two customers on one IP.
- *Block a device*: for a stolen or lost device. The device is disconnected within a minute and refused when it dials in again (RADIUS mode refuses the login). On API mode routers the billing system also keeps one firewall raw drop rule per blocked MAC (comment `billing-blocked-mac`); unblocking removes it. The list shows how many times a blocked device tried to connect.
- Viewing needs `routers.view`; blocking, unblocking and locking need `routers.manage`. Every change is in the audit log.

Limits to know: PPPoE in API mode is enforced by disconnecting the session every minute (it can redial for up to a minute), RADIUS mode refuses it at once. A static-IP customer's device is identified by the router's ARP table, so a blocked MAC behind another router is not seen. To move a customer to a new device after theft, block the old MAC and lock the new one on the customer page.

**Usage charts.** The customer page (Usage tab) and the customer portal (/my, "Data used") show download and upload as stacked bars with buttons for 7 days, 30 days, 90 days and 12 months, plus the total, average and busiest day. Hover a bar for the exact figure. Figures come from the router counters (about every 10 minutes) or RADIUS accounting, kept for 400 days; traffic between a sample and a session ending can be missed.

## Okoa Internet (borrow now, pay with the next package)

After updating: `git pull && php bin/migrate.php`. It is **off** until you switch it on under Customers → Okoa Internet.

A customer whose package has ended can borrow a short time at once, like Okoa Jahazi. When they next buy any package (M-Pesa prompt, Paybill, voucher, balance, points) the borrowed time plus a fee is taken off the new package's time. A customer never has to chase you and you never have to chase them.

Ways a customer borrows:
- **WhatsApp**: send **OKOA** to see the terms, then **OKOA YES** to take it (also *KOPA*, *BORROW*; *NDIO* works instead of YES). Matched by the phone number WhatsApp reports.
- **Customer portal** (`/my`): an "Out of time?" button.
- **"Payments are due" page** (PPPoE): the customer types their registered phone number to borrow; a different number is refused.
- **Staff**: Okoa Internet page → Lend time to a customer.

Settings: time lent (1 to 168 hours, default 24), fee (0 to 50 percent extra time, default 10), payments needed first (default 1, so brand-new customers cannot borrow). It never lends more than half of the customer's package length (a daily package lends 12 hours). One open loan per customer; suspended accounts and Smart TVs cannot borrow.

Example: 24 hours with a 10% fee. The customer gets 24 h now. Buying a 30-day package later gives 30 days minus 26 h 24 min. Repayment never takes more than 80% of one package; anything left stays owed for the next purchase. The customer gets a message (template under Messages) when they borrow.

The page shows what is still owed (and the KES value of that time at the package price), what was paid back, the fee time earned, and lets you write a loan off. Hotspot customers can borrow from the portal or WhatsApp (not from the hotspot login page, which does not know who they are). The time is repaid in time, not KES, so it does not appear in income reports.

## Scheduled hotspot plans (Sunday Njema)

A hotspot plan can be sold only inside a weekly window, for example Sundays 6:00 am to 9:00 am. Outside the window it disappears from the hotspot page and cannot be bought; when the window closes, customers on it are disconnected.

**Set up**

1. `git pull && php bin/migrate.php`
2. Plans → add or edit a hotspot plan. In the **Schedule** box tick the days and set From / Until (for example Sunday, 06:00 to 09:00). Leave every day unticked for a normal always-on plan.
3. The plan list shows the schedule and when it is next on sale.

**How it behaves**

- Name, price and duration work like any plan. Access lasts the plan's duration or until the window closes, whichever comes first.
- A plan stops being sold in the last 5 minutes of its window.
- Buying the same scheduled plan again while it is still active does not stack time.
- Vouchers for a scheduled plan can only be redeemed inside the window.
- Okoa Internet is not offered on scheduled plans.
- Payments applied outside the window (staff, Paybill) get the plan's full duration.
- Times use the server's timezone. Windows must be within one day (end later than start) and at least 10 minutes long.
- Scheduled plans are for hotspot only. Outside the window the plan is hidden, with no "coming soon" teaser.

## Expiry reminders: days and last hours

Messages go out by SMS or WhatsApp (whichever gateway you chose under Messages), with a one-tap M-Pesa pay link.

- Messages → Automatic → **Timing and limits**. "Remind this many days before expiry" defaults to `3,1`. The new "and this many hours before" box defaults to `1`, so customers hear 3 days, 1 day and 1 hour before expiry. Clear the hours box to turn the last-hour message off.
- Each customer gets at most one reminder per lead time per expiry, and renewing re-arms them.
- The last-hour wording is its own template ("Expiry reminder (last hours)"); `{paylink}` adds the pay link. The link needs M-Pesa prompts and "pay links" switched on.
- Reminders respect the sending hours (default 8 am to 8 pm), so an expiry in the night is covered by the day-before message.
- Hotspot customers are included only if "Include hotspot customers" is ticked.

## Dashboard: needs attention, growth and income breakdown

No setup needed. Three cards were added to the dashboard:

- **Needs attention** (top): offline routers, payments received but not applied (older than 10 minutes), Paybill payments waiting to be assigned, and failed messages from the last day. Each line links to the page that fixes it. Only items the signed-in person may open are shown, and the card is hidden when there is nothing to do.
- **Growth and churn**: new customers, renewals, lapsed customers and renewal rate, this month against last month. Renewals and lapses cover PPPoE and static IP customers.
- **Income this month**: by source (M-Pesa prompt, Paybill, vouchers, staff-entered, account credits, invoices, refunds) and by package. Needs the payments permission.

## "I paid but I'm not connected" (hotspot page)

`git pull && php bin/migrate.php`. No settings.

On the hotspot page the **Already paid? Reconnect** box now handles disputes. The customer types the M-Pesa code from their message:

1. If we already hold that payment, they are logged in. If it was received but the router had missed it, it is applied first.
2. If we have no record, the box asks for the phone number they paid with, then looks again:
   - a prompt still waiting for Safaricom is checked straight away;
   - a Paybill or till payment from the same phone whose amount equals exactly one hotspot package is applied at once and they are logged in;
   - anything else (amount fits two packages, a different payer, a code we never received) becomes a request for staff and you get a notification.
3. Staff: **Payments → Hotspot visitors saying they paid**. Pick the package (the one matching the amount is preselected) and **Confirm and switch on**. If the payment is not in our records you are confirming it from the M-Pesa statement, so check the statement first. It needs the manual-payments permission. **Decline** closes it.

Safety: a code can only be used once, a payment from another phone is never given away (the visitor is told nothing about it), 5 tries per phone and 25 per address per hour, and open claims show on the dashboard under Needs attention.

## Light theme and coloured icons

The panel now has a **Light** look by default: white menu, soft shadows, and one colour per section (Dashboard indigo, Customers blue, Network teal, Money green, Sales amber, Engage pink, System slate). Menu icons sit in tinted tiles of their section colour, and the **browser-tab icon** changes colour with the section you are in, showing your business monogram, so several tabs are easy to tell apart.

Settings → General → **Panel look** switches between Light and Classic (dark menu, follows the device's dark mode). Your brand colour still drives buttons, links and the logo tile. No migration is needed.

## Accent colour presets and better tables

- **Accent colour** (Settings → General): tap Indigo, Emerald, Ocean, Sunset, Rose, Violet, Gold or Graphite, or pick any colour. The panel repaints at once as a preview; press Save to keep it. The colour also tints button shadows, text selection, focus rings and card highlights.
- **Tables** (every list in the panel): the header row stays in view while you scroll long lists, rows alternate shading and light up under the pointer, and the action buttons in the last column stay visible when a wide table scrolls sideways. Tall tables scroll inside their card; on phones and when printing, tables behave as before.

## ONU: connected devices (DHCP client list)

Open any ONU (Network → Devices → ONUs → the ONU). The **Connected devices** card lists everything the ONU's router has seen: name, IP address, MAC address, how it is connected (WiFi 2.4 GHz, WiFi 5 GHz, or cable with the LAN port), whether it is connected now, the DHCP lease time left, and whether the address is DHCP or static. Filter by All, Connected now, WiFi or Cable.

- **Refresh list from the ONU** asks the ONU to re-read its table through GenieACS; reload a few seconds later. The list shows what the ONU last reported, with the time.
- Devices that hide their real MAC address (most modern phones) are marked "private".
- No migration needed. The default path is `InternetGatewayDevice.LANDevice.1.Hosts.Host` (TR-098: Huawei, ZTE and most ONUs) or `Device.Hosts.Host` (TR-181), chosen by the device type in Settings. If a model reports it elsewhere, use **Detect parameters on this device**, find "Connected devices table (Hosts)", and save it, or type it under Settings → ACS parameter paths.
- Some ONUs do not report a client list at all. The card then says so and tells you what to try.

The ONU list (Network → Devices → ONUs) also shows **who is online**: each online ONU card and table row has a "Devices online" count split into WiFi and cable, and a fleet total sits beside the other numbers at the top. Counts are as last reported by each ONU (use Refresh on an ONU to update it), and offline ONUs show a dash.

### "Your connection is not private" when opening a station from anywhere

Opening a radio at `https://system.eazyradius.co.ke:25004` fails with `NET::ERR_CERT_AUTHORITY_INVALID` and no "Proceed" button. Cause: the panel sends HSTS, and browsers apply HSTS to the host name on **every port**, so the radio's own (self-signed) certificate can never be accepted on that name.

- "Open from anywhere" now uses the server's public IP for https radios (an IP has no HSTS), so the normal one-time certificate warning appears with **Advanced → Proceed**.
- Better: **Routers → Remote access → Address for device links**. Enter the server IP, or a second host name pointing at the same server (for example `devices.eazyradius.co.ke`, no HSTS and no website on it). Router "Connect" addresses use it too.
- A phone that already cached the block on the panel name keeps it until you clear it: Chrome → `chrome://net-internals/#hsts` → delete `system.eazyradius.co.ke`. Using the new link avoids needing that.

### Signals on the Devices page

- Signal appears only when the system can read it from a radio. Station signals now refresh automatically: each check of an access point (or PtP end) that has a login saved also reads its station list and updates every listed station matched by MAC or IP. No need to press **Scan connected stations**.
- The AP's own row shows the average of its stations when the radio reports none.
- Where there is no signal, the cell now says why: no login saved on the radio or its access point, a failed login (with the reason), or not checked yet.
- Run the migration: `php bin/migrate.php` (adds `devices.poll_note`). The cron `cron/devices.php` (every 2 minutes) does the reading.
- To see signals: save the airOS login on each access point, and make sure each station's MAC (or IP) in Devices matches what the AP lists.

### "Login read failed: … dh key too small"

Old airOS firmware offers a weak Diffie-Hellman key (and TLS 1.0/1.1). OpenSSL 3 on the server refuses that by default. The device reader now connects with a relaxed TLS security level (`DEFAULT:@SECLEVEL=0`, TLS 1.0 and up) for radio checks only. It applies to the device HTTP calls (status, station list, reboot), not to anything else on the panel. If the error remains, tick "plain HTTP" on that device (if its web page allows it) or update the radio's firmware.

### "Login read failed: The device did not return its status (…)"

The login worked but the radio's status page did not answer with airOS JSON. The message now says what came back:
- `redirect to https://…`: the radio forces HTTPS. Untick "plain HTTP" on the device.
- `redirect to http://…`: the radio is HTTP only. Tick "plain HTTP".
- `HTTP 200, page says "…"`: the address is not an airOS radio (a router, a different brand, or a web page in front of it). Check the IP, or that this device really is a Ubiquiti airOS radio.
- `HTTP 404/403/401`: the firmware has no `status.cgi`, or the login user is read-only. Use the radio's admin user.
JSON with extra characters around it (a BOM or whitespace) is now accepted.

### Reading radios over Telnet instead of the web page

On a device, **Read signal using → Telnet (port 23)** makes the server log in on the radio's command line and run `mca-status` (signal, CCQ, rates, distance, SSID, firmware, model) or, for an access point, `wstalist` (its stations). Reboot sends `reboot`. No HTTPS or TLS is involved, so errors like "dh key too small" cannot happen.

- Turn it on in the radio: **System → Services → Telnet Server**, then save.
- Telnet is plain text. The server reaches radios through the WireGuard tunnel, so passwords never cross the internet, but do not use it over a public path.
- Needs the migration: `php bin/migrate.php` (adds `devices.read_via`).
- Errors say what is wrong: cannot connect (Telnet is off), login not accepted, or logged in but `mca-status` returned nothing readable (not an airOS radio).

### Modern alerts and emails

- Staff alerts (router offline or back online, device down, payment not applied, backup failed, tickets, quotes, payment claims) are now formatted by `src/Notice.php`: a coloured status dot (🔴 problem, 🟢 recovered, 🟠 needs a look, 🔵 information), a topic icon, a short list of facts, the time and your business name. WhatsApp gets bold text, Telegram plain text.
- "Router back online" now says how long the router was down.
- Every email is sent as a branded HTML page with a plain-text twin (mail apps that cannot show HTML show the text). The top bar uses the same colours; sign-in and reset codes are shown large. Alert emails include an **Open dashboard** button (uses `public_url` from the config). Emails with a PDF (invoices, quotes, receipts) keep the attachment.
- The staff WhatsApp sign-in code message is restyled. SMS messages stay plain text on purpose: emoji turn an SMS into a short, more expensive one.
- To restyle a message from code: `notify_admin($subject, $text, ['📡 Router' => 'demo'])`. The subject picks the colour and icon (words such as offline, down, failed, back online, paid).

### Reading radios over SSH (recommended over Telnet)

On a device, **Read signal using → SSH (port 22)**. The server logs in with the saved username and password and runs `mca-status` (or `wstalist` on an access point; `reboot` for a restart), the same commands as the Telnet reader, but encrypted.

- In the radio: **System → Services → SSH Server** on, port 22, password login allowed.
- The server needs the `ssh` program (`apt install openssh-client`; Ubuntu already has it) and PHP `proc_open` enabled. The password is handed to ssh through an environment variable and a temporary 0700 helper script (removed straight after), never on the command line.
- Old airOS firmware only knows old SSH algorithms (`ssh-rsa`, `diffie-hellman-group1-sha1`, CBC ciphers). The reader allows the ones the server's ssh still has. If the radio is too old for that, the error says so; use Telnet for that radio.
- Same migration as Telnet (`php bin/migrate.php`, adds `devices.read_via`).
- Errors say what is wrong: connection refused (turn SSH on), password not accepted, no answer in time, or algorithms refused.

### Modern customer messages (payments, reminders, plan changes)

Receipts, expiry reminders, expired notices, debt reminders, plan changes, Okoa and the hotspot login message now come in a WhatsApp look: a status emoji, bold key facts (amount, plan, expiry, Paybill) and short lines. Example:

```
✅ *Payment received*

Thank you Wanjiku! 🙏

💰 Amount: *KES 1,500*
📦 Plan: *Home 5M*
📅 Active until: *29 Nov 2026*
💳 Balance: KES 0
🧾 View receipt: https://…
```

- **Messages → Message texts → Style**: *Automatic* (modern on WhatsApp gateways, plain classic text on SMS gateways, because emoji make an SMS shorter and dearer), *Modern everywhere* or *Plain everywhere*.
- A text you never changed follows the style. A text you edited is kept exactly as you typed it. To go back to the built-in one, empty the box and Save.
- New placeholders for your own texts: `{paylink_line}` ("👉 Pay in one tap: link", blank when payment links are off), `{receipt_line}` and `{support_line}` (each a whole line that disappears when there is nothing to show).
- Staff alerts about payments (not applied, invoice paid, payment claims) now carry a short list: amount, phone, M-Pesa code, invoice.

## FUP (fair usage) tab

Menu: Customers → FUP. Replaces the "speed after cap" fields on the plan form.

**Set up**
1. `php bin/migrate.php` (adds the FUP tables).
2. Add the cron line (every minute): `* * * * * php /var/www/billing/cron/fup.php`
3. FUP tab → Add a rule: name, period (hourly / daily / monthly / per package), limit in GB, slow speed (e.g. `1M/1M`), warn at % (default 80), reset price (KES, 0 = no paid reset), then tick the plans it applies to.

**How it works**
- Each minute the collector reads the router counters (simple queue named after the username; PPPoE falls back to the `<pppoe-user>` interface, hotspot to the hotspot user) and adds the new bytes to the customer's usage for the current hour / day / month / package.
- At the warning % the customer gets one message; at the limit the customer is slowed (profile `-fup` twin for PPPoE/hotspot, queue max-limit for static) and told the slow speed, when it resets and the price to reset now.
- Usage resets by itself when the hour/day/month changes or the package is renewed. Staff can press **Reset FUP** (FUP tab or customer page). The customer can pay the reset price from the portal (M-Pesa prompt); a paid reset does not renew the plan.
- Messages can be turned off on the FUP tab; wording is under Messages (FUP warning / limit reached / FUP reset).
- Older per-package caps and data packages still work and are listed in "Older style" on the FUP tab. A plan cannot have both a FUP rule and an older cap.

**Not tested on real hardware:** per-minute reads from live MikroTik queues, speed changes on a real router, and the paid reset on a live M-Pesa account (tested against mocks only). Try one customer first.

## Adding a client by service and router, and moving a client

**Add customer** (Customers → Add customer): pick the **Service** (PPPoE, Static IP, Hotspot), then the **Router**, then the **Package on this router** (only active packages of that service on that router are listed). For Static IP the form reads the router's ports (ethernet, bridges, VLANs) and picks a free /30 from the range you give. The account is created on the router **disabled** and is switched on by the first payment or when staff recharge/renew.

**Move to another router** (customer page → Actions → Move to another router): choose the new router and a package of the same service on it (for static, also the port and optionally a new address range; blank keeps the IP). The account is removed from the old router and created on the new one in the same on/off state; time left and balance are kept. If the new router refuses, the old account is restored and nothing changes. Create the package on the new router (Plans) first.

Not tested on real routers: the port list and the account creation/removal were tested against a mock RouterOS only. If the old router is offline at the time of the move, the old account stays there and the page says so.

### FUP Manager layout
The FUP page has tabs: **Rules** (add/edit rule, Run poll now, Reset FUP by client username or by plan, rules table with Edit/Toggle/Delete, messages, activity, older per-package caps), **Throttled (n)**, **Usage**, **Live** (read in the last 5 minutes, refreshes every minute), **Charts** (24-hour usage and the customers closest to their limit) and **Reset pricing** (the price a customer pays to lift the slow-down). "When exceeded" only offers throttling; blocking is not supported.

### WhatsApp keywords for FUP
Customers can send **USAGE** (also "my usage", MATUMIZI, FUP): data used, fair-usage limit, percentage, speed and when it resets. **RESET FUP** (also RESET, UNLOCK) sends an M-Pesa prompt for the rule's reset price; paying restores full speed and does not renew the package. With several accounts on one phone they send `RESET username`. HELP lists both words once a FUP rule exists. BALANCE, EXPIRY, PAY, PASSWORD, FIX, TOPUP, OKOA and FAULT already existed. Tested with mock M-Pesa, not a live WhatsApp number.

### More WhatsApp keywords
Run `php bin/migrate.php` (adds `customers.paused_at`, `last_pause_at`, `chat_threads.lang`). Customers can send:

| Keyword | What happens |
|---|---|
| RECEIPT / STATEMENT | Last payment / last five (date, amount, M-Pesa code, package) |
| PAYBILL (ACCOUNT) | Your Paybill and their account number |
| SPEED | Package speed, or the slow speed if FUP slowed them |
| PLANS, then UPGRADE n, then UPGRADE n YES | Lists packages they can switch to (same router, type and period). An upgrade charges the time-left difference from their **account balance** (refused with the reason if it does not cover it); a downgrade starts at the next renewal |
| NEWDEVICE | Releases the device (MAC) lock, twice a month at most; with "auto bind" on, the next device to connect is locked |
| RESTART | Reboots the customer's linked radio, else their ONU through GenieACS (once an hour); otherwise hands over to staff |
| WIFI NAME x / WIFI PASS x | Changes Wi-Fi on the customer's ONU through GenieACS (3 a day). The password is never repeated in the reply, **but it is stored in the chat history**; tell customers to change it again later if worried |
| PAUSE / RESUME | Freezes the package (needs 3+ days left, once every 60 days). The paused days are added back on resume; it resumes by itself after 30 days (cron/monitor.php). Staff pressing Resume also gets the days back |
| AGENT | Flags the chat "wants a person" in the inbox and alerts the admins |
| SWAHILI / ENGLISH | Swahili is translated for the HELP menu, balance, receipts, Paybill and a few confirmations; the other replies stay English |

The HELP text is now longer than an SMS; WhatsApp messages may be up to 1500 characters. If you saved your own HELP text earlier, add the new keywords to it (Messages → Replies) or clear it to use the built-in one.
Tested with mock services only; WIFI, RESTART (ONU) and the router actions have not been tried on real hardware.

## Router backups and replacing a failed router

Menu: Network → **Router backups**. Admins only (settings rights), because a backup holds passwords and keys.

**Set up**
1. `php bin/migrate.php`
2. Cron every 15 minutes: `*/15 * * * * php /var/www/billing/cron/router_backup.php` (it only works when a router's last backup is older than the interval; default **2 days**, keeps the last 15 per router; both are set on the page).
3. Press **Back up now** on one router to check it works.

**What is saved.** The router's own text `/export` (identity, IPs, firewall, queues, PPP profiles and secrets, API users, WireGuard keys), encrypted with the app key in the database. If a router does not upload it (RouterOS older than 7, or it cannot reach the server), a **partial snapshot** is rebuilt from API reads and clearly marked: it lacks user passwords, WireGuard keys, certificates and scripts, so a full export is needed for a clean replacement. The page also shows what changed since the previous backup and lets you download the .rsc.

**Replace a failed router.** Backups → Replace router… on the backup you want:
1. Reset the new router: `/system reset-configuration no-defaults=yes skip-backup=yes`, then give it internet (`/ip dhcp-client add interface=ether1 disabled=no`).
2. If it is a different model, map the old port names to the new ones (`ether5=ether3`).
3. Create restore command, paste it in the new router. It downloads the backup (one-time link, 2 hours, 3 downloads) and imports it. With a full export the router comes back with the same identity, addresses and WireGuard tunnel, so the billing system sees the same router.
4. Press **Re-sync accounts** to send all plan profiles and customer accounts to it again (customers added since the backup come back too).

**Not tested on real hardware:** the router-side upload (`/export` + `/tool fetch upload=yes`) and the import of a restore on a real MikroTik were tested against a mock only. Whether `upload=yes` over HTTP works depends on the RouterOS version, so check one router first; the partial snapshot is the fallback. Test a restore on a spare router before you need it.

## Audit alerts to WhatsApp

Your **Alert WhatsApp number** (Settings) now also receives security alerts and an activity feed.

- **Sent at once:** a mass delete (5 deletions by one person in 10 minutes), a manual credit, refund or write-off of KES 5,000 or more, a staff sign-in from a browser that person has not used before, a changed Paybill/Till/M-Pesa setting (secrets are never shown), 5 failed sign-ins in 10 minutes, role-permission changes, router removal, backup downloads, write-offs and payment reassignments.
- **Everything else:** one short digest per minute (up to 20 lines, then "and N more"), at most 20 digests an hour so WhatsApp is never flooded.
- **Controls:** Audit log page → *WhatsApp alerts*: Every activity / Only risky / Off, the big-credit amount, the mass-delete count, and a **Send test** button.
- A person's first-ever browser is learned silently; a browser update is not a new device.
- **Install:** `sudo sh bin/install_cron.sh` adds `cron/audit_alerts.php` (every minute). The first run starts from now and does not replay old history. Run `php bin/migrate.php` for migration `20261224_audit_alerts.sql`.
- **WhatsApp limit:** on the Meta Cloud API, free-form messages only arrive within 24 hours of your last message to the business number. Reply to the bot daily or use a template; WAHA-style gateways have no such limit.
- Tested only against mock servers, not a real WhatsApp account.

## Who's online (Live sessions)

Customers → **Who's online** now shows every active PPPoE and hotspot session on **all routers** in one list (or pick one router).

- Each row shows the customer's name (linked to their page), login, plan, type, router, IP, device MAC, uptime, download, upload and total. Heaviest users first. A login that is not a customer is labelled.
- The header counts people online, split into PPPoE and hotspot, with total usage.
- **Find** filters live by name, login, IP, MAC or router; **Show** limits to PPPoE or hotspot; **Refresh every 30 s** is remembered in your browser and pauses while you are typing in Find.
- **Disconnect** (needs the "Disconnect live sessions" permission) kicks that session on its own router and writes `session.disconnect` to the audit log. A customer with an active plan reconnects in seconds, so use it to apply a changed speed or clear a stuck session.
- Routers already marked offline are skipped and named, so the page never waits on a dead router; unreachable ones show an error line.
- PPPoE usage comes from the router's counters on each customer's PPPoE interface; tested only against a mock RouterOS.

## One Backups page, and SMS as a fallback for WhatsApp

- **Backups** (System) now has two tabs: **Database** and **Routers**. "Router backups" is no longer a separate menu item; the old address `index.php?p=router_backup` still works and keeps Backups highlighted.
- **WhatsApp first, SMS if it fails.** Messages → Gateway → tick *If a WhatsApp message cannot be delivered, send it as an SMS instead*, and fill in Africa's Talking (or the other SMS gateway), which appears when the box is ticked. When WhatsApp is the main channel, a message that WhatsApp refuses twice (or at once for "24-hour window", "template" or "not on WhatsApp" errors) goes out by SMS. WhatsApp bold marks are removed from the SMS. The message log shows *Sent by SMS because WhatsApp failed: …*. A message WhatsApp delivers is never also sent by SMS. Off by default.
- Tested only against mock servers, not a real WhatsApp or SMS account.

## Bulk customer actions

Customers page: tick customers (or the box at the top of the list for everyone shown), and a bar appears with **Do something with them…**. Choose:

- **Suspend / Resume.** Suspend takes them off the router and keeps their remaining time. Resume only touches suspended customers and adds no time.
- **Add days.** 1 to 365 days, with a reason that goes into the audit log. Use it for outage compensation.
- **Change plan.** Same rules as changing one customer's plan (same router and period, PPPoE or static). An upgrade charge is taken from the customer's *balance* only and is never recorded as a payment; customers who cannot cover it are listed as failed. A downgrade starts at their next renewal.
- **Move to another router.** Each customer gets the package with the same name on the new router, or else one with the same type, price and period. Customers with no matching package, with no package at all, and static IP customers (they need a port and an address) are listed as failed and stay where they are.
- **Send a message.** Personalised with the usual placeholders ({name}, {plan}, {expiry}…), queued on your WhatsApp/SMS gateway. Needs the "Send SMS to customers" permission.

Details: up to 200 customers at a time; each customer is handled separately, so one failure never stops the rest. After it runs you get a summary of how many were done, which were skipped (nothing to do) and which failed and why. Every customer gets their own audit line marked "(bulk)", plus one `customer.bulk` summary line, which is also sent to your WhatsApp as a security alert at once. Needs the "customers.manage" permission.

Tested only against a mock RouterOS and mock WhatsApp, not real routers.
