<?php
requireAdmin();

$action = $_GET['action'] ?? 'list';
$app_id = isset($_GET['id']) ? intval($_GET['id']) : 0;

// 处理删除
if ($action == 'delete' && $app_id > 0) {
    // 检查是否有授权码关联
    $check = $db->fetchOne("SELECT id FROM licenses WHERE app_id = $app_id LIMIT 1");
    if ($check) {
        $error = '该应用存在关联授权码，无法删除';
    } else {
        $db->query("DELETE FROM apps WHERE id = $app_id");
        redirect('?page=apps');
    }
}

// 处理编辑/添加
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $name = trim($_POST['name'] ?? '');
    $description = trim($_POST['description'] ?? '');
    $price = floatval($_POST['price'] ?? 0);
    $duration_days = intval($_POST['duration_days'] ?? 0);
    $status = intval($_POST['status'] ?? 1);
    $app_key = trim($_POST['app_key'] ?? '');
    
    if (empty($name)) {
        $error = '应用名称不能为空';
    } elseif (empty($app_key)) {
        $error = '应用标识不能为空';
    } elseif (!preg_match('/^[a-zA-Z0-9_]+$/', $app_key)) {
        $error = '应用标识只能包含字母、数字和下划线';
    } else {
        if ($action == 'edit' && $app_id > 0) {
            // 编辑时检查应用标识是否被其他应用使用
            $check = $db->fetchOne("SELECT id FROM apps WHERE app_key = '$app_key' AND id != $app_id");
            if ($check) {
                $error = '应用标识已存在';
            } else {
                $db->query("UPDATE apps SET name='$name', description='$description', price=$price, duration_days=$duration_days, status=$status, app_key='$app_key' WHERE id=$app_id");
                redirect('?page=apps');
            }
        } elseif ($action == 'add') {
            // 添加时检查应用标识是否已存在
            $check = $db->fetchOne("SELECT id FROM apps WHERE app_key = '$app_key'");
            if ($check) {
                $error = '应用标识已存在';
            } else {
                $db->query("INSERT INTO apps (name, description, price, duration_days, status, app_key) VALUES ('$name', '$description', $price, $duration_days, $status, '$app_key')");
                redirect('?page=apps');
            }
        }
    }
}

// 获取应用列表
$apps = $db->fetchAll("SELECT * FROM apps ORDER BY id DESC");

// 编辑模式获取数据
$edit_app = null;
if ($action == 'edit' && $app_id > 0) {
    $edit_app = $db->fetchOne("SELECT * FROM apps WHERE id = $app_id");
}
?>

<?php if ($action == 'add' || ($action == 'edit' && $edit_app)): ?>
    <!-- 添加/编辑表单 -->
    <div class="form-container">
        <div class="page-header">
            <h2><?php echo $action == 'add' ? '添加应用' : '编辑应用'; ?></h2>
            <a href="?page=apps" class="btn btn-secondary">返回列表</a>
        </div>
        
        <?php if (isset($error)): ?>
            <div class="alert alert-error"><?php echo $error; ?></div>
        <?php endif; ?>
        
        <div class="form-card">
            <form method="POST">
                <div class="form-group">
                    <label>应用名称 *</label>
                    <input type="text" name="name" required value="<?php echo htmlspecialchars($edit_app['name'] ?? ''); ?>">
                </div>
                <div class="form-group">
                    <label>应用标识 *</label>
                    <input type="text" name="app_key" required value="<?php echo htmlspecialchars($edit_app['app_key'] ?? ''); ?>" placeholder="例如：your_app_name" <?php echo $action == 'edit' ? 'readonly' : ''; ?>>
                    <small>唯一标识，用于授权验证，<?php echo $action == 'edit' ? '不可修改' : '创建后不可修改'; ?></small>
                </div>
                <div class="form-group">
                    <label>应用描述</label>
                    <textarea name="description" rows="4"><?php echo htmlspecialchars($edit_app['description'] ?? ''); ?></textarea>
                </div>
                <div class="form-row">
                    <div class="form-group">
                        <label>价格 (元) *</label>
                        <input type="number" name="price" step="0.01" required value="<?php echo $edit_app['price'] ?? 0; ?>">
                    </div>
                    <div class="form-group">
                        <label>授权期限 (天) *</label>
                        <input type="number" name="duration_days" required value="<?php echo $edit_app['duration_days'] ?? 0; ?>">
                        <small>0表示永久</small>
                    </div>
                </div>
                <div class="form-group">
                    <label>状态</label>
                    <select name="status">
                        <option value="1" <?php echo (isset($edit_app['status']) && $edit_app['status'] == 1) ? 'selected' : ''; ?>>启用</option>
                        <option value="0" <?php echo (isset($edit_app['status']) && $edit_app['status'] == 0) ? 'selected' : ''; ?>>禁用</option>
                    </select>
                </div>
                <div class="form-actions">
                    <button type="submit" class="btn btn-primary">保存</button>
                    <a href="?page=apps" class="btn btn-secondary">取消</a>
                </div>
            </form>
        </div>
    </div>
    
<?php else: ?>
    <!-- 应用列表 -->
    <div class="apps-manager">
        <div class="page-header">
            <h2>应用管理</h2>
            <a href="?page=apps&action=add" class="btn btn-primary">+ 添加应用</a>
        </div>
        
        <div class="table-container">
            <table class="data-table">
                <thead>
                    <tr>
                        <th>ID</th>
                        <th>应用名称</th>
                        <th>应用标识</th>
                        <th>描述</th>
                        <th>价格</th>
                        <th>授权期限</th>
                        <th>状态</th>
                        <th>创建时间</th>
                        <th>操作</th>
                    </thead>
                <tbody>
                    <?php if (empty($apps)): ?>
                        <tr><td colspan="9" style="text-align: center;">暂无应用</td></tr>
                    <?php else: ?>
                        <?php foreach ($apps as $app): ?>
                            <tr>
                                <td><?php echo $app['id']; ?></td>
                                <td><strong><?php echo htmlspecialchars($app['name']); ?></strong></td>
                                <td><code><?php echo htmlspecialchars($app['app_key']); ?></code></td>
                                <td><?php echo htmlspecialchars(mb_substr($app['description'] ?? '', 0, 50)); ?></td>
                                <td>¥<?php echo number_format($app['price'], 2); ?></td>
                                <td><?php echo $app['duration_days'] ? $app['duration_days'] . '天' : '永久'; ?></td>
                                <td>
                                    <span class="status-badge status-<?php echo $app['status'] ? 'active' : 'inactive'; ?>">
                                        <?php echo $app['status'] ? '启用' : '禁用'; ?>
                                    </span>
                                </td>
                                <td><?php echo $app['created_at']; ?></td>
                                <td>
                                    <a href="?page=apps&action=edit&id=<?php echo $app['id']; ?>" class="btn-icon" title="编辑">✏️</a>
                                    <a href="?page=apps&action=delete&id=<?php echo $app['id']; ?>" class="btn-icon" onclick="return confirm('确定删除此应用吗？删除后相关授权也将失效。')" title="删除">🗑️</a>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
    </div>
<?php endif; ?>

<style>
.form-container {
    max-width: 600px;
}
.form-card {
    background: var(--bg-primary);
    border-radius: var(--radius-md);
    padding: 30px;
    border: 1px solid var(--border-color);
}
.form-row {
    display: grid;
    grid-template-columns: 1fr 1fr;
    gap: 20px;
}
.form-actions {
    margin-top: 20px;
    display: flex;
    gap: 10px;
}
.btn-icon {
    background: none;
    border: none;
    cursor: pointer;
    font-size: 18px;
    padding: 4px 8px;
    border-radius: 4px;
}
.btn-icon:hover {
    background: var(--bg-secondary);
}
.status-badge {
    padding: 3px 8px;
    border-radius: 20px;
    font-size: 12px;
}
.status-active {
    background: #d1fae5;
    color: #065f46;
}
.status-inactive {
    background: #fee2e2;
    color: #991b1b;
}
</style>