{% extends 'layout_default.html.twig' %}

{% block meta_title %}{{ 'Hosting management'|trans }}{% endblock %}

{% set active_menu = 'system' %}

{% block breadcrumbs %}
<ul class="breadcrumb">
    <li class="breadcrumb-item">
        <a href="{{ '/'|alink }}">
            <svg class="icon">
                <use xlink:href="#home" />
            </svg>
        </a>
    </li>
    <li class="breadcrumb-item">
        <a href="{{ 'servicehosting'|alink }}">{{ 'Hosting plans and servers'|trans }}</a>
    </li>
    <li class="breadcrumb-item active" aria-current="page">{{ server.name }}</li>
</ul>
{% endblock %}

{% block content %}
<div class="card">
    <div class="card-body">
        <h3>{{ 'Server management'|trans }}</h3>

        <form method="post" action="{{ 'api/admin/servicehosting/server_update'|link }}" id="server-update" class="api-form" data-api-msg="{{ 'Server updated'|trans }}">
            <input type="hidden" name="CSRFToken" value="{{ CSRFToken }}"/>
            <div class="mb-3 row">
                <label class="form-label col-3 col-form-label">{{ 'Name'|trans }}:</label>
                <div class="col">
                    <input class="form-control" type="text" name="name" value="{{ server.name }}" required placeholder="{{ 'Unique name to identify this server'|trans }}">
                </div>
            </div>
            <div class="mb-3 row">
                <label class="form-label col-3 col-form-label">{{ 'Hostname'|trans }}:</label>
                <div class="col">
                    <input class="form-control" type="text" name="hostname" value="{{ server.hostname }}" placeholder="host1.domain.com">
                </div>
            </div>
            <div class="mb-3 row">
                <label class="form-label col-3 col-form-label">{{ 'IP'|trans }}:</label>
                <div class="col">
                    <input class="form-control" type="text" name="ip" value="{{ server.ip }}" required placeholder="{{ 'Primary IP address of the server used to connect to it like: 127.0.0.1'|trans }}">
                </div>
            </div>
            <div class="mb-3 row">
                <label class="form-label col-3 col-form-label">{{ 'Assigned IP Addresses'|trans }}:</label>
                <div class="col">
                    <textarea class="form-control" name="assigned_ips" rows="5" placeholder="List the IP Addresses assigned to the server (One per line)">{% for v in server.assigned_ips %}{{ v }}{{constant("PHP_EOL")}}{% endfor %}</textarea>
                </div>
            </div>
            <div class="mb-3 row">
                <label class="form-label col-3 col-form-label">{{ 'Enable/Disable'|trans }}:</label>
                <div class="col">
                    <div class="form-check form-check-inline">
                        <input class="form-check-input" id="radioActiveYes" type="radio" name="active" value="1"{% if server.active %} checked{% endif %}>
                        <label class="form-check-label" for="radioActiveYes">{{ 'Yes'|trans }}</label>
                    </div>
                    <div class="form-check form-check-inline">
                        <input class="form-check-input" id="radioActiveNo" type="radio" name="active" value="0"{% if not server.active %} checked{% endif %}>
                        <label class="form-check-label" for="radioActiveNo">{{ 'No'|trans }}</label>
                    </div>
                </div>
            </div>
            <hr>

            <h5>{{ 'Server manager'|trans }}</h5>
            <div class="mb-3 row">
                <label class="form-label col-3 col-form-label">{{ 'Server manager'|trans }}:</label>
                <div class="col">
                    <select class="form-select" name="manager" onchange="handleManagerChange(this)">
                        {% for code, manager in admin.servicehosting_manager_get_pairs %}
                        <option value="{{ code }}"{% if server.manager == code %} selected{% endif %}>{{ manager.label }}</option>
                        {% endfor %}
                    </select>
                </div>
            </div>

            <div id="credentials"></div>

            <div class="mb-3 row">
                <label class="form-label col-3 col-form-label">{{ 'Connection port'|trans }}:</label>
                <div class="col">
                    <input class="form-control" type="number" name="port" min="1" max="65535" value="{{ server.port }}" placeholder="{{ 'Custom port. Use blank to use default. Used to connect to the API'|trans }}">
                </div>
            </div>
            <div class="mb-3 row">
                <label class="form-label col-3 col-form-label">{{ 'Password length'|trans }}:</label>
                <div class="col">
                    <input class="form-control" type="number" name="passwordLength" min="1" max="100" value="{{ server.passwordLength }}" placeholder="{{ 'Length of generated passwords when creating user accounts. Defaults to 10'|trans }}">
                </div>
            </div>
            <div class="mb-3 row">
                <label class="form-label col-3 col-form-label">{{ 'Use secure connection'|trans }}:</label>
                <div class="col">
                    <div class="form-check form-check-inline">
                        <input class="form-check-input" id="radioSecureConnectionYes" type="radio" name="secure" value="1"{% if server.secure %} checked{% endif %}>
                        <label class="form-check-label" for="radioSecureConnectionYes">{{ 'Yes'|trans }}</label>
                    </div>
                    <div class="form-check form-check-inline">
                        <input class="form-check-input" id="radioSecureConnectionNo" type="radio" name="secure" value="0"{% if not server.secure %} checked{% endif %}>
                        <label class="form-check-label" for="radioSecureConnectionNo">{{ 'No'|trans }}</label>
                    </div>
                </div>
            </div>

            <input class="btn btn-primary w-100" id="test-connection" type="button" value="{{ 'Update and test connection'|trans }}">

            <h5>{{ 'Optional configuration'|trans }}</h5>
            <div class="mb-3 row">
                <label class="form-label col-3 col-form-label">{{ 'Users prefix'|trans }}:</label>
                <div class="col">
                    <input class="form-control" type="text" name="userprefix" value="{{ server.config.userprefix }}" placeholder="{{ 'Prefix for created users (especially for database)'|trans }}">
                    <span class="text-muted">{{ 'Some server managers may ignore this option due to limitations / requirements for usernames imposed by the control panel.'|trans }}</span>
                </div>
            </div>

            <hr>

            <h5>{{ 'Nameservers'|trans }}</h5>
            <div class="mb-3 row">
                <label class="form-label col-3 col-form-label">{{ 'Nameserver 1'|trans }}:</label>
                <div class="col">
                    <input class="form-control" type="text" name="ns1" value="{{ server.ns1 }}" placeholder="ns1.yourdomain.com">
                </div>
            </div>
            <div class="mb-3 row">
                <label class="form-label col-3 col-form-label">{{ 'Nameserver 2'|trans }}:</label>
                <div class="col">
                    <input class="form-control" type="text" name="ns2" value="{{ server.ns2 }}" placeholder="ns2.yourdomain.com">
                </div>
            </div>
            <div class="mb-3 row">
                <label class="form-label col-3 col-form-label">{{ 'Nameserver 3'|trans }}:</label>
                <div class="col">
                    <input class="form-control" type="text" name="ns3" value="{{ server.ns3 }}" placeholder="ns3.yourdomain.com">
                </div>
            </div>
            <div class="mb-3 row">
                <label class="form-label col-3 col-form-label">{{ 'Nameserver 4'|trans }}:</label>
                <div class="col">
                    <input class="form-control" type="text" name="ns4" value="{{ server.ns4 }}" placeholder="ns4.yourdomain.com">
                </div>
            </div>

            <input type="hidden" name="id" value="{{ server.id }}">
            <input type="submit" value="{{ 'Update server'|trans }}" class="btn btn-primary w-100">
        </form>
    </div>
</div>
{% endblock %}

{% block js%}
<script>
    $(function() {
        $('#test-connection').on('click', function(event){
            event.preventDefault();
              formElement = document.getElementById('server-update');
              const formData = new FormData(formElement);
              if(formElement.getAttribute('method').toLowerCase() != 'get'){
                 data = formData.serializeJSON();
              }else{
                data =  formData.serialize();
              }
              API.makeRequest(formElement.getAttribute('method'), bb.restUrl(formElement.getAttribute('action')),  data , function (result) {
                return bb._afterComplete(formElement, result);
              }, function (error) {
                FOSSBilling.message(`${error.message} (${error.code})`, 'error');
              });

              API.makeRequest(formElement.getAttribute('method'), bb.restUrl('admin/servicehosting/server_test_connection'),  { id: {{ server.id }}, CSRFToken: "{{ CSRFToken }}" }, function (result) {
                  FOSSBilling.message(`{{ 'Server connected'|trans }}`, 'message');
                }, function (error) {
                  FOSSBilling.message(`${error.message} (${error.code})`, 'error');
                });
            return false;
        });
    });

    function handleManagerChange (select) {
        var pairs = {{ admin.servicehosting_manager_get_pairs|json_encode|raw }} // PHP array returned by the server manager converted to a JavaScript object
        var defaults = {
            form: {
                credentials: {
                    fields: [
                        {
                            name: 'username',
                            label: 'Username',
                            type: 'text',
                            placeholder: 'Username to connect to the server',
                            required: true
                        },
                        {
                            name: 'password',
                            label: 'Password',
                            type: 'password',
                            placeholder: 'Password to connect to the server',
                            required: true
                        }
                    ],
                },
            },
        } // Default form fields. If server manager does not provide any, use these.

        var values = {{ server|json_encode|raw }}; // Server data returned by the server manager converted to a JavaScript object

        var credentials = document.getElementById('credentials'); // HTML element where the form fields will be inserted.
        var manager = select.value; // Selected server manager code.

        credentials.innerHTML = ''; // Clear the form fields.

        if (pairs[manager].form && pairs[manager].form.credentials && pairs[manager].form.credentials.fields) {
            var data = pairs[manager].form.credentials.fields;
        } else {
            var data = defaults.form.credentials.fields;
        }

        for (var i = 0; i < data.length; i++) {
            // Create a new form field and append it to the credentials element.
            var field = data[i];
            var div = document.createElement('div');
            div.className = 'mb-3 row';

            var label = document.createElement('label');
            label.className = 'form-label col-3 col-form-label';
            label.innerHTML = field.label + ':';
            div.appendChild(label);

            var input = document.createElement('input');
            input.className = 'form-control';
            input.type = field.type;
            input.name = field.name;
            input.value = values[field.name];
            input.placeholder = field.placeholder;
            input.required = field.required;

            var col = document.createElement('div');
            col.className = 'col';
            col.appendChild(input);
            div.appendChild(col);

            credentials.appendChild(div);
        }
    }

    window.onload = function () {
        handleManagerChange(document.querySelector('select[name="manager"]'));
    };
</script>
{% endblock %}
