# PHP → TypeScript porting guide (ppa-team-api)

Source (read-only): `/home/claude/src/ppa-employee-api/application/` (CodeIgniter 3 REST).
Target: `/home/claude/ppa-team-api/src/`. Goal: **drop-in replacement** — same URLs, same
request parsing, same JSON field names/values/types, same status codes, same SQL.

Port **1:1**: same class names, same method names (including `_get`/`_post`/`_put`/`_delete`
suffixes and their exact case), same parameters (keep PHP defaults as TS defaults — the
router uses `fn.length` to emulate PHP's ArgumentCountError), same control flow, same SQL
strings. Do not refactor, "fix", or simplify behaviour. Commented-out PHP code can be dropped.

Reference ports: `src/controllers/api/Survey.ts`, `src/models/M_survey.ts`.
Core runtime (do NOT edit; report bugs instead): `src/core/*`, `src/utils/php.ts`.
If you need extra PHP-compat helpers, put them in `src/utils/compat/<YourGroup>.ts`.

## File layout & naming
| PHP | TS |
|---|---|
| `controllers/api/Home.php` class `Home` | `src/controllers/api/Home.ts` `export class Home extends Controller` |
| `models/M_api.php` class `M_api` | `src/models/M_api.ts` `export class M_api extends Model` |
| `libraries/HoPlafondApi.php` | `src/libraries/HoPlafondApi.ts` `export class HoPlafondApi extends Library` — constructor `(CI, params = null)` |
| `helpers/fcm_helper.php` | `src/helpers/fcm_helper.ts` exporting functions |
| `views/create_pdf/p2h.php` | `src/views/create_pdf/p2h.ts` `export default function (data: any): string` |

Imports: `import { Controller } from '../../core/Controller'`, `import { Model } from '../core/Model'`,
`import { Library } from '../core/Model'`, PHP helpers from `'../../utils/php'`.

## Async rules (most important)
* **Every** model method, library method and helper function is `async` (even if it does not
  touch the DB) and **every call to them is awaited**. Controller endpoint methods are `async`.
* DB calls that execute SQL are async: `get`, `get_where`, `query`, `insert`, `update`,
  `delete`, `replace`, `insert_batch`, `update_batch`, `count_all_results`, `trans_start`,
  `trans_complete`, `trans_begin`, `trans_commit`, `trans_rollback`.
  Builder calls (`select/from/join/where/...`, `get_compiled_select`) are sync & chainable.
  `insert_id()`, `affected_rows()`, `trans_status()`, `last_query()`, `error()` are sync.
* `$this->db->get()->result()` → `(await this.db.get()).result()`.
  `$q = $this->db->query($sql); $q->row()` → `const q = await this.db.query(sql); q.row()`.
* Constructors stay synchronous. If a PHP constructor runs queries, move that part to
  `async _init()` (controllers only; the router awaits it).

## Helper / library calling conventions (fixed for all groups)
* Helper files `fcm_helper`, `cuti_notification_helper`, `izin_notification_helper`,
  `revisi_absen_notification_helper`: **every exported function takes the controller (`CI`)
  as first argument**, then the PHP arguments: `await send_fcm_notification(this, userId, title, body)`.
  (Inside a model: pass `this.CI`.)
* `ticket_helper`, `uuid_helper`, `db_helper`: exact PHP signature, no CI argument (still async).
* `authorization_helper`/`jwt_helper` → `import { AUTHORIZATION, JWT } from '../../core/jwt'`
  (`AUTHORIZATION.validateToken(t)` is **sync**, returns payload object or `false`, throws on bad
  signature — same as PHP).
* Libraries are loaded like CI: `this.load.library('ApprovalRuleService')` → `this.approvalruleservice`
  (property name = lower-cased class name, or alias). Methods keep their PHP names and are async.
  `this.load.library('upload', config)` / `this.upload.initialize(config)` / `await this.upload.do_upload('field')`
  / `this.upload.data()` / `this.upload.display_errors()` are provided by core.
* Models: `this.load.model('M_api')` → `this.M_api`; `this.load.model('m_checkin')` → `this.m_checkin`
  (property name exactly as given, file lookup is case-insensitive). Models can reach anything on the
  controller (`this.db`, `this.load`, other loaded models) like CI's `__get`.
* `$this->load->database('db_hrga', TRUE)` → `this.load.database('db_hrga', true)` (returns a new `DB`).

## Request / response
* `$this->get('x')`, `$this->post('x')`, `$this->put('x')`, `$this->delete('x')`, `$this->query('x')`
  → same names on `this`; return `null` when missing. URL segments arrive as method parameters (raw,
  not URL-decoded — keep `str_replace('%20', ' ', ...)` calls).
* `$this->input->post('x')` / `->get('x')` / `->server('HTTP_X')` / `->method()` / `->ip_address()`
  / `->raw_input_stream` / `->request_headers()` → `this.input.*` (same semantics).
* `$_FILES['f']` → `this.files['f']` (`{name,type,tmp_name,error,size}`); `$_SERVER['X']` → `this.server['X']`;
  `$_POST` → `this.input.post()`; `$_GET` → `this.input.get()`.
* `$this->response($data, $code)` → `return this.response(data, code)`. It **throws** a `Halt` (PHP exits).
  Code after it never runs, exactly like PHP. `$this->set_response()` → `this.set_response()` (continues).
* `echo $x;` → `this.echo(x)`; `exit;`/`die('x')` → `this.exit()` / `this.exit('x')`.
  `header('Content-Type: ...')` → `this.header('Content-Type: ...')`.
* **Every `catch (e)` must begin with `rethrowHalt(e);`** (`import { rethrowHalt } from '../../core/Halt'`)
  otherwise a `response()` inside the try would be swallowed.
* `log_message('error', $m)` → `log_message('error', m)` from `'../../core/logger'`.
* Constants (`JOBSITE`, `COMP_ID_NEW`, `UP_PPA`, `URL_STORAGE`, ...) → `import { ... } from '../../config/constants'`.
  Optional ones (`AIRPORT_CITY`, `LOCAL_CITIES`, `CAMERA_CHECKIN_ENABLED`, `TICKET_SOURCE_MODULE`) are
  `undefined` when not configured: `defined('X') ? X : d` → `X !== undefined ? X : d`.
  `$this->config->item('base_url', 'ho_api')` → `this.config.item('base_url', 'ho_api')`.
* Hard-coded storage paths (`/var/www/html/storage/...`) are fine for the upload library; for direct
  filesystem calls use `src/core/storage.ts` (`file_exists`, `is_dir`, `mkdir`, `unlink`,
  `move_uploaded_file`, `file_put_contents`) which maps them to `STORAGE_ROOT`.
* cURL / file_get_contents(url) → `curl()` / `file_get_contents_url()` from `src/core/http.ts`.

## PHP semantics you must preserve (use `src/utils/php.ts`)
* **DB values are strings** (or null) — exactly like mysqli. PHP arithmetic on them yields numbers:
  `$a + $b` → `num(a) + num(b)`; `$a * 2` → `num(a) * 2`; `$a / $b` → `div(a, b)` (throws on 0 like PHP 8);
  `$a % $b` → `mod(a, b)`. String concatenation `.` → template/`+` with `strval()` for floats/bools/null.
  `(int)` → `intval()`, `(float)` → `floatval()`, `(string)` → `strval()`, `round()` → `round()`.
* Values that PHP leaves as strings must stay strings in JSON (don't convert `"5"` to `5`), and values
  PHP computes as numbers must be numbers.
* Loose comparison `==`/`!=` → `eq()`/`neq()` unless both sides are certainly the same JS type.
  `===` → `===` (watch out: DB values are strings, so `$row->x === 1` is false in PHP too).
* Truthiness: `if ($x)` → `if (toBool(x))` when `x` may be `'0'` or `[]`. `empty($x)` → `empty(x)`
  (for PHP arrays that are JS objects use `emptyArr`). `isset($a['k'])` → `isset(a?.k)`.
* Reading a property/index of `null` is only a *warning* in PHP (result `null`) → use `?.` / `?? null`.
  Calling a method on null is fatal in PHP (500) → leave it un-guarded in TS too.
* Undefined array index → `null` in PHP. Missing keys must not silently disappear from JSON
  (`json_encode`/`response` turn `undefined` into `null`, so assigning `x.k = undefined` is fine).
* **PHP arrays are copied on assignment / when passed to functions**; JS arrays/objects are references.
  When PHP code copies an array and then mutates the copy, clone it (`[...a]`, `{...o}`,
  `structuredClone`). DB row objects (stdClass) are handles in PHP too — no clone needed.
* Auto-vivification `$a['x']['y'][] = 1` → create the intermediate objects/arrays explicitly.
* List vs map: PHP `array()` with keys 0..n-1 in order → JSON array; anything else → JSON object.
  `array_filter()` keeps keys (→ may become an object in JSON!) unless wrapped in `array_values()`.
  Use `array_filter_keep_keys`/`phpList` from utils when the original JSON shape depends on it.
  Beware JS objects order integer-like keys first; if PHP builds a map with numeric keys in a
  non-ascending order and encodes it, preserve order using a `Map` → object conversion only if it
  matters for the output (note it in a comment).
* `in_array` (loose!) → `in_array()`; `array_search` → `array_search()`; `count()`/`sizeof()` → `count()`.
* `substr`, `strpos` (returns `false`), `str_replace`, `explode`, `implode`, `str_pad`, `ucwords`,
  `number_format`, `sprintf`, `md5`, `json_encode`, `json_decode`, `date`, `strtotime`, `mktime`,
  `checkdate`, `cal_days_in_month`, `DateTime`, `DateInterval`, `date_create`, `date_diff`,
  `date_format`, `date_add`, `uniqid`, `serialize`, `openssl_encrypt/decrypt` → from `utils/php`.
  `date()`/`strtotime()`/`DateTime::diff` were differential-tested against PHP 8 — always use them,
  never `new Date()` arithmetic.
* `usort($a, fn)` mutates in place → `a.sort(fn)` (comparator must return a number).
* `array_merge` re-indexes lists and overrides string keys → `[...a, ...b]` for lists, `{...a, ...b}` for maps.

## Query Builder
`src/core/db/DB.ts` is a line-by-line port of CI3's query builder (verified to emit identical SQL),
so translate builder chains literally, keeping the same arguments (including `FALSE` escape flags →
`false`). `where_in` with an empty array throws (as in PHP 8 fork) — keep that behaviour.
On SQL errors (production) queries return `false` like CI with `db_debug = FALSE`; do not add guards
PHP didn't have.

## Hand-built SQL (security rule)
Never interpolate a value into an SQL string as is. Use `src/core/db/sqlsafe.ts`:
`'${sqlq(x)}'` inside quotes, `implode_t("','", sqlq_each(list))` for IN lists, `${sqln(x)}` for
unquoted numbers, `${sqlid(col)}` for a column name from a parameter. Subqueries from
`get_compiled_select()` and constants can be interpolated directly. Prefer the Query Builder
(`where('col', x)`) which escapes values itself.

## TypeScript
`strict` is off and controllers/models have an index signature, so `this.M_api` etc. are `any`.
Do not declare class fields for loaded models/libraries (field initialisers would overwrite them).
Your files must compile: `npx tsc --noEmit -p . 2>&1 | grep -E 'src/(your|files)'` must be empty.
