// SSL证书功能
?>
<div class="card">
    <div class="card-header d-flex justify-content-between align-items-center">
        <h3 class="card-title mb-0"><?php echo L('ssl', 'menu'); ?></h3>
    </div>

    <div class="card-body">
        <ul class="nav nav-tabs mb-4" id="sslTabs" role="tablist">
            <li class="nav-item">
                <a class="nav-link active" id="ssl-status-tab" data-toggle="tab" href="#ssl-status" role="tab">当前证书</a>
            </li>
            <li class="nav-item">
                <a class="nav-link" id="ssl-list-tab" data-toggle="tab" href="#ssl-list" role="tab" onclick="loadSSLCertList()">证书列表</a>
            </li>
            <li class="nav-item">
                <a class="nav-link" id="ssl-apply-tab" data-toggle="tab" href="#ssl-apply" role="tab">申请证书</a>
            </li>
        </ul>

        <div class="tab-content" id="sslTabsContent">
            <!-- SSL部署 -->
            <div class="tab-pane fade show active" id="ssl-status" role="tabpanel">
                <!-- 状态提示栏 -->
                <div id="sslStatusGuide" class="alert alert-warning align-items-center justify-content-between mb-4 d-none">
                    <div>
                        <div id="sslStatusTitle" class="font-weight-bold mb-1">网站未开启HTTPS，站点访问可能存在风险</div>
                        <div id="sslStatusDesc" class="small opacity-80">建议立即开启HTTPS保护您的网站</div>
                    </div>
                    <button type="button" class="btn btn-success btn-sm" onclick="$('#sslKey').focus()">
                        <i class="fas fa-shield-alt"></i> 前往开启
                    </button>
                </div>

                <div class="mb-4">
                    <div class="d-flex align-items-center mb-3">
                        <i class="fas fa-shield-alt text-success mr-2"></i>
                        <h5 class="mb-0">当前证书 - [<span id="sslStatusText" class="text-muted">正在获取...</span>]</h5>
                    </div>
                    
                    <div class="row bg-light rounded p-3 mx-0">
                        <div class="col-md-3 col-sm-6 mb-3 mb-md-0">
                            <div class="small text-muted mb-1">证书分类</div>
                            <div id="sslCertType" class="font-weight-bold">-</div>
                        </div>
                        <div class="col-md-3 col-sm-6 mb-3 mb-md-0">
                            <div class="small text-muted mb-1">证书品牌</div>
                            <div id="sslCertBrand" class="font-weight-bold">-</div>
                        </div>
                        <div class="col-md-3 col-sm-6 mb-3 mb-md-0">
                            <div class="small text-muted mb-1">认证域名</div>
                            <div id="sslCertDomains" class="font-weight-bold text-truncate" title="">-</div>
                        </div>
                        <div class="col-md-3 col-sm-6">
                            <div class="small text-muted mb-1">到期时间</div>
                            <div id="sslCertExpiry" class="font-weight-bold">-</div>
                        </div>
                    </div>

                    <div class="mt-3 d-flex align-items-center">
                        <span class="mr-3 font-weight-bold">强制HTTPS</span>
                        <div class="custom-control custom-switch">
                            <input type="checkbox" class="custom-control-input" id="forceHttpsSwitch" onchange="toggleForceHttps(this)">
                            <label class="custom-control-label" for="forceHttpsSwitch"></label>
                        </div>
                    </div>
                </div>
                
                <!-- 证书内容区域 -->
                <div class="row mb-4">
                    <div class="col-md-6 form-group">
                        <label class="font-weight-bold">密钥(KEY)</label>
                        <textarea class="form-control text-monospace small" id="sslKey" style="height: 200px;" placeholder="请输入密钥内容"></textarea>
                    </div>
                    <div class="col-md-6 form-group">
                        <label class="font-weight-bold">证书(PEM格式)</label>
                        <textarea class="form-control text-monospace small" id="sslPem" style="height: 200px;" placeholder="请输入证书内容"></textarea>
                    </div>
                </div>
                
                <div class="alert alert-info small mb-4">
                    <i class="fas fa-info-circle mr-1"></i> 粘贴您的 *.key 以及 *.pem 内容，然后保存即可部署。
                </div>

                <div class="d-flex justify-content-between align-items-center border-top pt-3">
                    <div class="btn-group">
                        <button type="button" class="btn btn-primary btn-sm" onclick="saveSSLCertificate()">
                            <i class="fas fa-save mr-1"></i> 保存并启用
                        </button>
                        <button type="button" class="btn btn-danger btn-sm" onclick="closeSSL()">
                            <i class="fas fa-times mr-1"></i> 关闭SSL
                        </button>
                    </div>
                    <button type="button" class="btn btn-outline-primary btn-sm" onclick="loadSSLStatus()">
                        <i class="fas fa-sync-alt mr-1"></i> 刷新状态
                    </button>
                </div>

                <style>
                @media (max-width: 768px) {
                    #ssl-status .btn-group .btn {
                        padding: 6px 10px;
                        font-size: 12px;
                        border-radius: 8px;
                    }

                    #ssl-status .btn-outline-primary.btn-sm {
                        padding: 6px 10px;
                        font-size: 12px;
                        border-radius: 8px;
                    }
                }
                </style>
            </div>

            <!-- 证书列表 -->
            <div class="tab-pane fade" id="ssl-list" role="tabpanel">
                <div class="alert alert-info mb-4">
                    <i class="fas fa-info-circle mr-1"></i>
                    这里列出了您名下的所有可用证书，您可以选择一个进行部署。
                </div>
                <div id="sslCertList" class="min-vh-20">
                    <div class="text-center py-5 text-muted">
                        <i class="fas fa-spinner fa-spin fa-2x mb-2"></i>
                        <div>加载中...</div>
                    </div>
                </div>
            </div>

            <!-- 申请证书 -->
            <div class="tab-pane fade" id="ssl-apply" role="tabpanel">
                <div class="alert alert-info mb-4">
                    <i class="fas fa-info-circle mr-1"></i>
                    通过 Let's Encrypt 申请免费证书。申请前请确保域名已解析到本服务器。
                </div>
                
                <form id="applyCertForm">
                    <div class="form-group mb-4">
                        <label class="font-weight-bold">申请域名</label>
                        <div id="applyDomainList" class="d-flex flex-wrap mb-2 p-3 border rounded bg-light">
                            <div class="text-muted small"><i class="fas fa-spinner fa-spin mr-1"></i> 正在加载域名...</div>
                        </div>
                        <small class="text-muted">请勾选需要申请证书的域名</small>
                    </div>

                    <div class="form-group mb-4">
                        <label class="font-weight-bold d-block">验证方式</label>
                        <div class="custom-control custom-radio custom-control-inline">
                            <input type="radio" id="verify_file" name="verify_method" class="custom-control-input" value="file" checked>
                            <label class="custom-control-label" for="verify_file">文件验证 (推荐)</label>
                        </div>
                        <div class="custom-control custom-radio custom-control-inline">
                            <input type="radio" id="verify_dns" name="verify_method" class="custom-control-input" value="dns">
                            <label class="custom-control-label" for="verify_dns">DNS验证</label>
                        </div>
                    </div>

                    <div class="border-top pt-4">
                        <button type="button" class="btn btn-primary" onclick="applySSLCertificate()">
                            <i class="fas fa-paper-plane mr-1"></i> 提交申请
                        </button>
                    </div>
                </form>
            </div>

        </div>
    </div>

<script>
// 加载SSL状态
function loadSSLStatus() {
    var $statusText = $('#sslStatusText');
    $statusText.text('正在获取...');
    
    $.ajax({
        url: 'ajax.php?egn=getssl',
        type: 'GET',
        dataType: 'json',
        success: function(res) {
            if (res.status === true) {
                var data = res.data;
                $statusText.text(data.status ? '已部署' : '未部署');
                
                if (data.status) {
                    $('#sslCertType').text(data.type || '宝塔证书');
                    $('#sslCertBrand').text(data.cert_data && data.cert_data.issuer ? data.cert_data.issuer : '-');
                    $('#sslCertDomains').text(data.cert_data && data.cert_data.dns ? data.cert_data.dns.join(', ') : '-');
                    $('#sslCertExpiry').text(data.cert_data && data.cert_data.notAfter ? data.cert_data.notAfter : '-');
                    $('#forceHttpsSwitch').prop('checked', data.httpToHttps === true);
                    
                    // 填充证书内容（如果后端返回了）
                    if (data.key) $('#sslKey').val(data.key);
                    if (data.csr) $('#sslPem').val(data.csr);
                    
                    if (data.httpToHttps) {
                        $('#sslStatusGuide').addClass('d-none').removeClass('d-flex');
                    } else {
                        $('#sslStatusGuide').addClass('d-flex').removeClass('d-none');
                        $('#sslStatusTitle').text('网站未开启强制HTTPS跳转');
                        $('#sslStatusDesc').text('建议开启强制HTTPS，确保所有访问都通过加密连接');
                    }
                } else {
                    $('#sslStatusGuide').addClass('d-flex').removeClass('d-none');
                    $('#sslStatusTitle').text('网站未开启HTTPS，站点访问可能存在风险');
                    $('#sslStatusDesc').text('建议立即开启HTTPS保护您的网站');
                }
            } else {
                $statusText.text('获取失败');
                layer.alert(res.msg || '获取SSL状态失败');
            }
        },
        error: function() {
            $statusText.text('网络错误');
        }
    });
}

// 切换强制HTTPS
function toggleForceHttps(el) {
    var checked = $(el).is(':checked');
    var ii = layer.load(2, {shade: [0.1, '#fff']});
    $.ajax({
        url: 'ajax.php?egn=setHttpToHttps',
        type: 'POST',
        data: { type: checked ? 1 : 0 },
        dataType: 'json',
        success: function(res) {
            layer.close(ii);
            if (res.code === '配置成功' || res.status === true || res.code === '设置成功') {
                layer.msg(res.msg || '设置成功');
                loadSSLStatus();
            } else {
                layer.alert(res.msg || res.code || '操作失败');
                $(el).prop('checked', !checked);
            }
        },
        error: function() {
            layer.close(ii);
            layer.msg('网络错误');
            $(el).prop('checked', !checked);
        }
    });
}

// 保存SSL证书
function saveSSLCertificate() {
    var key = $('#sslKey').val().trim();
    var pem = $('#sslPem').val().trim();
    
    if (!key || !pem) {
        layer.alert('请填写完整的密钥和证书内容');
        return;
    }
    
    var $btn = $(event.currentTarget);
    var originalHtml = $btn.html();
    var ii = layer.load(2, {shade: [0.1, '#fff']});
    $btn.prop('disabled', true).html('<i class="fas fa-spinner fa-spin"></i> 正在保存...');
    
    $.ajax({
        url: 'ajax.php?egn=setssl',
        type: 'POST',
        data: {
            type: 1, // 自定义证书
            key: key,
            cert: pem
        },
        dataType: 'json',
        success: function(res) {
            layer.close(ii);
            if (res.code === '配置成功' || res.status === true) {
                layer.msg('证书部署成功');
                loadSSLStatus();
            } else {
                layer.alert(res.msg || '部署失败');
            }
        },
        error: function() {
            layer.close(ii);
            layer.msg('网络错误');
        },
        complete: function() {
            $btn.prop('disabled', false).html(originalHtml);
        }
    });
}

// 关闭SSL
function closeSSL() {
    layer.confirm('确定要关闭SSL吗？（此操作将停用HTTPS访问）', {
        btn: ['确定', '取消']
    }, function() {
        var ii = layer.load(2, {shade: [0.1, '#fff']});
        $.ajax({
            url: 'ajax.php?egn=setssl',
            type: 'POST',
            data: {
                type: -1 // 关闭
            },
            dataType: 'json',
            success: function(res) {
                layer.close(ii);
                if (res.code === '配置成功' || res.status === true) {
                    layer.msg('SSL已成功关闭');
                    loadSSLStatus();
                } else {
                    layer.alert(res.msg || '操作失败');
                }
            },
            error: function() {
                layer.close(ii);
                layer.msg('网络错误');
            }
        });
    });
}

// 加载证书列表
function loadSSLCertList() {
    var $list = $('#sslCertList');
    $list.html('<div class="text-center py-4 text-muted"><i class="fas fa-spinner fa-spin"></i> 正在获取证书列表...</div>');
    
    $.ajax({
        url: 'ajax.php?egn=getsslcert&_t=' + Date.now(),
        type: 'GET',
        dataType: 'json',
        cache: false,
        success: function(res) {
            console.log('证书列表响应:', res);
            if (res.code === 'success') {
                var certs = res.certificates || [];
                if (certs.length === 0) {
                    // 空列表时显示提示信息
                    $list.html('<div style="text-align: center; padding: 60px 20px; color: #5f6368;">' +
                        '<i class="fas fa-certificate" style="font-size: 48px; color: #dadce0; margin-bottom: 16px;"></i>' +
                        '<div style="font-size: 16px; margin-bottom: 8px;">暂无可用证书</div>' +
                        '<div style="font-size: 14px; color: #80868b;">您还没有申请或上传任何SSL证书</div>' +
                        '</div>');
                    return;
                }
                
                var html = '<div class="table-responsive"><table class="table table-hover"><thead><tr>' +
                    '<th>证书品牌</th><th>域名</th><th>到期时间</th><th>状态</th><th>操作</th>' +
                    '</tr></thead><tbody>';
                
                certs.forEach(function(cert) {
                    var statusClass = cert.status === 'valid' ? 'text-success' : 'text-danger';
                    var statusText = cert.status === 'valid' ? '有效' : '已过期';
                    
                    // 优先使用本地证书ID，其次是hash
                    var certId = cert.id || '';
                    var certHash = cert.hash || '';
                    
                    html += '<tr>' +
                        '<td>' + (cert.brand || '-') + '</td>' +
                        '<td>' + (cert.domain || '-') + '</td>' +
                        '<td>' + (cert.expire_date || '-') + ' <small class="text-muted">(' + cert.expire_days + '天)</small></td>' +
                        '<td class="' + statusClass + '">' + statusText + '</td>' +
                        '<td>' +
                            '<button class="btn btn-primary btn-sm mr-1" onclick="deployCert(\'' + certHash + '\', ' + certId + ')">部署</button> ' +
                            '<button class="btn btn-danger btn-sm" onclick="deleteCert(\'' + certHash + '\', ' + certId + ')">删除</button>' +
                        '</td>' +
                        '</tr>';
                });
                
                html += '</tbody></table></div>';
                $list.html(html);
            } else {
                $list.html('<div class="alert alert-danger">' + (res.msg || '获取列表失败') + '</div>');
            }
        },
        error: function(xhr, status, error) {
            console.error('证书列表加载错误:', xhr, status, error);
            // 网络错误时显示友好的错误提示
            $list.html('<div style="text-align: center; padding: 60px 20px; color: #5f6368;">' +
                '<i class="fas fa-exclamation-triangle" style="font-size: 48px; color: #f4b400; margin-bottom: 16px;"></i>' +
                '<div style="font-size: 16px; margin-bottom: 8px;">加载失败</div>' +
                '<div style="font-size: 14px; color: #80868b; margin-bottom: 16px;">网络连接出现问题，请检查网络后重试</div>' +
                '<button class="btn btn-primary btn-sm" onclick="loadSSLCertList()">重新加载</button>' +
                '</div>');
        }
    });
}

// 部署证书
function deployCert(hash, certId) {
    if (!hash && !certId) {
        layer.alert('证书标识为空，无法部署');
        return;
    }
    layer.confirm('确定要部署此证书吗？', {
        btn: ['确定', '取消']
    }, function() {
        var ii = layer.load(2, {shade: [0.1, '#fff']});
        var postData = { cert_hash: hash };
        if (certId) {
            postData.cert_id = certId;
        }
        $.ajax({
            url: 'ajax.php?egn=deploycert',
            type: 'POST',
            data: postData,
            dataType: 'json',
            success: function(res) {
                layer.close(ii);
                if (res.code === 'success' || res.status === true || res.code === '部署成功') {
                    layer.msg('证书部署成功');
                    $('#ssl-status-tab').tab('show');
                    loadSSLStatus();
                } else {
                    var msg = res.msg || res.code || '部署失败';
                    if (res.details) {
                        msg += '<br><br>详情: ' + res.details;
                    }
                    layer.alert(msg);
                }
            },
            error: function(xhr) {
                layer.close(ii);
                layer.msg('网络错误: ' + (xhr.statusText || '未知错误'));
            }
        });
    });
}

// 删除证书
function deleteCert(hash, certId) {
    if (!hash && !certId) {
        layer.alert('证书标识为空，无法删除');
        return;
    }
    layer.confirm('确定要从证书库中删除此证书吗？', {
        btn: ['确定', '取消']
    }, function() {
        var ii = layer.load(2, {shade: [0.1, '#fff']});
        var postData = { action: 'deletecert', cert_hash: hash };
        if (certId) {
            postData.cert_id = certId;
        }
        $.ajax({
            url: './api/api_router.php',
            type: 'POST',
            data: postData,
            dataType: 'json',
            success: function(res) {
                layer.close(ii);
                console.log('删除证书响应:', res);
                if (res.code === 'success' || res.status === true || res.msg === '删除成功' || (res.msg && res.msg.indexOf('已删除') !== -1) || (res.msg && res.msg.indexOf('已清理') !== -1)) {
                    layer.msg('删除成功');
                    // 延迟500ms后刷新列表，确保服务器端删除完成
                    setTimeout(function() {
                        loadSSLCertList();
                    }, 500);
                } else {
                    layer.alert(res.msg || res.code || '删除失败');
                }
            },
            error: function(xhr) {
                layer.close(ii);
                console.error('删除证书错误:', xhr);
                layer.msg('网络错误: ' + (xhr.statusText || '未知错误'));
            }
        });
    });
}

// 加载申请域名的列表
function loadApplyDomains() {
    var $container = $('#applyDomainList');
    $container.html('<div class="text-center py-4 text-muted"><i class="fas fa-spinner fa-spin"></i> 正在加载域名...</div>');
    
    $.ajax({
        url: 'ajax.php?egn=getssl',
        type: 'GET',
        dataType: 'json',
        success: function(res) {
            if (res.status === true && res.data) {
                // 优先使用 site_domains (站点绑定域名)，如果没有则退而求其次使用 cert_data.dns (证书域名)
                var domains = (res.data.site_domains && res.data.site_domains.length > 0) ? res.data.site_domains : (res.data.cert_data ? res.data.cert_data.dns : null);
                
                if (domains && Array.isArray(domains) && domains.length > 0) {
                    var html = '';
                    domains.forEach(function(domain) {
                        html += '<label class="m-1" style="display: flex; align-items: center; background: #f8f9fa; padding: 8px 15px; border-radius: 20px; cursor: pointer; border: 1px solid #eef2f7;">' +
                            '<input type="checkbox" name="apply_domains" class="mr-2" value="' + domain + '" checked> ' + domain +
                            '</label>';
                    });
                    $container.html(html);
                } else {
                    $container.html('<div class="alert alert-warning">未能获取到网站域名，请前往“域名管理”添加域名后再试</div>');
                }
            } else {
                $container.html('<div class="alert alert-warning">未能获取到网站域名，请刷新重试</div>');
            }
        },
        error: function() {
            $container.html('<div class="alert alert-danger">加载域名失败</div>');
        }
    });
}

// 申请SSL证书
function applySSLCertificate() {
    var domains = [];
    $('input[name="apply_domains"]:checked').each(function() {
        domains.push($(this).val());
    });
    
    if (domains.length === 0) {
        layer.alert('请至少勾选一个域名');
        return;
    }
    
    var verifyMethod = $('input[name="verify_method"]:checked').val();
    var $btn = $(event.currentTarget);
    var originalHtml = $btn.html();
    
    var ii = layer.load(2, {shade: [0.1, '#fff']});
    $btn.prop('disabled', true).html('<i class="fas fa-spinner fa-spin"></i> 正在申请并部署...');
    
    $.ajax({
        url: 'ajax.php?egn=applycert',
        type: 'POST',
        data: {
            brand: 'letsencrypt',
            verifyMethod: verifyMethod,
            domains: JSON.stringify(domains)
        },
        dataType: 'json',
        success: function(res) {
            layer.close(ii);
            if (res.code === 'success' || res.status === true || (res.msg && res.msg.indexOf('成功') !== -1)) {
                layer.msg(res.msg || '申请证书成功并已部署');
                $('#ssl-status-tab').tab('show');
                loadSSLStatus();
            } else {
                var msg = res.msg || res.code || '申请失败';
                if (res.details) {
                    msg += '<br><br>详情: ' + res.details;
                }
                layer.alert(msg);
            }
        },
        error: function(xhr) {
            layer.close(ii);
            layer.msg('网络错误: ' + (xhr.statusText || '未知错误'));
        },
        complete: function() {
            $btn.prop('disabled', false).html(originalHtml);
        }
    });
}

// 初始化
$(document).ready(function() {
    loadSSLStatus();
});

// 监听Tab切换
$(document).on('shown.bs.tab', 'a[data-toggle="tab"]', function (e) {
    if (e.target.id === 'ssl-apply-tab') {
        loadApplyDomains();
    }
});
</script>