&1", escapeshellarg($PGHOST), escapeshellarg($PGUSER), escapeshellarg($PGDB), escapeshellarg($sql)); return trim(shell_exec($cmd)); } function json_q($sql) { $cmd = sprintf("psql -h %s -U admin -d adx_system -tAc %s 2>&1", escapeshellarg('10.1.0.3'), escapeshellarg("SELECT json_agg(row_to_json(t)) FROM (" . $sql . ") t")); $r = trim(shell_exec($cmd)); $j = json_decode($r, true); return $j ?: []; } if ($action === 'list') { $cat = $_GET['category'] ?? ''; $where = "active=TRUE"; if ($cat) $where .= " AND category = " . "'" . addslashes($cat) . "'"; $rows = json_q("SELECT decision_key, decision_value, context, category, usage_count, created_at, updated_at FROM admin.wevia_decisions WHERE $where ORDER BY updated_at DESC LIMIT 200"); echo json_encode(['ok'=>true, 'count'=>count($rows), 'decisions'=>$rows], JSON_PRETTY_PRINT|JSON_UNESCAPED_UNICODE); exit; } if ($action === 'recall' || $action === 'get') { $key = $_GET['key'] ?? ''; if (!$key) { http_response_code(400); echo json_encode(['error'=>'key required']); exit; } // Safe query with parametrized call $sql = "SELECT decision_key, decision_value, context, category, usage_count, created_at FROM admin.wevia_decisions WHERE decision_key = " . "'" . addslashes($key) . "' AND active=TRUE"; $rows = json_q($sql); if (!$rows) { // Fuzzy search $esc = addslashes($key); $rows = json_q("SELECT decision_key, decision_value, context, category FROM admin.wevia_decisions WHERE active=TRUE AND (decision_key ILIKE '%$esc%' OR decision_value ILIKE '%$esc%') LIMIT 5"); } else { // Increment usage q("UPDATE admin.wevia_decisions SET usage_count = usage_count + 1, last_used_at = NOW() WHERE decision_key = '" . addslashes($key) . "'"); } echo json_encode(['ok'=>true, 'matches'=>$rows], JSON_PRETTY_PRINT|JSON_UNESCAPED_UNICODE); exit; } if ($action === 'categories') { $rows = json_q("SELECT category, COUNT(*) as count FROM admin.wevia_decisions WHERE active=TRUE GROUP BY category ORDER BY count DESC"); echo json_encode(['ok'=>true, 'categories'=>$rows]); exit; } if ($action === 'summary') { $total = q("SELECT COUNT(*) FROM admin.wevia_decisions WHERE active=TRUE"); $cats = json_q("SELECT category, COUNT(*) as count FROM admin.wevia_decisions WHERE active=TRUE GROUP BY category"); echo json_encode(['ok'=>true, 'total'=>(int)$total, 'by_category'=>$cats]); exit; } echo json_encode(['error'=>'unknown action', 'actions'=>['list','recall','get','categories','summary']]);