/**
 *
 * You can write your JS code here, DO NOT touch the default style file
 * because it will make it harder for you to update.
 *
 */

"use strict";

function gatherWithdrawalInfo(id) {
    $("#reject_reason_section").removeClass("flex");
    $("#reject_reason_section").css("display", "none");
    if (id > 0) {
        $('input[name="reject_id"]').val(id);
        $.ajax({
            headers: {
                "X-CSRF-TOKEN": $('meta[name="csrf-token"]').attr("content"),
            },
            url: "/admin/withdrawal/info",
            method: "POST",
            data: {
                id: id,
            },
            success: function (data) {
                if (data.status == "success") {
                    $("#formModal").html("Withdrawal Information");
                    $("#actual_name").html(data.withdrawal.name);
                    $("#bank_name").html(data.withdrawal.bank_name);
                    $("#upi").html(data.withdrawal.upi);
                    $("#bank_account").html(data.withdrawal.account);
                    $("#ifsc").html(data.withdrawal.ifsc);
                    $("#mobile").html(data.withdrawal.mobile);
                    $("#email").html(data.withdrawal.email);
                    $("#total_withdrawal").html(data.total_withdrawal);
                    $("#total_recharge").html(data.total_recharge);
                    $("#total_rewards").html(data.total_bonus);
                    $("#total_bet").html(data.total_bet);
                    $("#total_betting").html(data.total_betting);
                    $("#total_commission").html(data.total_commission);
                    $("#total_interest").html(data.total_interest);
                    $("#state").html(data.withdrawal.state);
                    $("#city").html(data.withdrawal.city);
                    $("#address").html(data.withdrawal.address);
                    if (data.withdrawal_status == 2) {
                        $("#reject_reason_section").addClass("flex");
                        $("#rejection_reason").html(data.rejection_reason);
                    }
                    if (data.withdrawal_status == 0) {
                        $("#withdrawal_actions").html(
                            `<a href="/admin/withdrawal/agree/${id}" class="text-decoration-none"><div class="badge badge-primary">Agree</div></a>&nbsp;<a href="/admin/withdrawal/approve/${id}" class="text-decoration-none"><div class="badge badge-success">Approve</div></a>&nbsp;<a href="/admin/withdrawal/accept-api/${id}" class="text-decoration-none"><div class="badge badge-success">API PAYOUT (APPROVE)</div></a>&nbsp;<button onclick="withdrawRejectReason()" type="button" class="badge badge-warning" style="border:none;" data-toggle="modal" data-target="#exampleModal1">Reject</button>`
                        );
                    } else {
                        $("#withdrawal_actions").html(
                            `<a href="/admin/withdrawal/approve/${id}" class="text-decoration-none"><div class="badge badge-success">Approve</div></a>&nbsp;<button type="button"
                                                    onclick="withdrawRejectReason()" class="badge badge-warning" style="border:none;" data-toggle="modal"
                                                    data-target="#exampleModal1">Reject</button>`
                        );
                    }
                }
            },
        });
    }
}

function withdrawRejectReason() {
    $("#mainModal").click();
}

function replyToComplaint(id) {
    $("input[name='id']").val(id);
}

// function fetchBettingRecords(tab, type = null) {
//     let game_code_manual = $("input[name='game_code_manual']").val();

//     $.ajax({
//         headers: {
//             "X-CSRF-TOKEN": $('meta[name="csrf-token"]').attr("content"),
//         },
//         url: "/admin/betting/records",
//         method: "POST",
//         data: {
//             tab: tab,
//         },
//         success: function (data) {
//             if (data.status == "success") {
//                 let html = "";
//                 // let user_count = 0;
//                 $.each(data.game_points, function (key, point) {
//                     html += `<tr>
//                                 <td>
//                                     ${point.html}
//                                 </td>
//                                 <td class="text-center">${point.game_code}</td>
//                                 <td class="text-center">${point.count}</td><td class="text-center">${point.total_amount}</td>`;

//                     if (game_code_manual != "" && game_code_manual == point.game_code) {
//                         html += `<td class="text-center"><input type="radio" name="select_game_code" value="${point.game_code}" checked></td></tr>`;
//                     } else {
//                         html += `<td class="text-center"><input type="radio" name="select_game_code" value="${point.game_code}"></td></tr>`;
//                     }
//                 });
//                 if (type != null) {
//                     // let second_reference = data.date_now;
//                     let check_difference = data.last_game_time - data.date_now;
//                     console.log("check_difference " + check_difference);
//                     if (check_difference < 0) {
//                         return;
//                     }
//                     $("#manual_no").prop("checked", true);
//                     reference = data.last_game_time;
//                     $("#active_game_id").html(data.gameid.game_id);
//                     update = false;
//                 }
//                 $("#records_table").html(html);
//                 $('input[type=radio][name="select_game_code"]').change(
//                     function () {
//                         $("input[name='game_code_manual']").val($(this).val());
//                         setGameSettings();
//                     }
//                 );
//             }
//         },
//     });
// }

function updateBettingRecords(tab) {
    let game_code_manual = $("input[name='game_code_manual']").val();
    $.ajax({
        headers: {
            "X-CSRF-TOKEN": $('meta[name="csrf-token"]').attr("content"),
        },
        url: "/admin/betting/records",
        method: "POST",
        data: {
            tab: tab,
        },
        success: function (data) {
            if (data.status == "success") {
                let html = "";
                $.each(data.game_points, function (key, point) {
                    html += `<tr>
                                <td>${point.html}</td>
                                <td class="text-center">${point.game_code}</td>
                                <td class="text-center">${point.count}</td>
                                <td class="text-center">${point.total_amount}</td>`;

                    if (
                        game_code_manual != "" &&
                        game_code_manual == point.game_code
                    ) {
                        html += `<td class="text-center"><input type="radio" name="select_game_code" value="${point.game_code}" checked></td></tr>`;
                    } else {
                        html += `<td class="text-center"><input type="radio" name="select_game_code" value="${point.game_code}"></td></tr>`;
                    }
                });
                let updated_tab = $('input[name="tabValue"]').val();
                if (tab == updated_tab) {
                    $("#records_table").html(html);
                    $('input[type=radio][name="select_game_code"]').change(
                        function () {
                            $("input[name='game_code_manual']").val(
                                $(this).val()
                            );
                            setGameSettings();
                        }
                    );
                }
            }
        },
    });
}

function betting_users_count_with_code(bettings, game_code) {
    let count = 0;
    if (bettings == null) {
        return count;
    }
    $.each(bettings, function (key, betting) {
        if (betting.code == game_code && betting.type == "individual") {
            count++;
        } else if (betting.type == "join") {
            let betting_codes = betting.code.split(",");
            betting_codes = betting_codes.slice(0, -1);
            let lowest = betting_codes.reduce((a, b) => Math.min(a, b));
            if (lowest == game_code) {
                count++;
            }
        }
    });
    return count;
}

function betting_amount_with_code(bettings, game_code) {
    let amount = 0;
    if (bettings == null) {
        return amount;
    }
    $.each(bettings, function (key, betting) {
        if (betting.code == game_code && betting.type == "individual") {
            if (betting.code == 0 || betting.code == 5) {
                amount += betting.amount * number_two_color_multiple;
            } else {
                amount += betting.amount * number_one_color_multiple;
            }
        } else if (betting.type == "join") {
            let betting_codes = betting.code.split(",");
            betting_codes = betting_codes.slice(0, -1);
            let lowest = betting_codes.reduce((a, b) => Math.min(a, b));
            if (lowest == game_code) {
                amount += betting.amount;
            }
        }
    });
    return amount;
}

function setGameSettings() {
    let manual = $("input[name='game_manual']").val();
    let code = $("input[name='game_code_manual']").val();
    let tabValue = $("input[name='tabValue']").val();

    console.log("manual " + manual);

    if (tabValue == "") {
        toastShow("Please select tab");
        return;
    }
    if (manual == 1) {
        if (code == "") {
            toastShow("Please select game code");
            return;
        }
    }

    let tab_in_words = "1 Minute";
    if (tabValue == "three_minute") {
        tab_in_words = "3 Minute";
    } else if (tabValue == "five_minute") {
        tab_in_words = "5 Minute";
    } else if (tabValue == "two_minute") {
        tab_in_words = "2 Minute";
    }
    $.ajax({
        headers: {
            "X-CSRF-TOKEN": $('meta[name="csrf-token"]').attr("content"),
        },
        url: "/admin/set/gameSettings",
        method: "POST",
        data: {
            manual: manual,
            code: code,
            tab: tabValue,
        },
        success: function (data) {
            if (data.status == "success") {
                toastShow(
                    "Settings updated. Tab: " +
                        tab_in_words +
                        " Manual: " +
                        manual +
                        " Code: " +
                        code
                );
            } else {
                toastShow("Settings updated failed");
            }
        },
    });
}

function gatherOrderInfo(id) {
    if (id > 0) {
        $.ajax({
            headers: {
                "X-CSRF-TOKEN": $('meta[name="csrf-token"]').attr("content"),
            },
            url: "/admin/order/info",
            method: "POST",
            data: {
                id: id,
            },
            success: function (data) {
                if (data.status == "success") {
                    let order = data.order;
                    $("#formModal").html("Order Information");
                    $("#product_name").html(order.product.title);
                    $("#user_mobile").html(order.user.mobile);
                    $("#amount").html(order.amount);
                    $("#state").html(order.user.state);
                    $("#city").html(order.user.city);
                    $("#address").html(order.user.address);
                    let actions_html = `<div class="form-group">
                                <select class="form-control form-control-sm" name="orderStatus" onchange="updateOrderStatus(${order.id})">`;
                    if (order.status == "Processing") {
                        actions_html += `<option value="Processing" checked>Processing</option>
                        <option value="Undelivered">Undelivered</option>
                        <option value="Unreceived">Unreceived</option>
                        <option value="Success">Success</option>`;
                    } else if (order.status == "Undelivered") {
                        actions_html += `<option value="Processing">Processing</option>
                        <option value="Undelivered" checked>Undelivered</option>
                        <option value="Unreceived">Unreceived</option>
                        <option value="Success">Success</option>`;
                    } else if (order.status == "Unreceived") {
                        actions_html += `<option value="Processing">Processing</option>
                        <option value="Undelivered">Undelivered</option>
                        <option value="Unreceived" checked>Unreceived</option>
                        <option value="Success">Success</option>`;
                    } else if (order.status == "Success") {
                        actions_html += `<option value="Processing">Processing</option>
                        <option value="Undelivered">Undelivered</option>
                        <option value="Unreceived">Unreceived</option>
                        <option value="Success" checked>Success</option>`;
                    }
                    actions_html += `</select></div>`;
                    $("#order_actions").html(actions_html);
                }
            },
        });
    }
}

function updateOrderStatus(id) {
    let status = $("select[name='orderStatus']").val();
    $.ajax({
        headers: {
            "X-CSRF-TOKEN": $('meta[name="csrf-token"]').attr("content"),
        },
        url: "/admin/order/update",
        method: "POST",
        data: {
            id: id,
            status: status,
        },
        success: function (data) {
            if (data.status == "success") {
                $("#status_" + id).html(status);
                $("#modal_dismiss").click();
            }
        },
    });
}

$("#tradeHistoryForm").on("submit", function (e) {
    e.preventDefault();

    let user_mobile = $("input[id='user_mobile']").val();
    console.log(user_mobile);
    if (user_mobile == null || user_mobile == "") {
        $("#user_error").html("This field is required.");
        return;
    }
    $("#pagination").addClass("d-none");

    $("#user_error").html("");
    $("#record_table").html(
        `<tr><td class="text-center" colspan="7">Loading...</td></tr>`
    );

    let type = $("select[id='bet_type']").val();

    $.ajax({
        headers: {
            "X-CSRF-TOKEN": $('meta[name="csrf-token"]').attr("content"),
        },
        method: "POST",
        url: "/admin/trade-history/search",
        data: {
            user_mobile: user_mobile,
            type: type,
        },
        success: function (response) {
            if (response.status == "success") {
                let betting = response.betting;
                let html = "";
                if (response.betting.length > 0) {
                    $.each(betting, function (index, bet) {
                        html += `<tr>
                        <td>${bet.id}</td>
                        <td>${bet.game_id}</td>
                        <td>${bet.user.mobile}</td>
                        <td>${bet.amount}</td>`;
                        if (bet.status == 0) {
                            html += `<td>Wait</td>`;
                        } else {
                            if (bet.result == 1) {
                                html += `<td class="success">Won</td>`;
                            } else {
                                html += `<td class="error">Lost</td>`;
                            }
                        }
                        if (bet.winning_amount != null) {
                            html += `<td>${bet.winning_amount}</td>`;
                        } else {
                            html += `<td>0</td>`;
                        }
                        html += `<td>${bet.created}</td>
                        </tr>`;
                    });
                } else {
                    html = `<tr><td colspan="7" class="text-center">No Data Found.</td></tr>`;
                }
                $("#record_table").html(html);
            } else {
            }
        },
    });
});

$("#bonusHistoryForm").on("submit", function (e) {
    e.preventDefault();

    let user_mobile = $("input[id='user_mobile']").val();
    if (user_mobile == null || user_mobile == "") {
        $("#user_error").html("This field is required.");
        return;
    }
    $("#pagination").addClass("d-none");

    $("#user_error").html("");
    $("#record_table").html(
        `<tr><td class="text-center" colspan="5">Loading...</td></tr>`
    );

    $.ajax({
        headers: {
            "X-CSRF-TOKEN": $('meta[name="csrf-token"]').attr("content"),
        },
        method: "POST",
        url: "/admin/bonus-history/search",
        data: {
            user_mobile: user_mobile,
        },
        success: function (response) {
            if (response.status == "success") {
                let bonuses = response.bonuses;
                let html = "";
                if (response.bonuses.length > 0) {
                    $.each(bonuses, function (index, bonus) {
                        html += `<tr>
                        <td>${bonus.id}</td>
                        <td>${bonus.bonus_given_to.mobile}</td>
                        <td>${bonus.bonus}</td>`;
                        if (bonus.level1 == 1) {
                            html += `<td>Level 1</td>`;
                        } else if (bonus.level2 == 1) {
                            html += `<td>Level 2</td>`;
                        } else if (bonus.level3 == 1) {
                            html += `<td>Level 3</td>`;
                        } else if (bonus.comment == "signin") {
                            html += `<td>Sign In</td>`;
                        } else if (bonus.comment == "redenvelope") {
                            html += `<td>Red Envelope</td>`;
                        } else {
                            html += `<td>Reward</td>`;
                        }
                        html += `<td>${bonus.created}</td>
                        </tr>`;
                    });
                } else {
                    html = `<tr><td colspan="5" class="text-center">No Data Found.</td></tr>`;
                }
                $("#record_table").html(html);
            } else {
            }
        },
    });
});

function toastShow(text) {
    console.log("toast show " + text);
    // Get the snackbar DIV
    var x = document.getElementById("snackbar");
    x.innerText = text;
    // Add the "show" class to DIV
    x.className = "show";

    // After 3 seconds, remove the show class from DIV
    setTimeout(function () {
        x.className = x.className.replace("show", "");
    }, 2000);
}

$("#commissionHistoryForm").on("submit", function (e) {
    e.preventDefault();
    let user_mobile = $("input[id='user_mobile']").val();
    if (user_mobile == null || user_mobile == "") {
        $("#user_error").html("This field is required.");
        return;
    }
    $("#pagination").addClass("d-none");

    $("#user_error").html("");
    $("#record_table").html(
        `<tr><td class="text-center" colspan="5">Loading...</td></tr>`
    );

    $.ajax({
        headers: {
            "X-CSRF-TOKEN": $('meta[name="csrf-token"]').attr("content"),
        },
        method: "POST",
        url: "/admin/commission-history/search",
        data: {
            user_mobile: user_mobile,
        },
        success: function (response) {
            if (response.status == "success") {
                let commissions = response.commissions;
                let html = "";
                if (response.commissions.length > 0) {
                    $.each(commissions, function (index, commission) {
                        html += `<tr>
                        <td>${++index}</td>
                        <td>${commission.commission_given_to.mobile}</td>
                        <td>${commission.commission}</td>`;
                        if (commission.level1 == 1) {
                            html += `<td>Level 1</td>`;
                        } else if (commission.level2 == 1) {
                            html += `<td>Level 2</td>`;
                        } else if (commission.level3 == 1) {
                            html += `<td>Level 3</td>`;
                        } else {
                            html += `<td>Reward</td>`;
                        }
                        html += `<td>${commission.created}</td>
                        </tr>`;
                    });
                } else {
                    html = `<tr><td colspan="5" class="text-center">No Data Found.</td></tr>`;
                }
                $("#record_table").html(html);
            } else {
            }
        },
    });
});

$("#interestHistoryForm").on("submit", function (e) {
    e.preventDefault();
    let user_mobile = $("input[id='user_mobile']").val();
    if (user_mobile == null || user_mobile == "") {
        $("#user_error").html("This field is required.");
        return;
    }
    $("#pagination").addClass("d-none");
    $("#user_error").html("");
    $("#record_table").html(
        `<tr><td class="text-center" colspan="5">Loading...</td></tr>`
    );

    $.ajax({
        headers: {
            "X-CSRF-TOKEN": $('meta[name="csrf-token"]').attr("content"),
        },
        method: "POST",
        url: "/admin/interest-history/search",
        data: {
            user_mobile: user_mobile,
        },
        success: function (response) {
            if (response.status == "success") {
                let interests = response.interests;
                let html = "";
                if (response.interests.length > 0) {
                    $.each(interests, function (index, interest) {
                        html += `<tr>
                        <td>${++index}</td>
                        <td>${interest.user.mobile}</td>
                        <td>${interest.amount}</td>
                        <td>${interest.interest}</td>`;
                        html += `<td>${interest.created}</td>`;
                        html += `</tr>`;
                    });
                } else {
                    html = `<tr><td colspan="5" class="text-center">No Data Found.</td></tr>`;
                }
                $("#record_table").html(html);
            } else {
            }
        },
    });
});

$("#rechargeHistoryForm").on("submit", function (e) {
    e.preventDefault();
    $("#pagination").addClass("d-none");
    let user_mobile = $("input[id='user_mobile']").val();
    if (user_mobile == null || user_mobile == "") {
        $("#user_error").html("This field is required.");
        return;
    }
    $("#user_error").html("");
    $("#record_table").html(
        `<tr><td class="text-center" colspan="5">Loading...</td></tr>`
    );

    $.ajax({
        headers: {
            "X-CSRF-TOKEN": $('meta[name="csrf-token"]').attr("content"),
        },
        method: "POST",
        url: "/admin/recharge-history/search",
        data: {
            user_mobile: user_mobile,
        },
        success: function (response) {
            if (response.status == "success") {
                console.log(response);
                // return;
                let recharges = response.recharges;
                let html = "";
                if (response.recharges.length > 0) {
                    $.each(recharges, function (index, recharge) {
                        html += `<tr>
                        <td>${recharge.id}</td>
                        <td>${recharge.user.mobile}</td>
                        <td>${recharge.type}</td>
                        <td>${recharge.ref_no}</td>
                        <td>${recharge.amount}</td>
                        <td>${recharge.created}</td>`;
                        if (recharge.status == 0) {
                            html += `<td>Pending</td>`;
                        } else if (recharge.status == 1) {
                            html += `<td>Approved</td>`;
                        } else if (recharge.status == 2) {
                            html += `<td>Rejected</td>`;
                        }
                        if (recharge.status !== 1) {
                            html += `<td><a href="/admin/recharge/approve/${recharge.id}" class="text-decoration-none">
                                                    <div class="badge badge-success">Approve</div>
                                                </a></td>`;
                        }
                        if (recharge.status !== 2) {
                            html += `<td><button type="button"
                                                        onclick="rejectRecharge(${recharge.id})"
                                                        class="badge badge-warning" style="border:none;" data-toggle="modal"
                                                        data-target="#exampleModal">Reject</button></td>`;
                        }
                        html += `</tr>`;
                    });
                } else {
                    html = `<tr><td colspan="8" class="text-center">No Data Found.</td></tr>`;
                }
                $("#recharge_table").html(html);
            } else {
            }
        },
    });
});

$("#withdrawalHistoryForm").on("submit", function (e) {
    e.preventDefault();
    $("#pagination").addClass("d-none");
    let user_mobile = $("input[id='user_mobile']").val();
    if (user_mobile == null || user_mobile == "") {
        $("#user_error").html("This field is required.");
        return;
    }
    $("#user_error").html("");
    $("#record_table").html(
        `<tr><td class="text-center" colspan="5">Loading...</td></tr>`
    );

    $.ajax({
        headers: {
            "X-CSRF-TOKEN": $('meta[name="csrf-token"]').attr("content"),
        },
        method: "POST",
        url: "/admin/withdrawal-history/search",
        data: {
            user_mobile: user_mobile,
        },
        success: function (response) {
            if (response.status == "success") {
                console.log(response);
                // return;
                let withdrawals = response.withdrawals;
                let html = "";
                if (response.withdrawals.length > 0) {
                    $.each(withdrawals, function (index, withdrawal) {
                        html += `<tr>
                        <td>${withdrawal.id}</td>
                        <td>${withdrawal.user.mobile}</td>
                        <td>${withdrawal.amount}</td>
                        <td>${withdrawal.payout}</td>
                        <td>${withdrawal.created}</td>`;
                        if (withdrawal.status == 0) {
                            html += `<td>Pending</td>`;
                        } else if (withdrawal.status == 1) {
                            html += `<td>Approved</td>`;
                        } else if (withdrawal.status == 2) {
                            html += `<td>Rejected</td>`;
                        } else if (withdrawal.status == 3) {
                            html += `<td>Agree</td>`;
                        }
                        html += `<td>
                        <button type="button" onclick="gatherWithdrawalInfo(${withdrawal.id})" class="badge badge-success" style="border:none;" data-toggle="modal"
                        data-target="#exampleModal"><i class="fas fa-ellipsis-h"></i></button>
                        <a href="/admin/withdrawal/delete/${withdrawal.id}" class="text-decoration-none"> <div class="badge badge-danger"><i class="material-icons font_size_14">delete</i></div></a>
                        </td>`;

                        html += `</tr>`;
                    });
                } else {
                    html = `<tr><td colspan="7" class="text-center">No Data Found.</td></tr>`;
                }
                $("#withdrawal_table").html(html);
            }
        },
    });
});
