<div class="page-breadcrumb">
    <div class="row">
        <div class="col-5 align-self-center">
            <h4 class="page-title">User Online</h4>
        </div>
        <div class="col-7 align-self-center">
            <div class="d-flex align-items-center justify-content-end">
                <nav aria-label="breadcrumb">
                    <ol class="breadcrumb">
                        <li class="breadcrumb-item"><a href="#">Monitoring</a></li>
                        <li class="breadcrumb-item active">User Online</li>
                    </ol>
                </nav>
            </div>
        </div>
    </div>
</div>

<div class="container-fluid">
    <div class="row">
        <div class="col-lg-12">
            <div class="card">

                <div class="card-body">
                    <h4 class="card-title">Current Playing Users</h4>
                </div>

                <div class="table-responsive">
                    <table class="table table-striped table-bordered">
                        <thead>
                        <tr>
                            <th>#</th>
                            <th>User Code</th>
                            <th>Provider</th>
                            <th>Game</th>
                            <th>Bet</th>
                            <th>Balance</th>
                            <th>Total Debit</th>
                            <th>Total Credit</th>
                            <th>Target RTP</th>
                            <th>Real RTP</th>
                            <th>Status</th>
                            <th>Action</th>
                        </tr>
                        </thead>

                        <!-- 🔥 PENTING -->
                        <tbody id="onlineUsers">
                            <tr>
                                <td colspan="12" class="text-center">Loading...</td>
                                <td>
    <button class="btn btn-sm btn-primary"
        onclick="openCallModal(
            '${p.user_code}',
            '${p.provider_code}',
            '${p.game_code}',
            ${p.bet}
        )">
        Call Action
    </button>
</td>
                            </tr>
                        </tbody>

                    </table>
                </div>

            </div>
        </div>
    </div>
</div>


<div class="modal fade" id="callModal" tabindex="-1">
  <div class="modal-dialog modal-dialog-centered">
    <div class="modal-content bg-dark text-white">

      <div class="modal-header">
        <h5 class="modal-title">Call Apply</h5>
        <button class="close text-white" data-dismiss="modal">&times;</button>
      </div>

      <div class="modal-body">

        <input type="hidden" id="call_user">
        <input type="hidden" id="call_provider">
        <input type="hidden" id="call_game">

        <div class="form-group">
          <label>User Code</label>
          <input class="form-control" id="call_user_view" disabled>
        </div>

        <div class="form-group">
          <label>Provider</label>
          <input class="form-control" id="call_provider_view" disabled>
        </div>

        <div class="form-group">
          <label>Game Code</label>
          <input class="form-control" id="call_game_view" disabled>
        </div>

        <div class="form-group">
          <label>Bet</label>
          <input class="form-control" id="call_bet" disabled>
        </div>

        <div class="form-group">
          <label>Call List</label>
          <select class="form-control" id="call_list">
            <option>Loading...</option>
          </select>
        </div>

      </div>

      <div class="modal-footer">
        <button class="btn btn-secondary" data-dismiss="modal">Cancel</button>
        <button class="btn btn-success" onclick="applyCall()">Apply</button>
      </div>

    </div>
  </div>
</div>


<script>
function loadOnlineUsers() {
    fetch('../template/page/users_online/ajax_online_user.php')
        .then(res => res.json())
        .then(res => {
            const tbody = document.getElementById('onlineUsers');
            tbody.innerHTML = '';

            if (!res || res.status !== 1 || !Array.isArray(res.data) || res.data.length === 0) {
                tbody.innerHTML = `
                    <tr>
                        <td colspan="11" class="text-center text-danger">
                            Gagal load data
                        </td>
                    </tr>`;
                return;
            }

            res.data.forEach((p, i) => {
    tbody.innerHTML += `
    <tr>
        <td>${i + 1}</td>
        <td>${p.user_code}</td>
        <td>${p.provider_code}</td>
        <td>${p.game_code}</td>
        <td>Rp ${Number(p.bet).toLocaleString('id-ID')}</td>
        <td>Rp ${Number(p.balance).toLocaleString('id-ID')}</td>
        <td>Rp ${Number(p.total_debit).toLocaleString('id-ID')}</td>
        <td>Rp ${Number(p.total_credit).toLocaleString('id-ID')}</td>
        <td>${p.target_rtp}%</td>
        <td>
            <span class="badge badge-${p.real_rtp >= p.target_rtp ? 'success' : 'danger'}">
                ${Number(p.real_rtp).toFixed(2)}%
            </span>
        </td>
        <td>
            <span class="badge badge-success">ON GAME</span>
        </td>
        <td>
            <button class="btn btn-sm btn-primary"
                onclick="openCallModal(
                    '${p.user_code}',
                    '${p.provider_code}',
                    '${p.game_code}',
                    ${p.bet}
                )">
                Call Action
            </button>
        </td>
    </tr>
    `;
});
        })
        .catch(err => {
            document.getElementById('onlineUsers').innerHTML = `
                <tr>
                    <td colspan="11" class="text-center text-danger">
                        JS Error: ${err}
                    </td>
                </tr>`;
        });
}

// 🔄 load pertama
loadOnlineUsers();

// 🔁 auto refresh tiap 5 detik (optional)
setInterval(loadOnlineUsers, 5000);
</script>


<script>
function openCallModal(user, provider, game, bet) {
    document.getElementById('call_user').value = user;
    document.getElementById('call_provider').value = provider;
    document.getElementById('call_game').value = game;

    call_user_view.value = user;
    call_provider_view.value = provider;
    call_game_view.value = game;
    call_bet.value = bet;

    $('#callModal').modal('show');

    loadCallList(provider, game);
}

function loadCallList(provider, game) {
    fetch('../template/page/users_online/ajax_online_user.php?action=call_list', {
        method: 'POST',
        headers: {'Content-Type': 'application/json'},
        body: JSON.stringify({
            provider_code: provider,
            game_code: game
        })
    })
    .then(r => r.json())
    .then(res => {
        const sel = document.getElementById('call_list');
        sel.innerHTML = '';

        if(res.status !== 1 || !res.calls){
            sel.innerHTML = `<option>Error load call list</option>`;
            return;
        }

        res.calls.forEach(c => {
            sel.innerHTML += `
              <option value="${c.rtp}">
                RTP ${c.rtp} (${c.call_type})
              </option>`;
        });
    });
}

function applyCall() {
    const data = {
        user_code: call_user.value,
        provider_code: call_provider.value,
        game_code: call_game.value,
        call_rtp: call_list.value
    };

    fetch('../template/page/users_online/ajax_online_user.php?action=call_apply', {
        method: 'POST',
        headers: {'Content-Type':'application/json'},
        body: JSON.stringify(data)
    }) 
    .then(r=>r.json())
    .then(res=>{
        if(res.status==1){
            alert('CALL SUCCESS');
            $('#callModal').modal('hide');
        } else {
            alert(res.msg || 'CALL FAILED');
        }
    });
}
</script>