{% extends 'hiddify-flask-admin/list.html' %}

{% block body %}
{% if hconfig(ConfigEnum.telegram_bot_token) and g.bot %}
<div class="callout callout-success">
    <details>
        <summary>
            {{_("Send Message to User's Telegram")}}
        </summary>
        <div style="margin-top: 10px;">
            <button onclick="show_send_message('all')" type="button" class="btn hbtn bg-h-green">
                {{_("All Users")}}
            </button>
            <button onclick="show_send_message('active')" type="button" class="btn hbtn bg-h-green"
                style="margin-left: 5px;margin-right: 5px;">
                {{_("Active Users")}}
            </button>
            <button onclick="show_send_message('selected')" type="button" class="btn hbtn bg-h-green">
                {{_("Seleted Users")}}
            </button>
        </div>

        <div style="margin-top: 10px;">
            <button onclick="show_send_message('offline 1h')" type="button" class="btn  hbtn bg-h-red">
                {{_("Offline more than 1 hour")}}</button>
            <button onclick="show_send_message('offline 1d')" type="button" class="btn  hbtn bg-h-red"
                style="margin-left: 5px;">
                {{_("Offline more than 1 day")}}</button>
            <button onclick="show_send_message('offline 1w')" type="button" class="btn hbtn bg-h-red"
                style="margin-left: 5px;margin-right: 5px;">
                {{_("Offline more than 1 week")}}
            </button>
            <button onclick="show_send_message('expired')" type="button" class="btn hbtn bg-h-red">
                {{_("Expired Users")}}
            </button>
        </div>
    </details>
</div>
{% endif %}
{{super()}}

<div class="callout callout-success">
    {{_('adminuser.force_update_usage',link=hurl_for("admin.Actions:update_usage"))}}

</div>
<style>
    .table td {
        vertical-align: middle;
    }

    .col-name {
        white-space: nowrap;
    }

    .col-expiry_time {
        white-space: nowrap;
    }

    td.col-domain {
        /* direction:ltr */
    }

    .col-UserLinks a {
        text-overflow: ellipsis;
        white-space: nowrap;
        max-width: 100px;
        overflow: hidden;
    }

    .col-uuid span {
        text-overflow: ellipsis;
        white-space: nowrap;
        width: 80px;
        overflow: hidden;
        display: inline-block;
    }

    .table td {
        text-align: start;
    }
</style>
{% endblock %}
{% block tail_js%}
{{super()}}
<script>
    function get_selected_users_id() {
        let ids = [];
        $('input[type="checkbox"][name="rowid"]:checked[value][class="action-checkbox"]').each(function () {
            ids.push($(this).val());
        });
        return ids
    }
    function show_send_message(id) {
        if (id == 'selected') {
            id = get_selected_users_id();
            if (id.length == 0) {
                alert(`{{_("Please select at least one user")}}`);
                return
            }
        }
        bootbox.prompt({
            title: '{{_("Please type your message to send to the telegram:")}}',
            inputType: 'textarea',
            locale: '{{get_locale()}}',
            callback: function (msg) {
                console.log(msg);
                if (!msg) return
                // let dialog = bootbox.dialog({           
                //     message: '<p><i class="fas fa-spin fa-spinner"></i> {{_("Sending")}}</p>'
                // });
                $.ajax({
                    type: "POST",
                    url: '{{hurl_for("api_v1.sendmsgresource")}}',

                    data: JSON.stringify({ 'text': msg, 'id': id }),
                    contentType: "application/json",
                    dataType: "json",
                    error: function (jqx, status, error) {
                        // dialog.modal('hide');
                        // dialog.find('.bootbox-body').html(status+" "+error+" "+JSON.stringify(jqx));
                        $(document).Toasts('create', {
                            class: 'bg-danger',
                            position: "{{'topRight' if get_locale()=='fa' else 'topLeft'}}",
                            title: $('<div>').text(status + " " + error).html(),
                            body: $('<div>').text(JSON.stringify(jqx)).html(),
                            autohide: true,
                            delay: 5000
                        });
                        
                        console.error('API Error:', {
                            status: status,
                            error: error,
                            details: jqx
                        });
                    },
                    success: function (data) {
                        // dialog.modal('hide');
                        if (data['msg'] == 'success') {
                            $(document).Toasts('create', {
                                class: 'bg-success',
                                autohide: true,
                                position: "{{'topRight' if get_locale()=='fa' else 'topLeft'}}",
                                title: `{{_('Success')}}`,
                                body: `{{_("The message has been sent.")}}`
                            })
                        } else {
                            res = '{{_("Hover the user to see the reason")}}'
                            for (const uuid in data['res']) {
                                element = data['res'][uuid]
                                res += `<span class='badge badge-info' title='${element["error"]}'>${element['name']}</span>`
                            }

                            $(document).Toasts('create', {
                                class: 'bg-danger',
                                position: "{{'topRight' if get_locale()=='fa' else 'topLeft'}}",
                                title: `{{_('The message was not sent to')}}`,
                                body: res
                            })
                        }
                    },

                });

            }
        });
    }

</script>
{% endblock %}