<?php
session_start();
$adminPwd = "Mingxuan0504.";

if(isset($_POST['login'])){
    if($_POST['pwd'] === $adminPwd){
        $_SESSION['admin'] = true;
    }else{
        $err = "密码错误";
    }
}
if(isset($_GET['logout'])){
    session_destroy();
    header("Location:admin.php");exit;
}

if(empty($_SESSION['admin'])){
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>管理员登录</title>
<link rel="stylesheet" href="assets/style.css">
</head>
<body>
<div class="container" style="max-width:500px">
    <div class="form-box">
        <h2>后台登录</h2>
        <?php if(!empty($err)) echo "<p style='color:red'>$err</p>";?>
        <form method="post">
            <input type="password" name="pwd" placeholder="输入管理员密码" required>
            <button type="submit" name="login" class="btn">登录</button>
        </form>
    </div>
</div>
</body>
</html>
<?php
exit;
}

$editFile = $_GET['edit'] ?? '';
$editTitle = '';
$editContent = '';
if($editFile && file_exists("articles/$editFile")){
    $data = file_get_contents("articles/$editFile");
    $lines = explode("\n",$data,2);
    $editTitle = $lines[0];
    $editContent = $lines[1] ?? '';
}
$files = glob('articles/*.md');
rsort($files);
?>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<title>管理员后台</title>
<link rel="stylesheet" href="assets/style.css">
<script src="https://cdn.jsdelivr.net/npm/marked/marked.min.js"></script>
</head>
<body>
<div class="container">
    <header>
        <h1>文章管理后台</h1>
        <div>
            <a href="index.php" class="btn">前台首页</a>
            <a href="admin.php?logout=1" class="btn btn-danger">退出登录</a>
        </div>
    </header>

    <div class="form-box">
        <h3><?=$editFile?'编辑文章':'新建文章'?></h3>

        <!-- 文件上传区域 -->
        <div class="upload-area">
            <h4>上传图片/视频（≤15MB）</h4>
            <p class="tip">支持 jpg png gif webp mp4 mov，上传后点击插入到编辑器</p>
            <input type="file" id="fileUpload" accept="image/*,video/mp4,video/mov">
            <div class="upload-preview" id="previewBox"></div>
        </div>

        <form action="save.php" method="post">
            <?php if($editFile): ?>
                <input type="hidden" name="oldfile" value="<?=htmlspecialchars($editFile)?>">
            <?php endif; ?>
            <input type="text" name="title" placeholder="文章标题" value="<?=htmlspecialchars($editTitle)?>" required>
            <textarea id="mdEditor" name="mdcontent" placeholder="Markdown内容"><?=htmlspecialchars($editContent)?></textarea>
            <div class="operate-bar">
                <button class="btn" type="submit">保存文章</button>
                <button type="button" class="btn btn-success" id="previewBtn">本地预览效果</button>
            </div>
        </form>

        <!-- 实时预览区 -->
        <div id="localPreview" class="markdown-body" style="margin-top:20px;display:none"></div>
    </div>

    <div class="form-box">
        <h3>现有文章</h3>
        <?php foreach($files as $f):
            $fn = basename($f);
            $raw = file_get_contents($f);
            $t = explode("\n",$raw)[0];
        ?>
        <div class="article-item" style="display:flex;justify-content:space-between;align-items:center">
            <span><?=htmlspecialchars($t)?></span>
            <div>
                <a href="admin.php?edit=<?=urlencode($fn)?>" class="btn">编辑</a>
                <a href="delete.php?file=<?=urlencode($fn)?>" class="btn btn-danger" onclick="return confirm('确定删除？')">删除</a>
            </div>
        </div>
        <?php endforeach; ?>
    </div>
</div>

<script>
const editor = document.getElementById('mdEditor');
const fileInput = document.getElementById('fileUpload');
const previewBox = document.getElementById('previewBox');
const previewBtn = document.getElementById('previewBtn');
const localPreview = document.getElementById('localPreview');

// 上传文件
fileInput.onchange = async function(){
    const file = this.files[0];
    if(!file) return;

    // 本地缩略预览
    previewBox.innerHTML = "";
    let dom;
    if(file.type.startsWith('image/')){
        dom = document.createElement('img');
        dom.src = URL.createObjectURL(file);
    }else{
        dom = document.createElement('video');
        dom.src = URL.createObjectURL(file);
    }
    dom.className = "upload-preview-item";
    previewBox.appendChild(dom);

    // 提交到后端
    const formData = new FormData();
    formData.append("file",file);
    const res = await fetch("upload.php",{method:"POST",body:formData});
    const json = await res.json();
    if(json.code===1){
        // 把markdown代码插入光标位置
        insertText(json.md);
        alert("上传成功，已自动插入内容！");
    }else{
        alert(json.msg);
    }
}

// 在文本框光标处插入文本
function insertText(text){
    const start = editor.selectionStart;
    const end = editor.selectionEnd;
    const val = editor.value;
    editor.value = val.substring(0,start)+text+val.substring(end);
    editor.selectionStart = editor.selectionEnd = start + text.length;
    editor.focus();
}

// 本地预览Markdown
previewBtn.onclick = function(){
    localPreview.innerHTML = marked.parse(editor.value);
    localPreview.style.display = 'block';
}
</script>
</body>
</html>