<?php
/**
 * 王一一 · 写日记 / 编辑日记
 */
require_once __DIR__ . '/../config.php';
require_login();

// ===== 判断是新增还是编辑 =====
$editId = isset($_GET['id']) ? (int)$_GET['id'] : 0;
$isEdit = $editId > 0;

$article = [
    'title'   => '',
    'content' => '',
    'mood'    => '',
];

if ($isEdit) {
    try {
        $stmt = db()->prepare('SELECT * FROM articles WHERE id = :id');
        $stmt->execute([':id' => $editId]);
        $article = $stmt->fetch();

        if (!$article) {
            $error = '找不到这篇日记';
            $isEdit = false;
        }
    } catch (PDOException $e) {
        $error = '数据库查询失败：' . $e->getMessage();
        $isEdit = false;
    }
}

// ===== 处理表单提交 =====
if (!isset($error)) { $error = ''; }

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $title   = isset($_POST['title']) ? trim($_POST['title']) : '';
    $content = isset($_POST['content']) ? trim($_POST['content']) : '';
    $mood    = isset($_POST['mood']) ? trim($_POST['mood']) : '';
    // 自定义心情优先：如果用户在手写框输入了内容，用它覆盖 radio 的值
    $moodCustom = isset($_POST['mood_custom']) ? trim($_POST['mood_custom']) : '';
    if ($moodCustom !== '') {
        $mood = $moodCustom;
    }

    // 验证
    $errors = [];
    if ($title === '') {
        $errors[] = '请输入标题';
    } elseif (mb_strlen($title) > 200) {
        $errors[] = '标题不能超过 200 个字';
    }
    if ($content === '') {
        $errors[] = '请输入日记内容';
    }
    if ($mood !== '' && mb_strlen($mood) > 50) {
        $errors[] = '心情标签不能超过 50 个字';
    }

    if (empty($errors)) {
        try {
            if ($isEdit) {
                $stmt = db()->prepare(
                    'UPDATE articles SET title = :title, content = :content, mood = :mood WHERE id = :id'
                );
                $stmt->execute([
                    ':title'   => $title,
                    ':content' => $content,
                    ':mood'    => $mood,
                    ':id'      => $editId,
                ]);
            } else {
                $stmt = db()->prepare(
                    'INSERT INTO articles (title, content, mood) VALUES (:title, :content, :mood)'
                );
                $stmt->execute([
                    ':title'   => $title,
                    ':content' => $content,
                    ':mood'    => $mood,
                ]);
                $editId = (int)db()->lastInsertId();
            }

            // 保存成功，跳转到详情页
            header('Location: ../diary-detail.php?id=' . $editId);
            exit;
        } catch (PDOException $e) {
            $errors[] = '保存失败：' . $e->getMessage();
        }
    }

    $error = implode('；', $errors);

    // 表单回填
    $article['title']   = $title;
    $article['content'] = $content;
    $article['mood']    = $mood;
}

$pageTitle = ($isEdit ? '编辑日记' : '写日记') . ' — ' . SITE_NAME;
$moods = mood_list();
?>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?= h($pageTitle) ?></title>
    <link rel="stylesheet" href="../style.css">
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Fredoka:wght@400;500;600;700&family=Nunito:wght@400;500;600;700&family=Noto+Sans+SC:wght@400;500;700&family=ZCOOL+KuaiLe&display=swap" rel="stylesheet">
</head>
<body>

<!-- 导航栏 -->
<nav class="navbar scrolled">
    <div class="container nav-container">
        <a href="../index.html" class="nav-logo"><?= SITE_NAME ?></a>
        <ul class="nav-menu">
            <li><a href="../index.html" class="nav-link">首页</a></li>
            <li><a href="../index.html#about" class="nav-link">关于我</a></li>
            <li><a href="../index.html#works" class="nav-link">作品集</a></li>
            <li><a href="../diary.php" class="nav-link active">📝 日记</a></li>
            <li><a href="../index.html#contact" class="nav-link">联系我</a></li>
        </ul>
        <button class="nav-toggle" aria-label="切换菜单">
            <span></span><span></span><span></span>
        </button>
    </div>
</nav>

<section class="write-section section">
    <div class="container">
        <div class="write-header">
            <h2 class="section-title"><?= $isEdit ? '✏️ 编辑日记' : '✏️ 写日记' ?></h2>
            <div class="write-header-links">
                <a href="../diary.php">📋 日记列表</a>
                <a href="logout.php">🚪 退出登录</a>
            </div>
        </div>

        <?php if ($error && strpos($error, '：') !== false): ?>
        <div class="write-error"><?= h($error) ?></div>
        <?php endif; ?>

        <?php if (!empty($errors)): ?>
        <div class="write-error"><?= h(implode('；', $errors)) ?></div>
        <?php endif; ?>

        <form method="POST" class="write-form">
            <div class="form-group">
                <label for="title">标题 <span class="required">*</span></label>
                <input type="text" id="title" name="title"
                       value="<?= h($article['title']) ?>"
                       placeholder="今天的日记标题…"
                       maxlength="200" required autofocus>
            </div>

            <div class="form-group">
                <label for="mood">心情</label>
                <div class="mood-picker">
                    <?php foreach ($moods as $mood): ?>
                    <label class="mood-option <?= $article['mood'] === $mood ? 'selected' : '' ?>">
                        <input type="radio" name="mood" value="<?= h($mood) ?>"
                               <?= $article['mood'] === $mood ? 'checked' : '' ?>>
                        <span class="mood-label"><?= h($mood) ?></span>
                    </label>
                    <?php endforeach; ?>
                    <label class="mood-option mood-custom <?= (!in_array($article['mood'], $moods) && $article['mood'] !== '') ? 'selected' : '' ?>">
                        <input type="radio" name="mood" value="__custom__"
                               <?= (!in_array($article['mood'], $moods) && $article['mood'] !== '') ? 'checked' : '' ?>>
                        <span class="mood-label">✍️ 自定义</span>
                    </label>
                </div>
                <input type="text" id="mood-custom" name="mood_custom"
                       value="<?= (!in_array($article['mood'], $moods) && $article['mood'] !== '') ? h($article['mood']) : '' ?>"
                       placeholder="输入你的心情…"
                       maxlength="50"
                       style="margin-top:0.5rem;<?= (!in_array($article['mood'], $moods) && $article['mood'] !== '') ? '' : 'display:none;' ?>">
            </div>

            <div class="form-group">
                <label for="content">日记内容 <span class="required">*</span></label>
                <textarea id="content" name="content" rows="18"
                          placeholder="今天发生了什么有趣的事呢？写下来吧…"
                          required><?= h($article['content']) ?></textarea>
            </div>

            <div class="write-buttons">
                <button type="submit" class="btn btn-primary btn-submit">
                    <?= $isEdit ? '💾 保存修改' : '📝 发布日记' ?>
                </button>
                <a href="../diary.php" class="btn btn-outline" style="color:var(--muted);box-shadow:inset 0 0 0 2px var(--faint);">取消</a>
            </div>
        </form>
    </div>
</section>

<script>
// 心情选择器交互
document.querySelectorAll('.mood-option input').forEach(radio => {
    radio.addEventListener('change', function() {
        document.querySelectorAll('.mood-option').forEach(l => l.classList.remove('selected'));
        this.closest('.mood-option').classList.add('selected');

        const customInput = document.getElementById('mood-custom');
        if (this.value === '__custom__') {
            customInput.style.display = 'block';
            customInput.focus();
        } else {
            customInput.style.display = 'none';
            customInput.value = '';
        }
    });
});
</script>
<script src="../script.js"></script>
</body>
</html>
