<?php
/**
 * JSON helper API for the coding view (coding.work).
 * Actions: cpt_search, icd_search, patient_lookup (GET) ; cpt_addon (POST + CSRF).
 */
require_once __DIR__ . '/../includes/config.php';
$user = require_login('internal');

header('Content-Type: application/json; charset=utf-8');

/* Keepalive: refresh the session (require_login already bumped last_activity) and hand back a
 * current CSRF token so a long-open coding chart never gets logged out mid-work. Allowed for any
 * signed-in internal user — runs before the coding-permission gate. */
if (($_GET['action'] ?? $_POST['action'] ?? '') === 'ping') {
    echo json_encode(['ok' => true, 'csrf' => csrf_token(), 'ts' => time()]);
    exit;
}

if (!can('coding.work') && !can('coding.audit')) { http_response_code(403); echo json_encode(['error' => 'forbidden']); exit; }

$pdo = db();
$action = $_GET['action'] ?? $_POST['action'] ?? '';

try {
    if ($action === 'cpt_search') {
        $fac = (int) ($_GET['facility_id'] ?? 0);
        $prov = (int) ($_GET['provider_id'] ?? 0);
        $q = strtoupper(trim((string) ($_GET['q'] ?? '')));
        echo json_encode(['items' => coding_cpt_validation_search($pdo, $fac, $prov, $q)]);
        exit;
    }

    if ($action === 'icd_search') {
        $q = strtoupper(trim((string) ($_GET['q'] ?? '')));
        if (strlen($q) < 2) { echo json_encode(['items' => []]); exit; }
        echo json_encode(['items' => coding_icd_search($pdo, $q)]);
        exit;
    }

    if ($action === 'patient_lookup') {
        $fac  = (int) ($_GET['facility_id'] ?? 0);
        $mrn  = trim((string) ($_GET['mrn'] ?? ''));
        $name = trim((string) ($_GET['name'] ?? ''));
        $exclude = (int) ($_GET['exclude_id'] ?? 0);
        $demo = coding_patient_demographics($pdo, $fac, $mrn ?: null, $name ?: null, $exclude);
        // Show the patient's FULL coded history (not just the last 5) — the "Past coded DOS" panel lists every
        // prior coded chart for this MRN at this facility. Capped high to bound payload size.
        $hist = coding_patient_history($pdo, $fac, $mrn ?: null, $name ?: null, $exclude, 200);
        echo json_encode(['found' => (bool) ($demo || $hist), 'demographics' => $demo, 'history' => $hist]);
        exit;
    }

    if ($action === 'cpt_addon' && $_SERVER['REQUEST_METHOD'] === 'POST') {
        if (!csrf_check()) { http_response_code(419); echo json_encode(['error' => 'csrf']); exit; }
        if (!can('coding.cpt.manage')) { http_response_code(403); echo json_encode(['error' => 'CPTs are managed by a supervisor/manager via Hierarchy.']); exit; }   // coders may not add CPTs
        $fac  = (int) ($_POST['facility_id'] ?? 0);
        $prov = (int) ($_POST['provider_id'] ?? 0);
        $code = strtoupper(trim((string) ($_POST['code'] ?? '')));
        $desc = trim((string) ($_POST['description'] ?? ''));
        if (!$fac || !$prov || !preg_match('/^[A-Z0-9]{3,7}$/', $code)) { http_response_code(422); echo json_encode(['error' => 'invalid']); exit; }
        if (coding_provider_is_scribe($pdo, $prov)) { http_response_code(422); echo json_encode(['error' => 'A scribe is global and cannot be linked to a facility.']); exit; }
        coding_cpt_add_on($pdo, $fac, $prov, $code, $desc, (int) $user['id']);
        audit_log('coding.cpt.addon', 'coding_cpt_validation', null, null, ['facility_id'=>$fac,'provider_id'=>$prov,'cpt'=>$code]);
        echo json_encode(['ok' => true, 'code' => $code, 'description' => $desc]);
        exit;
    }

    http_response_code(400);
    echo json_encode(['error' => 'unknown action']);
} catch (Throwable $e) {
    http_response_code(500);
    echo json_encode(['error' => APP_DEBUG ? $e->getMessage() : 'server error']);
}
