<?php
// Copyright 1999-2021. Plesk International GmbH. All rights reserved.
?>
<div class='form-row'>
    <div class='single-row'>
        <?php echo $this->content ?>
        <?php if (isset($this->phpInfoUrl) && '' != $this->phpInfoUrl): ?>
            <a class="i-link" href="<?php echo $this->phpInfoUrl ?>" target="_blank" id="show-php-info"><i class="icon-info"></i> <span><?php echo $this->lmsg('components.forms.php-settings.showPhpInfo') ?></span></a>
        <?php endif; ?>
        <?php if ($this->phpHandlerService) : ?>
            <span id="phpHandlerServiceActions"></span>
        <?php endif; ?>
        <?php if ($this->fpmDedicatedHandlerHint) : ?>
            <span class='hint' style="display:none" id="fpmDedicatedHandlerHint">
                <i class="icon-attention"></i> <?php echo $this->fpmDedicatedHandlerHint ?>
            </span>
        <?php endif; ?>
        <?php if ($this->handlerChangeHint) : ?>
            <span class='hint' style="display:none" id="phpHandlerChangeHint">
                <i class="icon-warning"></i> <?php echo $this->handlerChangeHint ?>
            </span>
        <?php endif; ?>
        <?php if (isset($this->hint)): ?>
            <span class='hint'><?php echo $this->hint ?></span>
        <?php endif; ?>
        <?php if (isset($this->helpLink)): ?>
            <a id='phpSettingsHelpLink' href="<?php echo isset($this->helpLink['href']) ? $this->baseUrl($this->helpLink['href']) : '#' ?>" <?php echo isset($this->helpLink['onclick']) ? "onclick='{$this->helpLink['onclick']}'" : '' ?> target='_blank'><?php echo $this->helpLink['title'] ?></a>
        <?php endif; ?>
        <span class='field-errors'></span>
    </div>
</div>
<script type='text/javascript'>
//<![CDATA[
    function getCurrentPhpHandlerType() {
        var phpHandlerTypeIds = <?php echo json_encode($this->phpHandlerTypeIds) ?>;
        for (var i = 0; i < phpHandlerTypeIds.length; i++) {
            var phpHandlerTypeSelect = document.getElementById(phpHandlerTypeIds[i]);
            if (phpHandlerTypeSelect.style.display !== 'none') {
                return phpHandlerTypeSelect.options[phpHandlerTypeSelect.selectedIndex].text;
            }
        }
        return false;
    }
    function onAfterPhpHandlerChange() {
        var phpHandlerTypeIds = <?php echo json_encode($this->phpHandlerTypeIds) ?>;
        for (var i = 0; i < phpHandlerTypeIds.length; i++) {
            document.getElementById(phpHandlerTypeIds[i]).style.display = 'none';
        }
        var phpHandler = document.getElementById('<?php echo $this->phpHandlerId ?>').value;
        document.getElementById('<?php echo $this->phpHandlerId ?>').style.display = '';
        document.getElementById('<?php echo $this->phpHandlerId ?>Id' + phpHandler).style.display = '';
    }
    Jsw.onReady(function() {
        const phpHandlerId = '<?= $this->phpHandlerId ?>';
        if (!phpHandlerId) {
            return;
        }
        const phpHandler = document.getElementById(phpHandlerId);
        if (!phpHandler) {
            return;
        }

        phpHandler.addEventListener('change', function (e) {
            var currentHandlerType = getCurrentPhpHandlerType();
            onAfterPhpHandlerChange();
            if (!currentHandlerType) {
                return;
            }
            var phpHandler = document.getElementById('<?php echo $this->phpHandlerId ?>').value;
            var handlerTypeSelect = document.getElementById('<?php echo $this->phpHandlerId ?>Id' + phpHandler);
            for (var j = 0; j < handlerTypeSelect.options.length; j++) {
                if (currentHandlerType === handlerTypeSelect.options[j].text) {
                    handlerTypeSelect.selectedIndex = j;
                    break;
                }
            }
        });
        onAfterPhpHandlerChange();

        <?php if (isset($this->phpInfoUrl) && '' != $this->phpInfoUrl): ?>
        var formValues = new Jsw.form.Values({ selector: '*[name*=php],*[name*=mainSettings]' });
        var showButton = document.getElementById('show-php-info');
        if (showButton) {
            showButton.addEventListener('click', function (e){
                if (!formValues.isChanged()) {
                    return;
                }
                e.preventDefault();
                var linkElement = e.target.closest('a');
                new Jsw.Popup({
                    title: <?php echo $this->jsLmsg('components.forms.php-settings.showPhpInfoTitle') ?>,
                    content: <?php echo $this->jsLmsg('components.forms.php-settings.showPhpInfoDescription') ?>,
                    buttons: [
                        {
                            title: <?php echo $this->jsLmsg('components.buttons.apply') ?>,
                            handler: function (e2) {
                                Jsw.submit(linkElement, true);
                                e2.target.innerHTML = '<span class="wait">' + <?php echo $this->jsLmsg('components.buttons.wait') ?> + '</span>';
                            }
                        },
                        {
                            title: <?php echo $this->jsLmsg('components.forms.php-settings.showPhpInfoButton') ?>,
                            handler: function (e2, popup) {
                                Jsw.redirect(linkElement.getAttribute('href'), {}, '_blank');
                                popup._onCloseClick();
                            }
                        },
                        {
                            title: <?php echo $this->jsLmsg('components.buttons.cancel') ?>,
                            handler: function (e2, popup) {
                                popup._onCloseClick();
                            }
                        }
                    ]
                });
            });
        }
        <?php endif; ?>

        <?php if ($this->phpHandlerService || $this->fpmDedicatedHandlerHint) : ?>

            var phpHandlerElements = document.querySelectorAll(`[id^=${phpHandlerId}]`);
            phpHandlerElements.forEach(function (el) {
                el.addEventListener('change', function () {
                    const phpHandlerType = document.getElementById(phpHandlerId + 'Id' + phpHandler.value);

                    <?php if ($this->phpHandlerService) : ?>
                    if (phpHandlerType.id == document.getElementById('currentPhpHandlerName').value &&
                        phpHandlerType.value == document.getElementById('currentPhpHandlerValue').value) {
                        document.getElementById('phpHandlerServiceActions').style.display = '';
                    } else {
                        document.getElementById('phpHandlerServiceActions').style.display = 'none';
                    }
                    <?php endif; ?>

                    <?php if ($this->fpmDedicatedHandlerHint) : ?>
                    document.getElementById('fpmDedicatedHandlerHint').style.display = phpHandlerType.value.includes('fpm-dedicated') ? '' : 'none';
                    <?php endif; ?>
                });
            });
        <?php endif; ?>

        <?php if ($this->phpHandlerService) : ?>
            const phpHandlerService = '<?= $this->phpHandlerService ?>';

            var servicesLocale = new Jsw.Locale(<?= json_encode(Zend_Registry::get('translate')->getSection('admin.components.lists.services')) ?>);
            function renderActions(item) {
                var renderButton = function (action) {
                    var description, disabled;
                    if (['notInstalled', 'notConfigured'].indexOf(item.state) !== -1) {
                        description = servicesLocale.lmsg('serviceDisabled');
                        disabled = true;
                    } else {
                        description = servicesLocale.lmsg(item.status + action.capitalize());
                        disabled = item.status === 'running' ? action === "start" : action !== "start";
                    }

                    return '<span>' +
                        '<span class="tooltipData">' + description + '</span>' +
                        '<a' + (disabled ? ' class="disabled i-link"' : ' class="i-link"') +
                        (disabled ? '' : ' data-action-name="' + action + '"') + '>' +
                        '<i class="icon-' + action +  '"></i>' +
                        '</a>' +
                        '</span>';
                };

                return ["start", "stop", "restart"].map(renderButton.bind(this)).join('');
            }

            function onReloadActions(serviceActive) {
                var serviceElem = document.getElementById('phpHandlerServiceActions');
                serviceElem.innerHTML = renderActions({
                    'state': serviceActive ? 'active' : 'inActive',
                    'status': serviceActive ? 'running' : 'notRunning',
                });
                serviceElem.querySelectorAll('a[data-action-name]').forEach(link => {
                    link.addEventListener('click', event => {
                        event.preventDefault();
                        doAction(link.dataset.actionName, phpHandlerService);
                    });
                });
            }
            onReloadActions(document.getElementById('currentPhpHandlerServiceStatus').value);

            function reloadActions() {
                new Ajax.Request(document.URL, {
                    method: 'get',
                    onSuccess: function(transport) {
                        const parser = new DOMParser();
                        const doc = parser.parseFromString(transport.responseText, 'text/html');
                        onReloadActions(doc.getElementById('currentPhpHandlerServiceStatus').value);
                    }
                });
            }

            var operationLocale = new Jsw.Locale(<?= json_encode(Zend_Registry::get('translate')->getSection('admin.controllers.services.operation')) ?>);
            var doAction = function (action, serviceId) {
                var actionUrl = Jsw.prepareUrl('/admin/services/operation/id/' + encodeURIComponent(serviceId) + '/act/' + action);
                Jsw.api.post(actionUrl)
                    .then(function (status) {
                        if (status.redirect) {
                            Jsw.redirect(status.redirect);
                        } else {
                            reloadActions();
                        }

                        status.statusMessages.forEach(function (message) {
                            Jsw.addStatusMessage(message.status, message.content);
                        });
                    })
                    .catch(function (e) {
                        reloadActions();
                        if (['nginx', 'web'].indexOf(serviceId) !== -1) {
                            // No response from server when start/stop/restart web and nginx services is considered as success
                            Jsw.addStatusMessage('info', operationLocale.lmsg(action + 'ServiceMessage'));
                        } else {
                            Jsw.addStatusMessage('error', operationLocale.lmsg(action + 'ActionError', { error: e.message }));
                        }
                    });
            };
        <?php endif; ?>
    });
//]]>
</script>
