<script>
    $(function() {
        $('#filterCategory').val("{{ Request()->category ?? 'premium' }}");
        $('#filterProxies').val("{{ Request()->proxies ?? 'trojan' }}");
        $('#filterCountry').val("{{ Request()->country ?? 'id' }}");
        $('#createAccount').on('click', function() {
            $('#modalFilterAccount').modal('show');
        });
        $('#searchAccountFilter').on('click', function() {
            category = $('#filterCategory').val();
            proxies = $('#filterProxies').val();
            country = $('#filterCountry').val();
            location.href = "{{ route('member.product-list') }}" + '?category=' + category +
                '&proxies=' + proxies + '&country=' + country;
        });
        $(document).off('click', '.detail-account').on('click', '.detail-account', function(e) {
            e.preventDefault();
            var id = $(this).data('id') ?? 0;
            $('#modalDetailAccountIP').html('***************');
            $('.btn-ip').removeAttr('data-id');
            $('.generate-uuid').removeAttr('data-id');
            $('.btn-ip').attr('data-id', id);
            $('.generate-uuid').attr('data-id', id);
            $.ajax({
                type: 'GET',
                url: "{{ route('member.product-detail', '') }}/" + id,
                success: (res) => {
                    console.log(res);
                    $('#modalDetailAccount').modal('show');
                    $('#modalDetailAccountStatus').html(res.response.deleted_at ==
                        null ?
                        '<strong class="text-success">active</strong>' :
                        '<strong class="text-success">disabled</strong>');
                    $('#modalDetailAccountMaxSession').html(res.response
                        .max_session + ' IP');
                    $('#modalDetailAccountServerName').html(res.response
                        .vps_name);
                    $('#modalDetailAccountProxy').html(res.response
                        .vps_proxies_name);
                    $('#modalDetailAccountCity').html(res.response
                        .vps_country_name);
                    $('#modalDetailAccountServerHost').html(res.response
                        .vps_hostname);
                    $('#modalDetailAccountUsername').html(res.response
                        .username);
                    $('#modalDetailAccountUUID').html(res.response.password);
                    $('#modalDetailAccountChargeCredit').html(res.response
                        .price_hour);
                    $('#modalDetailAccountChargePoint').html(res.response
                        .balance);
                    $('#modalDetailAccountBandwidthUsage').html(res.response
                        .used_traffic);

                    var resultHtml = '';
                    res.response.accounts.forEach(function(url) {
                        var decodedUrl = decodeURIComponent(
                            url);
                        var regex =
                            /#\((.*?)\)\s*\[(.*?)\]\s*(TLS|nTLS)/;
                        var match = decodedUrl.match(
                            regex);
                        if (match) {
                            resultHtml +=
                                `<a class="dropdown-item copy-btn" href="#" data-url="${url}">
                                    [${match[2].toUpperCase()}] ${match[3].toUpperCase()} ✅
                                </a>`;
                        }
                    });
                    $('#modalDetailAccountConfig').html(resultHtml);
                },
                error: function(e) {
                    toastr.error(e);
                },
            });
        });
        $(document).off('click', '.btn-ip').on('click', '.btn-ip', function(e) {
            e.preventDefault();
            var id = $(this).data('id') ?? 0;
            $.ajax({
                type: 'GET',
                url: "{{ route('member.vps-server-ipaddress', '') }}/" + id,
                success: (res) => {
                    var textToCopy = res.response.ipaddress;
                    $('#modalDetailAccountIP').html(textToCopy);
                    copyToClipboard(textToCopy).then(function() {
                        Swal.fire({
                            title: "Success!",
                            text: `IP Berhasil di copy : [${textToCopy}]`,
                            icon: "success"
                        }).then((result) => {
                            toastr.success('Text copied to clipboard');
                        });
                    }).catch(function(err) {
                        toastr.error('Failed to copy text');
                    });
                },
                error: function(res) {
                    msg = res.responseJSON.metadata.message
                    if (msg) {
                        toastr.options = {
                            "closeButton": true,
                            "positionClass": "toast-top-right",
                            "onclick": function() {
                                window.open('https://t.me/LingVPN',
                                    '_blank');
                            }
                        };
                        toastr.error(msg);
                    }
                },
            });
        });
        $(document).off('click', '.generate-uuid').on('click', '.generate-uuid', function(e) {
            e.preventDefault();
            var id = $(this).data('id') ?? 0;
            $.ajax({
                type: 'POST',
                url: "{{ route('member.product-uuid') }}",
                data: {
                    id: id,
                    _token: "{{ csrf_token() }}"
                },
                success: (res) => {
                    if (res.response) {
                        $('#modalDetailAccountUUID').html(res.response);
                        toastr.success('UUID generated');
                    } else {
                        toastr.error('UUID failed to generate');
                    }
                },
                error: function(res) {
                    msg = res.responseJSON.metadata.message
                    if (msg) {
                        toastr.error(msg);
                    }
                },
            });
        });

        function copyToClipboard(text) {
            if (navigator.clipboard && window.isSecureContext) {
                // Browser mendukung navigator.clipboard
                return navigator.clipboard.writeText(text);
            } else {
                // Fallback untuk browser Android/WebView
                let textArea = document.createElement("textarea");
                textArea.value = text;
                textArea.style.position = "fixed"; // Hindari scroll
                textArea.style.opacity = "0";
                document.body.appendChild(textArea);
                textArea.focus();
                textArea.select();

                return new Promise((resolve, reject) => {
                    if (document.execCommand('copy')) {
                        document.body.removeChild(textArea);
                        resolve();
                    } else {
                        document.body.removeChild(textArea);
                        reject();
                    }
                });
            }
        }
        $(document).off('click', '.copy-btn').on('click', '.copy-btn', function(e) {
            e.preventDefault();
            var targetId = $(this).data('target');
            var textToCopy = $('#' + targetId).text().trim();
            var urlToCopy = $(this).data('url');
            if (textToCopy === '') {
                textToCopy = urlToCopy;
            }
            copyToClipboard(textToCopy).then(function() {
                toastr.success('Text copied to clipboard');
            }).catch(function(err) {
                toastr.error('Failed to copy text');
            });
        });
    });
</script>
