<?php
// Copyright 1999-2023. Plesk International GmbH. All rights reserved.
?>

<script type="text/javascript">
//<![CDATA[
Jsw.onReady(function () {
    var updateControlsState = function (objectType, objectId, showLastPeak) {
        var url = '/outgoing-mail/messages/type/' + objectType + '/id/' + objectId + '/date/';

        if (!showLastPeak) {
            url += document.getElementById('outgoingMailMessagesDate').value;
        }

        new Ajax.Request(Jsw.prepareUrl(url), {
            method: 'get',
            onCreate: function () {
                document.getElementById('outgoingMailMessagesResult').innerHTML = (
                    '<div class="ajax-loading">' +
                        <?php echo $this->jsLmsg('loading'); ?> +
                    '</div>'
                );
            },
            onSuccess: function (transport) {
                if ('' == transport.responseText) {
                    return;
                }
                Jsw.render(document.getElementById('outgoingMailMessagesResult'), transport.responseText, 'inner');
                var currentElement = document.getElementById('exceeding-attempts-hint-item-' + objectType + '-' + objectId);
                var popupElement = document.getElementById('outgoingMailMessagesPopup');
                var pos = Element.cumulativeOffset(currentElement);
                var elWidth = Element.getWidth(popupElement);
                var elHeight = Element.getHeight(popupElement);
                var leftPos = (pos[0] - elWidth);
                var topPos = (pos[1] - (elHeight / 2) + 18);

                var topOffset = 0;
                var marginTop = parseFloat(popupElement.style.marginTop);
                var dimensions = document.viewport.getDimensions();
                var viewportOffset = currentElement.getBoundingClientRect();
                var popupBottom = (elHeight / 2 + 2 * Math.abs(marginTop) + viewportOffset.top);
                var popupTop = popupBottom - elHeight;
                var offset = dimensions.height - popupBottom;

                if (offset < 0) {
                    topPos += offset;
                    topOffset -= offset;
                    if (topPos < 0) {
                        topPos = 0;
                        topOffset -= topPos;
                    }
                } else {
                    if (topPos < 0) {
                        topOffset = topPos;
                        topPos = 0;
                        if (marginTop < 0 ) {
                            topOffset += marginTop;
                            topPos =  Math.abs(marginTop);
                        }
                    } else {
                        if (popupTop < 0) {
                            topPos -= popupTop;
                            topOffset += popupTop;
                        }
                    }
                }

                popupElement.classList.remove('collapsed');
                popupElement.style.left = leftPos + 'px';
                popupElement.style.top = topPos + 'px';

                var arrowElement = document.querySelector('.arrow');
                arrowElement.style.top = '50%';
                if (topOffset != 0) {
                    var topPercent = 50 * (elHeight + 2 * topOffset) / elHeight;
                    arrowElement.style.top = topPercent.toFixed(2) + '%';
                }
            },
        });
    };

    var showMessagesStats = function (event) {
        event.preventDefault();
        var ids = this.id.replace('exceeding-attempts-hint-item-', '').split('-');
        var dateElement = document.getElementById('outgoingMailMessagesDate');
        var handleDateChange = function () {
            updateControlsState(ids[0], ids[1]);
        };

        if (dateElement._handleDateChange) {
            dateElement.removeEventListener('change', dateElement._handleDateChange);
        }
        dateElement.addEventListener('change', handleDateChange);
        dateElement._handleDateChange = handleDateChange;
        updateControlsState(ids[0], ids[1], true);
        document.getElementById('outgoingMailMessagesPopup').classList.remove('collapsed', false);
    };

    new Jsw.Panel({
        cls: 'list-box',
        renderTo: 'main',
        items: [
            new Jsw.Hint({
                hint: <?php echo $this->hint
                ? $this->jsLmsg($this->hint, ['periodValue' => $this->periodValue, 'mailServerSettingsLink' => $this->mailServerSettingsLink ])
                : $this->jsLmsg($this->listType . ($this->isAdmin ? 'HintAdmin' : 'HintClient'), ['periodValue' => $this->periodValue, 'mailServerSettingsLink' => $this->mailServerSettingsLink ]);
                ?>
            }),
            new Jsw.List({
                id: 'admin-outgoing-mail-<?php echo $this->listType;?>-list',
                searchOveral: 'name',
                searchFilters: <?php echo Zend_Json::encode($this->list->getSearchFilterConfig()); ?>,
                data: <?php echo Zend_Json::encode($this->list->fetchData()); ?>,
                dataUrl: '/outgoing-mail/list-data/type/<?php echo $this->listType;?>',
                columns: [
                    {
                        header: <?php echo $this->list->jsLmsg('name');?>,
                        sortable: true,
                        dataIndex: 'name',
                        renderer: function (item) {
                            <?php if ('general' != $this->listType): ?>
                            return '<a href="' + Jsw.prepareUrl('/outgoing-mail/detail/type/' + item.objectType + '/id/' + item.id) + '">' + Jsw.escapeHtml(item.name) + '</a>';
                            <?php endif ?>

                            var icon = '';
                            switch (item.objectType) {
                                case 'mbox': icon = '<?php echo $this->skinUrl('/icons/16/plesk/mail.png') ?>'; break;
                                case 'domain': icon = '<?php echo $this->skinUrl('/icons/16/plesk/domain.png') ?>'; break;
                                case 'subscription': icon = '<?php echo $this->skinUrl('/icons/16/plesk/subs.png') ?>'; break;
                            }
                            var link = (
                                '<span class="b-indent-icon">' +
                                    '<img src="' + icon + '" alt="" title="">' +
                                '</span> ' +
                                '<a href="' + Jsw.prepareUrl('/outgoing-mail/detail/type/' + item.objectType + '/id/' + item.id) + '">' +
                                    Jsw.escapeHtml(item.name) +
                                '</a>'
                            );

                            return '<div class="b-indent">' + link + '</div>';
                        },
                    }, {
                        header: <?php echo $this->list->jsLmsg('maxOutgoingMessages');?>,
                        sortable: true,
                        dataIndex: 'maxOutgoingMessages',
                        renderer: function (item) {
                            var maxOutgoingMessages = 0 > item.maxOutgoingMessages
                                ? <?php echo $this->list->jsLmsg('limitValueUnlimited');?> : item.maxOutgoingMessages;
                            if (!item.isSpeciallySpecified) {
                                return maxOutgoingMessages;
                            }
                            var limitHintId = 'limit-hint-item-' + Jsw.escapeHtml(item.objectType) + '-' + item.id;
                            return '<a class="toggler limit-hint-info" id="' + limitHintId + '" href="#">' + maxOutgoingMessages + '</a>'
                        },
                    }, {
                        header: <?php echo $this->list->jsLmsg('numOfExceedingAttempts');?>,
                        sortable: true,
                        dataIndex: 'numOfExceedingAttempts',
                        renderer: function (item) {
                            if (0 == item.numOfExceedingAttempts) {
                                return '-';
                            }
                            var exceedingAttemptsHintId = 'exceeding-attempts-hint-item-' + Jsw.escapeHtml(item.objectType) + '-' + item.id;
                            return (
                                '<a class="toggler exceeding-attempts-hint-info" id="' + exceedingAttemptsHintId + '" href="#">' +
                                    item.numOfExceedingAttempts +
                                '</a>'
                            );
                        },
                    }, {
                        header: <?php echo $this->list->jsLmsg('lastAttemptAt');?>,
                        sortable: true,
                        dataIndex: 'lastAttemptAt',
                        renderer: function (item) {
                            if (!item.lastAttemptAt) {
                                return '-';
                            }
                            return Jsw.escapeHtml(item.lastAttemptAt);
                        },
                    }, {
                        header: <?php echo $this->list->jsLmsg('mailStatus');?>,
                        sortable: false,
                        dataIndex: 'mailStatus',
                        renderer: function (item) {
                            var status = 'ok';
                            var statusIcon = '<?php echo $this->skinUrl('/icons/16/plesk/ok.png') ?>';
                            var statusMsg = <?php echo $this->list->jsLmsg('mailStatusSending');?>;
                            var statusDescription = <?php echo $this->list->jsLmsg('mailStatusSendingDesc');?>;
                            if (!item.isSending) {
                                status = 'att';
                                statusIcon = '<?php echo $this->skinUrl('/icons/16/plesk/att.png') ?>';
                                statusMsg = <?php echo $this->list->jsLmsg('mailStatusNotSending');?>;
                                statusDescription = <?php echo $this->list->jsLmsg('mailStatusNotSendingDesc');?>;
                            }

                            var link = (
                                '<div class="b-indent">' +
                                    '<span class="b-indent-icon">' +
                                        '<span class="tooltipData">' + Jsw.escapeHtml(statusDescription) + '</span>' +
                                        '<img src="' + statusIcon + '" alt="' + status + '" title="">' +
                                    '</span> ' +
                                    '<nobr>' + Jsw.escapeHtml(statusMsg) + '</nobr>' +
                                '</div>'
                            );

                            return link;
                        }
                    }
                ],
                <?php if ($this->isAdmin): ?>
                operations: [
                    {
                       componentType: 'Jsw.SmallButton',
                       title: <?php echo $this->jsLmsg('refreshButton'); ?>,
                       addCls: 'sb-refresh',
                       href: '/outgoing-mail/refresh/type/' + '<?php echo $this->listType; ?>'
                    }
                ],
                <?php endif;?>
                onRedraw: function () {
                    document.querySelectorAll('a.toggler.exceeding-attempts-hint-info').forEach(function (hintElement) {
                        hintElement.addEventListener('click', showMessagesStats)
                    });
                    document.querySelectorAll('a.toggler.limit-hint-info').forEach(function (hintElement) {
                        var ids = hintElement.id.replace('limit-hint-item-', '').split('-');
                        new Jsw.DynamicPopupHint.Instance({
                            title: <?php echo $this->jsLmsg('controllers.outgoing-mail.limit-hint.title'); ?>,
                            waitMsg: <?php echo $this->jsLmsg('controllers.outgoing-mail.limit-hint.waitMessage'); ?>,
                            url: '/outgoing-mail/limit-hint/objId/' + ids[1] + '/objType/' + ids[0],
                            placement: 'right',
                            target: hintElement.id,
                        });
                    });
                },
            }),
        ],
    });

    document.getElementById('outgoingMailMessagesPopup').querySelector('.close').addEventListener('click', function () {
        document.getElementById('outgoingMailMessagesPopup').classList.toggle('collapsed');
    });
});
//]]>
</script>

<div class="popup-box left outgoing-messages-stats collapsed" id="outgoingMailMessagesPopup" >
<table class="popup-wrapper" cellspacing="0"><tbody><tr><td class="popup-container">
<div class="c1"><div class="c2"><div class="c3"><div class="c4"><div class="c5">
<div class="popup-heading">
    <div class="heading-area">
        <span class="close"></span>
        <h4><span><?php echo $this->lmsg('messagesByDay'); ?></span></h4>
    </div>
</div>
<div class="popup-content">
<div class="popup-content-area">
<span class="arrow"></span>
    <table class="bar-chart-table" id="outgoingMailMessagesHead" cellspacing="0">
        <thead>
        <tr>
            <td colspan="2"><?php echo $this->lmsg('selectDay'); ?> :</td>
            <td class="bar-chart-table-data">
                <select class="f-max-size" name="outgoingMailMessagesDate" id="outgoingMailMessagesDate">
                    <?php foreach($this->messagesDates as $date): ?>
                        <option value="<?php echo $date;?>"><?php echo ldate(strtotime($date));?></option>
                    <?php endforeach; ?>
                </select>
            </td>
        </tr>
        <tr><td colspan="3"><hr></td></tr>
        </thead>
        <tbody id="outgoingMailMessagesResult"></tbody>
    </table>
</div>
</div>
</div></div></div></div></div>
</td></tr></tbody></table>
</div>
