<?php
session_start();
require_once __DIR__ . '/../config/call_refund.php';

/**
 * =========================================================
 * Helper: One-time token (anti double submit)
 * =========================================================
 */
function generateCallToken(): string {
    return bin2hex(random_bytes(16));
}
if (!isset($_SESSION['used_call_tokens'])) {
    $_SESSION['used_call_tokens'] = [];
}

/**
 * =========================================================
 * Helper: Cek pending call (0=Waiting, 1=Processing)
 * =========================================================
 */
function hasPendingCall(array $callHistory, string $userCode, string $provider, string $game): bool {
    foreach ($callHistory as $h) {
        if (($h['user_code'] ?? '') !== $userCode) continue;
        if (($h['provider_code'] ?? '') !== $provider) continue;
        if (($h['game_code'] ?? '') !== $game) continue;

        $status = (int)($h['status'] ?? -1);
        if ($status === 0 || $status === 1) return true;
    }
    return false;
}

function findCallPlayerRow(array $callPlayerResponse, string $userCode, string $provider, string $game): array {
    foreach (($callPlayerResponse['data'] ?? []) as $row) {
        if (($row['user_code'] ?? '') !== $userCode) continue;
        if (($row['provider_code'] ?? '') !== $provider) continue;
        if (($row['game_code'] ?? '') !== $game) continue;

        return $row;
    }

    return [];
}

function callMemberScopeWhere(mysqli $call, array $agentRefs, string $agentLevel): string {
    $agentRefsSql = agent_sql_values($call, $agentRefs);

    if ($agentLevel === 'admin') {
        return '1=1';
    }

    return "(tb_user.agent_code IN ($agentRefsSql) OR tb_agent.agent_name IN ($agentRefsSql))";
}

/**
 * =========================================================
 * INIT
 * =========================================================
 */
$callResult   = [];
$justPosted   = false;   // untuk replaceState agar refresh tidak re-POST
$openModalId  = '';      // agar modal tetap kebuka setelah submit (opsional)

/**
 * =========================================================
 * Ambil daftar member sesuai scope login.
 * Admin: semua member.
 * Head agent / agent: member milik akun itu sendiri.
 * =========================================================
 */
$currentAgentName = agent_public_name((array)($data_admin ?? []));
$currentAgentRefs = agent_identity_values((array)($data_admin ?? []));
$currentAgentLevel = trim((string)($data_admin['agent_level'] ?? 'agent'));
$memberScopeWhere = callMemberScopeWhere($call, $currentAgentRefs, $currentAgentLevel);

$cek_member = mysqli_query($call, "
    SELECT tb_user.intUser, tb_user.extUser, tb_user.agent_code, tb_agent.agent_name, tb_agent.agent_balance
    FROM tb_user
    LEFT JOIN tb_agent ON tb_user.agent_code = tb_agent.agent_name OR tb_user.agent_code = tb_agent.agent_code
    WHERE $memberScopeWhere
    ORDER BY tb_user.created DESC
");
if (!$cek_member) die("Query gagal: " . mysqli_error($call));

// Map user
$allowedUsers = [];
$agentBalanceByUser = [];
$agentNameByUser = [];
while ($row = mysqli_fetch_assoc($cek_member)) {
    $intUser = $row['intUser'];
    $allowedUsers[$intUser] = $row['extUser'];
    $agentBalanceByUser[$intUser] = (float)($row['agent_balance'] ?? 0);
    $agentNameByUser[$intUser] = (string)($row['agent_name'] ?? '');
}

/**
 * =========================================================
 * POST: Apply Call
 * NOTE: TIDAK pakai header redirect agar tidak blank di layout include.
 * Anti refresh double: pakai history.replaceState di bawah.
 * =========================================================
 */
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['call_apply'])) {

    $justPosted  = true;
    $openModalId = trim($_POST['modal_id'] ?? '');

    // ====== Anti double submit token ======
    $call_token = trim($_POST['call_token'] ?? '');
    if ($call_token === '') {
        $callResult = ['status'=>0,'msg'=>'INVALID TOKEN'];
    } elseif (isset($_SESSION['used_call_tokens'][$call_token])) {
        $callResult = ['status'=>0,'msg'=>'DUPLICATE SUBMIT (TOKEN USED)'];
    } else {
        $_SESSION['used_call_tokens'][$call_token] = time();

        // batasi ukuran session token
        if (count($_SESSION['used_call_tokens']) > 500) {
            $_SESSION['used_call_tokens'] = array_slice($_SESSION['used_call_tokens'], -200, null, true);
        }

        // ====== Ambil input ======
        $username      = mysqli_real_escape_string($call, trim($_POST['username'] ?? ''));
        $provider_code = trim($_POST['provider_code'] ?? '');
        $game_code     = trim($_POST['game_code'] ?? '');
        $call_rtp      = (int)($_POST['call_rtp'] ?? 0);
        $call_type     = (int)($_POST['call_type'] ?? 1);
        $betAmount     = 0;

        if (isset($allowedUsers[$username]) && $provider_code && $game_code && $call_rtp > 0 && in_array($call_type,[1,2], true)) {

            // Ambil bet terbaru dari provider, bukan dari input hidden.
            $callPlayersNowRaw = $GS->callPlayer();
            $playerNow = is_array($callPlayersNowRaw)
                ? findCallPlayerRow($callPlayersNowRaw, $username, $provider_code, $game_code)
                : [];
            $betAmount = (float)($playerNow['bet'] ?? 0);

            // Nominal debit agent / credit user
            $payout_percentage = $betAmount * ($call_rtp / 100);

            if ($betAmount <= 0 || $payout_percentage <= 0) {
                $callResult = ['status'=>0,'msg'=>'PLAYER DATA NOT FOUND OR BET INVALID'];
            } else {
                // Cari agent pemilik member, tetap dikunci ke scope login agar tidak bocor.
                $agentInfoQuery = mysqli_query($call, "
                    SELECT tb_agent.agent_name, tb_agent.agent_code, tb_agent.agent_balance
                    FROM tb_user
                    LEFT JOIN tb_agent ON tb_user.agent_code = tb_agent.agent_name OR tb_user.agent_code = tb_agent.agent_code
                    WHERE tb_user.intUser = '$username'
                      AND $memberScopeWhere
                    LIMIT 1
                ");
                if (!$agentInfoQuery || mysqli_num_rows($agentInfoQuery) === 0) {
                    $callResult = ['status'=>0,'msg'=>'AGENT NOT FOUND'];
                } else {
                    $agentInfo = mysqli_fetch_assoc($agentInfoQuery);
                    $agentName = trim((string)($agentInfo['agent_name'] ?? ''));
                    $agentBalance = (float)($agentInfo['agent_balance'] ?? 0);

                    if ($agentName === '') {
                        $callResult = ['status'=>0,'msg'=>'AGENT NOT FOUND'];
                    } elseif ($agentBalance < $payout_percentage) {
                        $callResult = ['status'=>0,'msg'=>'INSUFFICIENT AGENT BALANCE'];
                    } else {
                        // ====== Cek pending call terbaru (biar akurat) ======
                        $callHistoryNowRaw = $GS->callHistory(0, 200);
                        $callHistoryNow = $callHistoryNowRaw['data'] ?? [];

                        if (hasPendingCall($callHistoryNow, $username, $provider_code, $game_code)) {
                            $callResult = ['status'=>0,'msg'=>'MASIH ADA CALL WAITING/PROCESSING, TUNGGU SELESAI'];
                        } else {
                            mysqli_begin_transaction($call);
                            try {
                                // Debit agent pemilik member lebih dulu dengan guard balance.
                                $agentEscaped = mysqli_real_escape_string($call, $agentName);
                                $updateAgent = mysqli_query($call, "
                                    UPDATE tb_agent
                                    SET agent_balance = agent_balance - $payout_percentage
                                    WHERE agent_name = '$agentEscaped'
                                      AND agent_balance >= $payout_percentage
                                ");
                                if (!$updateAgent || mysqli_affected_rows($call) !== 1) {
                                    throw new Exception("INSUFFICIENT AGENT BALANCE");
                                }

                                // Buat call baru (hanya saat klik Apply + tidak pending)
                                $result = $GS->callApply($provider_code, $game_code, $username, $call_rtp, $call_type);
                                $callResult = $result ?? ['status'=>0,'msg'=>'No response from API'];

                                if (($callResult['status'] ?? 0) == 1) {
                                    // Credit user lokal sesuai nominal call.
                                    $updateUser = mysqli_query($call, "
                                        UPDATE tb_user
                                        SET balance = balance + $payout_percentage
                                        WHERE intUser = '$username'
                                    ");
                                    if (!$updateUser) throw new Exception("Gagal update saldo user: " . mysqli_error($call));

                                    $ledgerRecorded = call_rtp_record_apply($call, [
                                        'provider_response' => $callResult,
                                        'intUser' => $username,
                                        'extUser' => $allowedUsers[$username] ?? '',
                                        'agent_name' => $agentName,
                                        'agent_code' => $agentInfo['agent_code'] ?? '',
                                        'provider_code' => $provider_code,
                                        'game_code' => $game_code,
                                        'call_rtp' => $call_rtp,
                                        'call_type' => $call_type,
                                        'bet_amount' => $betAmount,
                                        'called_money' => $payout_percentage,
                                        'user_credit_amount' => $payout_percentage,
                                        'source' => 'web',
                                    ]);
                                    if (!$ledgerRecorded) throw new Exception("Gagal mencatat ledger call RTP");

                                    mysqli_commit($call);

                                    $newAgentBalance = max(0, $agentBalance - $payout_percentage);
                                    foreach ($agentNameByUser as $mappedUser => $mappedAgentName) {
                                        if ($mappedAgentName === $agentName) {
                                            $agentBalanceByUser[$mappedUser] = $newAgentBalance;
                                        }
                                    }

                                    $callResult['called_money'] = $payout_percentage;
                                } else {
                                    mysqli_rollback($call);
                                }
                            } catch (Exception $e) {
                                mysqli_rollback($call);
                                $callResult = ['status'=>0,'msg'=>$e->getMessage()];
                            }
                        }
                    }
                }
            }

        } else {
            $callResult = ['status'=>0,'msg'=>'Missing or invalid parameters'];
        }
    }
}

/**
 * =========================================================
 * Data untuk tampilan (GET atau setelah POST)
 * =========================================================
 */
$apiDataRaw = $GS->callPlayer();
$apiData = $apiDataRaw;

$callHistoryDataRaw = $GS->callHistory(0, 200);
$callHistory = $callHistoryDataRaw['data'] ?? [];
$callRefundSummary = call_rtp_refund_rejected_history($call, $callHistory, $allowedUsers);

if (!empty($callRefundSummary['agent_balances'])) {
    foreach ($agentNameByUser as $mappedUser => $mappedAgentName) {
        if (isset($callRefundSummary['agent_balances'][$mappedAgentName])) {
            $agentBalanceByUser[$mappedUser] = $callRefundSummary['agent_balances'][$mappedAgentName];
        }
    }

    if (isset($callRefundSummary['agent_balances'][$currentAgentName])) {
        $data_admin['agent_balance'] = $callRefundSummary['agent_balances'][$currentAgentName];
        $_SESSION['admin']['agent_balance'] = $callRefundSummary['agent_balances'][$currentAgentName];
    }
}

/**
 * =========================================================
 * Cache callList provider|game (biar tidak call berulang)
 * =========================================================
 */
$callListCache = [];
$activeCallPlayers = is_array($apiData['data'] ?? null) ? count($apiData['data']) : 0;
$visibleCallPlayers = 0;
$pendingCallTotal = 0;
foreach (($apiData['data'] ?? []) as $playerRow) {
    if (isset($allowedUsers[$playerRow['user_code'] ?? ''])) {
        $visibleCallPlayers++;
    }
}
foreach ($callHistory as $historyRow) {
    if (!isset($allowedUsers[$historyRow['user_code'] ?? ''])) {
        continue;
    }

    $status = (int)($historyRow['status'] ?? -1);
    if ($status === 0 || $status === 1) {
        $pendingCallTotal++;
    }
}
?>

<div class="app-page-shell">
    <?php if (!empty($callRefundSummary) && ((int)($callRefundSummary['refunded'] ?? 0) > 0 || !empty($callRefundSummary['errors']))): ?>
        <div class="alert <?= !empty($callRefundSummary['errors']) ? 'alert-warning' : 'alert-success' ?> mb-4">
            <?php if ((int)($callRefundSummary['refunded'] ?? 0) > 0): ?>
                <?= (int)$callRefundSummary['refunded'] ?> rejected call sudah direfund ke saldo agent.
            <?php endif; ?>
            <?php if (!empty($callRefundSummary['errors'])): ?>
                <?= (int)count($callRefundSummary['errors']) ?> refund rejected call belum berhasil diproses.
            <?php endif; ?>
        </div>
    <?php endif; ?>
    <div class="row g-4">
    <div class="col-12">
        <div class="card">
            <div class="card-header">
                <h4 class="card-title mb-1">Member Call Player</h4>
                <p class="text-muted mb-0">Pilih target RTP dan tipe call untuk setiap user.</p>
            </div>
            <div class="card-body">
                <div class="table-responsive">
                    <table class="table table-striped table-hover align-middle">
                        <thead class="table-light">
                        <tr>
                            <th>User Site</th>
                            <th class="text-end">Balance</th>
                            <th class="text-nowrap">Game</th>
                            <th class="text-nowrap">Vendor</th>
                            <th class="text-end">Bet Amount</th>
                            <th class="text-end">Total Debit</th>
                            <th class="text-end">Total Credit</th>
                            <th class="text-end">Target RTP</th>
                            <th class="text-end">Real RTP</th>
                            <th>Call List</th>
                        </tr>
                        </thead>
                        <tbody>
                        <?php if (!empty($apiData['data'])): ?>
                            <?php foreach ($apiData['data'] as $info):
                                $intUser = $info['user_code'];
                                if (!isset($allowedUsers[$intUser])) continue; // Filter user

                                $extUser = $allowedUsers[$intUser];
                                $modalKey = $extUser . '_' . $intUser;
                                $modalId = "modalCallList_" . preg_replace('/[^a-zA-Z0-9_\-]/', '_', $modalKey);

                                $provider = $info['provider_code'];
                                $game     = $info['game_code'];
                                $cacheKey = $provider . '|' . $game;

                                if (!isset($callListCache[$cacheKey])) {
                                    $resp = $GS->callList($provider, $game);
                                    $callListCache[$cacheKey] = $resp['calls'] ?? [];
                                }
                                $calls = $callListCache[$cacheKey];

                                $agentBalance = (float)($agentBalanceByUser[$intUser] ?? 0);
                                $agentName = trim((string)($agentNameByUser[$intUser] ?? ''));
                                $betAmount = (float)($info['bet'] ?? 0);
                                $agentBalanceValue = number_format($agentBalance, 0, '.', '');

                                // Pending? disable create call baru
                                $isPending = hasPendingCall($callHistory, $intUser, $provider, $game);

                                // Token unik per form
                                $token = generateCallToken();
                            ?>
                                <tr>
                                    <td><?= htmlspecialchars($extUser, ENT_QUOTES) ?></td>
                                    <td class="text-end"><?= number_format((float)$info['balance'], 0, ',', '.') ?></td>
                                    <td class="text-nowrap"><?= htmlspecialchars($info['game_code'], ENT_QUOTES) ?></td>
                                    <td class="text-nowrap"><?= htmlspecialchars($info['provider_code'], ENT_QUOTES) ?></td>
                                    <td class="text-end"><?= number_format((float)$info['bet'], 0, ',', '.') ?></td>
                                    <td class="text-end"><?= number_format((float)$info['total_debit'], 0, ',', '.') ?></td>
                                    <td class="text-end"><?= number_format((float)$info['total_credit'], 0, ',', '.') ?></td>
                                    <td class="text-end">
                                        <span class="badge bg-light-primary">
                                            <?= htmlspecialchars($info['target_rtp'], ENT_QUOTES) ?>%
                                        </span>
                                    </td>
                                    <td class="text-end">
                                        <span class="badge bg-light-success">
                                            <?= htmlspecialchars($info['real_rtp'], ENT_QUOTES) ?>%
                                        </span>
                                    </td>
                                    <td>
                                        <button type="button" class="btn btn-sm btn-outline-primary"
                                                data-bs-toggle="modal" data-bs-target="#<?= htmlspecialchars($modalId, ENT_QUOTES) ?>">
                                            View Call List
                                        </button>
                                    </td>
                                </tr>

                                <!-- Modal -->
                                <div class="modal fade" id="<?= htmlspecialchars($modalId, ENT_QUOTES) ?>" tabindex="-1" aria-labelledby="<?= htmlspecialchars($modalId, ENT_QUOTES) ?>Label" aria-hidden="true">
                                    <div class="modal-dialog modal-dialog-centered modal-lg" role="document">
                                        <div class="modal-content">
                                            <div class="modal-header">
                                                <h5 class="modal-title" id="<?= htmlspecialchars($modalId, ENT_QUOTES) ?>Label">Call List for <?= htmlspecialchars($extUser, ENT_QUOTES) ?></h5>
                                                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                                            </div>
                                            <div class="modal-body">
                                                <?php if (!empty($calls)): ?>
                                                    <?php
                                                    $hasSelectableCall = false;
                                                    foreach ($calls as $c) {
                                                        $rtpValue = (float)($c['rtp'] ?? 0);
                                                        $requiredAmount = $betAmount * ($rtpValue / 100);
                                                        if ($requiredAmount <= $agentBalance) { $hasSelectableCall = true; break; }
                                                    }
                                                    $selectedSet = false;
                                                    ?>

                                                    <form method="post"
                                                          class="call-apply-form"
                                                          data-agent-balance="<?= htmlspecialchars($agentBalanceValue, ENT_QUOTES) ?>"
                                                          onsubmit="this.querySelector('.call-apply-btn').disabled=true;">
                                                        <input type="hidden" name="_token" value="<?= htmlspecialchars(csrf_token(), ENT_QUOTES) ?>">
                                                        <input type="hidden" name="username" value="<?= htmlspecialchars($intUser, ENT_QUOTES) ?>">
                                                        <input type="hidden" name="game_code" value="<?= htmlspecialchars($info['game_code'], ENT_QUOTES) ?>">
                                                        <input type="hidden" name="provider_code" value="<?= htmlspecialchars($info['provider_code'], ENT_QUOTES) ?>">
                                                        <input type="hidden" name="call_apply" value="1">
                                                        <input type="hidden" name="bet" value="<?= htmlspecialchars($info['bet'], ENT_QUOTES) ?>">

                                                        <!-- supaya setelah submit modal kebuka lagi -->
                                                        <input type="hidden" name="modal_id" value="<?= htmlspecialchars($modalId, ENT_QUOTES) ?>">

                                                        <!-- One-time token -->
                                                        <input type="hidden" name="call_token" value="<?= htmlspecialchars($token, ENT_QUOTES) ?>">

                                                        <div class="row g-3">
                                                            <div class="col-12 col-md-6">
                                                                <label class="form-label">Select Call RTP</label>
                                                                <select name="call_rtp" class="form-select call-rtp-select"
                                                                        <?= ($hasSelectableCall && !$isPending) ? '' : 'disabled' ?>>
                                                                    <?php foreach ($calls as $c): ?>
                                                                        <?php
                                                                        $rtpValue = (float)($c['rtp'] ?? 0);
                                                                        $requiredAmount = $betAmount * ($rtpValue / 100);
                                                                        $requiredValue = number_format($requiredAmount, 0, '.', '');
                                                                        $disabled = $requiredAmount > $agentBalance;
                                                                        $selectedAttr = '';
                                                                        if (!$disabled && !$selectedSet) { $selectedAttr=' selected'; $selectedSet=true; }
                                                                        ?>
                                                                        <option value="<?= htmlspecialchars($rtpValue, ENT_QUOTES) ?>"
                                                                                data-required="<?= htmlspecialchars($requiredValue, ENT_QUOTES) ?>"
                                                                                <?= $disabled ? ' disabled' : '' ?><?= $selectedAttr ?>>
                                                                            <?= htmlspecialchars($c['call_type'], ENT_QUOTES) ?> - <?= number_format((float)$c['rtp'], 0, ',', '.') ?><?= $disabled ? ' (Saldo agent tidak cukup)' : '' ?>
                                                                        </option>
                                                                    <?php endforeach; ?>
                                                                </select>
                                                            </div>
                                                            <div class="col-12 col-md-6">
                                                                <label class="form-label">Call Type</label>
                                                                <select name="call_type" class="form-select" <?= ($hasSelectableCall && !$isPending) ? '' : 'disabled' ?>>
                                                                    <option value="1">Common Free</option>
                                                                    <option value="2">Buy Bonus Free</option>
                                                                </select>
                                                            </div>
                                                        </div>

                                                        <div class="mt-2 small text-muted">
                                                            Saldo Agent<?= $agentName !== '' ? ' (' . htmlspecialchars($agentName, ENT_QUOTES) . ')' : '' ?>: <span class="call-agent-balance"><?= number_format($agentBalance, 0, ',', '.') ?></span>
                                                        </div>
                                                        <div class="small text-muted">
                                                            Nominal Call: <span class="call-required">0</span>
                                                        </div>

                                                        <?php if ($isPending): ?>
                                                            <div class="mt-2 text-warning small">
                                                                Masih ada call <b>Waiting/Processing</b> untuk game ini. Tunggu selesai dulu.
                                                            </div>
                                                        <?php endif; ?>

                                                        <?php if (!empty($callResult) && $openModalId === $modalId): ?>
                                                            <div class="mt-3 <?= ($callResult['status'] ?? 0) == 1 ? 'alert alert-success' : 'alert alert-danger' ?>">
                                                                <?= htmlspecialchars($callResult['msg'] ?? '') ?>
                                                                <?php if (isset($callResult['called_money'])): ?>
                                                                    <br>Called Money: <?= number_format((float)$callResult['called_money'], 0, ',', '.') ?>
                                                                <?php endif; ?>
                                                            </div>
                                                        <?php endif; ?>

                                                        <div class="mt-3">
                                                            <button type="submit" class="btn btn-primary btn-sm call-apply-btn"
                                                                    <?= ($hasSelectableCall && !$isPending) ? '' : 'disabled' ?>>
                                                                Apply
                                                            </button>
                                                        </div>
                                                    </form>
                                                <?php else: ?>
                                                    <p class="text-danger mb-0">No call list data available.</p>
                                                <?php endif; ?>
                                            </div>
                                        </div>
                                    </div>
                                </div>

                            <?php endforeach; ?>
                        <?php else: ?>
                            <tr><td colspan="10" class="text-center">No data from CallPlayer API.</td></tr>
                        <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>

    <!-- Call History -->
    <div class="col-12">
        <div class="card">
            <div class="card-header">
                <h4 class="card-title mb-1">Call History</h4>
                <p class="text-muted mb-0">Riwayat hasil call RTP untuk user yang aktif.</p>
            </div>
            <div class="card-body">
                <div class="table-responsive">
                    <table class="table table-striped table-hover align-middle">
                        <thead class="table-light">
                        <tr>
                            <th>ID</th>
                            <th>User</th>
                            <th class="text-nowrap">Provider</th>
                            <th class="text-nowrap">Game</th>
                            <th class="text-end">Bet</th>
                            <th class="text-end">Expect</th>
                            <th class="text-end">Missed</th>
                            <th class="text-end">Real</th>
                            <th>Type</th>
                            <th>Status</th>
                            <th>Message</th>
                            <th class="text-nowrap">Created At</th>
                        </tr>
                        </thead>
                        <tbody>
                        <?php if (!empty($callHistory)): ?>
                            <?php foreach ($callHistory as $h): ?>
                                <?php
                                if (!isset($allowedUsers[$h['user_code']])) continue;
                                $extUser = $allowedUsers[$h['user_code']];

                                $statusMap = [
                                    0 => ['Waiting', 'bg-light-warning text-warning'],
                                    1 => ['Processing', 'bg-light-info text-info'],
                                    2 => ['Finished', 'bg-light-success text-success'],
                                    3 => ['Rejected By GameServer', 'bg-light-danger text-danger'],
                                    4 => ['Canceled', 'bg-light-secondary text-secondary']
                                ];
                                $statusKey = (int)($h['status'] ?? -1);
                                $statusInfo = $statusMap[$statusKey] ?? ['Unknown', 'bg-light-secondary text-secondary'];
                                ?>
                                <tr>
                                    <td><?= htmlspecialchars($h['id']) ?></td>
                                    <td><?= htmlspecialchars($extUser) ?></td>
                                    <td class="text-nowrap"><?= htmlspecialchars($h['provider_code']) ?></td>
                                    <td class="text-nowrap"><?= htmlspecialchars($h['game_code']) ?></td>
                                    <td class="text-end"><?= number_format((float)$h['bet'], 0, ',', '.') ?></td>
                                    <td class="text-end"><?= number_format((float)$h['expect'], 0, ',', '.') ?></td>
                                    <td class="text-end"><?= number_format((float)$h['missed'], 0, ',', '.') ?></td>
                                    <td class="text-end"><?= number_format((float)$h['real'], 0, ',', '.') ?></td>
                                    <td><?= htmlspecialchars($h['type']) ?></td>
                                    <td>
                                        <span class="badge <?= $statusInfo[1] ?>">
                                            <?= htmlspecialchars($statusInfo[0]) ?>
                                        </span>
                                    </td>
                                    <td><?= htmlspecialchars($h['msg'] ?? '') ?></td>
                                    <td class="text-nowrap"><?= htmlspecialchars($h['created_at']) ?></td>
                                </tr>
                            <?php endforeach; ?>
                        <?php else: ?>
                            <tr><td colspan="12" class="text-center">No call history found.</td></tr>
                        <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
</div>
</div>

<!-- =========================================================
     FIX REFRESH DOUBLE (tanpa redirect server supaya tidak blank)
     - Jika barusan POST, ubah history jadi GET
========================================================== -->
<?php if ($justPosted): ?>
<script>
  if (window.history && window.history.replaceState) {
    window.history.replaceState(null, document.title, window.location.href);
  }
</script>
<?php endif; ?>

<!-- =========================================================
     OPTIONAL: buka lagi modal setelah submit
========================================================== -->
<?php if (!empty($openModalId)): ?>
<script>
  (function() {
    var el = document.getElementById("<?= htmlspecialchars($openModalId, ENT_QUOTES) ?>");
    if (el && window.bootstrap && bootstrap.Modal) {
      var m = bootstrap.Modal.getOrCreateInstance(el);
      m.show();
    }
  })();
</script>
<?php endif; ?>

<?php if ($justPosted && !empty($callResult) && (int)($callResult['status'] ?? 0) === 1): ?>
<script>
  document.addEventListener("DOMContentLoaded", function() {
    var message = <?= json_encode($callResult['msg'] ?? 'Success Call', JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_QUOT | JSON_HEX_AMP) ?>;

    if (window.Swal) {
      Swal.fire({
        icon: "success",
        title: "Success Call",
        text: message || "Call berhasil diproses.",
        confirmButtonText: "OK"
      });
      return;
    }

    alert(message || "Success Call");
  });
</script>
<?php endif; ?>
