/**
 * CustomAstDB UCP widget client.
 *
 * Follows the same pattern as the FreePBX core `donotdisturb` and
 * `callforward` UCP widgets (see /var/www/html/admin/modules/donotdisturb/ucp/assets/js/global.js):
 *   - Extends UCPMC so the framework discovers + instantiates this class
 *   - displayWidget(widget_id, dashboard_id) binds DOM event handlers
 *   - AJAX always goes through $.post(UCP.ajaxUrl, ...) with module+command in the payload
 *   - poll(data) reconciles external state changes back into the widget DOM
 *
 * Selectors scope by .grid-stack-item[data-rawname=customastdb] so multiple
 * widget instances (one per assigned extension) don't cross-talk.
 */
var CustomastdbC = UCPMC.extend({
    init: function () {
        this.stopPropagation = {};
    },

    prepoll: function () {
        var exts = [];
        $(".grid-stack-item[data-rawname=customastdb]").each(function () {
            exts.push($(this).data("widget_type_id"));
        });
        return exts;
    },

    poll: function (data) {
        var self = this;
        $.each(data.states || {}, function (ext, state) {
            if (self.stopPropagation[ext]) return true;
            var $w = $(".grid-stack-item[data-rawname=customastdb][data-widget_type_id='" + ext + "']:visible");
            if (!$w.length) return true;

            // DND toggle
            var $dnd = $w.find("input.customastdb-dnd-toggle");
            if ($dnd.length && $dnd.is(":checked") !== !!state.dnd) {
                self.stopPropagation[ext] = true;
                $dnd.bootstrapToggle(state.dnd ? 'on' : 'off');
                self.stopPropagation[ext] = false;
            }

            // CF/CFB/CFU text fields — DO NOT touch a field the user is
            // actively typing in; the poll reconciler would otherwise
            // overwrite mid-input with the (stale) server value and eat
            // the typed characters. Skip focused fields AND fields the
            // user has dirtied since the last save (tracked by a marker
            // class set in the input handler below).
            $w.find("input.customastdb-cf-field").each(function () {
                var $f = $(this);
                if ($f.is(":focus") || $f.hasClass('customastdb-cf-dirty')) return;
                var type = ($f.data('type') || '').toLowerCase();
                var val = (state[type] !== undefined && state[type] !== false) ? state[type] : '';
                if ($f.val() !== val) $f.val(val);
            });
        });
    },

    displayWidget: function (widget_id, dashboard_id) {
        var self = this;
        var $root = $(".grid-stack-item[data-id='" + widget_id + "'][data-rawname=customastdb]");
        if (!$root.length) return;
        var extension = $root.data("widget_type_id");

        // Mark CF fields dirty as the user types so poll() doesn't clobber
        // in-progress input. Cleared on successful Save / Clear All.
        $root.find("input.customastdb-cf-field")
            .off('input.customastdb').on('input.customastdb', function () {
                $(this).addClass('customastdb-cf-dirty');
            });

        // DND toggle — bound once per widget instance
        $root.find("input.customastdb-dnd-toggle").off('change.customastdb').on('change.customastdb', function () {
            if (self.stopPropagation[extension]) return;
            var checked = $(this).is(':checked');
            self.stopPropagation[extension] = true;
            $.post(UCP.ajaxUrl, {
                module: 'customastdb',
                command: 'setDnd',
                ext: extension,
                enabled: checked ? '1' : '0'
            }, function (res) {
                if (res && res.message) {
                    UCP.showAlert(res.message, res.status ? 'success' : 'danger');
                }
            }, 'json').always(function () {
                self.stopPropagation[extension] = false;
            });
        });

        // Save CF — fire one request per field, aggregate the outcome
        $root.find(".customastdb-save-cf").off('click.customastdb').on('click.customastdb', function () {
            var $fields = $root.find("input.customastdb-cf-field");
            var pending = $fields.length;
            var failed  = 0;
            $fields.each(function () {
                var $f = $(this);
                $.post(UCP.ajaxUrl, {
                    module: 'customastdb',
                    command: 'setCf',
                    ext: extension,
                    type: $f.data('type'),
                    number: $f.val()
                }, function (res) {
                    if (!res || !res.status) failed++;
                    else $f.removeClass('customastdb-cf-dirty');
                }, 'json').always(function () {
                    pending--;
                    if (pending === 0) {
                        if (failed > 0) UCP.showAlert(failed + ' CF save(s) failed.', 'danger');
                        else            UCP.showAlert('Call Forward settings saved.', 'success');
                    }
                });
            });
        });

        // Clear all — single AJAX, then blank the fields locally
        $root.find(".customastdb-clear-cf").off('click.customastdb').on('click.customastdb', function () {
            if (!confirm('Clear all Call Forward destinations for ' + extension + '?')) return;
            $.post(UCP.ajaxUrl, {
                module: 'customastdb',
                command: 'clearCf',
                ext: extension
            }, function (res) {
                if (res && res.status) {
                    $root.find("input.customastdb-cf-field").val('').removeClass('customastdb-cf-dirty');
                    UCP.showAlert(res.message || 'All Call Forwards cleared.', 'success');
                } else {
                    UCP.showAlert((res && res.message) || 'Clear failed.', 'danger');
                }
            }, 'json');
        });
    },

    displaySimpleWidget: function (widget_id) {
        return this.displayWidget(widget_id);
    }
});
