<?php
session_start();
$pageTitle = '管理后台';
require_once 'config.php';
require_once 'header.php';

if (!isset($_SESSION['user_id'])) {
    header('Location: login.php');
    exit;
}

// 验证管理员权限
$isAdmin = false;
$stmt = $pdo->prepare("SELECT username FROM users WHERE id = ?");
$stmt->execute([$_SESSION['user_id']]);
$user = $stmt->fetch(PDO::FETCH_ASSOC);
// 简单权限检查：username为'admin'的是管理员
if ($user && $user['username'] === 'admin') {
    $isAdmin = true;
}

// 生成CSRF Token
if (empty($_SESSION['csrf_token'])) {
    $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
}
$csrfToken = $_SESSION['csrf_token'];

// 处理删除操作（改为POST + CSRF验证）
if ($isAdmin && $_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action'])) {
    // 验证CSRF Token
    if (!isset($_POST['csrf_token']) || $_POST['csrf_token'] !== $_SESSION['csrf_token']) {
        die('CSRF验证失败');
    }
    
    if ($_POST['action'] === 'delete_category') {
        $stmt = $pdo->prepare("DELETE FROM custom_categories WHERE id = ?");
        $stmt->execute([(int)$_POST['id']]);
        header('Location: admin.php');
        exit;
    }
    if ($_POST['action'] === 'delete_detail') {
        $stmt = $pdo->prepare("DELETE FROM custom_details WHERE id = ?");
        $stmt->execute([(int)$_POST['id']]);
        header('Location: admin.php');
        exit;
    }
    if ($_POST['action'] === 'delete_testimonial') {
        $stmt = $pdo->prepare("DELETE FROM testimonials WHERE id = ?");
        $stmt->execute([(int)$_POST['id']]);
        header('Location: admin.php');
        exit;
    }
    if ($_POST['action'] === 'delete_user') {
        $stmt = $pdo->prepare("DELETE FROM users WHERE id = ?");
        $stmt->execute([(int)$_POST['id']]);
        header('Location: admin.php');
        exit;
    }
    if ($_POST['action'] === 'delete_vendor') {
        $stmt = $pdo->prepare("DELETE FROM vendors WHERE id = ?");
        $stmt->execute([(int)$_POST['id']]);
        header('Location: admin.php');
        exit;
    }
    if ($_POST['action'] === 'delete_gallery') {
        $stmt = $pdo->prepare("DELETE FROM wedding_gallery WHERE id = ?");
        $stmt->execute([(int)$_POST['id']]);
        header('Location: admin.php');
        exit;
    }
}

// 处理添加操作（需要CSRF验证）
if ($isAdmin && $_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action'])) {
    // 跳过delete操作（已处理），只处理add操作
    if (strpos($_POST['action'], 'delete_') === 0) {
        // delete已在上方处理
    } elseif ($_POST['action'] === 'add_category') {
        $stmt = $pdo->prepare("INSERT INTO custom_categories (icon, name, sort_order) VALUES (?, ?, ?)");
        $stmt->execute([$_POST['icon'], $_POST['name'], (int)$_POST['sort_order']]);
        header('Location: admin.php');
        exit;
    } elseif ($_POST['action'] === 'add_detail') {
        $stmt = $pdo->prepare("INSERT INTO custom_details (category_id, title, content, tips, sort_order) VALUES (?, ?, ?, ?, ?)");
        $stmt->execute([(int)$_POST['category_id'], $_POST['title'], $_POST['content'], $_POST['tips'] ?? '', (int)$_POST['sort_order']]);
        header('Location: admin.php');
        exit;
    } elseif ($_POST['action'] === 'add_vendor') {
        $stmt = $pdo->prepare("INSERT INTO vendors (name, type, rating, address, phone, description, sort_order) VALUES (?, ?, ?, ?, ?, ?, ?)");
        $stmt->execute([$_POST['name'], $_POST['type'], (float)$_POST['rating'], $_POST['address'], $_POST['phone'], $_POST['description'], (int)$_POST['sort_order']]);
        header('Location: admin.php');
        exit;
    } elseif ($_POST['action'] === 'add_gallery') {
        $stmt = $pdo->prepare("INSERT INTO wedding_gallery (title, groom_name, bride_name, wedding_date, type, description, gradient_start, gradient_end, icon, sort_order) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
        $stmt->execute([$_POST['title'], $_POST['groom_name'], $_POST['bride_name'], $_POST['wedding_date'], $_POST['type'], $_POST['description'], $_POST['gradient_start'], $_POST['gradient_end'], $_POST['icon'], (int)$_POST['sort_order']]);
        header('Location: admin.php');
        exit;
    }
}
?>

<main class="site-main">
<?php if (!$isAdmin): ?>
    <div class="container" style="text-align:center; padding:100px 0;">
        <h2>请先登录</h2>
        <p>您需要登录后才能访问管理后台。</p>
        <a href="login.php" class="btn btn-primary">前往登录</a>
    </div>
<?php else: ?>

<!-- ================================ 管理后台 ================================ -->
<section class="admin-section">
    <div class="container">
        <div class="admin-header">
            <h2>管理后台</h2>
            <p>管理网站内容</p>
        </div>

        <!-- 标签页切换 -->
        <div class="admin-tabs">
            <button class="admin-tab-btn active" data-tab="categories">分类管理</button>
            <button class="admin-tab-btn" data-tab="details">风俗详情管理</button>
            <button class="admin-tab-btn" data-tab="vendors">商家管理</button>
            <button class="admin-tab-btn" data-tab="gallery">案例管理</button>
            <button class="admin-tab-btn" data-tab="testimonials">评价管理</button>
            <button class="admin-tab-btn" data-tab="users">用户管理</button>
        </div>

        <!-- 分类管理 -->
        <div class="admin-panel active" id="panel-categories">
            <h3>分类列表</h3>
            <table class="admin-table">
                <thead>
                    <tr>
                        <th>ID</th>
                        <th>图标</th>
                        <th>名称</th>
                        <th>排序</th>
                        <th>操作</th>
                    </tr>
                </thead>
                <tbody>
                    <?php
                    $cats = $pdo->query("SELECT * FROM custom_categories ORDER BY sort_order")->fetchAll();
                    foreach ($cats as $cat):
                    ?>
                    <tr>
                        <td><?php echo (int)$cat['id']; ?></td>
                        <td><?php echo htmlspecialchars($cat['icon']); ?></td>
                        <td><?php echo htmlspecialchars($cat['name']); ?></td>
                        <td><?php echo (int)$cat['sort_order']; ?></td>
                        <td>
                            <button class="btn-small btn-edit" onclick="editCategory(<?php echo (int)$cat['id']; ?>)">编辑</button>
                            <button class="btn-small btn-delete" onclick="deleteCategory(<?php echo (int)$cat['id']; ?>)">删除</button>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>

            <h4>添加新分类</h4>
            <form method="POST" class="admin-form">
                <input type="hidden" name="action" value="add_category">
                <input type="text" name="icon" placeholder="图标 (emoji)" required>
                <input type="text" name="name" placeholder="分类名称" required>
                <input type="number" name="sort_order" placeholder="排序" value="0">
                <button type="submit" class="btn-primary">添加分类</button>
            </form>
        </div>

        <!-- 风俗详情管理 -->
        <div class="admin-panel" id="panel-details">
            <h3>风俗详情列表</h3>
            <table class="admin-table">
                <thead>
                    <tr>
                        <th>ID</th>
                        <th>标题</th>
                        <th>分类</th>
                        <th>排序</th>
                        <th>操作</th>
                    </tr>
                </thead>
                <tbody>
                    <?php
                    $detailsAdmin = $pdo->query("SELECT cd.*, cc.name as cat_name FROM custom_details cd LEFT JOIN custom_categories cc ON cd.category_id = cc.id ORDER BY cd.category_id, cd.sort_order")->fetchAll();
                    foreach ($detailsAdmin as $d):
                    ?>
                    <tr>
                        <td><?php echo (int)$d['id']; ?></td>
                        <td><?php echo htmlspecialchars($d['title']); ?></td>
                        <td><?php echo htmlspecialchars($d['cat_name']); ?></td>
                        <td><?php echo (int)$d['sort_order']; ?></td>
                        <td>
                            <button class="btn-small btn-edit" onclick="editDetail(<?php echo (int)$d['id']; ?>)">编辑</button>
                            <button class="btn-small btn-delete" onclick="deleteDetail(<?php echo (int)$d['id']; ?>)">删除</button>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>

            <h4>添加新风俗详情</h4>
            <form method="POST" class="admin-form">
                <input type="hidden" name="action" value="add_detail">
                <select name="category_id" required>
                    <option value="">选择分类</option>
                    <?php foreach ($cats as $cat): ?>
                    <option value="<?php echo $cat['id']; ?>"><?php echo htmlspecialchars($cat['name']); ?></option>
                    <?php endforeach; ?>
                </select>
                <input type="text" name="title" placeholder="标题" required>
                <textarea name="content" placeholder="详细内容" rows="5" required></textarea>
                <textarea name="tips" placeholder="小贴士" rows="2"></textarea>
                <input type="number" name="sort_order" placeholder="排序" value="0">
                <button type="submit" class="btn-primary">添加详情</button>
            </form>
        </div>

        <!-- 评价管理 -->
        <div class="admin-panel" id="panel-testimonials">
            <h3>用户评价列表</h3>
            <table class="admin-table">
                <thead>
                    <tr>
                        <th>ID</th>
                        <th>作者</th>
                        <th>角色</th>
                        <th>评分</th>
                        <th>时间</th>
                        <th>操作</th>
                    </tr>
                </thead>
                <tbody>
                    <?php
                    $testimonialsAdmin = $pdo->query("SELECT * FROM testimonials ORDER BY created_at DESC")->fetchAll();
                    foreach ($testimonialsAdmin as $t):
                    ?>
                    <tr>
                        <td><?php echo (int)$t['id']; ?></td>
                        <td><?php echo htmlspecialchars($t['author']); ?></td>
                        <td><?php echo htmlspecialchars($t['role']); ?></td>
                        <td><?php echo htmlspecialchars($t['rating']); ?></td>
                        <td><?php echo htmlspecialchars($t['created_at']); ?></td>
                        <td>
                            <button class="btn-small btn-delete" onclick="deleteTestimonial(<?php echo (int)$t['id']; ?>)">删除</button>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>

        <!-- 用户管理 -->
        <div class="admin-panel" id="panel-users">
            <h3>用户列表</h3>
            <table class="admin-table">
                <thead>
                    <tr>
                        <th>ID</th>
                        <th>用户名</th>
                        <th>注册时间</th>
                        <th>操作</th>
                    </tr>
                </thead>
                <tbody>
                    <?php
                    $usersAdmin = $pdo->query("SELECT id, username, created_at FROM users ORDER BY created_at DESC")->fetchAll();
                    foreach ($usersAdmin as $u):
                    ?>
                    <tr>
                        <td><?php echo (int)$u['id']; ?></td>
                        <td><?php echo htmlspecialchars($u['username']); ?></td>
                        <td><?php echo htmlspecialchars($u['created_at']); ?></td>
                        <td>
                            <button class="btn-small btn-delete" onclick="deleteUser(<?php echo (int)$u['id']; ?>)">删除</button>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>

        <!-- 商家管理 -->
        <div class="admin-panel" id="panel-vendors">
            <h3>商家列表</h3>
            <table class="admin-table">
                <thead>
                    <tr>
                        <th>ID</th>
                        <th>名称</th>
                        <th>类型</th>
                        <th>评分</th>
                        <th>电话</th>
                        <th>排序</th>
                        <th>操作</th>
                    </tr>
                </thead>
                <tbody>
                    <?php
                    $vendorsAdmin = $pdo->query("SELECT * FROM vendors ORDER BY sort_order")->fetchAll();
                    foreach ($vendorsAdmin as $v):
                    ?>
                    <tr>
                        <td><?php echo (int)$v['id']; ?></td>
                        <td><?php echo htmlspecialchars($v['name']); ?></td>
                        <td><?php echo htmlspecialchars($v['type']); ?></td>
                        <td><?php echo htmlspecialchars($v['rating']); ?></td>
                        <td><?php echo htmlspecialchars($v['phone']); ?></td>
                        <td><?php echo (int)$v['sort_order']; ?></td>
                        <td>
                            <button class="btn-small btn-delete" onclick="deleteVendor(<?php echo (int)$v['id']; ?>)">删除</button>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>

            <h4>添加商家</h4>
            <form method="POST" class="admin-form">
                <input type="hidden" name="action" value="add_vendor">
                <input type="text" name="name" placeholder="商家名称" required>
                <select name="type" required>
                    <option value="">选择类型</option>
                    <option value="婚庆">婚庆</option>
                    <option value="婚车">婚车</option>
                    <option value="摄影">摄影</option>
                    <option value="化妆">化妆</option>
                    <option value="礼服">礼服</option>
                    <option value="其他">其他</option>
                </select>
                <input type="number" name="rating" placeholder="评分 (如: 4.5)" step="0.1" min="1" max="5" value="4.5" required>
                <input type="text" name="address" placeholder="地址">
                <input type="text" name="phone" placeholder="电话">
                <textarea name="description" placeholder="描述" rows="3"></textarea>
                <input type="number" name="sort_order" placeholder="排序" value="0">
                <button type="submit" class="btn-primary">添加商家</button>
            </form>
        </div>

        <!-- 案例管理 -->
        <div class="admin-panel" id="panel-gallery">
            <h3>婚礼案例列表</h3>
            <table class="admin-table">
                <thead>
                    <tr>
                        <th>ID</th>
                        <th>标题</th>
                        <th>类型</th>
                        <th>新郎</th>
                        <th>新娘</th>
                        <th>日期</th>
                        <th>排序</th>
                        <th>操作</th>
                    </tr>
                </thead>
                <tbody>
                    <?php
                    $galleryAdmin = $pdo->query("SELECT * FROM wedding_gallery ORDER BY sort_order, id DESC")->fetchAll();
                    foreach ($galleryAdmin as $g):
                    ?>
                    <tr>
                        <td><?php echo (int)$g['id']; ?></td>
                        <td><?php echo htmlspecialchars($g['title']); ?></td>
                        <td><?php echo htmlspecialchars($g['type']); ?></td>
                        <td><?php echo htmlspecialchars($g['groom_name']); ?></td>
                        <td><?php echo htmlspecialchars($g['bride_name']); ?></td>
                        <td><?php echo htmlspecialchars($g['wedding_date']); ?></td>
                        <td><?php echo (int)$g['sort_order']; ?></td>
                        <td>
                            <button class="btn-small btn-delete" onclick="deleteGallery(<?php echo (int)$g['id']; ?>)">删除</button>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>

            <h4>添加案例</h4>
            <form method="POST" class="admin-form">
                <input type="hidden" name="action" value="add_gallery">
                <input type="text" name="title" placeholder="标题" required>
                <input type="text" name="groom_name" placeholder="新郎姓名">
                <input type="text" name="bride_name" placeholder="新娘姓名">
                <input type="date" name="wedding_date" placeholder="婚礼日期">
                <select name="type" required>
                    <option value="">选择类型</option>
                    <option value="中式">中式</option>
                    <option value="西式">西式</option>
                    <option value="户外">户外</option>
                    <option value="主题">主题</option>
                </select>
                <textarea name="description" placeholder="描述" rows="3"></textarea>
                <input type="text" name="gradient_start" placeholder="渐变色起始 (如: #e74c3c)" value="#e74c3c">
                <input type="text" name="gradient_end" placeholder="渐变色结束 (如: #c0392b)" value="#c0392b">
                <input type="text" name="icon" placeholder="图标 (emoji)" value="🏮">
                <input type="number" name="sort_order" placeholder="排序" value="0">
                <button type="submit" class="btn-primary">添加案例</button>
            </form>
        </div>
    </div>
</section>

<script>
document.querySelectorAll('.admin-tab-btn').forEach(function(tab) {
    tab.addEventListener('click', function() {
        document.querySelectorAll('.admin-tab-btn').forEach(function(t) { t.classList.remove('active'); });
        document.querySelectorAll('.admin-panel').forEach(function(p) { p.classList.remove('active'); });
        tab.classList.add('active');
        document.getElementById('panel-' + tab.dataset.tab).classList.add('active');
    });
});

function editCategory(id) { alert('编辑功能开发中... ID: ' + id); }
function deleteCategory(id) { if (confirm('确定删除此分类?')) { postDelete('delete_category', id); } }
function editDetail(id) { alert('编辑功能开发中... ID: ' + id); }
function deleteDetail(id) { if (confirm('确定删除此详情?')) { postDelete('delete_detail', id); } }
function deleteTestimonial(id) { if (confirm('确定删除此评价?')) { postDelete('delete_testimonial', id); } }
function deleteUser(id) { if (confirm('确定删除此用户?')) { postDelete('delete_user', id); } }
function deleteVendor(id) { if (confirm('确定删除此商家?')) { postDelete('delete_vendor', id); } }
function deleteGallery(id) { if (confirm('确定删除此案例?')) { postDelete('delete_gallery', id); } }

function postDelete(action, id) {
    var form = document.createElement('form');
    form.method = 'POST';
    form.action = 'admin.php';
    form.style.display = 'none';
    var actionInput = document.createElement('input');
    actionInput.name = 'action';
    actionInput.value = action;
    form.appendChild(actionInput);
    var idInput = document.createElement('input');
    idInput.name = 'id';
    idInput.value = id;
    form.appendChild(idInput);
    var csrfInput = document.createElement('input');
    csrfInput.name = 'csrf_token';
    csrfInput.value = '<?php echo $csrfToken; ?>';
    form.appendChild(csrfInput);
    document.body.appendChild(form);
    form.submit();
}
</script>

<?php endif; ?>
</main>

<?php require_once 'footer.php'; ?>