<?php
ob_start();
/**
 * 2026企业CMS - 后台案例管理
 */
require_once __DIR__ . '/header.php';
$pageTitle = '案例管理';
$action = $_GET['action'] ?? 'list';
$id = intval($_GET['id'] ?? 0);

if ($action === 'delete' && $id) {
    check_permission('editor');
    $c = db_query_one("SELECT `title` FROM `cases` WHERE `id`=?", [$id]);
    db_exec("DELETE FROM `cases` WHERE `id`=?", [$id]);
    add_log('delete', 'cases', '删除案例: ' . ($c['title'] ?? ''));
    header('Location: /admin/cases.php?msg=' . urlencode('删除成功！'));
    exit;
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['save'])) {
	// CSRF 保护
	if (!csrf_validate($_POST["csrf_token"] ?? "")) {
	    die("CSRF 验证失败");
	}

    check_permission('editor');
    $title = trim($_POST['title'] ?? '');
    $slug = trim($_POST['slug'] ?? '');
    $summary = trim($_POST['summary'] ?? '');
    $content = $_POST['content'] ?? '';
    $clientName = trim($_POST['client_name'] ?? '');
    $category = trim($_POST['category'] ?? '');
    if (!$slug) $slug = generate_slug($title);
    
    if ($action === 'add') {
        db_exec("INSERT INTO `cases` (`title`,`slug`,`summary`,`content`,`client_name`,`category`) VALUES (?,?,?,?,?,?)",
            [$title, $slug, $summary, $content, $clientName, $category]);
        add_log('add', 'cases', '添加案例: ' . $title);
        header('Location: /admin/cases.php?msg=' . urlencode('添加成功！'));
        exit;
    } elseif ($action === 'edit' && $id) {
        db_exec("UPDATE `cases` SET `title`=?,`slug`=?,`summary`=?,`content`=?,`client_name`=?,`category`=? WHERE `id`=?",
            [$title, $slug, $summary, $content, $clientName, $category, $id]);
        add_log('edit', 'cases', '编辑案例: ' . $title);
        header('Location: /admin/cases.php?msg=' . urlencode('保存成功！'));
        exit;
    }
}

$case = [];
if (($action === 'edit' || $action === 'add') && $action !== 'list') {
    if ($id) $case = db_query_one("SELECT * FROM `cases` WHERE `id`=?", [$id]);
?>
<div class="page-header">
    <h2><?php echo htmlspecialchars($action, ENT_QUOTES, "UTF-8")==='add'?'添加案例':'编辑案例'; ?></h2>
    <a href="/admin/cases.php" class="btn">← 返回列表</a>
</div>
<div class="form-card">
    <form method="post" action="">
        <?php echo csrf_input(); ?>
        <div class="form-row">
            <div class="form-group" style="flex:2;">
                <label>案例标题 <span style="color:red;">*</span></label>
                <input type="text" name="title" value="<?php echo xss_clean($case['title'] ?? ''); ?>" required>
            </div>
            <div class="form-group">
                <label>URL别名</label>
                <input type="text" name="slug" value="<?php echo xss_clean($case['slug'] ?? ''); ?>" placeholder="自动生成">
            </div>
        </div>
        <div class="form-row">
            <div class="form-group">
                <label>客户名称</label>
                <input type="text" name="client_name" value="<?php echo xss_clean($case['client_name'] ?? ''); ?>">
            </div>
            <div class="form-group">
                <label>案例分类</label>
                <input type="text" name="category" value="<?php echo xss_clean($case['category'] ?? ''); ?>" placeholder="如：网站建设">
            </div>
        </div>
        <div class="form-group">
            <label>摘要</label>
            <textarea name="summary" rows="3"><?php echo xss_clean($case['summary'] ?? ''); ?></textarea>
        </div>
        <div class="form-group">
            <label>详细内容</label>
            <textarea name="content" id="content-editor"><?php echo $case['content'] ?? ''; ?></textarea>
        </div>
        <div style="margin-top:30px;">
            <button type="submit" name="save" class="btn btn-primary" style="margin-right:10px;">保存</button>
            <a href="/admin/cases.php" class="btn">取消</a>
        </div>
    </form>
</div>
<script src="https://cdn.ckeditor.com/4.25.1-lts/full/ckeditor.js"></script>
<script>if(typeof CKEDITOR!=='undefined'){CKEDITOR.replace('content-editor');}</script>
<?php
require_once __DIR__ . '/footer.php';
exit;
}

// 案例列表
$page = max(1, intval($_GET['page'] ?? 1));
$pageSize = 12;
$total = db_count('cases');
$offset = ($page - 1) * $pageSize;
$cases = db_query("SELECT * FROM `cases` ORDER BY `sort_order` ASC, `id` DESC LIMIT {$offset},{$pageSize}");
?>
<div class="page-header">
    <h2>案例管理</h2>
    <a href="/admin/cases.php?action=add" class="btn btn-primary"><i class="fas fa-plus"></i> 添加案例</a>
</div>

<div class="table-wrapper">
    <table>
        <thead><tr><th>ID</th><th>案例标题</th><th>客户</th><th>分类</th><th>浏览</th><th>操作</th></tr></thead>
        <tbody>
            <?php foreach ($cases as $c): ?>
            <tr>
                <td><?php echo $c['id']; ?></td>
                <td><a href="/case/<?php echo $c['slug']; ?>.html" target="_blank"><?php echo xss_clean(str_cut($c['title'], 30)); ?></a></td>
                <td><?php echo xss_clean($c['client_name']); ?></td>
                <td><?php echo xss_clean($c['category']); ?></td>
                <td><?php echo $c['views']; ?></td>
                <td class="actions">
                    <a href="/admin/cases.php?action=edit&id=<?php echo $c['id']; ?>" class="btn btn-sm btn-primary">编辑</a>
                    <a href="javascript:void(0)" onclick="if(confirmDelete(<?php echo $c['id']; ?>,'<?php echo xss_clean($c['title']); ?>')){location.href='/admin/cases.php?action=delete&id=<?php echo $c['id']; ?>'}" class="btn btn-sm btn-danger">删除</a>
                </td>
            </tr>
            <?php endforeach; ?>
        </tbody>
    </table>
</div>
<?php if ($total > $pageSize): $totalPage=ceil($total/$pageSize); ?>
<div class="pagination">
    <?php for ($i=1; $i<=$totalPage; $i++): ?><a href="/admin/cases.php?page=<?php echo $i; ?>" <?php echo $i==$page?'class="current"':''; ?>><?php echo $i; ?></a><?php endfor; ?>
</div>
<?php endif; ?>
<?php require_once __DIR__ . '/footer.php'; ?>
