<?php

/*
 * File     : egwapi_test.php
 * Purpose  : EGW API Test Script
 * Requires : egwapi_class.php, egw_ledger.php in same directory
 */

// https://emberpay.net/sysfiles/egwapi/egwapi_test.php

session_start();

require("../inc.php");
require($sysfiles."/debug.php");
debug_max_errors(2);

require __DIR__ . '/egwapi_class.php';
require __DIR__ . '/egw_ledger.php';

// ---------------------------------------------------------------------------
// Endpoint definitions
// ---------------------------------------------------------------------------

const ENDPOINTS = [
	'local'   => 'https://emberpay.net/sysfiles/egwapi/egwapi_server.php',
	'sandbox' => 'https://sandbox.playegamesnow.com',
	'live'    => 'https://egwapi.playegamesnow.com',
];

const DEFAULT_OPERATOR_ID = '73b83a81-0293-45ae-99ba-bdd7f3555aa4';

// Path to egwapi.log — fill in before deploying.
define('EGW_LOG_PATH', $rootpath.'/applogs/egwapi.log');

$groupId = 1;
$phoneNumber = "+15168485044";	// 33
//$phoneNumber = "+15163562155";	// 34
$default_partner_id = 'STG-AF1-2';

$game_distributor_id = "73b83a81-0293-45ae-99ba-bdd7f3555aa4";

// ---------------------------------------------------------------------------
// Persist endpoint selection in session
// ---------------------------------------------------------------------------

if ( isset($_POST['endpoint']) && array_key_exists($_POST['endpoint'], ENDPOINTS) ) {
	$_SESSION['egw_endpoint'] = $_POST['endpoint'];
}
$active_endpoint_key = $_SESSION['egw_endpoint'] ?? 'sandbox';
$active_endpoint_url = ENDPOINTS[$active_endpoint_key];

// ---------------------------------------------------------------------------
// Handle POST
// ---------------------------------------------------------------------------

$result        = null;
$request       = null;
$error         = null;
$fn_called     = null;
$meta          = [];

// ---------------------------------------------------------------------------
// Helpers
// ---------------------------------------------------------------------------

function field( string $name, string $label, string $value ) : string {
	$id  = htmlspecialchars( $name );
	$val = htmlspecialchars( $value );
	$lbl = htmlspecialchars( $label );
	return "<div class='field'><label for='{$id}'>{$lbl}</label><input type='text' id='{$id}' name='{$id}' value='{$val}'></div>";
}

function json_pretty( $data ) : string {
	if ( $data === null || $data === false ) return 'null';
	if ( is_string($data) ) {
		$decoded = json_decode( $data, true );
		$data    = ( $decoded !== null ) ? $decoded : $data;
	}
	return json_encode( $data, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES );
}

?><!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>EGW API Test Script</title>
<style>

	:root {
		--bg:        #f5f6f8;
		--bg2:       #ffffff;
		--bg3:       #eef0f3;
		--border:    #d0d4dd;
		--accent:    #ff6b00;
		--accent2:   #e05a00;
		--text:      #1a1c22;
		--text-dim:  #6b7280;
		--text-head: #0d0f14;
		--ok:        #16a34a;
		--err:       #dc2626;
		--radius:    8px;
		--mono:      'JetBrains Mono', 'Fira Code', 'Cascadia Code', monospace;
		--sans:      'DM Sans', 'Segoe UI', system-ui, sans-serif;
	}

	* { box-sizing: border-box; margin: 0; padding: 0; }

	body {
		background: var(--bg);
		color: var(--text);
		font-family: var(--sans);
		font-size: 14px;
		line-height: 1.6;
		min-height: 100vh;
	}

	/* ── Header ── */
	.page-header {
		background: var(--bg2);
		border-bottom: 1px solid var(--border);
		padding: 20px 32px;
	}
	.page-header h1 {
		font-size: 18px;
		font-weight: 600;
		color: var(--text-head);
		letter-spacing: .02em;
	}

	/* ── Config bar ── */
	.config-bar {
		background: var(--bg2);
		border-bottom: 1px solid var(--border);
		padding: 12px 32px;
		display: flex;
		align-items: center;
		gap: 24px;
		flex-wrap: wrap;
	}
	.config-label {
		font-size: 11px;
		text-transform: uppercase;
		letter-spacing: .07em;
		color: var(--text-dim);
		white-space: nowrap;
	}
	.config-bar input[type=text] {
		flex: 1;
		min-width: 200px;
		max-width: 420px;
		background: var(--bg3);
		border: 1px solid var(--border);
		border-radius: var(--radius);
		color: var(--text);
		font-family: var(--mono);
		font-size: 12px;
		padding: 7px 12px;
		outline: none;
	}
	.config-bar input[type=text]:focus { border-color: var(--accent); }

	/* ── Endpoint switcher ── */
	.ep-switcher { display: flex; gap: 6px; align-items: center; }
	.ep-btn {
		background: var(--bg3);
		border: 1px solid var(--border);
		border-radius: var(--radius);
		color: var(--text-dim);
		font-family: var(--sans);
		font-size: 12px;
		font-weight: 600;
		padding: 6px 14px;
		cursor: pointer;
		transition: all .15s;
	}
	.ep-btn:hover { border-color: var(--accent); color: var(--text); }
	.ep-btn.active-local-server   { background: #dbeafe; border-color: #3b82f6; color: #1d4ed8; }
	.ep-btn.active-remote-sandbox { background: #dcfce7; border-color: #22c55e; color: #15803d; }
	.ep-btn.active-remote-live    { background: #fee2e2; border-color: #ef4444; color: #b91c1c; }
	.ep-url { font-family: var(--mono); font-size: 11px; color: var(--text-dim); }

	/* ── Layout ── */
	.page-body { padding: 32px; max-width: 1400px; }

	/* ── Function table ── */
	.fn-table {
		width: 100%;
		border-collapse: collapse;
		margin-bottom: 40px;
	}
	.fn-table th {
		background: var(--bg3);
		border: 1px solid var(--border);
		color: var(--text-dim);
		font-size: 11px;
		font-weight: 600;
		letter-spacing: .07em;
		padding: 10px 14px;
		text-align: left;
		text-transform: uppercase;
	}
	.fn-table td {
		background: var(--bg2);
		border: 1px solid var(--border);
		padding: 10px 14px;
		vertical-align: top;
	}
	.fn-table tr:hover td { background: var(--bg3); }

	.method-badge {
		font-size: 10px;
		font-weight: 700;
		letter-spacing: .06em;
		padding: 2px 7px;
		border-radius: 4px;
		text-transform: uppercase;
		white-space: nowrap;
	}
	.method-post { background: #dcfce7; color: #15803d; }
	.method-get  { background: #dbeafe; color: #1d4ed8; }
	.method-patch { background: #fef9c3; color: #854d0e; }
	.method-flow { background: #f3e8ff; color: #7e22ce; }
	.method-flow-err { background: #fee2e2; color: #b91c1c; }

	.fn-table td, .fn-table th { vertical-align: top; }
	.fn-table td:first-child { }
	.fn-table td:first-child .method-badge { display: block; margin-top: 6px; }
	.fn-name { font-family: var(--mono); font-size: 13px; font-weight: 600; color: var(--text-head); white-space: nowrap; }
	.fn-endpoint { font-family: var(--mono); font-size: 11px; color: var(--text-dim); }

	/* ── Inline fields in table ── */
	.fields-inline { display: flex; flex-wrap: wrap; gap: 8px; align-items: flex-end; }
	.field-inline label {
		display: block;
		font-size: 10px;
		text-transform: uppercase;
		letter-spacing: .06em;
		color: var(--text-dim);
		margin-bottom: 3px;
	}
	.field-inline input {
		background: var(--bg3);
		border: 1px solid var(--border);
		border-radius: var(--radius);
		color: var(--text);
		font-family: var(--mono);
		font-size: 12px;
		padding: 6px 10px;
		outline: none;
		width: 150px;
		transition: border-color .15s;
	}
	.field-inline input.short { width: 75px; }
	.field-inline input.medium { width: 110px; }
	.field-inline input.large { width: 280px; }
	.field-inline input:focus { border-color: var(--accent); }

	.field-inline select {
		background: var(--bg3);
		border: 1px solid var(--border);
		border-radius: var(--radius);
		color: var(--text);
		font-family: var(--mono);
		font-size: 12px;
		padding: 6px 10px;
		outline: none;
		width: 175px;
		transition: border-color .15s;
		appearance: none;
		-webkit-appearance: none;
		background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='10' height='6' viewBox='0 0 10 6'%3E%3Cpath d='M0 0l5 6 5-6z' fill='%236b7280'/%3E%3C/svg%3E");
		background-repeat: no-repeat;
		background-position: right 10px center;
		padding-right: 28px;
	}
	.field-inline select.short { width: 75px; }
	.field-inline select.medium { width: 106px; }
	.field-inline select.large { width: 280px; }
	.field-inline select:focus { border-color: var(--accent); }
	
	/* ── Run button ── */
	.btn-run {
		background: var(--accent);
		color: #fff;
		border: none;
		border-radius: var(--radius);
		font-family: var(--mono);
		font-size: 13px;
		font-weight: 600;
		padding: 6px 10px;
		cursor: pointer;
		white-space: nowrap;
		transition: background .15s;
		width: 100%;
		text-align: left;
	}
	.btn-run:hover { background: var(--accent2); }
	.btn-run.danger { background: #dc2626; }
	.btn-run.danger:hover { background: #b91c1c; }

	/* ── Section label ── */
	.section-label {
		font-size: 11px;
		font-weight: 700;
		letter-spacing: .1em;
		text-transform: uppercase;
		color: var(--text-dim);
		padding: 18px 0 8px;
	}

	/* ── Output panel ── */
	.output-panel {
		background: var(--bg2);
		border: 1px solid var(--border);
		border-radius: var(--radius);
		padding: 24px;
		margin-top: 8px;
	}
	.output-title {
		font-size: 13px;
		font-weight: 700;
		color: var(--text-head);
		margin-bottom: 16px;
		display: flex;
		align-items: center;
		gap: 12px;
	}
	.status-badge {
		font-size: 11px;
		font-weight: 700;
		letter-spacing: .08em;
		text-transform: uppercase;
		padding: 3px 10px;
		border-radius: 4px;
	}
	.status-ok  { background: #dcfce7; color: var(--ok); }
	.status-err { background: #fee2e2; color: var(--err); }

	.output-cols { display: grid; grid-template-columns: 1fr 1fr; gap: 16px; margin-bottom: 16px; }
	.output-col-label {
		font-size: 11px;
		text-transform: uppercase;
		letter-spacing: .07em;
		color: var(--text-dim);
		margin-bottom: 6px;
	}
	.json-box {
		background: var(--bg);
		border: 1px solid var(--border);
		border-radius: var(--radius);
		color: #166534;
		font-family: var(--mono);
		font-size: 12px;
		line-height: 1.7;
		padding: 14px 16px;
		overflow-x: auto;
		white-space: pre;
		margin: 0;
	}
	.json-box.dim { color: var(--text-dim); }
	.json-box.webhook { color: #1d4ed8; }

	.error-msg {
		background: #fee2e2;
		border: 1px solid #fca5a5;
		border-radius: var(--radius);
		color: #b91c1c;
		font-family: var(--mono);
		font-size: 12px;
		padding: 10px 14px;
		margin-bottom: 14px;
	}

	.section-divider {
		border: none;
		border-top: 1px solid var(--border);
		margin: 16px 0;
	}

	.webhook-section-title {
		font-size: 11px;
		font-weight: 700;
		letter-spacing: .08em;
		text-transform: uppercase;
		color: #1d4ed8;
		margin-bottom: 12px;
	}

	.msg-list { display: flex; flex-direction: column; gap: 6px; }
	.msg-row  { display: flex; align-items: baseline; gap: 10px; font-size: 13px; }
	.msg-role { font-size: 10px; font-weight: 700; letter-spacing: .06em; padding: 2px 7px; border-radius: 4px; text-transform: uppercase; flex-shrink: 0; }
	.msg-role.player      { background: #dbeafe; color: #1d4ed8; }
	.msg-role.distributor { background: #dcfce7; color: #15803d; }
	.msg-to   { font-family: var(--mono); font-size: 12px; color: var(--text-dim); flex-shrink: 0; }
	.msg-text { color: var(--text); }

	details.meta { margin-top: 12px; }
	details.meta summary { font-size: 12px; color: var(--text-dim); cursor: pointer; user-select: none; margin-bottom: 8px; }
	details.meta summary:hover { color: var(--text); }

	/* ── Two-column page layout ── */
	.page-columns {
		display: grid;
		grid-template-columns: 1fr 50%;
		gap: 0;
		align-items: start;
	}
	.col-controls { padding: 32px; min-width: 0; }
	.col-log { padding: 32px 32px 32px 0; position: sticky; top: 0; }
	.log-panel {
		background: var(--bg2);
		border: 1px solid var(--border);
		border-radius: var(--radius);
	}
	.log-panel-header {
		display: flex;
		align-items: center;
		justify-content: space-between;
		padding: 10px 14px;
		border-bottom: 1px solid var(--border);
	}
	.log-panel-title {
		font-size: 11px;
		font-weight: 700;
		letter-spacing: .08em;
		text-transform: uppercase;
		color: var(--text-dim);
	}
	.btn-refresh {
		background: var(--bg3);
		border: 1px solid var(--border);
		border-radius: var(--radius);
		color: var(--text-dim);
		font-family: var(--sans);
		font-size: 11px;
		font-weight: 600;
		padding: 4px 12px;
		cursor: pointer;
		transition: all .15s;
	}
	.btn-refresh:hover { border-color: var(--accent); color: var(--text); }
	#log-box {
		background: var(--bg);
		color: #166534;
		font-family: var(--mono);
		font-size: 11px;
		line-height: 1.6;
		padding: 12px 14px;
		margin: 0;
		width: 100%;
		height: 600px;
		overflow-y: auto;
		white-space: pre-wrap;
		word-break: break-all;
		border: none;
		border-radius: 0 0 var(--radius) var(--radius);
		resize: vertical;
	}

	@media (max-width: 900px) {
		.output-cols { grid-template-columns: 1fr; }
		.page-columns { grid-template-columns: 1fr; }
		.col-log { padding: 0 16px 32px; }
		.col-controls { padding: 16px; }
		.config-bar { padding: 16px; }
		.fields-inline { flex-direction: column; }
		.field-inline input, .field-inline input.short, .field-inline input.medium, .field-inline input.large { width: 100%; }
	}

</style>
</head>
<body>

<div class="page-header">
	<h1>EGW API Test Script</h1>
</div>

<form method="POST">

<div class="config-bar">
	<span class="config-label">Endpoint</span>
	<div class="ep-switcher">
		<?php foreach ( ENDPOINTS as $key => $url ) :
			$active_map = [ 'local' => 'active-local-server', 'sandbox' => 'active-remote-sandbox', 'live' => 'active-remote-live' ];
			$cls   = ( $key === $active_endpoint_key ) ? ( $active_map[$key] ?? '' ) : '';
			$label = [ 'local' => 'Local Server', 'sandbox' => 'Remote Sandbox', 'live' => 'Remote Live' ][$key] ?? ucfirst($key);
		?>
		<button type="submit" name="endpoint" value="<?= $key ?>" class="ep-btn <?= $cls ?>">
			<?= $label ?>
		</button>
		<?php endforeach; ?>
	</div>
	<span class="ep-url">FIXED <?= htmlspecialchars($active_endpoint_url) ?></span>
</div>

</form>

<div class="page-columns">
<div class="col-controls">

<?php

// ---------------------------------------------------------------------------
// Inline field helper for table rows
// ---------------------------------------------------------------------------
function ifield( string $name, string $label, string $value, string $size = '' ) : string {
	$id    = htmlspecialchars($name);
	$val   = htmlspecialchars($value);
	$lbl   = htmlspecialchars($label);
	$class = $size ? " class='{$size}'" : '';
	
	return "<div class='field-inline'><label for='{$id}'>{$lbl}</label><input type='text' id='{$id}' name='{$id}' value='{$val}'{$class}></div>";
}

function sfield( string $name, string $label, string $value, string $size = '' ) : string {
	$id    = htmlspecialchars($name);
	$val   = htmlspecialchars($value);
	$lbl   = htmlspecialchars($label);
	$class = $size ? " class='{$size}'" : '';
	
	$games_list = getOperatorGamesIdList( DEFAULT_OPERATOR_ID );
	
	$s = "<div class='field-inline'>
		<label for='{$id}'>{$lbl}</label>
		<select id='{$id}' name='{$id}'{$class}>
			<option value=''>Select</option>
		";
	
	foreach( $games_list as $game ) {
		$s .= "<option value='{$game['operator_game_id']}'>({$game['operator_game_id']}) {$game['display_name']}</option>";
	}
	
	$s .= "</select>
		</div>
		";
	
	return $s;
}

?>

	<!-- ================================================================ -->
	<!-- EGW API CALLS                                                     -->
	<!-- ================================================================ -->
	<div class="section-label">EGW API Calls</div>
	<table class="fn-table">
		<thead>
			<tr>
				<th style="width:140px">Function</th>
				<th>Parameters</th>
			</tr>
		</thead>
		<tbody>

			<!-- Purchase -->
			<tr>
				<td><form method="POST">
					<button type="submit" name="fn" value="purchase" class="btn-run">purchase()</button>
					<div class="fn-endpoint">/operator/g/purchase/</div>
					<span class="method-badge method-post">POST</span>
				</td>
				<td>
					<div class="fields-inline">
						<?= ifield('purchase_operator_id',         'operator_id',         $_POST['purchase_operator_id']         ?? DEFAULT_OPERATOR_ID, 'large') ?>
						<?= sfield('purchase_operator_game_id',    'operator_game_id',    $_POST['purchase_operator_game_id']    ?? '42', 'medium') ?>
						<?= ifield('purchase_operator_wallet_id',  'operator_wallet_id',  $_POST['purchase_operator_wallet_id']  ?? '900100000000') ?>
						<?= ifield('purchase_player_game_user_id', 'player_game_user_id', $_POST['purchase_player_game_user_id'] ?? '456', 'medium') ?>
						<?= ifield('purchase_player_wallet_id',    'player_wallet_id',    $_POST['purchase_player_wallet_id']    ?? '123', 'medium') ?>
						<?= ifield('purchase_payment_provider_id', 'payment_provider_id', $_POST['purchase_payment_provider_id'] ?? 'paypal', 'medium') ?>
						<?= ifield('purchase_amount',              'amount',              $_POST['purchase_amount']              ?? '10.00', 'short') ?>
					</div>
				</form></td>
			</tr>

			<!-- Redeem -->
			<tr>
				<td><form method="POST">
					<button type="submit" name="fn" value="redeem" class="btn-run">redeem()</button>
					<div class="fn-endpoint">/operator/g/redeem/</div>
					<span class="method-badge method-post">POST</span>
				</td>
				<td>
					<div class="fields-inline">
						<?= ifield('redeem_operator_id',         'operator_id',         $_POST['redeem_operator_id']         ?? DEFAULT_OPERATOR_ID, 'large') ?>
						<?= sfield('redeem_operator_game_id',    'operator_game_id',    $_POST['redeem_operator_game_id']    ?? '42', 'medium') ?>
						<?= ifield('redeem_operator_wallet_id',  'operator_wallet_id',  $_POST['redeem_operator_wallet_id']  ?? '900100000000') ?>
						<?= ifield('redeem_player_game_user_id', 'player_game_user_id', $_POST['redeem_player_game_user_id'] ?? '456', 'medium') ?>
						<?= ifield('redeem_player_wallet_id',    'player_wallet_id',    $_POST['redeem_player_wallet_id']    ?? '123', 'medium') ?>
						<?= ifield('redeem_payment_provider_id', 'payment_provider_id', $_POST['redeem_payment_provider_id'] ?? 'paypal', 'medium') ?>
						<?= ifield('redeem_amount',              'amount',              $_POST['redeem_amount']              ?? '5.00', 'short') ?>
					</div>
				</form></td>
			</tr>

			<!-- Get Active Games -->
			<tr>
				<td><form method="POST">
					<button type="submit" name="fn" value="get_active_games" class="btn-run">getActiveGames()</button>
					<div class="fn-endpoint">/operator/{id}/games/</div>
					<span class="method-badge method-get">GET</span>
				</td>
				<td>
					<div class="fields-inline">
						<?= ifield('games_operator_id', 'operator_id', $_POST['games_operator_id'] ?? DEFAULT_OPERATOR_ID, 'large') ?>
					</div>
				</form></td>
			</tr>

			<!-- Get Available Games (processor-level) -->
			<tr>
				<td><form method="POST">
					<button type="submit" name="fn" value="get_available_games" class="btn-run">getAvailableGames()</button>
					<div class="fn-endpoint">/operator/games/</div>
					<span class="method-badge method-get">GET</span>
				</td>
				<td>
					<div class="fields-inline">
						<span class="field-note">No parameters</span>
					</div>
				</form></td>
			</tr>

			<!-- Create Operator Game -->
			<tr>
				<td><form method="POST">
					<button type="submit" name="fn" value="create_operator_game" class="btn-run">createOperatorGame()</button>
					<div class="fn-endpoint">/operator/{id}/games/</div>
					<span class="method-badge method-post">POST</span>
				</td>
				<td>
					<div class="fields-inline">
						<?= ifield('cog_operator_id',    'operator_id',   $_POST['cog_operator_id']   ?? DEFAULT_OPERATOR_ID, 'large') ?>
						<?= ifield('cog_game_id',        'game_id',       $_POST['cog_game_id']       ?? 'c55d8e02-e7db-41dc-a9d1-c9637d66c8b7', 'large') ?>
						<?= ifield('cog_display_name',   'display_name',  $_POST['cog_display_name']   ?? 'Golden Dragon') ?>
						<?= ifield('cog_pos_username',   'pos_username',  $_POST['cog_pos_username']   ?? 'cashier', 'medium') ?>
						<?= ifield('cog_pos_password',   'pos_password',  $_POST['cog_pos_password']   ?? 'secret', 'medium') ?>
						<?= ifield('cog_publish_site',   'publish_site',  $_POST['cog_publish_site']   ?? 'true', 'short') ?>
						<?= ifield('cog_drawer',         'drawer',        $_POST['cog_drawer']         ?? '1', 'short') ?>
						<?= ifield('cog_kiosk_number',   'kiosk_number',  $_POST['cog_kiosk_number']   ?? 'K-01', 'short') ?>
						<?= ifield('cog_station_number', 'station_number',$_POST['cog_station_number'] ?? '1', 'short') ?>
						<?= ifield('cog_order',          'order',         $_POST['cog_order']          ?? '10', 'short') ?>
						<?= ifield('cog_pos_category',   'pos_category',  $_POST['cog_pos_category']   ?? 'casino', 'medium') ?>
					</div>
				</form></td>
			</tr>

			<!-- Update Operator Game -->
			<tr>
				<td><form method="POST">
					<button type="submit" name="fn" value="update_operator_game" class="btn-run">updateOperatorGame()</button>
					<div class="fn-endpoint">/operator/{id}/games/{id}/</div>
					<span class="method-badge method-patch">PATCH</span>
				</td>
				<td>
					<div class="fields-inline">
						<?= ifield('uog_operator_id',      'operator_id',      $_POST['uog_operator_id']      ?? DEFAULT_OPERATOR_ID, 'large') ?>
						<?= sfield('uog_operator_game_id', 'operator_game_id', $_POST['uog_operator_game_id'] ?? '42', 'medium') ?>
						<?= ifield('uog_game_id',          'game_id',          $_POST['uog_game_id']          ?? '6afeb970-2b45-4f00-ab6a-8f0938a067a2') ?>
						<?= ifield('uog_display_name',     'display_name',     $_POST['uog_display_name']     ?? 'Golden Dragon Updated') ?>
						<?= ifield('uog_publish_site',     'publish_site',     $_POST['uog_publish_site']     ?? 'true', 'short') ?>
					</div>
				</form></td>
			</tr>

			<!-- Create Player (not used) -->
			<tr>
				<td><form method="POST">
					<button type="submit" name="fn" value="create_player" class="btn-run" title="Not used — will die()">createPlayer()</button>
					<div class="fn-endpoint">/operator/g/create/</div>
					<span class="method-badge method-post">POST</span>
				</td>
				<td>
					<div class="fields-inline">
						<?= ifield('create_player_operator_id',			'operator_id',			$_POST['create_player_operator_id']			?? DEFAULT_OPERATOR_ID, 'large') ?>
						<?= ifield('create_player_payment_provider_id',	'payment_provider_id',	$_POST['create_player_payment_provider_id']	?? 'Leonardo', 'medium') ?>
						<?= ifield('create_player_operator_wallet_id',	'operator_wallet_id',	$_POST['create_player_operator_wallet_id']	?? '1231', 'medium') ?>
						<?= ifield('create_player_player_wallet_id',	'player_wallet_id',		$_POST['create_player_player_wallet_id']    ?? '123', 'medium') ?>
						
						<?= ifield('create_player_amount',				'amount',				$_POST['create_player_amount']				?? '25.00', 'short') ?>
						<?= ifield('create_player_game_id',				'game_id',           $_POST['create_player_game_id']      ?? '42', 'short') ?>
						<?= ifield('create_player_first_name',     'first_name',        $_POST['create_player_first_name']   ?? 'John', 'medium') ?>
						<?= ifield('create_player_last_name',      'last_name',         $_POST['create_player_last_name']    ?? 'Doe', 'medium') ?>
						<?= ifield('create_player_email',          'email',             $_POST['create_player_email']        ?? 'john@example.com') ?>
						<?= ifield('create_player_dob',            'date_of_birth',     $_POST['create_player_dob']          ?? '1975-01-18', 'medium') ?>
						
{
"operator_id": "0f6d7d8a-7e9a-4d95-9f73-5f7d9b8327a1",
"payment_provider_id": "Leonardo ",
"operator_wallet_id": "1231",
"player_wallet_id": "123",

"amount": "25.00",
"operator_game_id": 2,
"customer": {
	"first_name": "John",
	"last_name": "Doe",
	"email": "john@example.com",
	"date_of_birth": "1975-01-18"
	}
}
						
					</div>
				</form></td>
			</tr>

			<!-- Create Operator -->
			<tr>
				<td><form method="POST">
					<button type="submit" name="fn" value="create_operator" class="btn-run">createOperator()</button>
					<div class="fn-endpoint">/operator/create/</div>
					<span class="method-badge method-post">POST</span>
				</td>
				<td>
					<div class="fields-inline">
						<?= ifield('create_op_username',    'username',       $_POST['create_op_username']    ?? 'operator_demo_02') ?>
						<?= ifield('create_op_email',       'email',          $_POST['create_op_email']       ?? 'operator_demo_02@example.com') ?>
						<?= ifield('create_op_biz_name',    'business_name',  $_POST['create_op_biz_name']    ?? 'Fortune Hall') ?>
						<?= ifield('create_op_first_name',  'first_name',     $_POST['create_op_first_name']  ?? 'John', 'medium') ?>
						<?= ifield('create_op_last_name',   'last_name',      $_POST['create_op_last_name']   ?? 'Doe', 'medium') ?>
						<?= ifield('create_op_address',     'address',        $_POST['create_op_address']     ?? '221B Baker Street, London') ?>
						<?= ifield('create_op_phone',       'contact_phone',  $_POST['create_op_phone']       ?? '+380501112233', 'medium') ?>
						<?= ifield('create_op_site_url',    'site_url',       $_POST['create_op_site_url']    ?? 'https://operator.example.com') ?>
					</div>
				</form></td>
			</tr>

			<!-- Test Webhook Receiver -->
			<tr>
				<td><form method="POST">
					<button type="submit" name="fn" value="test_webhook" class="btn-run">Test Webhook</button>
					<div class="fn-endpoint">→ webhook_receiver</div>
					<span class="method-badge method-post">POST</span>
				</td>
				<td>
					<div class="fields-inline">
						<?= ifield('sim_session_id',          'session_id',          $_POST['sim_session_id']          ?? '', 'medium') ?>
						<?= ifield('sim_action',              'action',              $_POST['sim_action']              ?? 'purchase', 'medium') ?>
						<?= ifield('sim_status',              'status',              $_POST['sim_status']              ?? 'success', 'medium') ?>
						<?= ifield('sim_player_game_user_id', 'player_game_user_id', $_POST['sim_player_game_user_id'] ?? '', 'medium') ?>
						<?= ifield('sim_error_message',       'error_message',       $_POST['sim_error_message']       ?? '', 'medium') ?>
						<?= ifield('sim_webhook_token',       'webhook_token',       $_POST['sim_webhook_token']       ?? '', 'medium') ?>
					</div>
				</form></td>
			</tr>

			<!-- Disable All Operator Games -->
			<tr>
				<td><form method="POST">
					<button type="submit" name="fn" value="disable_all_games" class="btn-run">disableAllGames()</button>
					<div class="fn-endpoint">/operator/{id}/games/disable-all/</div>
					<span class="method-badge method-post">POST</span>
				</td>
				<td>
					<div class="fields-inline">
						<?= ifield('dag_operator_id', 'operator_id', $_POST['dag_operator_id'] ?? DEFAULT_OPERATOR_ID, 'large') ?>
					</div>
				</form></td>
			</tr>

			<!-- Enable All Operator Games -->
			<tr>
				<td><form method="POST">
					<button type="submit" name="fn" value="enable_all_games" class="btn-run">enableAllGames()</button>
					<div class="fn-endpoint">/operator/{id}/games/enable-all/</div>
					<span class="method-badge method-post">POST</span>
				</td>
				<td>
					<div class="fields-inline">
						<?= ifield('eag_operator_id', 'operator_id', $_POST['eag_operator_id'] ?? DEFAULT_OPERATOR_ID, 'large') ?>
					</div>
				</form></td>
			</tr>



		</tbody>
	</table>

	<!-- ================================================================ -->
	<!-- LEDGER FLOW FUNCTIONS                                             -->
	<!-- ================================================================ -->
	<div class="section-label">Ledger Flow Functions</div>
	<table class="fn-table">
		<thead>
			<tr>
				<th style="width:140px">Function</th>
				<th>Parameters</th>
				
			</tr>
		</thead>
		<tbody>

			<!-- rfpSuccess -->
			<tr>
				<td><form method="POST">
					<button type="submit" name="fn" value="rfpSuccess" class="btn-run">rfpSuccess()</button>
					<div class="fn-endpoint">Deposit Success</div>
				</td>
				<td>
					<div class="fields-inline">
						<?= ifield('ledger_game_distributor_id',  'game_distributor_id',     $_POST['ledger_game_distributor_id'] ?? DEFAULT_OPERATOR_ID) ?>
						<?= ifield('ledger_game_id',              'game_id',                 $_POST['ledger_game_id']             ?? '1111', 'short') ?>
						<?= ifield('ledger_game_name',            'game_name',               $_POST['ledger_game_name']           ?? 'Golden Dragon') ?>
					</div>
				</form></td>
			</tr>

			<!-- rfpFailure -->
			<tr>
				<td><form method="POST">
					<button type="submit" name="fn" value="rfpFailure" class="btn-run">rfpFailure()</button>
					<div class="fn-endpoint">Deposit Failure</div>
				</td>
				<td>
					<div class="fields-inline">
						<?= ifield('ledger_game_distributor_id',  'game_distributor_id',     $_POST['ledger_game_distributor_id'] ?? DEFAULT_OPERATOR_ID) ?>
						<?= ifield('ledger_game_id',              'game_id',                 $_POST['ledger_game_id']             ?? '1111', 'short') ?>
						<?= ifield('ledger_game_name',            'game_name',               $_POST['ledger_game_name']           ?? 'Golden Dragon') ?>
					</div>
				</form></td>
			</tr>
			
			<!-- rtpSuccess -->
			<tr>
				<td><form method="POST">
					<button type="submit" name="fn" value="rtpSuccess" class="btn-run">rtpSuccess()</button>
					<div class="fn-endpoint">Redemption Success</div>
				</td>
				<td>
					<div class="fields-inline">
						<?= ifield('ledger_game_distributor_id',  'game_distributor_id',     $_POST['ledger_game_distributor_id'] ?? DEFAULT_OPERATOR_ID) ?>
						<?= ifield('ledger_game_id',              'game_id',                 $_POST['ledger_game_id']             ?? '1111', 'short') ?>
						<?= ifield('ledger_game_name',            'game_name',               $_POST['ledger_game_name']           ?? 'Golden Dragon') ?>
					</div>
				</form></td>
			</tr>

			<!-- rtpFailure -->
			<tr>
				<td><form method="POST">
					<button type="submit" name="fn" value="rtpFailure" class="btn-run">rtpFailure()</button>
					<div class="fn-endpoint">Redemption Failure</div>
				</td>
				<td>
					<div class="fields-inline">
						<?= ifield('ledger_game_distributor_id',  'game_distributor_id',     $_POST['ledger_game_distributor_id'] ?? DEFAULT_OPERATOR_ID) ?>
						<?= ifield('ledger_game_id',              'game_id',                 $_POST['ledger_game_id']             ?? '1111', 'short') ?>
						<?= ifield('ledger_game_name',            'game_name',               $_POST['ledger_game_name']           ?? 'Golden Dragon') ?>
					</div>
				</form></td>
			</tr>
			
			<!-- egwPurchaseSuccess -->
			<tr>
				<td><form method="POST">
					<button type="submit" name="fn" value="egwPurchaseSuccess" class="btn-run">egwPurchaseSuccess()</button>
					<div class="fn-endpoint">egw purchase success</div>
				</td>
				<td>
					<div class="fields-inline">
						<?= ifield('ledger_partner_id', 'partner_id', $_POST['ledger_partner_id'] ?? $default_partner_id) ?>
					</div>
				</form></td>
			</tr>

			<!-- egwPurchaseFailure -->
			<tr>
				<td><form method="POST">
					<button type="submit" name="fn" value="egwPurchaseFailure" class="btn-run">egwPurchaseFailure()</button>
					<div class="fn-endpoint">egw purchase failed</div>
				</td>
				<td>
					<div class="fields-inline">
						<?= ifield('ledger_partner_id', 'partner_id', $_POST['ledger_partner_id'] ?? $default_partner_id) ?>
					</div>
				</form></td>
			</tr>

			<!-- egwRedeemSuccess -->
			<tr>
				<td><form method="POST">
					<button type="submit" name="fn" value="egwRedeemSuccess" class="btn-run">egwRedeemSuccess()</button>
					<div class="fn-endpoint">Deposit denied</div>
				</td>
				<td>
					<div class="fields-inline">
						<?= ifield('ledger_partner_id', 'partner_id', $_POST['ledger_partner_id'] ?? $default_partner_id) ?>
					</div>
				</form></td>
			</tr>

			<!-- egwRedeemFailure -->
			<tr>
				<td><form method="POST">
					<button type="submit" name="fn" value="egwRedeemFailure" class="btn-run">egwRedeemFailure()</button>
					<div class="fn-endpoint">Deposit denied</div>
				</td>
				<td>
					<div class="fields-inline">
						<?= ifield('ledger_partner_id', 'partner_id', $_POST['ledger_partner_id'] ?? $default_partner_id) ?>
					</div>
				</form></td>
			</tr>
					

			<!-- distributorYesResponse -->
			<tr>
				<td><form method="POST">
					<button type="submit" name="fn" value="distributorYesResponse" class="btn-run">distributorYesResponse()</button>
					<div class="fn-endpoint">Distributor responded Y to SMS message</div>
				</td>
				<td>
					<div class="fields-inline">
						<!-- $groupId -->
						<!-- $phoneNumber -->
						<?= ifield('ledger_partner_id',           'partner_id',             $_POST['ledger_partner_id']           ?? $default_partner_id) ?>
						<?= ifield('ledger_request_token',        'request_token',          $_POST['ledger_request_token']        ?? 'fake-token', 'short') ?>
						<?= ifield('ledger_redeem_amount',        'redeem_amount',          $_POST['ledger_redeem_amount']        ?? '5.00', 'short') ?>
						<?= ifield('ledger_game_distributor_id',  'game_distributor_id',    $_POST['ledger_game_distributor_id']  ?? DEFAULT_OPERATOR_ID, 'large') ?>
						<?= ifield('ledger_game_id',              'game_id',                $_POST['ledger_game_id']              ?? '42', 'short') ?>
						<?= ifield('ledger_game_name',            'game_name',              $_POST['ledger_game_name']            ?? 'Golden Dragon', 'medium') ?>
						<?= ifield('ledger_game_username',        'game_username',          $_POST['ledger_game_username']        ?? 'testplayer', 'medium') ?>
					</div>
				</form></td>
			</tr>

			<!-- distributorNoResponse -->
			<tr>
				<td><form method="POST">
					<button type="submit" name="fn" value="distributorNoResponse" class="btn-run">distributorNoResponse()</button>
					<div class="fn-endpoint">Redemption failed</div>
				</td>
				<td>
					<div class="fields-inline">
						<?= ifield('ledger_game_username',       'game_username',   $_POST['ledger_game_username']       ?? 'testplayer', 'medium') ?>
						<?= ifield('ledger_game_distributor_id', 'distributor_id',  $_POST['ledger_game_distributor_id'] ?? DEFAULT_OPERATOR_ID, 'medium') ?>
					</div>
				</form></td>
			</tr>
			
			
			<!-- distributorTimeoutResponse -->
			<tr>
				<td><form method="POST">
					<button type="submit" name="fn" value="distributorTimeoutResponse" class="btn-run">distributorTimeoutResponse()</button>
					<div class="fn-endpoint">distributor did not respond</div>
				</td>
				<td>
					<div class="fields-inline">
						<?= ifield('ledger_game_username',       'game_username',   $_POST['ledger_game_username']       ?? 'testplayer', 'medium') ?>
						<?= ifield('ledger_game_distributor_id', 'distributor_id',  $_POST['ledger_game_distributor_id'] ?? DEFAULT_OPERATOR_ID, 'medium') ?>
					</div>
				</form></td>
			</tr>
			
			
		</tbody>
	</table>

	<!-- ================================================================ -->
	<!-- OUTPUT                                                            -->
	<!-- ================================================================ -->

</div><!-- .col-controls -->

<div class="col-log">
	<div class="log-panel">
		<div class="log-panel-header">
			<span class="log-panel-title">egwapi.log</span>
			<button type="button" class="btn-refresh" onclick="clearLog()">Clear</button>
			<button type="button" class="btn-refresh" onclick="refreshLog()">Refresh</button>
		</div>
		<pre id="log-box">(loading…)</pre>
	</div>
</div>

</div><!-- .page-columns -->

<div class="page-body" style="padding-top:0">

	<?php if ( $fn_called ) : ?>

		<?php
			$http_code    = $meta['http_code'] ?? 0;
				$ok           = ( $result !== false && $result !== null )
				                && ( $http_code === 0 || ($http_code >= 200 && $http_code < 300) );
				$status_class = $ok ? 'status-ok'  : 'status-err';
				$status_text  = $ok ? '✓ SUCCESS'  : '✗ FAILED';
				$http_label   = $http_code ?: '—';

				$req_json  = json_encode( $request, JSON_PRETTY_PRINT|JSON_UNESCAPED_SLASHES|JSON_UNESCAPED_UNICODE );
				$resp_data = $result !== false ? $result : ($meta['raw_response'] ?? null);
				if ( is_string($resp_data) ) {
					$decoded = json_decode($resp_data, true);
					if ( $decoded !== null ) $resp_data = $decoded;
				}
				$resp_json = json_encode( $resp_data, JSON_PRETTY_PRINT|JSON_UNESCAPED_SLASHES|JSON_UNESCAPED_UNICODE );

				// Separate webhook data from main response for display
				$webhook_data = null;
				if ( is_array($resp_data) && isset($resp_data['webhook']) ) {
					$webhook_data = $resp_data['webhook'];
					unset($resp_data['webhook']);
					$resp_json = json_encode( $resp_data, JSON_PRETTY_PRINT|JSON_UNESCAPED_SLASHES|JSON_UNESCAPED_UNICODE );
				}
			?>

			<div class="output-title">
				<span class="status-badge <?= $status_class ?>"><?= $status_text ?></span>
				HTTP <?= $http_label ?>
			</div>

			<?php if ( $error ) : ?>
				<div class="error-msg">cURL error: <?= htmlspecialchars($error) ?></div>
			<?php endif; ?>

			<div class="output-cols">
				<div>
					<div class="output-col-label">Request</div>
					<pre class="json-box"><?= htmlspecialchars($req_json) ?></pre>
				</div>
				<div>
					<div class="output-col-label">Response</div>
					<pre class="json-box"><?= htmlspecialchars($resp_json) ?></pre>
				</div>
			</div>

			<?php if ( $webhook_data !== null ) : ?>
				<hr class="section-divider">
				<div class="webhook-section-title"> Webhook </div>
				<div class="output-cols">
					<div>
						<div class="output-col-label">Sent</div>
						<pre class="json-box webhook"><?= htmlspecialchars( json_encode($webhook_data['sent'] ?? $webhook_data, JSON_PRETTY_PRINT|JSON_UNESCAPED_SLASHES) ) ?></pre>
					</div>
					<div>
						<div class="output-col-label">Result</div>
						<pre class="json-box webhook"><?= htmlspecialchars( json_encode(['ok' => $webhook_data['ok'] ?? null, 'error' => $webhook_data['error'] ?? null], JSON_PRETTY_PRINT|JSON_UNESCAPED_SLASHES) ) ?></pre>
					</div>
				</div>
			<?php endif; ?>

			<details class="meta">
				<summary>Transport details</summary>
				<pre class="json-box dim"><?= htmlspecialchars( json_encode($meta, JSON_PRETTY_PRINT|JSON_UNESCAPED_SLASHES) ) ?></pre>
			</details>

	<?php endif; ?>

</div><!-- .page-body output -->

<script>
function clearLog() {
	var box = document.getElementById('log-box');
	box.textContent = 'Clearing\u2026';
	fetch('egwapi_log_tail.php?clear=1')
		.then(function(r) { return r.text(); })
		.then(function() {
			box.textContent = '(log cleared)';
		})
		.catch(function(e) {
			box.textContent = 'Error: ' + e.message;
		});
}
function refreshLog() {
	var box = document.getElementById('log-box');
	box.textContent = 'Loading\u2026';
	fetch('egwapi_log_tail.php')
		.then(function(r) { return r.text(); })
		.then(function(t) {
			box.textContent = t || '(log is empty)';
			box.scrollTop = box.scrollHeight;
		})
		.catch(function(e) {
			box.textContent = 'Error: ' + e.message;
		});
}
document.addEventListener('DOMContentLoaded', refreshLog);
</script>
</body>
</html>


<?php

if ( $_SERVER['REQUEST_METHOD'] === 'POST' && !empty($_POST['fn']) ) {

	$fn_called    = $_POST['fn'];
egwapi_log("fn_called=$fn_called");

	// -----------------------------------------------------------------------
	// test_webhook — POST directly to egwapi_webhooks.php
	// -----------------------------------------------------------------------
	if ( $fn_called === 'test_webhook' ) {

		$session_id          = trim( $_POST['sim_session_id']          ?? '' );
		$action              = trim( $_POST['sim_action']              ?? 'purchase' );
		$status              = trim( $_POST['sim_status']              ?? 'success' );
		$player_game_user_id = trim( $_POST['sim_player_game_user_id'] ?? '' );
		$error_message       = trim( $_POST['sim_error_message']       ?? '' );
		$webhook_token       = trim( $_POST['sim_webhook_token']       ?? '' );

		$webhook_url = EGW_WEBHOOK_URL;
		egwapi_log("egwapi_test: sending webhook test to $webhook_url");

		$payload = [
			'event'               => 'operator.transaction',
			'action'              => $action,
			'session_id'          => $session_id,
			'status'              => $status,
			'player_game_user_id' => $player_game_user_id !== '' ? $player_game_user_id : null,
			'error_message'       => $error_message !== '' ? $error_message : null,
		];

		$request = $payload;

		$ch = curl_init( $webhook_url );
		if (!$ch) { die("curl_init failed"); }

		curl_setopt_array( $ch, [
			CURLOPT_POST           => true,
			CURLOPT_POSTFIELDS     => json_encode( $payload ),
			CURLOPT_RETURNTRANSFER => true,
			CURLOPT_CONNECTTIMEOUT => 10,
			CURLOPT_TIMEOUT        => 10,
			CURLOPT_SSL_VERIFYPEER => false,
			CURLOPT_SSL_VERIFYHOST => 0,
			CURLOPT_HTTPHEADER     => [
				'Content-Type: application/json',
				'Authorization: Bearer ' . $webhook_token,
				'X-Idempotency-Key: tx:' . $session_id,
			],
		]);
		
		$wh_response = curl_exec( $ch );
		$wh_errno    = curl_errno( $ch );
		$wh_error    = curl_error( $ch );
		$wh_http     = (int) curl_getinfo( $ch, CURLINFO_HTTP_CODE );
		curl_close( $ch );

		$result = $wh_response ?: null;
		$error  = $wh_errno ? $wh_error : null;
		$meta   = [
			'http_code'    => $wh_http,
			'curl_errno'   => $wh_errno,
			'curl_error'   => $wh_error,
			'endpoint_url' => $webhook_url,
			'raw_response' => $wh_response,
		];

	} else {

		try {
			// instantiate class for selected mode
			$egw = new EgwApi( $active_endpoint_key );

			switch ( $fn_called ) {

				case 'create_player':
					$operator_id      = trim( $_POST['create_player_operator_id'] ?? '' );
					$player_wallet_id = trim( $_POST['create_player_player_wallet_id']   ?? '' );
					$amount           = (float)($_POST['create_player_amount']    ?? 0);
					$operator_game_id = (int)  ($_POST['create_player_game_id']   ?? 0);
					$first_name       = trim( $_POST['create_player_first_name']  ?? '' );
					$last_name        = trim( $_POST['create_player_last_name']   ?? '' );
					$email            = trim( $_POST['create_player_email']       ?? '' );
					$date_of_birth    = trim( $_POST['create_player_dob']         ?? '' );

					$request = compact('operator_id','player_wallet_id','amount','operator_game_id','first_name','last_name','email','date_of_birth');
					$result  = $egw->createPlayer( $operator_id, $player_wallet_id, $amount, $operator_game_id, $first_name, $last_name, $email, $date_of_birth );
					break;

				case 'create_operator':
					$username           = trim( $_POST['create_op_username']   ?? '' );
					$email              = trim( $_POST['create_op_email']      ?? '' );
					$business_name      = trim( $_POST['create_op_biz_name']   ?? '' );
					$contact_first_name = trim( $_POST['create_op_first_name'] ?? '' );
					$contact_last_name  = trim( $_POST['create_op_last_name']  ?? '' );
					$address            = trim( $_POST['create_op_address']    ?? '' );
					$contact_phone      = trim( $_POST['create_op_phone']      ?? '' );
					$operator_site_url  = trim( $_POST['create_op_site_url']   ?? '' );

					$request = compact('username','email','business_name','contact_first_name','contact_last_name','address','contact_phone','operator_site_url');
					$result  = $egw->createOperator( $username, $email, $business_name, $contact_first_name, $contact_last_name, $address, $contact_phone, $operator_site_url );
					break;

				case 'purchase':
					$operator_id         = trim( $_POST['purchase_operator_id']         ?? '' );
					$operator_game_id    = trim( $_POST['purchase_operator_game_id']    ?? '' );
					$operator_wallet_id  = trim( $_POST['purchase_operator_wallet_id']  ?? '' );
					$player_game_user_id = trim( $_POST['purchase_player_game_user_id'] ?? '' );
					$player_wallet_id    = trim( $_POST['purchase_player_wallet_id']    ?? '' );
					$payment_provider_id = trim( $_POST['purchase_payment_provider_id'] ?? '' );
					$amount              = (float)($_POST['purchase_amount']            ?? 0);

					$request = compact(        'operator_id','operator_game_id','operator_wallet_id','player_game_user_id','player_wallet_id','payment_provider_id','amount');
					$result  = $egw->purchase( $operator_id, $operator_game_id, $operator_wallet_id, $player_game_user_id, $player_wallet_id, $payment_provider_id, $amount );
					break;

				case 'redeem':
					$operator_id         = trim( $_POST['redeem_operator_id']         ?? '' );
					$operator_game_id    = trim( $_POST['redeem_operator_game_id']    ?? '' );
					$operator_wallet_id  = trim( $_POST['redeem_operator_wallet_id']  ?? '' );
					$player_game_user_id = trim( $_POST['redeem_player_game_user_id'] ?? '' );
					$player_wallet_id    = trim( $_POST['redeem_player_wallet_id']    ?? '' );
					$payment_provider_id = trim( $_POST['redeem_payment_provider_id'] ?? '' );
					$amount              = (float)($_POST['redeem_amount']            ?? 0);
					
					$request =       compact('operator_id','operator_game_id','operator_wallet_id','player_game_user_id','player_wallet_id','payment_provider_id','amount');
					$result  = $egw->redeem( $operator_id, $operator_game_id, $operator_wallet_id, $player_game_user_id, $player_wallet_id, $payment_provider_id, $amount );
					break;

				case 'get_active_games':
					$operator_id = trim( $_POST['games_operator_id'] ?? '' );
					$request     = [ 'operator_id' => $operator_id ];
					$result      = $egw->getActiveGames( $operator_id );
					break;

				case 'get_available_games':
					$request = [];
					$result  = $egw->getAvailableGames();
					break;

				case 'create_operator_game':
					$operator_id = trim( $_POST['cog_operator_id'] ?? '' );
					$fields = array_filter( [
						'game_id'        => trim( $_POST['cog_game_id']        ?? '' ),
						'display_name'   => trim( $_POST['cog_display_name']   ?? '' ),
						'pos_username'   => trim( $_POST['cog_pos_username']   ?? '' ),
						'pos_password'   => trim( $_POST['cog_pos_password']   ?? '' ),
						'publish_site'   => trim( $_POST['cog_publish_site']   ?? '' ),
						'drawer'         => trim( $_POST['cog_drawer']         ?? '' ),
						'kiosk_number'   => trim( $_POST['cog_kiosk_number']   ?? '' ),
						'station_number' => trim( $_POST['cog_station_number'] ?? '' ),
						'order'          => trim( $_POST['cog_order']          ?? '' ),
						'pos_category'   => trim( $_POST['cog_pos_category']   ?? '' ),
					], fn($v) => $v !== '' );
					$request = array_merge( ['operator_id' => $operator_id], $fields );
					$result  = $egw->createOperatorGame( $operator_id, $fields );
					break;

				case 'update_operator_game':
					$operator_id      = trim( $_POST['uog_operator_id']      ?? '' );
					$operator_game_id = (int) ($_POST['uog_operator_game_id'] ?? 0);
					$fields = array_filter( [
						'game_id'      => trim( $_POST['uog_game_id']      ?? '' ),
						'display_name' => trim( $_POST['uog_display_name'] ?? '' ),
						'publish_site' => trim( $_POST['uog_publish_site'] ?? '' ),
					], fn($v) => $v !== '' );
					$request = array_merge( ['operator_id' => $operator_id, 'operator_game_id' => $operator_game_id], $fields );
					$result  = $egw->updateOperatorGame( $operator_id, $operator_game_id, $fields );
					break;

				case 'disable_all_games':
					$operator_id = trim( $_POST['dag_operator_id'] ?? '' );
					$request     = [ 'operator_id' => $operator_id ];
					$result      = $egw->disableAllGames( $operator_id );
					break;

				case 'enable_all_games':
					$operator_id = trim( $_POST['eag_operator_id'] ?? '' );
					$request     = [ 'operator_id' => $operator_id ];
					$result      = $egw->enableAllGames( $operator_id );
					break;
			}

			$error = $egw->curl_errno ? $egw->curl_error : null;
			$meta  = [
				'http_code'    => $egw->http_code,
				'curl_errno'   => $egw->curl_errno,
				'curl_error'   => $egw->curl_error,
				'endpoint_url' => $active_endpoint_url.' FIXED',
				'raw_response' => $egw->json_response,
			];

		} catch ( InvalidArgumentException | RuntimeException $e ) {
			$error = $e->getMessage();
			$meta  = [];
		}

		// Ledger functions
		if ( in_array($fn_called, [
			'rfpSuccess','rfpFailure','rtpSuccess','rtpFailure',
			'egwPurchaseSuccess','egwPurchaseFailure','egwRedeemSuccess','egwRedeemFailure',
			'distributorYesResponse','distributorNoResponse','distributorTimeoutResponse'
			]) ) {
			$partner_id = trim( $_POST['ledger_partner_id'] ?? '' );
			
			$request_token = "fake-token";
			$redeemAmount = round(rand(10,99) / 100.0, 2);

			$game_distributor_id = trim( $_POST['ledger_game_distributor_id'] ?? '' );
			$game_id = (int) ($_POST['ledger_game_id'] ?? 0);
			$game_name = trim( $_POST['ledger_game_name'] ?? '' );
			$game_username = trim( $_POST['ledger_game_username'] ?? '' );
			
			switch ( $fn_called ) {
				case 'rfpSuccess': rfpSuccess( $groupId, $phoneNumber, $game_distributor_id, $game_id ); break;
				case 'rfpFailure': rfpFailure( $groupId, $phoneNumber, $game_distributor_id, $game_id, 'Manual test trigger' ); break;
				
				case 'rtpSuccess': rtpSuccess( $groupId, $phoneNumber, $game_distributor_id, $game_id ); break;
				case 'rtpFailure': rtpFailure( $groupId, $phoneNumber, $game_distributor_id, $game_id, 'Manual test trigger' ); break;
			
				case 'egwPurchaseSuccess': egwPurchaseSuccess( $groupId, $phoneNumber, $game_distributor_id, $game_id ); break;
				case 'egwPurchaseFailure': egwPurchaseFailure( $groupId, $phoneNumber, $game_distributor_id, $game_id, 'Manual test trigger' ); break;
				case 'egwRedeemSuccess': egwRedeemSuccess('manual test'); break;
				case 'egwRedeemFailure': egwRedeemFailure('manual test'); break;
				
				case 'distributorYesResponse': 
					distributorYesResponse( $groupId, $phoneNumber, $partner_id, $request_token, $redeemAmount, $game_distributor_id, $game_id, $game_name, $game_username );
					break;
				case 'distributorNoResponse': distributorNoResponse( $request_token ); break;
				case 'distributorTimeoutResponse': distributorTimeoutResponse( $request_token ); break;
			}
		}

	} // end else (non-webhook)
}

function getOperatorGamesIdList( $operator_id )
{
	global $active_endpoint_key;
	$egw = new EgwApi( $active_endpoint_key );
	$result = $egw->getActiveGames( $operator_id );
	return $result;
}