<?php $__env->startSection('panel'); ?>
<div class="row">
    <div class="col-lg-12 mb-3">
        <div class="card">
            <div class="card-body">
                <h5 class="card-title">Call Manage</h5>
                <div class="card-datatable table-responsive">
                    <table id="playing-user-table" class="table center-all table-bordered table-sm">
                    </table>
                </div>
            </div>
        </div>
    </div>

    <div class="modal fade" id="call-modal" data-backdrop="static" tabindex="-1" role="dialog"
        aria-labelledby="call-modal" aria-hidden="true">
        <div class="modal-dialog" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="call-modal">Call Apply</h5>
                    <button type="button" class="close" data-bs-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
                <div class="modal-body form-group">
                    <div class="form-group">
                        <label>User Code</label>
                        <input type="text" id="user-code" class="form-control" disabled />
                    </div>
                    <div class="form-group">
                        <label>Provider</label>
                        <input type="text" id="provider-code" class="form-control" disabled />
                    </div>
                    <div class="form-group">
                        <label>Game Code</label>
                        <input type="text" id="game-code" class="form-control" disabled />
                    </div>
                    <div class="form-group">
                        <label>Bet</label>
                        <input type="number" id="bet-money" class="form-control" disabled />
                    </div>
                    <div class="form-group">
                        <label>Call Type</label>
                        <select class="form-select" id="call-type">
                            <option value="1">Common</option>
                            <option value="2">Buy</option>
                        </select>
                    </div>
                    <div class="form-group">
                        <label>Call Amount</label>
                        <input type="number" id="call-money" class="form-control" />
                    </div>
                    <div class="form-group" id="call-list-area">
                        <label>Call List</label>
                        <select class="form-select" id="call-list" onchange="calculateCallMoney()"></select>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" id="btn-call-apply"  class="btn btn-primary" onclick="handleApplyCall()">Apply</button>
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                </div>
            </div>
        </div>
    </div>
</div>
<?php $__env->stopSection(); ?>


<?php $__env->startPush('page-js'); ?>
<script>
    function convertNumber(number, lang = "en") {
        let resultString = "";

        if (number == 0) {
            return 0;
        }

        if (lang == "ko") {
            let inputNumber = number < 0 ? false : number;
            let unitWords = ["", "만", "억", "조", "경"];
            let splitUnit = 10000;
            let splitCount = unitWords.length;
            let resultArray = [];

            for (let i = 0; i < splitCount; i++) {
                let unitResult = (inputNumber % Math.pow(splitUnit, i + 1)) / Math.pow(splitUnit, i);
                unitResult = Math.floor(unitResult);
                if (unitResult > 0) {
                    resultArray[i] = unitResult;
                }
            }

            for (let i = 0; i < resultArray.length; i++) {
                if (!resultArray[i]) continue;
                resultString = String(resultArray[i]) + unitWords[i] + resultString;
            }
        } else {
            resultString = Number(number).toLocaleString();
        }

        return resultString;
    }

    function convertString(input, length) {
        if (input.length > length) {
            return input.slice(0, length) + " ...";
        } else {
            return input;
        }
    }

        let playingUserTable;
        let callResultTable;

        // 게임중인 유저 내역
        function drawPlayingUsers() {
            if (playingUserTable) {
                playingUserTable.ajax.reload();
            } else {
                playingUserTable = $("#playing-user-table").DataTable({
                    order: [
                        [1, "desc"]
                    ],
                    columns: [{
                            title: "No",
                            data: "no",
                            width: "60px",
                            orderable: false
                        },
                        {
                            title: "User Code",
                            data: "userCode",
                            orderable: false
                        },
                        {
                            title: "Provider",
                            data: "providerCode",
                            orderable: false
                        },
                        {
                            title: "Game Code",
                            data: "gameCode",
                            orderable: false
                        },
                        {
                            title: "Balance",
                            data: "balance",
                            orderable: false
                        },
                        {
                            title: "Bet",
                            data: "lastBet",
                            orderable: false
                        },
                        {
                            title: "Total Debit",
                            data: "totalDebit",
                            orderable: false
                        },
                        {
                            title: "Total Credit",
                            data: "totalCredit",
                            orderable: false
                        },
                        {
                            title: "Rtp(Target/Real)",
                            data: "rtp",
                            orderable: false
                        },
                        {
                            title: "Call Action",
                            data: "callAction",
                            orderable: false
                        },
                        {
                            title: "Control Rtp",
                            data: "rtpAction",
                            orderable: false
                        },
                    ],
                    columnDefs: [
        { className: 'dt-center', targets: '_all' },
    ],
                    ajax: {
                        url: "<?php echo e(route('admin.website.call-players')); ?>",
                        type: "GET",
                        dataSrc: function(res) {
                            if (res.data) {
                                for (let i = 0; i < res.data.length; i++) {
                                    res.data[i].no = Number(i + 1) + Number(0);
                                    res.data[i].userCode = convertString(res.data[i].user_code, 30);
                                    res.data[i].providerCode = convertString(res.data[i].provider_code, 30);
                                    res.data[i].gameCode = convertString(res.data[i].game_code, 30);
                                    res.data[i].balance = convertNumber(res.data[i].balance);
                                    res.data[i].lastBet = convertNumber(res.data[i].bet);
                                    res.data[i].totalDebit = convertNumber(res.data[i].total_debit);
                                    res.data[i].totalCredit = convertNumber(res.data[i].total_credit);
                                    res.data[i].rtp = convertString(res.data[i].target_rtp + " / " + res.data[i]
                                        .real_rtp, 30);
                                    res.data[i].callAction =
                                        `<button type="button" id="btn-call" class="btn btn-xs btn-primary inline-block" onclick="handleCallModal('${res.data[i].user_code}', '${res.data[i].provider_code}', '${res.data[i].game_code}', '${res.data[i].bet}')">Call Action</button>`;
                                    res.data[i].rtpAction =
                                        `<button type="button" id="btn-call-rtp" class="btn btn-xs btn-primary inline-block" onclick="handleControlRtp('${res.data[i].user_code}', '${res.data[i].provider_code}', '${res.data[i].target_rtp}')">Control Rtp</button>`;
                                }
                            }

                            return res.data;
                        },
                    },
                });
            }
        }

        function calculateCallMoney() {
                const rtp = $("#call-list").val();
                const betMoney = Number($("#bet-money").val());
                const applyCallMoney = (betMoney * Number(rtp)) / 100;

                $("#call-money").val(applyCallMoney);
            }

        function handleCallModal(userCode, providerCode, gameCode, betMoney) {
                $("#user-code").val(userCode);
                $("#provider-code").val(providerCode);
                $("#game-code").val(gameCode);
                $("#bet-money").val(betMoney);

                $("#call-list-area").show();
                $("#call-generate-money-area").hide();
                $("#call-money").prop("disabled", true);
                $("#btn-call-generate").hide();
                $("#btn-call").attr("disabled", true);

                let data = {
                    providerCode: providerCode,
                    gameCode: gameCode,
                };

                $.ajax({
                    type: "GET",
                    url: "<?php echo e(route('admin.website.call_list')); ?>",
                    data: data,
                    success: function (res) {
    // 1. Pastikan res adalah object, jika masih string, parse manual
    let data = (typeof res === 'string') ? JSON.parse(res) : res;
    
    console.log("Data Response:", data);

    // 2. Cek apakah properti status dan calls ada (mencegah undefined)
    if (data && String(data.status) === "1" && Array.isArray(data.calls)) {
        let callListHtml = "";

        // 3. Gunakan loop yang aman
        data.calls.forEach(function(call) {
            // Pastikan properti rtp ada di dalam object call
            if (call.hasOwnProperty('rtp')) {
                let rtpStr = String(call.rtp);
                let typeStr = call.call_type ? String(call.call_type) : 'Free';
                
                // Kalkulasi Times (String / 100)
                let timesValue = String(Number(rtpStr) / 100);

                callListHtml += `<option value="${rtpStr}">Bet ${timesValue} (${typeStr})</option>`;
            }
        });

        $("#call-list").html(callListHtml);

        if (typeof calculateCallMoney === "function") {
            calculateCallMoney();
        }

        $("#call-modal").modal("show");
    } else {
        console.error("Struktur data tidak valid atau calls kosong:", data);
        alert("Gagal memuat data: Struktur respon tidak sesuai.");
    }

    $("#btn-call").prop("disabled", false);
},
                    error: function () {
                        $("#btn-call").removeAttr("disabled");
                    },
                });
            }


            function handleApplyCall() {
    // Ambil tombol dan disable segera untuk mencegah double klik
    const btnSubmit = $("#btn-call-apply");
    btnSubmit.prop("disabled", true);

    // Ambil nilai dan pastikan berupa String
    const userCode = String($("#user-code").val());
    const providerCode = String($("#provider-code").val());
    const gameCode = String($("#game-code").val());
    const callType = String($("#call-type").val());
    
    // Konversi ke angka untuk perhitungan
    const betMoney = Number($("#bet-money").val());
    const rtp = Number($("#call-list").val());
    
    // Hitung Call Win/Money
    const calculatedWin = (rtp / 100) * betMoney;

    let data = {
        userCode: userCode,
        providerCode: providerCode,
        gameCode: gameCode,
        callRtp: String(rtp), // Konversi ke string
        callWin: String(calculatedWin.toFixed(2)), // Pastikan 2 desimal dalam bentuk string
        callType: callType,
    };

    $.ajax({
        type: "GET",
        url: "<?php echo e(route('admin.website.call_apply')); ?>",
        data: data,
        dataType: "json", // Pastikan mengharap respon JSON
        success: function (res) {
            // Gunakan String() untuk pengecekan status agar konsisten
            if (String(res.status) === "1") {
                iziToast.success({
                    title: 'Congrats!',
                    position: 'topRight',
                    message: 'Operation is done successfully.',
                });
                $("#call-modal").modal("hide");
            } else {
                iziToast.error({
                    title: 'Error!',
                    position: 'topRight',
                    message: res.msg || 'Terjadi kesalahan pada server.',
                });
            }
        },
        error: function (xhr) {
            iziToast.error({
                title: 'System Error',
                position: 'topRight',
                message: 'Tidak dapat terhubung ke server.',
            });
        },
        complete: function() {
            // Aktifkan kembali tombol apapun hasilnya (sukses/error)
            btnSubmit.prop("disabled", false);
        }
    });
}

            // 콜 취소
            function handleCallCancel(callId) {
                let data = {
                    callId: callId,
                };

                    $("#btn-call-cancel").attr("disabled", true);

                    $.ajax({
                        type: "POST",
                        url: "/api/call/cancel",
                        data: data,
                        success: function (res) {
                            if (res.status == 1) {
                                iziToast.success({
                title: 'Congrats!',
                position: 'topRight',
                message: 'Operation is done successfully.',
            });
                            }
                            $("#btn-call-cancel").removeAttr("disabled");
                        },
                        error: function () {
                            $("#btn-call-cancel").removeAttr("disabled");
                        },
                    });
            }


            function handleControlRtp(userCode, providerCode, rtp) {
                let targetRtp = prompt("Please input rtp. (0 ~ 95).", rtp);
                if (targetRtp == null) {
                    return;
                }

                if (targetRtp && targetRtp > 0) {
                    let data = {
                        userCode: userCode,
                        providerCode: providerCode,
                        rtp: targetRtp,
                    };

                    $("#btn-call-rtp").attr("disabled", true);

                    $.ajax({
                        type: "GET",
                        url: "<?php echo e(route('admin.website.rtp')); ?>",
                        data: data,
                        success: function (res) {
                            if (res.status == 1) {
                                drawPlayingUsers();
                                iziToast.success({
                title: 'Congrats!',
                position: 'topRight',
                message: 'Operation is done successfully.',
            });
                            }
                            $("#btn-call-rtp").removeAttr("disabled");
                        },
                        error: function () {
                            $("#btn-call-rtp").removeAttr("disabled");
                        },
                    });
                } else {
                    iziToast.error({
                title: 'error!',
                position: 'topRight',
                message: 'Please input rtp exactly.',
            });
                    return;
                }
            }

        drawPlayingUsers();
</script>
<script src="https://cdn.jsdelivr.net/npm/popper.js@1.12.9/dist/umd/popper.min.js"
    integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous">
</script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@4.0.0/dist/js/bootstrap.min.js"
    integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous">
</script>
<?php $__env->stopPush(); ?>
<?php $__env->startPush('page-css'); ?>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.0.0/dist/css/bootstrap.min.css"
    integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
<?php $__env->stopPush(); ?>

<?php echo $__env->make('backend.layouts.main', \Illuminate\Support\Arr::except(get_defined_vars(), ['__data', '__path']))->render(); ?><?php /**PATH /www/wwwroot/website/sewa/dibandung/resources/views/backend/call.blade.php ENDPATH**/ ?>