<?php

require_once __DIR__ . '/common.php';

admin_require_login();

$pdo       = db();
$adminUser = admin_current_user();
$siteTitle = get_setting('site.title', '六柱博客');

$errors = [];
$infos  = [];

ensure_new_sites_style_key_column($pdo);
$newSiteStyleOptions = get_new_site_style_options();

function normalize_new_site_url(string $url): string
{
    $url = trim($url);
    if ($url === '') {
        return '';
    }
    if (!preg_match('#^https?://#i', $url)) {
        $url = 'https://' . ltrim($url, '/');
    }
    return $url;
}


if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (!admin_csrf_check($_POST['csrf_token'] ?? null)) {
        $errors[] = '请求已失效，请刷新页面后重试。';
    } else {
        $type   = $_POST['type']   ?? '';
        $action = $_POST['action'] ?? '';

        try {
            if ($type === 'friend_link') {
                if ($action === 'create') {
                    $name        = trim((string)($_POST['name'] ?? ''));
                    $url         = trim((string)($_POST['url'] ?? ''));
                    $description = trim((string)($_POST['description'] ?? ''));
                    $sortOrder   = (int)($_POST['sort_order'] ?? 0);
                    if ($name !== '' && $url !== '') {
                        $stmt = $pdo->prepare("
                            INSERT INTO friend_links
                                (name, url, description, sort_order, status, is_manual, created_at, updated_at)
                            VALUES
                                (:name, :url, :description, :sort_order, 'approved', 1, :t, :t)
                        ");
                        $t = time();
                        $stmt->execute([
                            ':name'        => $name,
                            ':url'         => $url,
                            ':description' => $description,
                            ':sort_order'  => $sortOrder,
                            ':t'           => $t,
                        ]);
                    }
                } elseif ($action === 'update') {
                    $id          = (int)($_POST['id'] ?? 0);
                    $name        = trim((string)($_POST['name'] ?? ''));
                    $url         = trim((string)($_POST['url'] ?? ''));
                    $description = trim((string)($_POST['description'] ?? ''));
                    $sortOrder   = (int)($_POST['sort_order'] ?? 0);
                    if ($id > 0 && $name !== '' && $url !== '') {
                        $stmt = $pdo->prepare("
                            UPDATE friend_links
                            SET name = :name,
                                url  = :url,
                                description = :description,
                                sort_order  = :sort_order,
                                updated_at  = :t
                            WHERE id = :id
                        ");
                        $stmt->execute([
                            ':name'        => $name,
                            ':url'         => $url,
                            ':description' => $description,
                            ':sort_order'  => $sortOrder,
                            ':t'           => time(),
                            ':id'          => $id,
                        ]);
                    }
                } elseif ($action === 'delete') {
                    $id = (int)($_POST['id'] ?? 0);
                    if ($id > 0) {
                        $stmt = $pdo->prepare("DELETE FROM friend_links WHERE id = :id");
                        $stmt->execute([':id' => $id]);
                    }
                }
            } elseif ($type === 'new_site') {
                if ($action === 'create') {
                    $name      = trim((string)($_POST['name'] ?? ''));
                    $url       = normalize_new_site_url((string)($_POST['url'] ?? ''));
                    $sortOrder = (int)($_POST['sort_order'] ?? 0);
                    $styleKey  = normalize_new_site_style_key((string)($_POST['style_key'] ?? 'auto'));
                    if ($name !== '' && $url !== '') {
                        $stmt = $pdo->prepare("
                            INSERT INTO new_sites (name, url, style_key, sort_order, is_active, created_at, updated_at)
                            VALUES (:name, :url, :style_key, :sort_order, 1, :t, :t)
                        ");
                        $t = time();
                        $stmt->execute([
                            ':name'       => $name,
                            ':url'        => $url,
                            ':style_key'  => $styleKey,
                            ':sort_order' => $sortOrder,
                            ':t'          => $t,
                        ]);
                        $infos[] = '已新增最新网址：' . $name;
                    }
                } elseif ($action === 'create_batch') {
                $raw = trim((string)($_POST['batch_lines'] ?? ''));
                $defaultSort = (int)($_POST['batch_sort_order'] ?? 0);
                $created = 0;
                $skipped = 0;

                if ($raw !== '') {
                    $stmt = $pdo->prepare("
                        INSERT INTO new_sites (name, url, style_key, sort_order, is_active, created_at, updated_at)
                        VALUES (:name, :url, :style_key, :sort_order, 1, :t, :t)
                    ");
                    $lines = preg_split('/\r\n|\r|\n/u', $raw) ?: [];
                    foreach ($lines as $line) {
                        $line = trim((string)$line);
                        if ($line === '') {
                            continue;
                        }

                        $parts = array_map('trim', explode('|', $line));
                        $name = '';
                        $url = '';
                        $styleKey = 'auto';

                        if (count($parts) >= 3) {
                            $name = (string)$parts[0];
                            $url = normalize_new_site_url((string)$parts[1]);
                            $styleKey = normalize_new_site_style_key((string)$parts[2]);
                        } elseif (count($parts) === 2) {
                            $name = (string)$parts[0];
                            $url = normalize_new_site_url((string)$parts[1]);
                        } else {
                            $url = normalize_new_site_url((string)$parts[0]);
                            $name = (string)$parts[0];
                        }

                        if ($name === '' || $url === '') {
                            $skipped++;
                            continue;
                        }

                        $now = time();
                        $stmt->execute([
                            ':name' => $name,
                            ':url' => $url,
                            ':style_key' => $styleKey,
                            ':sort_order' => $defaultSort,
                            ':t' => $now,
                        ]);
                        $created++;
                    }
                }

                if ($created > 0) {
                    $infos[] = '批量新增完成：成功 ' . $created . ' 条，跳过 ' . $skipped . ' 条。';
                } else {
                    $errors[] = '批量新增失败：没有可写入的有效行，请按“名称|URL|样式”格式填写。';
                }
            } elseif ($action === 'update') {
                $id        = (int)($_POST['id'] ?? 0);
                $name      = trim((string)($_POST['name'] ?? ''));
                $url       = normalize_new_site_url((string)($_POST['url'] ?? ''));
                $sortOrder = (int)($_POST['sort_order'] ?? 0);
                $styleKey  = normalize_new_site_style_key((string)($_POST['style_key'] ?? 'auto'));
                if ($id > 0 && $name !== '' && $url !== '') {
                    $stmt = $pdo->prepare("
                        UPDATE new_sites
                        SET name       = :name,
                            url        = :url,
                            style_key  = :style_key,
                            sort_order = :sort_order,
                            updated_at = :t
                        WHERE id = :id
                    ");
                    $stmt->execute([
                        ':name'       => $name,
                        ':url'        => $url,
                        ':style_key'  => $styleKey,
                        ':sort_order' => $sortOrder,
                        ':t'          => time(),
                        ':id'         => $id,
                    ]);
                    $infos[] = '已更新最新网址 ID=' . $id;
                }
            } elseif ($action === 'toggle') {
                $id     = (int)($_POST['id'] ?? 0);
                $active = (int)($_POST['is_active'] ?? 0);
                if ($id > 0) {
                    $stmt = $pdo->prepare("
                        UPDATE new_sites
                        SET is_active = :active, updated_at = :t
                        WHERE id = :id
                    ");
                    $stmt->execute([
                        ':active' => $active ? 1 : 0,
                        ':t'      => time(),
                        ':id'     => $id,
                    ]);
                    $infos[] = '已更新最新网址状态 ID=' . $id;
                }
            } elseif ($action === 'delete') {
                $id = (int)($_POST['id'] ?? 0);
                if ($id > 0) {
                    $stmt = $pdo->prepare("DELETE FROM new_sites WHERE id = :id");
                    $stmt->execute([':id' => $id]);
                    $infos[] = '已删除最新网址 ID=' . $id;
                }
            }
            }
        } catch (Throwable $e) {
            $errors[] = '操作失败：' . $e->getMessage();
        }
    }
}


$friendLinks = [];
$newSites    = [];

try {
    $stmt = $pdo->query("
        SELECT id, name, url, description, sort_order, status
        FROM friend_links
        ORDER BY sort_order DESC, id DESC
    ");
    $friendLinks = $stmt->fetchAll() ?: [];
} catch (Throwable $e) {
    $errors[] = '无法读取友情链接列表（可能尚未初始化数据库）。';
}

try {
    $stmt = $pdo->query("
        SELECT id, name, url, style_key, sort_order, is_active
        FROM new_sites
        ORDER BY sort_order DESC, id DESC
    ");
    $newSites = $stmt->fetchAll() ?: [];
} catch (Throwable $e) {
    $errors[] = '无法读取“最新网址”列表（可能尚未初始化数据库）。';
}

?><!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>友链与最新网址 - <?php echo h($siteTitle); ?></title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <style>
        html, body { height:100%;  margin:0; padding:0; }
        body {
            margin: 0; padding:0;
            font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", system-ui, sans-serif;
            background: #020617;
            color: #e5e7eb;
        }
        a { color: #60a5fa; text-decoration: none; }
        a:hover { text-decoration: underline; }

        .topbar {
            background: #0f172a;
            border-bottom: 1px solid #1f2937;
            padding:18px 16px 6px;
            display: flex;
            align-items:flex-start;
            justify-content: space-between;
         margin:0;  margin-top:-12px; }
        .topbar-title { font-size: 16px; font-weight: 600; }
        .topbar-user  { font-size: 13px; color: #9ca3af; }
        .topbar-nav a { margin-left: 10px; font-size: 13px; }

        .page {
            max-width: 1000px;
            margin: 0 auto;
            padding: 16px;
        }

        .card {
            background: #020617;
            border-radius: 6px;
            border: 1px solid #1f2937;
            padding: 12px 14px;
            margin-bottom: 12px;
        }
        .card-title {
            font-size: 14px;
            font-weight: 600;
            margin-bottom: 8px;
        }

        table {
            width: 100%;
            border-collapse: collapse;
            font-size: 13px;
        }
        th, td {
            border-bottom: 1px solid #1f2937;
            padding: 6px 4px;
            text-align: left;
            vertical-align: top;
        }
        th {
            color: #9ca3af;
            font-weight: 500;
        }

        .form-row {
            display: flex;
            gap: 6px;
            margin-bottom: 6px;
        }
        .form-row input,
        .form-row select,
        .form-row textarea {
            padding: 4px 6px;
            border-radius: 4px;
            border: 1px solid #374151;
            background: #020617;
            color: #e5e7eb;
            font-size: 13px;
        }

        .btn {
            border-radius: 999px;
            border: 1px solid #3b82f6;
            background: #1d4ed8;
            color: #e5e7eb;
            font-size: 12px;
            padding: 4px 8px;
            cursor: pointer;
        }

        .small-text {
            font-size: 12px;
            color: #9ca3af;
            margin-top: 4px;
        }

        .errors {
            background: #7f1d1d;
            border: 1px solid #fecaca;
            color: #fee2e2;
            padding: 6px 8px;
            border-radius: 4px;
            font-size: 12px;
            margin-bottom: 10px;
        }
    </style>
</head>
<body style="margin:0;padding:0;"><div class="topbar">
        <div class="topbar-title">六柱博客 · 后台</div>
        <div class="topbar-user">
            管理员：<?php echo h($adminUser['nickname'] ?? $adminUser['email'] ?? ''); ?>
            <span class="topbar-nav">
                <a href="index.php">仪表板</a>
                <a href="articles.php">文章</a>
                <a href="categories.php">分类</a>
                <a href="tags.php">&#26631;&#31614;</a>
                <a href="comments.php">评论</a>
                <a href="links.php">友链</a>
                <a href="media.php">文件</a>
                <a href="users.php">会员</a>
                <a href="sensitive_words.php">敏感词</a>
                <a href="stats.php">流量</a>
                <a href="security.php">防护</a>
                <a href="logs.php">日志</a>
                <a href="settings.php">设置</a>
                <a href="backup_sqlite.php">&#25968;&#25454;</a>
                <a href="../index.php">前台</a>
                <a href="../logout.php">退出</a>
            </span>
        </div>
    </div>

    <div class="page">
        <?php if ($errors): ?>
            <div class="errors">
                <?php foreach ($errors as $err): ?>
                    <div><?php echo h($err); ?></div>
                <?php endforeach; ?>
            </div>
        <?php endif; ?>
        <?php if ($infos): ?>
            <div class="small-text" style="margin-bottom:10px;color:#86efac;">
                <?php foreach ($infos as $msg): ?>
                    <div><?php echo h($msg); ?></div>
                <?php endforeach; ?>
            </div>
        <?php endif; ?>

        <div class="card">
            <div class="card-title">新增友情链接</div>
            <form method="post">
                <input type="hidden" name="csrf_token" value="<?php echo h(admin_csrf_token()); ?>">
                <input type="hidden" name="type" value="friend_link">
                <input type="hidden" name="action" value="create">
                <div class="form-row">
                    <input type="text" name="name" placeholder="站点名称" required>
                    <input type="text" name="url" placeholder="URL，例如：https://example.com" required>
                    <input type="number" name="sort_order" placeholder="排序" value="0">
                </div>
                <div class="form-row">
                    <input type="text" name="description" style="flex:1;" placeholder="说明（可选）">
                </div>
                <button type="submit" class="btn">添加友情链接</button>
            </form>
            <div class="small-text">
                前台可以在“友链页面”展示全部友情链接，左侧栏展示部分重要友链。
            </div>
        </div>

        <div class="card">
            <div class="card-title">友情链接列表</div>
            <?php if ($friendLinks): ?>
                <table>
                    <thead>
                        <tr>
                            <th>ID</th>
                            <th>名称</th>
                            <th>URL</th>
                            <th>说明</th>
                            <th>排序</th>
                            <th>状态</th>
                            <th>操作</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($friendLinks as $fl): ?>
                            <?php $id = (int)$fl['id']; ?>
                            <tr>
                                <td><?php echo $id; ?></td>
                                <td>
                                    <input type="text"
                                           name="name"
                                           value="<?php echo h($fl['name']); ?>"
                                           form="fl-form-<?php echo $id; ?>"
                                           style="width:120px;">
                                </td>
                                <td>
                                    <input type="text"
                                           name="url"
                                           value="<?php echo h($fl['url']); ?>"
                                           form="fl-form-<?php echo $id; ?>"
                                           style="width:220px;">
                                </td>
                                <td>
                                    <input type="text"
                                           name="description"
                                           value="<?php echo h($fl['description']); ?>"
                                           form="fl-form-<?php echo $id; ?>"
                                           style="width:160px;">
                                </td>
                                <td>
                                    <input type="number"
                                           name="sort_order"
                                           value="<?php echo (int)$fl['sort_order']; ?>"
                                           form="fl-form-<?php echo $id; ?>"
                                           style="width:60px;">
                                </td>
                                <td><?php echo h(status_label_cn((string)$fl['status'], 'link')); ?></td>
                                <td>
                                    <form method="post" id="fl-form-<?php echo $id; ?>" style="display:inline;">
                                        <input type="hidden" name="csrf_token" value="<?php echo h(admin_csrf_token()); ?>">
                                        <input type="hidden" name="type" value="friend_link">
                                        <input type="hidden" name="action" value="update">
                                        <input type="hidden" name="id" value="<?php echo $id; ?>">
                                    </form>
                                    <button type="submit" class="btn" form="fl-form-<?php echo $id; ?>">保存</button>

                                    <form method="post" style="display:inline;margin-left:4px;">
                                        <input type="hidden" name="csrf_token" value="<?php echo h(admin_csrf_token()); ?>">
                                        <input type="hidden" name="type" value="friend_link">
                                        <input type="hidden" name="action" value="delete">
                                        <input type="hidden" name="id" value="<?php echo $id; ?>">
                                        <button type="submit" class="btn" onclick="return confirm('确定删除该友情链接？')">删除</button>
                                    </form>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            <?php else: ?>
                <p class="small-text">暂无友情链接记录。</p>
            <?php endif; ?>
        </div>

        <div class="card">
            <div class="card-title">新增“最新网址”</div>
            <form method="post">
                <input type="hidden" name="csrf_token" value="<?php echo h(admin_csrf_token()); ?>">
                <input type="hidden" name="type" value="new_site">
                <input type="hidden" name="action" value="create">
                <div class="form-row">
                    <input type="text" name="name" placeholder="名称（如：主站域名 / 备用域名1）" required>
                    <input type="text" name="url" placeholder="域名或完整 URL" required>
                    <input type="number" name="sort_order" placeholder="排序" value="0">
                    <select name="style_key" title="样式主题">
                        <?php foreach ($newSiteStyleOptions as $styleValue => $styleLabel): ?>
                            <option value="<?php echo h($styleValue); ?>"><?php echo h($styleLabel); ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <button type="submit" class="btn">添加最新网址</button>
            </form>
            <div class="small-text">
                前台左侧“最新网址”模块显示这里配置的条目，用于主站被封时引导用户访问其他入口。<br>
                样式支持：自动 / 霓虹 / 琉璃 / 金属 / 糖果 / 警示 / 科技 / 极光。
            </div>

            <form method="post" style="margin-top:10px;">
                <input type="hidden" name="csrf_token" value="<?php echo h(admin_csrf_token()); ?>">
                <input type="hidden" name="type" value="new_site">
                <input type="hidden" name="action" value="create_batch">
                <div class="card-title" style="margin-bottom:6px;">批量添加（每行一条）</div>
                <div class="form-row">
                    <textarea name="batch_lines" rows="6" style="flex:1;" placeholder="名称|URL|样式&#10;备用网址1|https://a.example.com|霓虹&#10;备用网址2|b.example.com|科技&#10;备用网址3|https://c.example.com"></textarea>
                </div>
                <div class="form-row">
                    <input type="number" name="batch_sort_order" value="0" placeholder="批量默认排序">
                </div>
                <button type="submit" class="btn">批量添加最新网址</button>
                <div class="small-text">
                    格式：<code>名称|URL|样式</code>。样式可写中文或英文 key（如：霓虹 / neon）。<br>
                    若一行只写 <code>名称|URL</code>，则样式默认自动。
                </div>
            </form>
        </div>

        <div class="card">
            <div class="card-title">“最新网址”列表</div>
            <?php if ($newSites): ?>
                <table>
                    <thead>
                        <tr>
                            <th>ID</th>
                            <th>名称</th>
                            <th>URL</th>
                            <th>样式</th>
                            <th>排序</th>
                            <th>状态</th>
                            <th>操作</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($newSites as $ns): ?>
                            <?php $nid = (int)$ns['id']; ?>
                            <tr>
                                <td><?php echo $nid; ?></td>
                                <td>
                                    <input type="text"
                                           name="name"
                                           value="<?php echo h($ns['name']); ?>"
                                           form="ns-form-<?php echo $nid; ?>"
                                           style="width:140px;">
                                </td>
                                <td>
                                    <input type="text"
                                           name="url"
                                           value="<?php echo h($ns['url']); ?>"
                                           form="ns-form-<?php echo $nid; ?>"
                                           style="width:220px;">
                                </td>
                                <td>
                                    <select name="style_key" form="ns-form-<?php echo $nid; ?>" style="width:90px;">
                                        <?php foreach ($newSiteStyleOptions as $styleValue => $styleLabel): ?>
                                            <option value="<?php echo h($styleValue); ?>" <?php echo normalize_new_site_style_key((string)($ns['style_key'] ?? 'auto')) === $styleValue ? 'selected' : ''; ?>>
                                                <?php echo h($styleLabel); ?>
                                            </option>
                                        <?php endforeach; ?>
                                    </select>
                                </td>
                                <td>
                                    <input type="number"
                                           name="sort_order"
                                           value="<?php echo (int)$ns['sort_order']; ?>"
                                           form="ns-form-<?php echo $nid; ?>"
                                           style="width:60px;">
                                </td>
                                <td><?php echo ((int)$ns['is_active']) ? '启用' : '停用'; ?></td>
                                <td>
                                    <form method="post" id="ns-form-<?php echo $nid; ?>" style="display:inline;">
                                        <input type="hidden" name="csrf_token" value="<?php echo h(admin_csrf_token()); ?>">
                                        <input type="hidden" name="type" value="new_site">
                                        <input type="hidden" name="action" value="update">
                                        <input type="hidden" name="id" value="<?php echo $nid; ?>">
                                    </form>
                                    <button type="submit" class="btn" form="ns-form-<?php echo $nid; ?>">保存</button>

                                    <form method="post" style="display:inline;margin-left:4px;">
                                        <input type="hidden" name="csrf_token" value="<?php echo h(admin_csrf_token()); ?>">
                                        <input type="hidden" name="type" value="new_site">
                                        <input type="hidden" name="action" value="toggle">
                                        <input type="hidden" name="id" value="<?php echo $nid; ?>">
                                        <input type="hidden" name="is_active" value="<?php echo (int)!$ns['is_active']; ?>">
                                        <button type="submit" class="btn">
                                            <?php echo ((int)$ns['is_active']) ? '停用' : '启用'; ?>
                                        </button>
                                    </form>

                                    <form method="post" style="display:inline;margin-left:4px;">
                                        <input type="hidden" name="csrf_token" value="<?php echo h(admin_csrf_token()); ?>">
                                        <input type="hidden" name="type" value="new_site">
                                        <input type="hidden" name="action" value="delete">
                                        <input type="hidden" name="id" value="<?php echo $nid; ?>">
                                        <button type="submit" class="btn" onclick="return confirm('确定删除该条记录？')">删除</button>
                                    </form>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            <?php else: ?>
                <p class="small-text">暂无“最新网址”记录。</p>
            <?php endif; ?>
        </div>
    </div>
</body>
</html>
