# ABM SMS Gateway SaaS

Multi-tenant SMS gateway (CodeIgniter 4 / PHP 8.2 / MySQL) reselling upstream Bangladeshi SMS provider capacity to ~100 bike showroom clients. Full spec: [docs/SPEC.md](docs/SPEC.md). Phased build plan: [docs/PLAN.md](docs/PLAN.md).

## Non-negotiables
- Credit ledger (`sms_credit_ledger`) is append-only and is the source of truth for balance; `sms_tenants.balance_cached` is only a cache. Every balance mutation is `beginTransaction → SELECT ... FOR UPDATE on tenant row → check sufficiency → insert ledger row → update balance_cached → commit`. Never update balance without a ledger row in the same transaction. Corrections are new reversal rows, never edits/deletes.
- Strict tenant isolation: every tenant-owned table query must go through `Models\BaseTenantScopedModel` (auto-injects `tenant_id` from `Libraries\RequestContext`), not a manually-added `where()`.
- Table prefix `sms_`, all DB timestamps UTC, rendered Asia/Dhaka.
- Controllers are thin (validate → call service → format response); all business logic lives in `app/Services/`, all queries in `app/Models/`.
- Ask before: changing the table prefix, adding a Composer package outside the stack in SPEC §1, altering the credit ledger design, or introducing Redis as a hard dependency.

## CI4 gotchas hit so far (don't rediscover these)
- `Forge` (migrations) naively concatenates the `sms_` DBPrefix — always use bare table names in migrations (`tenants`, not `sms_tenants`).
- `DatabaseTestTrait` defaults to migrating only the `Tests\Support` namespace — any DB-backed test needs `protected $namespace = null;` or it silently runs against an unmigrated schema.
- Cache keys reject `{}()/\@:` (file cache handler validates this) — use `_` as a separator in cache keys, never `:`.
- DB row values come back as strings/mixed from the query builder even for integer columns — cast explicitly (`(int) $row['id']`) before assigning to a typed property/return.
- `RequestContext` (tenant + credential + request id, set once per request by `ApiAuthFilter`) is a static holder, safe under PHP-FPM only because it's unconditionally reset at the start of every request — never read it before `ApiAuthFilter` has run, and never make a new per-request static holder that skips that reset. CLI commands/workers have no request, so `BaseTenantScopedModel` takes an optional constructor `$tenantId` that wins over `RequestContext` when set — worker code always constructs tenant-scoped models with an explicit tenant id, never relies on the global.
- CI4's query builder has no `orWhereNull()`/`whereNull()` — pass `null` as the value to `where()`/`orWhere()` instead (`->orWhere('col', null)`); it auto-generates `IS NULL`.
- `$allowedFields` mass-assignment protection applies even to columns a base class auto-injects (e.g. `BaseTenantScopedModel::insert()` setting `tenant_id`) — if the column isn't listed, CI4 silently strips it before the query runs, which for a NOT NULL FK column surfaces as a confusing "foreign key constraint fails" error, not an obviously-related one. Every tenant-scoped model's `$allowedFields` must list `tenant_id` explicitly.
- `CURLRequest` defaults `http_errors` to `true` (sets `CURLOPT_FAILONERROR`), so a 4xx/5xx response throws instead of returning normally — pass `'http_errors' => false` in the request options whenever the caller needs to inspect a non-2xx body itself (every outbound provider/webhook call does: `Libraries\HttpClient` always sets this).
- `IncomingRequest::getJSON()` throws `HTTPException` on invalid JSON instead of returning null — never call it directly in code that must survive a malformed inbound payload (any public-facing, unauthenticated endpoint like the DLR webhook); decode the raw body with plain `json_decode()` and check the result yourself instead.
- A promoted-property default must be a `new Xxx()` expression (PHP 8.1's "new in initializers") — a static factory call like `Database::connect()` as a promoted default throws `Fatal error: Constant expression contains invalid operations`. Any service whose default dependency isn't built via plain `new` (a DB connection, anything from a container/factory) needs an old-style nullable param + `$this->x = $x ?? Database::connect();` in the constructor body instead.
- A `.env` value is always a string — `session.savePath = null` in `.env` does NOT mean "use the PHP default", it sets `Config\Session::$savePath` to the literal string `"null"`, which (not being absolute) resolves relative to the doc root and silently writes real session files to `public/null/`. This sat unnoticed from Phase 0 through Phase 7 because nothing used sessions until Phase 8's admin panel. Omit a `.env` key entirely to let the `Config\` class's own PHP-file default apply; never use the bareword `null` in `.env` expecting PHP-null semantics.
- `FeatureTestTrait::call()` resets `$_SESSION = []` at the start of *every* `get()`/`post()`/etc. call, so session state from one call never automatically carries into the next — call `$this->withSession()` (no args) right after a call that's supposed to leave the session mutated (e.g. login) to capture `$_SESSION` into the next call. Separately, CSRF (session-mode): `Services::security()` is a shared singleton for the whole test process, so `csrf_hash()` called anywhere in the test already returns the exact value the CSRF filter's `verify()` will check against — just post `[csrf_token() => csrf_hash(), ...fields]`, no session priming needed for the token itself. Also: bash variables never survive between separate tool-call invocations when live-curl-testing a session+CSRF flow — scrape the token and POST with it in the *same* shell invocation, or the token variable is empty on the second call and everything 403s.
- `CodeIgniter\I18n\Time::setDay()` internally does `strtotime("{$year}-{$month}")` (unpadded, e.g. `"2026-8"`) to find the target month's last day — that can fail (returns `false`, which then TypeErrors the next `date()` call) depending on PHP/locale. Avoid `setDay()`/similar fluent Time mutators for "start of month" style logic; build the date as a plain string instead (`$time->format('Y-m') . '-01'`) when a Time *object* isn't actually needed, just the date string.
- **`CLI::parseCommandLine()` never splits on `=`** — a spark command option must be passed space-separated (`--limit 500`), never `--limit=500`. The `=` form silently becomes an unrecognized option key (`"limit=500"`, not `"limit"`), so `CLI::getOption('limit')` returns null and the command falls back to its coded default with zero warning or error. This bit every `--limit=N` in `docker-compose.yml` and `docs/deployment.md`'s supervisor blocks from Phase 3 onward — found only in Phase 10 via live-testing the new `sms:archive --older-than` flag, fixed project-wide then. When adding any new spark command option, always live-test both the flag itself *and* its actual effect (not just "the command ran without error") — a silently-ignored flag looks identical to a working one until you check the number it produced.
- `Config\App::$proxyIPs` defaults to `[]` — behind any TLS-terminating reverse proxy (Caddy, nginx, an LB), `Request::isSecure()` then never trusts `X-Forwarded-Proto`, so `forceGlobalSecureRequests` redirects every request to itself forever (an infinite-redirect loop, not an error page). Never surfaces in local dev, which has no reverse proxy in front — only found on the actual first production deploy. Must be set to trust the proxy's immediate peer IP (this repo trusts the private RFC 1918 ranges, since only our own nginx container on a Docker-internal network can ever be that peer) — see docs/deployment.md's Environment section.

## Process
- Build in the phase order in [docs/PLAN.md](docs/PLAN.md) (0 → 10). Stop at the end of each phase, run its tests, report status, and wait before continuing to the next.
- Real upstream provider is BulkSMSBD (`Services\Provider\Adapters\BulkSmsBdProvider`). Real credentials arrived 2026-08-18 — the adapter has been reworked and fully verified against the live API (see docs/providers/bulksmsbd.md). It sends each message as its own `/api/smsapi` call rather than the originally-guessed `smsapimany` batch endpoint, which turned out to hit a server-side bug on BulkSMSBD's end regardless of payload shape. A real single-recipient test-send (2026-08-18, to a number ABM Soft explicitly provided) confirmed the success response shape exactly matches the adapter's assumption (`message_id` field, `response_code: 202`) — nothing left unconfirmed except the DLR push format/mechanism.
- **All 11 phases (0-10) complete — the build itself is done.** Deployed to production at `https://sms.nextmotogear.com` (co-hosted on the same VPS as the sibling `abm-leadflow`/`nextmotogear.com` project, behind that project's existing Caddy instance — see docs/deployment.md's "Co-hosting behind an existing Caddy" section for exactly how). `NullProvider` is still the only *active* provider in production as of this writing — `BulkSmsBdProvider` is code-complete, test-covered, and now fully verified against the live API, but its real credentials haven't been loaded into `sms_providers` yet (deliberately — going live means every future tenant send is a real, billed SMS, held pending explicit go-ahead); everything else (admin panel, tenant portal, API, workers) is live and functional.

## Bangladesh domain rules (see SPEC §2 for full detail)
- Phone numbers normalize to `8801XXXXXXXXX` (13 digits, no `+`); operator is derived from the prefix and stored on the message.
- Encoding: GSM-7 (160/153 chars per part) vs UCS-2 (70/67 chars per part) — a single non-GSM character forces the whole message to UCS-2. `EncodingDetector` must be pure/side-effect-free.
- Masking (branded sender ID) requires per-tenant approval (`sms_sender_ids.status`); non-masking is always available.
