{* Shared add/edit modal for servers/dns_servers/web_servers/mail_servers.
   Type/driver options come from the embedding template's driversByType map.
   The modal's field visibility (SSH vs. PowerDNS-API) is also driven by
   driver via puqApplyDriverVisibility() defined at the bottom of this file. *}
<div class="modal fade" id="puq-modal" tabindex="-1" role="dialog">
    <div class="modal-dialog modal-lg" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal">&times;</button>
                <h4 class="modal-title" id="puq-modal-title">Server</h4>
            </div>
            <div class="modal-body">
                <form id="puq-modal-form">
                    <input type="hidden" name="id" id="puq-field-id">
                    <div class="row">
                        <div class="col-md-5">
                            <div class="form-group" data-field="caps">
                                <label>Capabilities <span class="text-danger">*</span></label>
                                <div>
                                    <label class="checkbox-inline" style="margin-right:14px">
                                        <input type="checkbox" name="caps_web" id="puq-field-caps-web" value="1"> Web
                                    </label>
                                    <label class="checkbox-inline" style="margin-right:14px">
                                        <input type="checkbox" name="caps_mail" id="puq-field-caps-mail" value="1"> Mail
                                    </label>
                                    <label class="checkbox-inline">
                                        <input type="checkbox" name="caps_dns" id="puq-field-caps-dns" value="1"> DNS
                                    </label>
                                </div>
                                <small class="text-muted">Tick every role this physical server is provisioned for. Unified-deployment products need a server with both Web and Mail ticked. PowerDNS supports DNS only.</small>
                                {* `type` is the legacy primary-role marker — kept for back-compat
                                   reads and auto-derived from the first ticked cap on save. *}
                                <input type="hidden" name="type" id="puq-field-type" value="web">
                            </div>
                        </div>
                        <div class="col-md-4">
                            <div class="form-group" data-field="driver">
                                <label>Driver <span class="text-danger">*</span></label>
                                <select name="driver" id="puq-field-driver" class="form-control" required></select>
                            </div>
                        </div>
                        <div class="col-md-3">
                            <div class="form-group" data-field="status">
                                <label>Status</label>
                                <select name="status" id="puq-field-status" class="form-control">
                                    <option value="active">active</option>
                                    <option value="inactive">inactive</option>
                                    <option value="maintenance">maintenance</option>
                                </select>
                            </div>
                        </div>
                    </div>
                    <div class="row">
                        <div class="col-md-6">
                            <div class="form-group" data-field="name">
                                <label>Name <span class="text-danger">*</span></label>
                                <input type="text" name="name" id="puq-field-name" class="form-control" required>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="form-group" data-field="group_id">
                                <label>Group</label>
                                <select name="group_id" id="puq-field-group" class="form-control"><option value="">—</option></select>
                            </div>
                        </div>
                    </div>
                    <div class="row">
                        <div class="col-md-6">
                            <div class="form-group" data-field="hostname">
                                <label>Hostname <span class="text-danger">*</span></label>
                                <input type="text" name="hostname" id="puq-field-hostname" class="form-control" required placeholder="panel.example.com">
                            </div>
                        </div>
                        <div class="col-md-3" id="puq-ssh-ip-col">
                            <div class="form-group" data-field="ip">
                                <label>IP <span class="text-danger" id="puq-ip-required-star">*</span></label>
                                <input type="text" name="ip" id="puq-field-ip" class="form-control" placeholder="1.2.3.4">
                                <small class="text-muted" id="puq-ip-help-pdns" style="display:none">Optional for PowerDNS — server identity comes from the API hostname.</small>
                            </div>
                        </div>
                        <div class="col-md-3">
                            <div class="form-group" data-field="port">
                                <label id="puq-port-label">SSH port</label>
                                <input type="number" name="port" id="puq-field-port" class="form-control" value="22" min="1" max="65535">
                                <small class="text-muted" id="puq-port-help-pdns" style="display:none">PowerDNS HTTP API port (default 8081).</small>
                            </div>
                        </div>
                    </div>
                    {* ===== SSH-only block — hidden when driver=powerdns ===== *}
                    <div id="puq-ssh-block">
                        <div class="row">
                            <div class="col-md-6">
                                <div class="form-group" data-field="username">
                                    <label>SSH username <span class="text-danger">*</span></label>
                                    <input type="text" name="username" id="puq-field-username" class="form-control" placeholder="root" value="root">
                                    <small class="text-muted">Either <code>root</code> (recommended), or any user with full passwordless sudo (<code>NOPASSWD: ALL</code>).</small>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="form-group" data-field="ssh_auth_method">
                                    <label>SSH auth method <span class="text-danger">*</span></label>
                                    <div>
                                        <label class="radio-inline"><input type="radio" name="ssh_auth_method" value="password" id="puq-field-auth-pwd" checked> Password</label>
                                        <label class="radio-inline"><input type="radio" name="ssh_auth_method" value="key" id="puq-field-auth-key"> Private key</label>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <div class="row" id="puq-auth-password-row">
                            <div class="col-md-12">
                                <div class="form-group" data-field="ssh_password">
                                    <label>SSH password</label>
                                    <input type="password" name="ssh_password" id="puq-field-ssh-password" class="form-control" placeholder="leave blank to keep existing" autocomplete="new-password">
                                </div>
                            </div>
                        </div>
                        <div class="row" id="puq-auth-key-row" style="display:none">
                            <div class="col-md-8">
                                <div class="form-group" data-field="ssh_private_key">
                                    <label>SSH private key (PEM)</label>
                                    <textarea name="ssh_private_key" id="puq-field-ssh-private-key" class="form-control" rows="6" placeholder="-----BEGIN OPENSSH PRIVATE KEY-----&#10;...&#10;-----END OPENSSH PRIVATE KEY-----&#10;(leave blank to keep existing)" spellcheck="false" style="font-family:monospace;font-size:12px"></textarea>
                                </div>
                            </div>
                            <div class="col-md-4">
                                <div class="form-group" data-field="ssh_key_passphrase">
                                    <label>Key passphrase</label>
                                    <input type="password" name="ssh_key_passphrase" id="puq-field-ssh-key-passphrase" class="form-control" placeholder="(if encrypted)" autocomplete="new-password">
                                </div>
                            </div>
                        </div>
                        <div class="alert alert-warning" id="puq-hestia-alert" style="margin-top:10px">
                            <strong><i class="fas fa-exclamation-triangle"></i> Requirements on the HestiaCP server:</strong>
                            <ol style="margin:8px 0 0 0;padding-left:18px">
                                <li>SSH access enabled on port <code>22</code> (or custom port above).</li>
                                <li>SSH user can log in via password or private key.</li>
                                <li><strong>FULL passwordless sudo is required.</strong>
                                    The module runs both Hestia <code>v-*</code> commands and system probes
                                    (<code>df</code>, <code>/proc/*</code>, custom scripts) — partial NOPASSWD scoped only to
                                    <code>/usr/local/hestia/bin/*</code> is <strong>not enough</strong>.
                                    <br><br>
                                    Two ways to satisfy this:
                                    <ul style="margin:4px 0 0 0;padding-left:18px">
                                        <li><strong>(a) SSH as <code>root</code></strong> — easiest, no sudoers config needed.
                                            The module auto-detects <code>uid=0</code> and skips <code>sudo</code> entirely.</li>
                                        <li><strong>(b) Use a sudoer user</strong> — create
                                            <code>/etc/sudoers.d/puq-webhosting</code> on the Hestia server:
                                            <pre style="margin:4px 0;font-size:11px">sudo tee /etc/sudoers.d/puq-webhosting &lt;&lt;'EOF'
# Full passwordless sudo for PUQ Web Hosting integration.
# Replace "admin" with the SSH username configured above.
admin ALL=(ALL) NOPASSWD: ALL
EOF
sudo chmod 440 /etc/sudoers.d/puq-webhosting
sudo visudo -c    # syntax check — must say "parsed OK"</pre>
                                            Verify it works: <code>sudo -n -l</code> on the server must list a
                                            <code>NOPASSWD: ALL</code> rule.
                                        </li>
                                    </ul>
                                </li>
                                <li>For <em>private-key</em> auth — public key in <code>~/.ssh/authorized_keys</code> of the SSH user, perms <code>600</code>.</li>
                                <li>Recommended: firewall SSH so only the WHMCS server IP can connect.</li>
                            </ol>
                            <small>The Test connection button below runs <code>sudo -n -l</code> as a precheck — connection only succeeds if a <code>NOPASSWD: ALL</code> rule is in effect (or SSH is as root).</small>
                        </div>
                    </div>

                    {* ===== PowerDNS-only block — hidden when driver=hestiacp ===== *}
                    <div id="puq-pdns-block" style="display:none">
                        <div class="row">
                            <div class="col-md-12">
                                <div class="form-group" data-field="pdns_api_key">
                                    <label>PowerDNS API key <span class="text-danger">*</span></label>
                                    <input type="password" name="pdns_api_key" id="puq-field-pdns-api-key" class="form-control" placeholder="leave blank to keep existing" autocomplete="new-password" spellcheck="false">
                                    <small class="text-muted">The shared secret from PowerDNS <code>pdns.conf</code> → <code>api-key=</code>. Sent as the <code>X-API-Key</code> header on every request.</small>
                                </div>
                            </div>
                        </div>
                        <div class="alert alert-info" id="puq-pdns-alert" style="margin-top:10px">
                            <strong><i class="fas fa-info-circle"></i> Requirements on the PowerDNS server:</strong>
                            <ol style="margin:8px 0 0 0;padding-left:18px">
                                <li>Authoritative server with the HTTP API enabled:
                                    <pre style="margin:4px 0;font-size:11px">api=yes
api-key=<em>your-secret-here</em>
webserver=yes
webserver-address=0.0.0.0
webserver-port=8081
webserver-allow-from=<em>WHMCS_SERVER_IP/32</em></pre>
                                </li>
                                <li>The hostname above resolves to the PowerDNS server; the port is the <code>webserver-port</code>.</li>
                                <li>Pick <strong>API scheme</strong> = <code>https</code> only when the API is exposed publicly behind TLS — otherwise <code>http</code> works on localhost / VPN / private networks.</li>
                                <li>Recommended: keep <code>webserver-allow-from</code> tight to just the WHMCS server IP.</li>
                            </ol>
                            <small>Test connection issues <code>GET /api/v1/servers</code> — success returns the running PowerDNS version.</small>
                        </div>
                    </div>
                    <div class="row" id="puq-web-only" style="display:none">
                        <div class="col-md-6">
                            <div class="form-group" data-field="dns_template_id">
                                <label>DNS zone template</label>
                                <select name="dns_template_id" id="puq-field-template" class="form-control"><option value="">—</option></select>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="form-group" data-field="capacity_max">
                                <label>Capacity max</label>
                                <input type="number" name="capacity_max" id="puq-field-capacity" class="form-control" placeholder="e.g. 500">
                            </div>
                        </div>
                    </div>
                    <hr>
                    <h5>Driver-specific config</h5>
                    <div id="puq-driver-config"></div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-info pull-left" id="puq-test-btn" style="display:none"><i class="fa fa-plug"></i> Test connection</button>
                <button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
                <button type="button" class="btn btn-primary" id="puq-modal-save"><i class="fas fa-save"></i> Save</button>
            </div>
        </div>
    </div>
</div>

<div class="modal fade" id="puq-delete-modal" tabindex="-1" role="dialog">
    <div class="modal-dialog modal-sm" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal">&times;</button>
                <h4 class="modal-title">Confirm Delete</h4>
            </div>
            <div class="modal-body">
                <p>Delete this server?</p>
                <input type="hidden" id="puq-delete-id">
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
                <button type="button" class="btn btn-danger" id="puq-confirm-delete"><i class="fas fa-trash"></i> Delete</button>
            </div>
        </div>
    </div>
</div>

{literal}
<script>
/**
 * Populate the Capabilities checkboxes on modal open. Each list page
 * (web_servers / mail_servers / dns_servers) has its own primary type;
 * the primary cap is always pre-ticked and can't be unticked from the
 * scope of that list. Other caps reflect the row's stored caps_* (on
 * edit) or stay unticked (on add) so an admin can promote a server to
 * multi-role for unified-deployment.
 */
window.puqApplyServerCaps = function(row, primaryType) {
    var prim = (primaryType || 'web').toLowerCase();
    var caps = {
        web:  !!(row && (parseInt(row.caps_web, 10)  === 1 || row.caps_web  === true || row.caps_web  === '1')),
        mail: !!(row && (parseInt(row.caps_mail, 10) === 1 || row.caps_mail === true || row.caps_mail === '1')),
        dns:  !!(row && (parseInt(row.caps_dns, 10)  === 1 || row.caps_dns  === true || row.caps_dns  === '1')),
    };
    // New row: pre-tick the primary cap only.
    if (!row) caps[prim] = true;
    // Edit row from a pre-caps install where every cap is still 0:
    // trust the legacy `type` column.
    if (row && !caps.web && !caps.mail && !caps.dns) {
        var t = (row.type || prim).toLowerCase();
        if (caps.hasOwnProperty(t)) caps[t] = true;
    }

    $('#puq-field-caps-web').prop('checked',  caps.web);
    $('#puq-field-caps-mail').prop('checked', caps.mail);
    $('#puq-field-caps-dns').prop('checked',  caps.dns);

    // Primary list-page cap is what `type` should hold on save — but the
    // admin can untick it (and tick another) to RECLASSIFY the row out
    // of this list, which is intentional. SaveServer derives `type` from
    // the first ticked cap if the hidden field is empty.
    $('#puq-field-type').val(prim);
};

/**
 * Apply driver-conditional visibility / labels to the shared server modal.
 * Called from each list page (servers / web_servers / mail_servers /
 * dns_servers) on modal open AND on driver-change. Idempotent.
 *
 * Currently recognises:
 *   hestiacp   → SSH block visible, Hestia alert shown, port label "SSH port"
 *   powerdns   → PowerDNS API block visible, port label "API port", IP optional
 *   <other>    → SSH block hidden (safe default)
 */
window.puqApplyDriverVisibility = function(driver) {
    driver = (driver || '').toLowerCase();
    var isHestia  = (driver === 'hestiacp');
    var isPowerDns = (driver === 'powerdns');

    // SSH block (username, auth method, password/key, hestia alert) — Hestia only.
    $('#puq-ssh-block').toggle(isHestia);
    // PowerDNS-only block (API key + pdns guidance).
    $('#puq-pdns-block').toggle(isPowerDns);

    // Port label + helper text + default value.
    $('#puq-port-label').text(isPowerDns ? 'API port' : 'SSH port');
    $('#puq-port-help-pdns').toggle(isPowerDns);
    // Only suggest 8081 for fresh forms (id empty). Editing keeps stored value.
    if (isPowerDns && !$('#puq-field-id').val() && (!$('#puq-field-port').val() || $('#puq-field-port').val() === '22')) {
        $('#puq-field-port').val(8081);
    }
    if (isHestia && !$('#puq-field-id').val() && (!$('#puq-field-port').val() || $('#puq-field-port').val() === '8081')) {
        $('#puq-field-port').val(22);
    }

    // IP is optional for PowerDNS (server identified by hostname:port).
    $('#puq-ip-required-star').toggle(!isPowerDns);
    $('#puq-field-ip').prop('required', !isPowerDns);
    $('#puq-ip-help-pdns').toggle(isPowerDns);
};
</script>
{/literal}
