<?php
// Network & SSL tab — HAProxy Configuration Management, HAProxy API Key, and
// System Service SSL.
// Variables ($current_config) are prepared in the parent server-settings.php
// before the include.
?>

<div class="row g-3">
    <!-- HAProxy Configuration Management -->
    <div class="col-lg-6">
        <div class="card mb-4">
            <div class="card-header">
                <h5 class="card-title mb-0">HAProxy Configuration Management</h5>
            </div>
            <div class="card-body">
                <p class="text-muted small">Manage HAProxy configuration and monitor health status.</p>

                <div class="d-grid gap-2">
                    <form method="post" class="d-inline">
                        <input type="hidden" name="action" value="haproxy_regenerate_config">
                        <input type="hidden" name="csrf_token" value="<?php echo get_csrf_token(); ?>">
                        <button type="submit" class="btn btn-primary w-100">
                            <i class="fa fa-cog"></i> Regenerate Configuration
                        </button>
                    </form>

                    <form method="post" class="d-inline">
                        <input type="hidden" name="action" value="haproxy_reload_config">
                        <input type="hidden" name="csrf_token" value="<?php echo get_csrf_token(); ?>">
                        <button type="submit" class="btn btn-warning w-100">
                            <i class="fa fa-refresh"></i> Reload Configuration
                        </button>
                    </form>

                    <form method="post" class="d-inline">
                        <input type="hidden" name="action" value="haproxy_health_check">
                        <input type="hidden" name="csrf_token" value="<?php echo get_csrf_token(); ?>">
                        <button type="submit" class="btn btn-info w-100">
                            <i class="fa fa-heart"></i> Health Check
                        </button>
                    </form>
                </div>

                <hr>

                <div class="small text-muted">
                    <strong>Functions:</strong><br>
                    <strong>Regenerate:</strong> Rebuild HAProxy configuration for all active sites<br>
                    <strong>Reload:</strong> Reload HAProxy configuration without restarting<br>
                    <strong>Health Check:</strong> Check HAProxy service health status
                </div>
            </div>
        </div>
    </div>

    <!-- HAProxy API Key -->
    <div class="col-lg-6">
        <div class="card mb-4">
            <div class="card-header">
                <h5 class="card-title mb-0">HAProxy API Key</h5>
            </div>
            <div class="card-body">
                <p class="text-muted small">Bearer token used to authenticate against the HAProxy Manager API.</p>

                <form method="post">
                    <input type="hidden" name="action" value="update_haproxy_api_key">
                    <input type="hidden" name="csrf_token" value="<?php echo get_csrf_token(); ?>">

                    <div class="mb-3">
                        <label for="haproxy_api_key" class="form-label">API Key</label>
                        <input type="text" class="form-control" id="haproxy_api_key" name="haproxy_api_key"
                               value="<?php echo htmlspecialchars($current_config['haproxy_api_key'] ?? ''); ?>"
                               placeholder="your-secure-api-key-here" minlength="16" required>
                        <div class="form-text text-muted">Minimum 16 characters. Restart the HAProxy container after updating to apply.</div>
                    </div>

                    <button type="submit" class="btn btn-primary">
                        <i class="fa fa-save"></i> Update API Key
                    </button>
                </form>
            </div>
        </div>
    </div>

    <!-- System Service SSL Management -->
    <div class="col-lg-6">
        <div class="card mb-4">
            <div class="card-header">
                <h5 class="card-title mb-0">System Service SSL Certificates</h5>
            </div>
            <div class="card-body">
                <p class="text-muted small">Enable SSL certificates for system services like HTTP and FTP.</p>

                <form method="post">
                    <input type="hidden" name="action" value="enable_system_service_ssl">
                    <input type="hidden" name="csrf_token" value="<?php echo get_csrf_token(); ?>">

                    <div class="mb-3">
                        <label for="service_name" class="form-label">Service</label>
                        <select class="form-control" id="service_name" name="service_name" required>
                            <option value="">Select Service</option>
                            <option value="httpd">Apache HTTP Server</option>
                            <option value="proftpd">ProFTPD Server</option>
                        </select>
                    </div>

                    <div class="mb-3">
                        <label for="domain_name" class="form-label">Domain Name</label>
                        <input type="text" class="form-control" id="domain_name" name="domain_name"
                               placeholder="example.com" required>
                        <div class="form-text text-muted">Domain name for the SSL certificate</div>
                    </div>

                    <button type="submit" class="btn btn-primary">
                        <i class="fa fa-lock"></i> Enable SSL
                    </button>
                </form>

                <hr>

                <?php
                // Display current system service SSL certificates
                try {
                    require_once('/docker/whp/web/libs/ssl_manager.php');
                    $ssl_manager = new ssl_manager();
                    $system_certs = $ssl_manager->getSystemServiceSSLCertificates();

                    if (!empty($system_certs)) {
                        echo '<div class="small">';
                        echo '<strong>Current SSL Certificates:</strong><br>';
                        foreach ($system_certs as $cert) {
                            $status_class = $cert['ssl_enabled'] ? 'text-success' : 'text-muted';
                            $status_text = $cert['ssl_enabled'] ? 'Enabled' : 'Disabled';
                            echo '<div class="' . $status_class . '">';
                            echo '<i class="fa fa-' . ($cert['ssl_enabled'] ? 'lock' : 'unlock') . '"></i> ';
                            echo htmlspecialchars($cert['service_name']) . ' - ' . htmlspecialchars($cert['domain_name']) . ' (' . $status_text . ')';
                            echo '</div>';
                        }
                        echo '</div>';
                    } else {
                        echo '<div class="small text-muted">No system service SSL certificates configured</div>';
                    }
                } catch (Exception $e) {
                    echo '<div class="small text-danger">Error loading SSL certificates: ' . htmlspecialchars($e->getMessage()) . '</div>';
                }
                ?>
            </div>
        </div>
    </div>

    <!-- SSL Renewal Orchestrator -->
    <div class="col-lg-12">
        <div class="card mb-4">
            <div class="card-header d-flex justify-content-between align-items-center">
                <h5 class="card-title mb-0">SSL Renewal Orchestrator</h5>
                <?php
                $ssl_renewal_settings = [];
                if (file_exists('/docker/whp/settings.json')) {
                    $_settings_for_ssl = json_decode(file_get_contents('/docker/whp/settings.json'), true) ?: [];
                    $ssl_renewal_settings = is_array($_settings_for_ssl['ssl_renewal'] ?? null)
                        ? $_settings_for_ssl['ssl_renewal']
                        : [];
                }
                $ssl_orchestrator_on = !empty($ssl_renewal_settings['orchestrator_enabled']);
                if ($ssl_orchestrator_on) {
                    echo '<span class="badge bg-success">Active</span>';
                } else {
                    echo '<span class="badge bg-secondary">Disabled</span>';
                }
                ?>
            </div>
            <div class="card-body">
                <p class="text-muted small">
                    The renewal orchestrator runs every 30 minutes, attempting issuance/renewal for any
                    domain whose certificate is approaching expiry or in a recoverable failure state.
                    Failures are classified (DNS unreachable, DNS-01 mismatch, ACME rate limit, etc.) and
                    retried on a backoff schedule. Customers are notified by email on state transitions.
                </p>

                <form method="post">
                    <input type="hidden" name="action" value="update_ssl_renewal_settings">
                    <input type="hidden" name="csrf_token" value="<?php echo get_csrf_token(); ?>">

                    <div class="row">
                        <div class="col-md-6">
                            <h6 class="fw-bold mb-2">Renewal engine</h6>
                            <div class="form-check form-switch mb-3">
                                <input class="form-check-input" type="checkbox" id="ssl_orchestrator_enabled" name="ssl_orchestrator_enabled" value="1"
                                    <?php echo $ssl_orchestrator_on ? 'checked' : ''; ?>>
                                <label class="form-check-label" for="ssl_orchestrator_enabled">
                                    Enable renewal orchestrator
                                </label>
                                <div class="form-text">
                                    When ON, the orchestrator owns renewal: failures retry with backoff,
                                    customers get notified, and the panel surfaces per-domain state.
                                    When OFF, the cron self-skips and the legacy in-container certbot
                                    cron continues handling renewals (with no failure visibility).
                                </div>
                            </div>
                        </div>

                        <div class="col-md-6">
                            <h6 class="fw-bold mb-2">Customer notifications</h6>
                            <div class="form-check form-switch mb-2">
                                <input class="form-check-input" type="checkbox" id="ssl_email_unreachable_enabled" name="ssl_email_unreachable_enabled" value="1"
                                    <?php echo !empty($ssl_renewal_settings['email_unreachable_enabled']) ? 'checked' : ''; ?>>
                                <label class="form-check-label" for="ssl_email_unreachable_enabled">
                                    Email when domain becomes unreachable (24h+ failure)
                                </label>
                            </div>
                            <div class="form-check form-switch mb-2">
                                <input class="form-check-input" type="checkbox" id="ssl_email_manual_review_enabled" name="ssl_email_manual_review_enabled" value="1"
                                    <?php echo !empty($ssl_renewal_settings['email_manual_review_enabled']) ? 'checked' : ''; ?>>
                                <label class="form-check-label" for="ssl_email_manual_review_enabled">
                                    Email when retries exhausted (manual review)
                                </label>
                            </div>
                            <div class="form-check form-switch mb-2">
                                <input class="form-check-input" type="checkbox" id="ssl_email_dns_validation_enabled" name="ssl_email_dns_validation_enabled" value="1"
                                    <?php echo !empty($ssl_renewal_settings['email_dns_validation_enabled']) ? 'checked' : ''; ?>>
                                <label class="form-check-label" for="ssl_email_dns_validation_enabled">
                                    Email TXT record details for DNS-01 issuance
                                </label>
                            </div>
                            <div class="form-check form-switch mb-2">
                                <input class="form-check-input" type="checkbox" id="ssl_email_recovered_enabled" name="ssl_email_recovered_enabled" value="1"
                                    <?php echo !empty($ssl_renewal_settings['email_recovered_enabled']) ? 'checked' : ''; ?>>
                                <label class="form-check-label" for="ssl_email_recovered_enabled">
                                    Email when a previously failing certificate recovers
                                </label>
                                <div class="form-text">
                                    Off by default — turning this on can be noisy if many certs are
                                    transiently failing.
                                </div>
                            </div>
                        </div>
                    </div>

                    <div class="alert alert-info small mb-3">
                        <i class="fa fa-info-circle"></i>
                        Per-domain emails honour a 7-day cooldown for the same state transition, and
                        per-customer digests collapse 3+ same-state alerts into a single summary email.
                    </div>

                    <button type="submit" class="btn btn-primary">
                        <i class="fa fa-save"></i> Save SSL renewal settings
                    </button>
                </form>

                <hr>

                <div class="d-flex justify-content-between align-items-start">
                    <div>
                        <h6 class="fw-bold mb-1">Force a sweep right now</h6>
                        <p class="text-muted small mb-0">
                            Skip the next 30-minute cron tick and run an immediate sweep. Bypasses the
                            <code>orchestrator_enabled</code> kill switch (so you can verify behavior even
                            while the cron is dormant). Honours all email-cooldown rules.
                        </p>
                    </div>
                    <button type="button" id="ssl_force_sweep_btn" class="btn btn-warning ms-3 flex-shrink-0">
                        <i class="fa fa-bolt"></i> Run sweep now
                    </button>
                </div>
                <div id="ssl_force_sweep_result" class="mt-3" style="display:none;"></div>
            </div>
        </div>
    </div>
</div>

<script>
(function () {
    const btn = document.getElementById('ssl_force_sweep_btn');
    const out = document.getElementById('ssl_force_sweep_result');
    if (!btn || !out) return;
    btn.addEventListener('click', function () {
        const orig = btn.textContent;
        btn.disabled = true;
        btn.textContent = 'Running…';
        out.style.display = 'none';
        out.textContent = '';

        fetch('api/ssl-orchestrator-sweep.php?nonce=' + encodeURIComponent(<?php echo json_encode(get_csrf_token()); ?>), {
            method: 'POST',
            headers: {'X-CSRF-Token': <?php echo json_encode(get_csrf_token()); ?>},
        })
        .then(r => r.json())
        .then(data => {
            btn.disabled = false;
            btn.textContent = orig;
            out.style.display = '';
            if (data.status === 'success') {
                const c = data.counts || {};
                out.className = 'alert alert-success mt-3 small';
                out.textContent =
                    'Sweep complete in ' + (data.elapsed_s ?? '?') + 's: '
                    + 'sites=' + (c.sites_processed ?? 0)
                    + ', individual=' + (c.individual_processed ?? 0)
                    + ', success=' + (c.success ?? 0)
                    + ', transient=' + (c.transient ?? 0)
                    + ', unreachable=' + (c.unreachable ?? 0)
                    + ', manual_review=' + (c.manual_review ?? 0)
                    + (c.exception ? (', exception=' + c.exception) : '');
            } else {
                out.className = 'alert alert-danger mt-3 small';
                out.textContent = 'Sweep failed: ' + (data.message || 'unknown error');
            }
        })
        .catch(e => {
            btn.disabled = false;
            btn.textContent = orig;
            out.style.display = '';
            out.className = 'alert alert-danger mt-3 small';
            out.textContent = 'Request failed: ' + e.message;
        });
    });
})();
</script>
