<div class="panel panel-default">
    <div class="panel-heading">
        <h3 class="panel-title pull-left"><i class="fa fa-sliders-h"></i> General Settings</h3>
        <button type="button" class="btn btn-primary btn-sm pull-right" id="puq-settings-save"><i class="fas fa-save"></i> Save</button>
        <div class="clearfix"></div>
    </div>
    <div class="panel-body" style="position:relative;">
        <div id="puq-settings-overlay" style="display:block;position:absolute;top:0;left:0;width:100%;height:100%;background:rgba(255,255,255,0.9);z-index:9999;border-radius:4px;">
            <div style="position:absolute;top:50%;left:50%;transform:translate(-50%,-50%);text-align:center;">
                <i class="fa fa-spinner fa-spin fa-3x text-primary"></i>
                <div style="margin-top:10px;font-size:16px;">Loading...</div>
            </div>
        </div>

        <form id="puq-settings-form">
            <ul class="nav nav-tabs" id="puq-settings-tabs" role="tablist">
                <li role="presentation" class="active"><a href="#puq-tab-general" data-toggle="tab"><i class="fa fa-cog"></i> General</a></li>
                <li role="presentation"><a href="#puq-tab-provisioning" data-toggle="tab"><i class="fa fa-server"></i> Provisioning</a></li>
                <li role="presentation"><a href="#puq-tab-dns" data-toggle="tab"><i class="fa fa-globe"></i> DNS</a></li>
                <li role="presentation"><a href="#puq-tab-ssl" data-toggle="tab"><i class="fa fa-lock"></i> SSL</a></li>
                <li role="presentation"><a href="#puq-tab-mail" data-toggle="tab"><i class="fa fa-envelope"></i> Mail &amp; Security</a></li>
                <li role="presentation"><a href="#puq-tab-logging" data-toggle="tab"><i class="fa fa-file-alt"></i> Logging &amp; Performance</a></li>
                <li role="presentation"><a href="#puq-tab-integrations" data-toggle="tab"><i class="fa fa-plug"></i> Integrations</a></li>
                <li role="presentation"><a href="#puq-tab-notifications" data-toggle="tab"><i class="fa fa-bell"></i> Notifications</a></li>
                <li role="presentation"><a href="#puq-tab-maintenance" data-toggle="tab"><i class="fa fa-tools"></i> Maintenance</a></li>
            </ul>

            <div class="tab-content" style="padding:18px 4px 4px 4px;">
                {* ============== GENERAL ============== *}
                <div role="tabpanel" class="tab-pane active" id="puq-tab-general">
                    <h5><i class="fa fa-clock"></i> API Timeouts</h5>
                    <div class="form-group" data-field="api_timeout_default">
                        <label>Default timeout <small class="text-muted">(seconds)</small></label>
                        <input type="number" name="api_timeout_default" id="puq-api-timeout-default" class="form-control" style="width:200px;" min="1" max="300" value="10">
                        <span class="help-block">Timeout for panel API requests from admin/client-area pages. Default: 10</span>
                    </div>
                    <div class="form-group" data-field="api_timeout_heavy">
                        <label>Heavy-operations timeout <small class="text-muted">(seconds)</small></label>
                        <input type="number" name="api_timeout_heavy" id="puq-api-timeout-heavy" class="form-control" style="width:200px;" min="1" max="600" value="60">
                        <span class="help-block">Timeout for cron operations (deploy, terminate, provision). Default: 60</span>
                    </div>
                    <hr>
                    <h5><i class="fa fa-redo"></i> Task Retry Policy</h5>
                    <span class="help-block">A task is &quot;terminally failed&quot; once all retry attempts are exhausted; from that point a notification (and optionally a support ticket) is raised.</span>
                    <div class="form-group" data-field="task_max_attempts">
                        <label>Max attempts</label>
                        <input type="number" name="task_max_attempts" id="puq-task-max-attempts" class="form-control" style="width:200px;" min="1" max="20" value="3">
                        <span class="help-block">How many times a failed task is retried before it is terminally failed. Default: 3</span>
                    </div>
                    <div class="form-group" data-field="task_backoff_minutes">
                        <label>Backoff <small class="text-muted">(minutes, CSV)</small></label>
                        <input type="text" name="task_backoff_minutes" id="puq-task-backoff" class="form-control" style="width:200px;" value="5,30,180">
                        <span class="help-block">Delays between retry attempts, comma-separated. Default: 5,30,180</span>
                    </div>
                    <div class="form-group" data-field="task_batch_size">
                        <label>Batch size</label>
                        <input type="number" name="task_batch_size" id="puq-task-batch-size" class="form-control" style="width:200px;" min="1" max="1000" value="50">
                        <span class="help-block">Max tasks processed per cron run. Default: 50</span>
                    </div>
                    <div class="form-group" data-field="task_retention_days">
                        <label>Task retention (days)</label>
                        <input type="number" name="task_retention_days" id="puq-task-retention-days" class="form-control" style="width:200px;" min="1" max="365" value="7">
                        <span class="help-block">Finished tasks older than this are purged by housekeeping. Default: 7</span>
                    </div>
                </div>

                {* ============== PROVISIONING ============== *}
                <div role="tabpanel" class="tab-pane" id="puq-tab-provisioning">
                    <h5><i class="fa fa-folder-open"></i> Defaults for new users</h5>
                    <div class="form-group" data-field="default_ftp_root_path">
                        <label>FTP root path</label>
                        <input type="text" name="default_ftp_root_path" id="puq-ftp-root" class="form-control" style="width:280px;" value="public_html">
                        <span class="help-block">Relative path (under <code>/home/$user/web/$domain/</code>) for the FTP account. Default: <code>public_html</code></span>
                    </div>
                    <div class="form-group" data-field="default_shell_for_users">
                        <label>Login shell</label>
                        <input type="text" name="default_shell_for_users" id="puq-default-shell" class="form-control" style="width:280px;" value="nologin">
                        <span class="help-block">Shell assigned to new Hestia users. Use <code>nologin</code> for managed hosting (no SSH).</span>
                    </div>
                    <h5 style="margin-top:18px;"><i class="fa fa-user-shield"></i> Hestia admin defaults</h5>
                    <div class="form-group" data-field="hestia_ssh_default_username">
                        <label>SSH default username</label>
                        <input type="text" name="hestia_ssh_default_username" id="puq-hestia-ssh-user" class="form-control" style="width:280px;" value="admin">
                        <span class="help-block">Fallback SSH username when the server row leaves it blank.</span>
                    </div>
                    <div class="form-group" data-field="hestia_admin_username">
                        <label>Hestia admin username</label>
                        <input type="text" name="hestia_admin_username" id="puq-hestia-admin" class="form-control" style="width:280px;" value="admin">
                        <span class="help-block">User that owns FileGator/net2ftp installs on the panel host. Default: <code>admin</code>.</span>
                    </div>
                </div>

                {* ============== DNS ============== *}
                <div role="tabpanel" class="tab-pane" id="puq-tab-dns">
                    <h5><i class="fa fa-clock"></i> Record TTL</h5>
                    <div class="form-group" data-field="dns_default_ttl">
                        <label>Default TTL <small class="text-muted">(seconds)</small></label>
                        <input type="number" name="dns_default_ttl" id="puq-dns-default-ttl" class="form-control" style="width:200px;" min="60" max="604800" value="3600">
                        <span class="help-block">Default TTL for new DNS records (and SOA TTL).</span>
                    </div>
                    <div class="form-group" data-field="dns_ttl_min_seconds">
                        <label>Min allowed TTL <small class="text-muted">(seconds)</small></label>
                        <input type="number" name="dns_ttl_min_seconds" id="puq-dns-ttl-min" class="form-control" style="width:200px;" min="1" max="86400" value="60">
                    </div>
                    <div class="form-group" data-field="dns_ttl_max_seconds">
                        <label>Max allowed TTL <small class="text-muted">(seconds)</small></label>
                        <input type="number" name="dns_ttl_max_seconds" id="puq-dns-ttl-max" class="form-control" style="width:200px;" min="60" max="604800" value="86400">
                    </div>
                    <div class="form-group" data-field="dns_record_max_value_length">
                        <label>Max record value length <small class="text-muted">(chars)</small></label>
                        <input type="number" name="dns_record_max_value_length" id="puq-dns-max-len" class="form-control" style="width:200px;" min="128" max="65535" value="65000">
                    </div>
                    <hr>
                    <h5><i class="fa fa-server"></i> SOA defaults</h5>
                    <span class="help-block">Module-wide defaults; overridden per-group via group editor when needed.</span>
                    <div class="form-group" data-field="dns_soa_refresh">
                        <label>SOA Refresh <small class="text-muted">(seconds)</small></label>
                        <input type="number" name="dns_soa_refresh" id="puq-dns-soa-refresh" class="form-control" style="width:200px;" min="60" value="7200">
                    </div>
                    <div class="form-group" data-field="dns_soa_retry">
                        <label>SOA Retry <small class="text-muted">(seconds)</small></label>
                        <input type="number" name="dns_soa_retry" id="puq-dns-soa-retry" class="form-control" style="width:200px;" min="60" value="3600">
                    </div>
                    <div class="form-group" data-field="dns_soa_expire">
                        <label>SOA Expire <small class="text-muted">(seconds)</small></label>
                        <input type="number" name="dns_soa_expire" id="puq-dns-soa-expire" class="form-control" style="width:200px;" min="3600" value="1209600">
                    </div>
                    <div class="form-group" data-field="dns_soa_minimum">
                        <label>SOA Minimum / NX cache <small class="text-muted">(seconds)</small></label>
                        <input type="number" name="dns_soa_minimum" id="puq-dns-soa-minimum" class="form-control" style="width:200px;" min="60" value="3600">
                    </div>
                </div>

                {* ============== SSL ============== *}
                <div role="tabpanel" class="tab-pane" id="puq-tab-ssl">
                    <h5><i class="fa fa-lock"></i> Auto-SSL cadence</h5>
                    <span class="help-block" style="margin-bottom:10px;">
                        Auto-SSL runs a state-machine per service (table <code>puqWebHosting_ssl_auto</code>).
                        Cron pulse <code>processSslAutoChecks</code> picks rows whose
                        <code>next_check_at</code> is due, runs DNS-check + TLS-probe, and enqueues
                        <code>service.sslAutoInstall</code> when issuance is needed.
                    </span>
                    <div class="form-group" data-field="ssl_fast_check_count">
                        <label>Fast-mode check count</label>
                        <input type="number" name="ssl_fast_check_count" id="puq-ssl-fast-check-count" class="form-control" style="width:200px;" min="1" max="500" value="20">
                        <span class="help-block">First N checks after deploy run at fast cadence (helps catch DNS propagation quickly).</span>
                    </div>
                    <div class="form-group" data-field="ssl_fast_check_minutes">
                        <label>Fast-mode interval <small class="text-muted">(minutes)</small></label>
                        <input type="number" name="ssl_fast_check_minutes" id="puq-ssl-fast-check-minutes" class="form-control" style="width:200px;" min="1" max="60" value="1">
                    </div>
                    <div class="form-group" data-field="ssl_normal_check_minutes">
                        <label>Normal interval <small class="text-muted">(minutes)</small></label>
                        <input type="number" name="ssl_normal_check_minutes" id="puq-ssl-normal-check-minutes" class="form-control" style="width:200px;" min="1" max="1440" value="5">
                    </div>
                    <div class="form-group" data-field="ssl_active_check_hours">
                        <label>Active-cert interval <small class="text-muted">(hours)</small></label>
                        <input type="number" name="ssl_active_check_hours" id="puq-ssl-active-check-hours" class="form-control" style="width:200px;" min="1" max="168" value="24">
                    </div>
                    <hr>
                    <h5><i class="fa fa-snowflake"></i> Let's Encrypt rate-limit guard</h5>
                    <div class="form-group" data-field="ssl_freeze_after_failures">
                        <label>Freeze after N consecutive failures</label>
                        <input type="number" name="ssl_freeze_after_failures" id="puq-ssl-freeze-after" class="form-control" style="width:200px;" min="1" max="20" value="3">
                        <span class="help-block">Lower = aggressive protection from LE limits. Higher = more retries before giving up.</span>
                    </div>
                    <div class="form-group" data-field="ssl_freeze_duration_hours">
                        <label>Freeze duration <small class="text-muted">(hours)</small></label>
                        <input type="number" name="ssl_freeze_duration_hours" id="puq-ssl-freeze-hours" class="form-control" style="width:200px;" min="1" max="168" value="24">
                    </div>
                </div>

                {* ============== MAIL & SECURITY ============== *}
                <div role="tabpanel" class="tab-pane" id="puq-tab-mail">
                    <h5><i class="fa fa-envelope"></i> Mail</h5>
                    <div class="form-group" data-field="webmail_url_pattern">
                        <label>Webmail URL pattern</label>
                        <input type="text" name="webmail_url_pattern" id="puq-webmail-pattern" class="form-control" style="width:340px;" value="https://webmail.{ldelim}domain{rdelim}">
                        <span class="help-block">Tokens: <code>{ldelim}domain{rdelim}</code>, <code>{ldelim}web_server_domain{rdelim}</code>, <code>{ldelim}mail_server_domain{rdelim}</code>.</span>
                    </div>
                    <div class="form-group" data-field="mail_server_host_pattern">
                        <label>Mail server hostname pattern</label>
                        <input type="text" name="mail_server_host_pattern" id="puq-mailhost-pattern" class="form-control" style="width:340px;" value="mail.{ldelim}domain{rdelim}">
                        <span class="help-block">IMAP/POP3/SMTP host shown to customers (welcome emails + Mail settings card). Default <code>mail.{ldelim}domain{rdelim}</code> matches the per-domain SSL cert so mail clients don't hit a certificate-name mismatch. Tokens: <code>{ldelim}domain{rdelim}</code>, <code>{ldelim}web_server_domain{rdelim}</code>, <code>{ldelim}mail_server_domain{rdelim}</code>. Leave blank to use the mail server's real hostname.</span>
                    </div>
                    <div class="form-group" data-field="phpmyadmin_url_pattern">
                        <label>phpMyAdmin URL pattern</label>
                        <input type="text" name="phpmyadmin_url_pattern" id="puq-pma-pattern" class="form-control" style="width:340px;" value="https://{ldelim}web_server_domain{rdelim}/phpmyadmin/">
                        <span class="help-block">Tokens: <code>{ldelim}domain{rdelim}</code>, <code>{ldelim}web_server_domain{rdelim}</code>, <code>{ldelim}mail_server_domain{rdelim}</code>.</span>
                    </div>
                    <div class="form-group" data-field="dkim_key_size_bits">
                        <label>DKIM key size <small class="text-muted">(bits)</small></label>
                        <select name="dkim_key_size_bits" id="puq-dkim-bits" class="form-control" style="width:200px;">
                            <option value="1024">1024</option>
                            <option value="2048" selected>2048 (recommended)</option>
                            <option value="4096">4096</option>
                        </select>
                    </div>
                    <div class="form-group" data-field="max_autoreply_message_length">
                        <label>Max auto-reply length <small class="text-muted">(chars)</small></label>
                        <input type="number" name="max_autoreply_message_length" id="puq-autoreply-max" class="form-control" style="width:200px;" min="128" max="65535" value="5000">
                    </div>
                    <hr>
                    <h5><i class="fa fa-key"></i> Password policy</h5>
                    <div class="form-group" data-field="min_password_length">
                        <label>Minimum password length</label>
                        <input type="number" name="min_password_length" id="puq-min-pass-len" class="form-control" style="width:200px;" min="4" max="128" value="8">
                        <span class="help-block">Applies to FTP, mailbox, DB and user passwords set by clients.</span>
                    </div>
                </div>

                {* ============== LOGGING & PERFORMANCE ============== *}
                <div role="tabpanel" class="tab-pane" id="puq-tab-logging">
                    <h5><i class="fa fa-download"></i> Log downloads</h5>
                    <div class="form-group" data-field="log_download_max_bytes">
                        <label>Max log download size <small class="text-muted">(bytes)</small></label>
                        <input type="number" name="log_download_max_bytes" id="puq-log-cap" class="form-control" style="width:240px;" min="1024" value="5242880">
                        <span class="help-block">Files larger than this require SSH/SFTP. Default: 5 MB.</span>
                    </div>
                    <div class="form-group" data-field="tail_log_min_lines">
                        <label>Min tail lines</label>
                        <input type="number" name="tail_log_min_lines" id="puq-tail-min" class="form-control" style="width:200px;" min="1" max="1000" value="50">
                    </div>
                    <div class="form-group" data-field="tail_log_max_lines">
                        <label>Max tail lines</label>
                        <input type="number" name="tail_log_max_lines" id="puq-tail-max" class="form-control" style="width:200px;" min="100" max="100000" value="5000">
                    </div>
                    <div class="form-group" data-field="mail_log_filter_tail_lines">
                        <label>Mail log filter window <small class="text-muted">(lines)</small></label>
                        <input type="number" name="mail_log_filter_tail_lines" id="puq-mail-tail" class="form-control" style="width:200px;" min="1000" max="1000000" value="50000">
                        <span class="help-block">How many tail lines to scan when grepping mail logs for a specific domain.</span>
                    </div>
                    <hr>
                    <h5><i class="fa fa-clock"></i> SSH timeouts</h5>
                    <div class="form-group" data-field="ssh_bash_timeout_seconds">
                        <label>Heavy bash timeout <small class="text-muted">(seconds)</small></label>
                        <input type="number" name="ssh_bash_timeout_seconds" id="puq-bash-timeout" class="form-control" style="width:200px;" min="10" max="3600" value="300">
                        <span class="help-block">Long-running provisioning scripts (FileGator/net2ftp installs etc.).</span>
                    </div>
                    <div class="form-group" data-field="apt_get_dpkg_lock_timeout_seconds">
                        <label>apt-get lock timeout <small class="text-muted">(seconds)</small></label>
                        <input type="number" name="apt_get_dpkg_lock_timeout_seconds" id="puq-apt-timeout" class="form-control" style="width:200px;" min="10" max="3600" value="120">
                    </div>
                </div>

                {* ============== INTEGRATIONS ============== *}
                <div role="tabpanel" class="tab-pane" id="puq-tab-integrations">
                    <span class="help-block">Override these to pin a private mirror or to track newer upstream releases. <strong>Use HTTPS only</strong> — the installer treats overridden URLs as &quot;custom build&quot; and skips checksum verification.</span>
                    <h5><i class="fa fa-folder"></i> File Managers</h5>
                    <div class="form-group" data-field="filegator_download_url">
                        <label>FileGator zip URL</label>
                        <input type="text" name="filegator_download_url" id="puq-fg-url" class="form-control" value="">
                    </div>
                    <div class="form-group" data-field="net2ftp_download_url">
                        <label>net2ftp zip URL</label>
                        <input type="text" name="net2ftp_download_url" id="puq-n2f-url" class="form-control" value="">
                    </div>
                    <div class="form-group" data-field="filegator_default_php_host">
                        <label>FileGator FTP host fallback</label>
                        <input type="text" name="filegator_default_php_host" id="puq-fg-host" class="form-control" style="width:200px;" value="127.0.0.1">
                    </div>
                    <hr>
                    <h5><i class="fa fa-code"></i> PHP repositories</h5>
                    <div class="form-group" data-field="php_ppa_ondrej_url">
                        <label>Ondrej PPA URL (Ubuntu)</label>
                        <input type="text" name="php_ppa_ondrej_url" id="puq-ppa-ondrej" class="form-control" value="">
                    </div>
                    <div class="form-group" data-field="php_ppa_sury_url">
                        <label>Sury PHP repo URL (Debian)</label>
                        <input type="text" name="php_ppa_sury_url" id="puq-ppa-sury" class="form-control" value="">
                    </div>
                    <div class="form-group" data-field="php_ppa_gpg_keyserver">
                        <label>GPG keyserver URL</label>
                        <input type="text" name="php_ppa_gpg_keyserver" id="puq-gpg-keyserver" class="form-control" value="">
                    </div>
                    <div class="form-group" data-field="ioncube_installer_url">
                        <label>IonCube installer script URL</label>
                        <input type="text" name="ioncube_installer_url" id="puq-ioncube-url" class="form-control" value="">
                    </div>
                </div>

                {* ============== NOTIFICATIONS ============== *}
                <div role="tabpanel" class="tab-pane" id="puq-tab-notifications">
                    <h5><i class="fa fa-ticket-alt"></i> Failure Ticket</h5>
                    <span class="help-block" style="margin-bottom:10px;">On <strong>terminal</strong> task failure (all retries exhausted) the module opens a support ticket.</span>
                    <div class="form-group" data-field="failure_ticket_enabled">
                        <div class="checkbox">
                            <label>
                                <input type="checkbox" name="failure_ticket_enabled" id="puq-failure-ticket-enabled" value="yes" checked>
                                <strong>Open a support ticket on terminal failure</strong>
                            </label>
                        </div>
                    </div>
                    <div class="form-group" data-field="failure_ticket_department_id">
                        <label>Department</label>
                        <select name="failure_ticket_department_id" id="puq-failure-ticket-dept" class="form-control" style="width:260px;">
                            <option value="0">— Select department —</option>
                        </select>
                    </div>
                    <div class="form-group" data-field="failure_ticket_priority">
                        <label>Priority</label>
                        <select name="failure_ticket_priority" id="puq-failure-ticket-priority" class="form-control" style="width:200px;">
                            <option value="Low">Low</option>
                            <option value="Medium" selected>Medium</option>
                            <option value="High">High</option>
                        </select>
                    </div>
                    <hr>
                    <h5><i class="fa fa-bell"></i> Client-area toast / polling</h5>
                    <div class="form-group" data-field="notification_display_duration_ms">
                        <label>Toast display duration <small class="text-muted">(ms)</small></label>
                        <input type="number" name="notification_display_duration_ms" id="puq-notif-ms" class="form-control" style="width:200px;" min="1000" max="60000" value="5000">
                    </div>
                    <div class="form-group" data-field="client_area_poll_max_duration_ms">
                        <label>Client-area max poll duration <small class="text-muted">(ms)</small></label>
                        <input type="number" name="client_area_poll_max_duration_ms" id="puq-poll-ms" class="form-control" style="width:200px;" min="60000" max="3600000" value="600000">
                        <span class="help-block">After this many milliseconds the client area stops auto-polling for status.</span>
                    </div>
                    <hr>
                    <h5><i class="fa fa-chart-line"></i> Analytics lookback</h5>
                    <div class="form-group" data-field="metric_lookback_days">
                        <label>Metric peak lookback <small class="text-muted">(days)</small></label>
                        <input type="number" name="metric_lookback_days" id="puq-metric-days" class="form-control" style="width:200px;" min="1" max="365" value="35">
                    </div>
                    <div class="form-group" data-field="recent_events_lookback_seconds">
                        <label>Recent events window <small class="text-muted">(seconds)</small></label>
                        <input type="number" name="recent_events_lookback_seconds" id="puq-events-sec" class="form-control" style="width:200px;" min="60" max="2592000" value="86400">
                    </div>
                </div>

                {* ============== MAINTENANCE ============== *}
                <div role="tabpanel" class="tab-pane" id="puq-tab-maintenance">
                    <h5><i class="fa fa-database"></i> Module Data</h5>
                    <div class="form-group" data-field="drop_tables_on_deactivate">
                        <div class="checkbox">
                            <label>
                                <input type="checkbox" name="drop_tables_on_deactivate" id="drop-tables-checkbox" value="yes">
                                <strong class="text-danger">Delete all database tables when module is deactivated</strong>
                            </label>
                        </div>
                        <span class="help-block">When disabled (default), tables are preserved after deactivation. Enable ONLY if fully uninstalling.</span>
                    </div>
                    <hr>
                    <h5><i class="fa fa-wrench"></i> Schema</h5>
                    <div class="form-group">
                        <label>Check &amp; repair tables</label>
                        <div>
                            <button type="button" class="btn btn-warning btn-sm" id="puq-repair-btn"><i class="fa fa-wrench"></i> Run schema check</button>
                        </div>
                        <span class="help-block">Scans every module table and brings it in sync with the current code: creates missing tables, adds missing columns, <strong class="text-danger">and drops columns that no longer exist in the code</strong>.</span>
                        <div id="puq-repair-result" style="margin-top:10px;"></div>
                    </div>
                </div>
            </div>
        </form>
    </div>
</div>

<div class="modal fade" id="puq-repair-confirm" 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 Schema Repair</h4>
            </div>
            <div class="modal-body">
                <p>This will add missing tables/columns and <strong class="text-danger">DROP any columns no longer defined in code</strong>. Proceed?</p>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
                <button type="button" class="btn btn-warning" id="puq-repair-go"><i class="fas fa-wrench"></i> Run</button>
            </div>
        </div>
    </div>
</div>

{literal}
<script>
(function() {
    var baseUrl = '{/literal}{$meta.admin_module_url}&ajax={literal}';

    // Map response key → input id. setVal walks this so adding a new field
    // is one line in defaults + one line here.
    var FIELD_IDS = {
        api_timeout_default: '#puq-api-timeout-default',
        api_timeout_heavy: '#puq-api-timeout-heavy',
        task_max_attempts: '#puq-task-max-attempts',
        task_backoff_minutes: '#puq-task-backoff',
        task_batch_size: '#puq-task-batch-size',
        task_retention_days: '#puq-task-retention-days',
        failure_ticket_priority: '#puq-failure-ticket-priority',
        dns_default_ttl: '#puq-dns-default-ttl',
        dns_ttl_min_seconds: '#puq-dns-ttl-min',
        dns_ttl_max_seconds: '#puq-dns-ttl-max',
        dns_record_max_value_length: '#puq-dns-max-len',
        dns_soa_refresh: '#puq-dns-soa-refresh',
        dns_soa_retry: '#puq-dns-soa-retry',
        dns_soa_expire: '#puq-dns-soa-expire',
        dns_soa_minimum: '#puq-dns-soa-minimum',
        ssl_fast_check_count: '#puq-ssl-fast-check-count',
        ssl_fast_check_minutes: '#puq-ssl-fast-check-minutes',
        ssl_normal_check_minutes: '#puq-ssl-normal-check-minutes',
        ssl_active_check_hours: '#puq-ssl-active-check-hours',
        ssl_freeze_after_failures: '#puq-ssl-freeze-after',
        ssl_freeze_duration_hours: '#puq-ssl-freeze-hours',
        default_ftp_root_path: '#puq-ftp-root',
        default_shell_for_users: '#puq-default-shell',
        hestia_ssh_default_username: '#puq-hestia-ssh-user',
        hestia_admin_username: '#puq-hestia-admin',
        webmail_url_pattern: '#puq-webmail-pattern',
        mail_server_host_pattern: '#puq-mailhost-pattern',
        phpmyadmin_url_pattern: '#puq-pma-pattern',
        dkim_key_size_bits: '#puq-dkim-bits',
        max_autoreply_message_length: '#puq-autoreply-max',
        min_password_length: '#puq-min-pass-len',
        log_download_max_bytes: '#puq-log-cap',
        tail_log_min_lines: '#puq-tail-min',
        tail_log_max_lines: '#puq-tail-max',
        mail_log_filter_tail_lines: '#puq-mail-tail',
        ssh_bash_timeout_seconds: '#puq-bash-timeout',
        apt_get_dpkg_lock_timeout_seconds: '#puq-apt-timeout',
        filegator_download_url: '#puq-fg-url',
        net2ftp_download_url: '#puq-n2f-url',
        filegator_default_php_host: '#puq-fg-host',
        php_ppa_ondrej_url: '#puq-ppa-ondrej',
        php_ppa_sury_url: '#puq-ppa-sury',
        php_ppa_gpg_keyserver: '#puq-gpg-keyserver',
        ioncube_installer_url: '#puq-ioncube-url',
        notification_display_duration_ms: '#puq-notif-ms',
        client_area_poll_max_duration_ms: '#puq-poll-ms',
        metric_lookback_days: '#puq-metric-days',
        recent_events_lookback_seconds: '#puq-events-sec'
    };

    // Load current settings
    $.ajax({
        url: baseUrl + 'getSettingsGeneral',
        dataType: 'json',
        success: function(r) {
            if (r.status === 'success' && r.data) {
                var d = r.data;
                Object.keys(FIELD_IDS).forEach(function(key){
                    if (d[key] !== undefined && d[key] !== null) $(FIELD_IDS[key]).val(d[key]);
                });
                $('#puq-failure-ticket-enabled').prop('checked', d.failure_ticket_enabled === 'yes');
                $('#drop-tables-checkbox').prop('checked', d.drop_tables_on_deactivate === 'yes');
                var $dept = $('#puq-failure-ticket-dept').empty().append('<option value="0">— Select department —</option>');
                var deps = d.departments || {};
                Object.keys(deps).forEach(function(id) {
                    $dept.append('<option value="' + id + '">' + esc(deps[id]) + '</option>');
                });
                $dept.val(d.failure_ticket_department_id || 0);
            } else {
                showNotification(r.msg || 'Failed to load settings', 'error');
            }
            $('#puq-settings-overlay').hide();
        },
        error: function() {
            showNotification('Failed to load settings', 'error');
            $('#puq-settings-overlay').hide();
        }
    });

    // Save
    $('#puq-settings-save').on('click', function() {
        formSubmit({
            btn: this,
            form: '#puq-settings-form',
            baseUrl: baseUrl,
            action: 'saveSettingsGeneral',
            onSuccess: function() {}
        });
    });

    // Schema repair
    $('#puq-repair-btn').on('click', function() {
        $('#puq-repair-confirm').modal('show');
    });

    $('#puq-repair-go').on('click', function() {
        var btn = this;
        var $out = $('#puq-repair-result').empty();
        btnSpinner(btn, 'Scanning...');

        $.ajax({
            url: baseUrl + 'repairSchema', type: 'POST', dataType: 'json',
            success: function(r) {
                $('#puq-repair-confirm').modal('hide');
                showNotification(r.msg || (r.status==='success'?'Done.':'Failed.'), r.status === 'success' ? 'success' : 'error');

                if (r.data && r.data.report) {
                    var html = '<table class="table table-condensed table-bordered" style="font-size:12px;margin-top:10px;"><thead><tr><th>Table</th><th>Result</th></tr></thead><tbody>';
                    Object.keys(r.data.report).forEach(function(t) {
                        var result = r.data.report[t];
                        var rowCls = '';
                        if (result.indexOf('ERROR') === 0) rowCls = 'class="danger"';
                        else if (result === 'created') rowCls = 'class="success"';
                        else if (result.indexOf('altered') === 0) rowCls = 'class="warning"';
                        html += '<tr ' + rowCls + '><td><code>' + esc(t) + '</code></td><td>' + esc(result) + '</td></tr>';
                    });
                    html += '</tbody></table>';
                    $out.html(html);
                }
            },
            error: function() {
                $('#puq-repair-confirm').modal('hide');
                showNotification('Request failed.', 'error');
            },
            complete: function() { btnRestore(btn, 'wrench', 'Run'); }
        });
    });
})();
</script>
{/literal}
