<?php
require_once __DIR__ . '/header.php';
$pdo = db();

$action = $_GET['action'] ?? 'list';
$id = $_GET['id'] ?? null;

// Handle Delete
if ($action === 'delete' && $id) {
    $stmt = $pdo->prepare("DELETE FROM cases WHERE id = ?");
    $stmt->execute([$id]);
    header('Location: cases.php?msg=deleted');
    exit;
}

// Handle Save (Add/Edit)
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $data = [
        'title' => $_POST['title'],
        'slug' => $_POST['slug'] ?: strtolower(preg_replace('/[^A-Za-z0-9-]+/', '-', $_POST['title'])),
        'tag' => $_POST['tag'],
        'category' => $_POST['category'],
        'img' => $_POST['img'],
        'description' => $_POST['description'],
        'content' => $_POST['content'],
        'challenge' => $_POST['challenge'],
        'solution' => $_POST['solution'],
        'result_stability' => $_POST['result_stability'],
        'result_throughput' => $_POST['result_throughput'],
        'result_cost' => $_POST['result_cost'],
        'tech' => $_POST['tech'],
        'is_featured' => isset($_POST['is_featured']) ? 1 : 0,
        'sort_order' => (int)$_POST['sort_order']
    ];

    if ($id) {
        $sql = "UPDATE cases SET title=:title, slug=:slug, tag=:tag, category=:category, img=:img, description=:description, content=:content, challenge=:challenge, solution=:solution, result_stability=:result_stability, result_throughput=:result_throughput, result_cost=:result_cost, tech=:tech, is_featured=:is_featured, sort_order=:sort_order WHERE id=:id";
        $data['id'] = $id;
    } else {
        $sql = "INSERT INTO cases (title, slug, tag, category, img, description, content, challenge, solution, result_stability, result_throughput, result_cost, tech, is_featured, sort_order) VALUES (:title, :slug, :tag, :category, :img, :description, :content, :challenge, :solution, :result_stability, :result_throughput, :result_cost, :tech, :is_featured, :sort_order)";
    }

    $stmt = $pdo->prepare($sql);
    $stmt->execute($data);
    header('Location: cases.php?msg=saved');
    exit;
}

// Fetch cases for list
$cases = $pdo->query("SELECT * FROM cases ORDER BY sort_order ASC, created_at DESC")->fetchAll();

// Fetch case for edit
$case = null;
if ($action === 'edit' && $id) {
    $stmt = $pdo->prepare("SELECT * FROM cases WHERE id = ?");
    $stmt->execute([$id]);
    $case = $stmt->fetch();
}
?>

<div class="card">
    <div class="card-header d-flex justify-content-between align-items-center">
        <span><?= $action === 'edit' ? '编辑案例' : ($action === 'add' ? '新增案例' : '案例列表') ?></span>
        <?php if ($action === 'list'): ?>
            <a href="cases.php?action=add" class="btn btn-sm btn-primary">新增案例</a>
        <?php else: ?>
            <a href="cases.php" class="btn btn-sm btn-secondary">返回列表</a>
        <?php endif; ?>
    </div>
    <div class="card-body">
        <?php if ($action === 'list'): ?>
            <div class="table-responsive">
                <table class="table align-middle">
                    <thead>
                        <tr>
                            <th>预览</th>
                            <th>标题 / 分类</th>
                            <th>标签</th>
                            <th>精选</th>
                            <th>排序</th>
                            <th>操作</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($cases as $c): ?>
                        <tr>
                            <td><img src="<?= htmlspecialchars($c['img']) ?>" width="60" class="rounded"></td>
                            <td>
                                <div><strong><?= htmlspecialchars($c['title']) ?></strong></div>
                                <div class="small text-muted"><?= htmlspecialchars($c['category']) ?></div>
                            </td>
                            <td><span class="badge badge-soft-primary"><?= htmlspecialchars($c['tag']) ?></span></td>
                            <td>
                                <?php if ($c['is_featured']): ?>
                                    <span class="badge bg-success">是</span>
                                <?php else: ?>
                                    <span class="badge bg-light text-dark">否</span>
                                <?php endif; ?>
                            </td>
                            <td><?= $c['sort_order'] ?></td>
                            <td>
                                <a href="cases.php?action=edit&id=<?= $c['id'] ?>" class="btn btn-sm btn-outline-primary"><i class="fas fa-edit"></i></a>
                                <a href="cases.php?action=delete&id=<?= $c['id'] ?>" class="btn btn-sm btn-outline-danger" onclick="return confirm('确定删除吗？')"><i class="fas fa-trash"></i></a>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        <?php else: ?>
            <form method="POST">
                <div class="row">
                    <div class="col-md-6 mb-3">
                        <label class="form-label">标题</label>
                        <input type="text" name="title" class="form-control" value="<?= htmlspecialchars($case['title'] ?? '') ?>" required>
                    </div>
                    <div class="col-md-6 mb-3">
                        <label class="form-label">Slug (URL标识)</label>
                        <input type="text" name="slug" class="form-control" value="<?= htmlspecialchars($case['slug'] ?? '') ?>" placeholder="留空自动生成">
                    </div>
                    <div class="col-md-4 mb-3">
                        <label class="form-label">分类</label>
                        <select name="category" class="form-select">
                            <?php 
                            $categories = ['海外资金盘', '点赞盘', '刷单盘', '商城盘', '云矿机', '新能源', '投资理财', '反波胆', '微交易', '时间盘', '交易所', '各类小程序', '机器人', '落地页定制', '远控系统', '授权系统', '在线客服', '获取通讯录'];
                            foreach ($categories as $cat): 
                            ?>
                                <option value="<?= $cat ?>" <?= ($case['category'] ?? '') == $cat ? 'selected' : '' ?>><?= $cat ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="col-md-4 mb-3">
                        <label class="form-label">标签</label>
                        <input type="text" name="tag" class="form-control" value="<?= htmlspecialchars($case['tag'] ?? '') ?>">
                    </div>
                    <div class="col-md-4 mb-3">
                        <label class="form-label">排序</label>
                        <input type="number" name="sort_order" class="form-control" value="<?= $case['sort_order'] ?? 0 ?>">
                    </div>
                    <div class="col-md-12 mb-3">
                        <label class="form-label">预览图 URL</label>
                        <input type="text" name="img" class="form-control" value="<?= htmlspecialchars($case['img'] ?? '') ?>" required>
                    </div>
                    <div class="col-md-12 mb-3">
                        <label class="form-label">简短描述</label>
                        <textarea name="description" class="form-control" rows="2"><?= htmlspecialchars($case['description'] ?? '') ?></textarea>
                    </div>
                    <div class="col-md-12 mb-3">
                        <label class="form-label">详细内容</label>
                        <textarea name="content" class="form-control" rows="4"><?= htmlspecialchars($case['content'] ?? '') ?></textarea>
                    </div>
                    <div class="col-md-6 mb-3">
                        <label class="form-label">核心挑战</label>
                        <textarea name="challenge" class="form-control" rows="3"><?= htmlspecialchars($case['challenge'] ?? '') ?></textarea>
                    </div>
                    <div class="col-md-6 mb-3">
                        <label class="form-label">解决方案</label>
                        <textarea name="solution" class="form-control" rows="3"><?= htmlspecialchars($case['solution'] ?? '') ?></textarea>
                    </div>
                    <div class="col-md-4 mb-3">
                        <label class="form-label">稳定性指标</label>
                        <input type="text" name="result_stability" class="form-control" value="<?= htmlspecialchars($case['result_stability'] ?? '') ?>">
                    </div>
                    <div class="col-md-4 mb-3">
                        <label class="form-label">吞吐量指标</label>
                        <input type="text" name="result_throughput" class="form-control" value="<?= htmlspecialchars($case['result_throughput'] ?? '') ?>">
                    </div>
                    <div class="col-md-4 mb-3">
                        <label class="form-label">成本指标</label>
                        <input type="text" name="result_cost" class="form-control" value="<?= htmlspecialchars($case['result_cost'] ?? '') ?>">
                    </div>
                    <div class="col-md-12 mb-3">
                        <label class="form-label">技术栈 (逗号分隔)</label>
                        <input type="text" name="tech" class="form-control" value="<?= htmlspecialchars($case['tech'] ?? '') ?>">
                    </div>
                    <div class="col-md-12 mb-3">
                        <div class="form-check">
                            <input class="form-check-input" type="checkbox" name="is_featured" id="is_featured" <?= ($case['is_featured'] ?? 0) ? 'checked' : '' ?>>
                            <label class="form-check-label" for="is_featured">设置为精选 (首页显示)</label>
                        </div>
                    </div>
                </div>
                <div class="mt-4">
                    <button type="submit" class="btn btn-primary">保存修改</button>
                    <a href="cases.php" class="btn btn-light ms-2">取消</a>
                </div>
            </form>
        <?php endif; ?>
    </div>
</div>

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