<?php
require __DIR__ . '/../../app/bootstrap.php';
require __DIR__ . '/../../app/database.php';
require __DIR__ . '/../../app/admin-sidebar.php';
require_login();

$adminName = isset($_SESSION['admin_name']) ? (string)$_SESSION['admin_name'] : 'Admin';
$adminUsername = isset($_SESSION['admin_username']) ? (string)$_SESSION['admin_username'] : 'admin';
$avatarText = strtoupper(substr($adminName !== '' ? $adminName : 'A', 0, 1));

$groups = list_domain_groups();
ensure_template_packs_dir();
initialize_builtin_template_packs();
$templatePacks = list_template_pack_options(array('page'));
$statuses = domain_status_options();

$error = '';
$success = '';
$recordFound = false;
$domainId = isset($_GET['id']) ? (int)$_GET['id'] : 0;
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['id'])) {
    $domainId = (int)$_POST['id'];
}

$form = array(
    'id' => $domainId,
    'domain' => '',
    'site_name' => '',
    'logo_url' => '',
    'site_language' => 'zh-CN',
    'group' => '',
    'template' => '',
    'status' => 'enabled',
    'remark' => ''
);

if ($domainId <= 0) {
    $error = '缺少有效的域名ID，无法编辑。';
} else {
    try {
        $pdo = db_connection();
        if ($_SERVER['REQUEST_METHOD'] === 'POST') {
            require_csrf();
            $form['domain'] = isset($_POST['domain']) ? trim((string)$_POST['domain']) : '';
            $form['site_name'] = isset($_POST['site_name']) ? trim((string)$_POST['site_name']) : '';
            $form['logo_url'] = isset($_POST['logo_url']) ? trim((string)$_POST['logo_url']) : '';
            $form['site_language'] = isset($_POST['site_language']) ? trim((string)$_POST['site_language']) : 'zh-CN';
            $form['group'] = isset($_POST['group']) ? trim((string)$_POST['group']) : '';
            $form['template'] = isset($_POST['template_pack']) ? trim((string)$_POST['template_pack']) : '';
            $form['status'] = isset($_POST['status']) ? trim((string)$_POST['status']) : 'enabled';
            $form['remark'] = isset($_POST['remark']) ? trim((string)$_POST['remark']) : '';
            try {
                update_domain_record($domainId, array(
                    'domain' => $form['domain'],
                    'site_name' => $form['site_name'],
                    'logo_url' => $form['logo_url'],
                    'site_language' => $form['site_language'],
                    'group_name' => $form['group'],
                    'template_pack' => $form['template'],
                    'status' => $form['status'],
                    'remark' => $form['remark'],
                ));
                $success = '域名 ' . $form['domain'] . ' 已更新成功。';
            } catch (Exception $innerEx) {
                $error = $innerEx->getMessage();
            }
        }

        ensure_domains_table_has_site_root();
        ensure_domains_table_has_template_pack();
        ensure_domains_table_has_variation();
        ensure_domains_table_has_logo_url();
        $loadStmt = $pdo->prepare('SELECT id, domain, site_name, logo_url, site_language, group_name, template_name, template_pack, template_variation, status, remark FROM domains WHERE id = :id LIMIT 1');
        $loadStmt->execute(array(':id' => $domainId));
        $row = $loadStmt->fetch();

        if (!$row) {
            $error = '未找到对应的域名记录。';
        } else {
            $recordFound = true;
            $form['id'] = (int)$row['id'];
            $form['domain'] = isset($row['domain']) ? $row['domain'] : $form['domain'];
            $form['site_name'] = isset($row['site_name']) ? $row['site_name'] : $form['site_name'];
            $form['logo_url'] = isset($row['logo_url']) ? $row['logo_url'] : $form['logo_url'];
            $form['site_language'] = isset($row['site_language']) ? $row['site_language'] : $form['site_language'];
            $form['group'] = isset($row['group_name']) ? $row['group_name'] : $form['group'];
            $form['template'] = isset($row['template_pack']) && $row['template_pack'] !== '' ? $row['template_pack'] : (isset($row['template_name']) ? $row['template_name'] : $form['template']);
            $form['status'] = isset($row['status']) ? $row['status'] : $form['status'];
            $form['remark'] = isset($row['remark']) ? $row['remark'] : $form['remark'];
        }
    } catch (Exception $e) {
        $error = '数据库操作失败：' . $e->getMessage();
    }
}
?><!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?php echo e(APP_NAME); ?> - 编辑域名</title>
    <link rel="stylesheet" href="/assets/css/admin-ui.css">
</head>
<body>
<div class="admin-shell">
    <?php render_admin_sidebar('domains', $adminName, $adminUsername, $avatarText); ?>
    <main class="admin-content">
        <div class="content-wrap">
            <header class="topbar">
                <div><h1>编辑域名</h1><p>修改域名基础信息并保存到 MySQL 数据库。</p></div>
                <div class="topbar-actions">
                    <a class="btn-ghost" href="/admin/domain/list.php">返回列表</a>
                </div>
            </header>

            <section class="page-card">
                <div class="card-head"><div><h2>域名编辑表单</h2><p>带 * 号为必填项。</p></div></div>

                <?php if ($success !== ''): ?>
                    <div class="mini-item" style="margin-bottom:16px; border-color: rgba(34,197,94,0.18); background: rgba(34,197,94,0.06);">
                        <strong style="color:#15803d;">保存成功</strong>
                        <p style="margin:0; color:#166534;"><?php echo e($success); ?></p>
                    </div>
                <?php endif; ?>

                <?php if ($error !== ''): ?>
                    <div class="mini-item" style="margin-bottom:16px; border-color: rgba(220,38,38,0.18); background: rgba(220,38,38,0.06);">
                        <strong style="color:#dc2626;">操作失败</strong>
                        <p style="margin:0; color:#b91c1c;"><?php echo e($error); ?></p>
                        <p style="margin:8px 0 0; color:#7f1d1d;">请确认该记录存在，且 `app/config.php` 与 `database/domains.sql` 已正确配置。</p>
                    </div>
                <?php endif; ?>

                <?php if ($recordFound): ?>
                    <form method="post" action="/admin/domain/edit.php?id=<?php echo (int)$form['id']; ?>">
                        <?php echo csrf_field(); ?>
                        <input type="hidden" name="id" value="<?php echo (int)$form['id']; ?>">
                        <div class="form-grid">
                            <div class="input-group">
                                <span>* 域名</span>
                                <input class="input" type="text" name="domain" value="<?php echo e($form['domain']); ?>" placeholder="例如 example.com">
                            </div>
                            <div class="input-group">
                                <span>* 站点名称</span>
                                <input class="input" type="text" name="site_name" value="<?php echo e($form['site_name']); ?>" placeholder="例如 AI企业站">
                            </div>
                            <div class="input-group" style="grid-column: 1 / -1;">
                                <span>站点 Logo <small style="color:#94a3b8;">（图片URL，留空则前台显示站点名称文本）</small></span>
                                <div style="display:flex; gap:10px; align-items:flex-start;">
                                    <input class="input" type="text" name="logo_url" id="logoUrlInput" value="<?php echo e($form['logo_url']); ?>" placeholder="https://example.com/logo.png 或 /uploads/logo.png" style="flex:1;">
                                    <label class="btn-soft" style="cursor:pointer; white-space:nowrap; margin:0; display:inline-flex; align-items:center; gap:4px;">
                                        <input type="file" accept="image/*" id="logoFileInput" style="display:none;">
                                        上传图片
                                    </label>
                                </div>
                                <?php if ($form['logo_url'] !== ''): ?>
                                <div style="margin-top:8px;"><img src="<?php echo e($form['logo_url']); ?>" alt="Logo预览" style="max-height:48px; max-width:240px; border:1px solid #e2e8f0; border-radius:6px; background:#f8fafc; padding:4px;" onerror="this.style.display='none'"></div>
                                <?php endif; ?>
                            </div>
                            <div class="input-group">
                                <span>* 站点语言</span>
                                <select class="select" name="site_language">
                                    <?php foreach (domain_language_options() as $langCode => $langLabel): ?>
                                        <option value="<?php echo e($langCode); ?>"<?php echo $form['site_language'] === $langCode ? ' selected' : ''; ?>><?php echo e($langLabel); ?></option>
                                    <?php endforeach; ?>
                                </select>
                                <p style="color:#6b7280;font-size:13px;margin:6px 0 0;">菜单、首页、AI 生成和定时任务会自动继承该语言。</p>
                            </div>
                            <div class="input-group" style="grid-column: 1 / -1;">
                                <span>站点目录</span>
                                <div class="input" style="display:flex; align-items:center; color:#64748b; background:#f8fafc;">系统自动使用共享站点目录：<?php echo e(default_shared_site_root()); ?></div>
                            </div>
                            <div class="input-group">
                                <span>* 域名分组</span>
                                <div style="display:flex; gap:8px; align-items:center;">
                                    <select class="select" id="groupSelect" onchange="toggleCustomGroup(this)" style="flex:1;">
                                        <option value="">请选择分组</option>
                                        <?php foreach ($groups as $g): ?>
                                            <option value="<?php echo e($g); ?>"<?php echo $form['group'] === $g ? ' selected' : ''; ?>><?php echo e($g); ?></option>
                                        <?php endforeach; ?>
                                        <option value="__custom__"<?php echo ($form['group'] !== '' && !in_array($form['group'], $groups, true)) ? ' selected' : ''; ?>>+ 自定义分组</option>
                                    </select>
                                    <input class="input" type="text" id="customGroupInput" placeholder="输入自定义分组名称" value="<?php echo ($form['group'] !== '' && !in_array($form['group'], $groups, true)) ? e($form['group']) : ''; ?>" style="flex:1; display:<?php echo ($form['group'] !== '' && !in_array($form['group'], $groups, true)) ? 'block' : 'none'; ?>; margin:0;">
                                </div>
                                <input type="hidden" name="group" id="groupValue" value="<?php echo e($form['group']); ?>">
                            </div>
                            <div class="input-group">
                                <span>* 模板套件</span>
                                <select class="select" name="template_pack">
                                    <option value="">请选择模板套件</option>
                                    <?php foreach ($templatePacks as $tp):
                                        $tpValue = isset($tp['value']) ? $tp['value'] : $tp['code'];
                                        $tpSelected = ($form['template'] === $tpValue || (strpos($form['template'], ':') === false && $form['template'] === $tp['code']));
                                    ?>
                                        <option value="<?php echo e($tpValue); ?>"<?php echo $tpSelected ? ' selected' : ''; ?>><?php echo e($tp['name']); ?> (<?php echo e(isset($tp['serial_label']) ? $tp['serial_label'] : $tp['code']); ?>) · <?php echo isset($tp['pack_type']) && $tp['pack_type'] === 'standard' ? '常规' : '变体'; ?></option>
                                    <?php endforeach; ?>
                                </select>
                                <small style="display:block;margin-top:6px;font-size:12px;color:#b45309;line-height:1.7;">
                                    ⚠ <strong>切换模板套件保存后</strong>，系统会自动清空 <code>site/<?php echo e($form['domain'] !== '' ? $form['domain'] : '{域名}'); ?>/</code> 下的旧静态文件（避免 nginx 命中旧模板）。<br>
                                    保存后请到「<a href="/admin/content/list.php" style="color:#4f46e5;">内容列表</a>」点击「全量静态发布」生成新模板的静态页面，否则前端会回落到 PHP 实时渲染（性能较差）。
                                </small>
                            </div>
                            <div class="input-group">
                                <span>状态</span>
                                <select class="select" name="status">
                                    <?php foreach ($statuses as $k => $v): ?>
                                        <option value="<?php echo e($k); ?>"<?php echo $form['status'] === $k ? ' selected' : ''; ?>><?php echo e($v); ?></option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                            <div class="input-group" style="grid-column: 1 / -1;">
                                <span>备注</span>
                                <textarea class="input" name="remark" rows="3" placeholder="可选，填写域名用途或关键词说明"><?php echo e($form['remark']); ?></textarea>
                            </div>
                        </div>
                        <div class="filter-row" style="margin-top:18px;">
                            <button class="btn-primary" type="submit">保存修改</button>
                            <a class="btn-ghost" href="/admin/domain/list.php">取消</a>
                        </div>
                    </form>

                    <?php
                    // 变异引擎预览（仅变体模板显示）
                    $editTpManifest = ($form['template'] !== '') ? load_template_pack_manifest($form['template']) : null;
                    $editTpType = $editTpManifest && isset($editTpManifest['pack_type']) ? $editTpManifest['pack_type'] : '';
                    if ($editTpType === '' && $form['template'] !== '') {
                        $editTpType = (strpos($form['template'], 'standard:') === 0) ? 'standard' : ((strpos($form['template'], 'variation:') === 0) ? 'variation' : '');
                    }
                    if ($editTpType === 'variation'):
                    $variation = function_exists('get_domain_variation') ? get_domain_variation($domainId) : array();
                    $colorSchemes = function_exists('variation_color_schemes') ? variation_color_schemes() : array();
                    $fontPairs = function_exists('variation_font_pairs') ? variation_font_pairs() : array();
                    $cIdx = isset($variation['color_index']) ? (int)$variation['color_index'] : 0;
                    $fIdx = isset($variation['font_index']) ? (int)$variation['font_index'] : 0;
                    $curColors = isset($colorSchemes[$cIdx]) ? $colorSchemes[$cIdx] : array();
                    $curFont = isset($fontPairs[$fIdx]) ? $fontPairs[$fIdx] : array();
                    ?>
                    <div style="margin-top:28px; padding:24px 28px; background:linear-gradient(135deg,#f8fafc,#eef2ff); border:1px solid #e2e8f0; border-radius:14px;">
                        <h3 style="margin:0 0 16px; font-size:16px; color:#1e293b;">🎨 模板变异方案 <span style="font-size:12px; color:#64748b; font-weight:400;">（基于域名ID自动生成，每个域名不同）</span></h3>
                        <div style="display:grid; grid-template-columns:1fr 1fr; gap:16px;">
                            <div style="background:#fff; padding:16px; border-radius:10px; border:1px solid #e2e8f0;">
                                <strong style="font-size:13px; color:#475569;">色彩方案 #<?php echo $cIdx + 1; ?></strong>
                                <div style="display:flex; gap:8px; margin-top:10px;">
                                    <?php foreach ($curColors as $prop => $val): ?>
                                    <div style="text-align:center;">
                                        <div style="width:36px;height:36px;border-radius:8px;background:<?php echo e($val); ?>;border:1px solid rgba(0,0,0,0.08);"></div>
                                        <span style="font-size:10px;color:#94a3b8;"><?php echo str_replace('--v-', '', $prop); ?></span>
                                    </div>
                                    <?php endforeach; ?>
                                </div>
                            </div>
                            <div style="background:#fff; padding:16px; border-radius:10px; border:1px solid #e2e8f0;">
                                <strong style="font-size:13px; color:#475569;">字体组合 #<?php echo $fIdx + 1; ?></strong>
                                <div style="margin-top:10px; font-size:12px; color:#64748b; line-height:1.8;">
                                    <div>标题：<span style="color:#1e293b;"><?php echo e(isset($curFont['heading']) ? mb_substr($curFont['heading'], 0, 40, 'UTF-8') : '-'); ?></span></div>
                                    <div>正文：<span style="color:#1e293b;"><?php echo e(isset($curFont['body']) ? mb_substr($curFont['body'], 0, 40, 'UTF-8') : '-'); ?></span></div>
                                </div>
                            </div>
                            <div style="background:#fff; padding:16px; border-radius:10px; border:1px solid #e2e8f0;">
                                <strong style="font-size:13px; color:#475569;">间距 / 圆角</strong>
                                <div style="margin-top:10px; font-size:12px; color:#64748b;">
                                    <span style="display:inline-block;padding:3px 10px;background:#f1f5f9;border-radius:6px;margin-right:8px;color:#334155;"><?php echo e(isset($variation['spacing']) ? $variation['spacing'] : '-'); ?></span>
                                    <span style="display:inline-block;padding:3px 10px;background:#f1f5f9;border-radius:6px;color:#334155;"><?php echo e(isset($variation['border']) ? $variation['border'] : '-'); ?></span>
                                </div>
                            </div>
                            <div style="background:#fff; padding:16px; border-radius:10px; border:1px solid #e2e8f0;">
                                <strong style="font-size:13px; color:#475569;">类名前缀 / 模块顺序</strong>
                                <div style="margin-top:10px; font-size:12px; color:#64748b;">
                                    <span style="font-family:monospace;color:#4f46e5;font-weight:600;"><?php echo e(isset($variation['class_prefix']) ? $variation['class_prefix'] : '-'); ?></span>
                                    <span style="margin-left:12px;">模块序：<?php echo e(isset($variation['module_order']) ? implode(',', $variation['module_order']) : '-'); ?></span>
                                </div>
                            </div>
                        </div>
                    </div>
                    <?php endif; ?>
                <?php endif; ?>
            </section>
        </div>
    </main>
</div>
<script src="/assets/js/admin-ui.js"></script>
<script>
function toggleCustomGroup(sel) {
    var customInput = document.getElementById('customGroupInput');
    var hiddenInput = document.getElementById('groupValue');
    if (sel.value === '__custom__') {
        customInput.style.display = '';
        customInput.focus();
        hiddenInput.value = customInput.value;
    } else {
        customInput.style.display = 'none';
        hiddenInput.value = sel.value;
    }
}
(function(){
    var customInput = document.getElementById('customGroupInput');
    if (customInput) {
        customInput.addEventListener('input', function(){
            document.getElementById('groupValue').value = this.value.trim();
        });
    }
    var form = document.querySelector('form[method="post"]');
    if (form) {
        form.addEventListener('submit', function(){
            var sel = document.getElementById('groupSelect');
            var hidden = document.getElementById('groupValue');
            if (sel && sel.value === '__custom__') {
                hidden.value = customInput ? customInput.value.trim() : '';
            } else if (sel) {
                hidden.value = sel.value;
            }
        });
    }
})();
(function(){
    var fileInput = document.getElementById('logoFileInput');
    var urlInput = document.getElementById('logoUrlInput');
    if (!fileInput || !urlInput) return;
    fileInput.addEventListener('change', function(){
        var file = this.files[0];
        if (!file) return;
        if (file.size > 5 * 1024 * 1024) { alert('图片不能超过5MB'); this.value = ''; return; }
        var fd = new FormData();
        fd.append('upload', file);
        var btn = this.parentElement;
        btn.style.opacity = '0.5';
        btn.style.pointerEvents = 'none';
        fetch('/admin/api/editor-upload-image.php', { method: 'POST', body: fd })
            .then(function(r){ return r.json(); })
            .then(function(d){
                btn.style.opacity = ''; btn.style.pointerEvents = '';
                if (d.uploaded && d.url) {
                    urlInput.value = d.url;
                    var preview = urlInput.closest('.input-group').querySelector('img');
                    if (preview) { preview.src = d.url; preview.style.display = ''; }
                    else {
                        var div = document.createElement('div');
                        div.style.marginTop = '8px';
                        div.innerHTML = '<img src="' + d.url + '" alt="Logo预览" style="max-height:48px;max-width:240px;border:1px solid #e2e8f0;border-radius:6px;background:#f8fafc;padding:4px;" onerror="this.style.display=\'none\'">';
                        urlInput.closest('.input-group').appendChild(div);
                    }
                } else {
                    alert(d.error && d.error.message ? d.error.message : '上传失败');
                }
            })
            .catch(function(){ btn.style.opacity = ''; btn.style.pointerEvents = ''; alert('上传请求失败'); });
        this.value = '';
    });
})();
</script>
</body>
</html>
