<?php
ob_start();
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>
                <img src="https://api.iconify.design/mdi:<?php echo $action == 'add' ? 'plus-circle' : 'pencil'; ?>.svg?color=%23667eea" width="24" height="24" style="vertical-align: middle; margin-right: 8px;" alt="">
                <?php echo $action == 'add' ? '添加应用' : '编辑应用'; ?>
            </h2>
            <a href="?page=apps" class="btn btn-secondary">
                <img src="https://api.iconify.design/mdi:arrow-left.svg?color=currentColor" width="18" height="18" style="vertical-align: middle; margin-right: 4px;" alt="">
                返回列表
            </a>
        </div>
        
        <?php if (isset($error)): ?>
            <div class="alert alert-error">
                <img src="https://api.iconify.design/mdi:alert-circle.svg?color=%23ef4444" width="20" height="20" style="vertical-align: middle; margin-right: 8px;" alt="">
                <?php echo $error; ?>
            </div>
        <?php endif; ?>
        
        <div class="form-card">
            <form method="POST">
                <div class="form-group">
                    <label>
                        <img src="https://api.iconify.design/mdi:application.svg?color=%23667eea" width="18" height="18" style="vertical-align: middle; margin-right: 6px;" alt="">
                        应用名称 *
                    </label>
                    <input type="text" name="name" required value="<?php echo htmlspecialchars($edit_app['name'] ?? ''); ?>" placeholder="请输入应用名称">
                </div>
                <div class="form-group">
                    <label>
                        <img src="https://api.iconify.design/mdi:identifier.svg?color=%23667eea" width="18" height="18" style="vertical-align: middle; margin-right: 6px;" alt="">
                        应用标识 *
                    </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>
                        <img src="https://api.iconify.design/mdi:information.svg?color=%236b7280" width="14" height="14" style="vertical-align: middle; margin-right: 4px;" alt="">
                        唯一标识，用于授权验证，<?php echo $action == 'edit' ? '不可修改' : '创建后不可修改'; ?>
                    </small>
                </div>
                <div class="form-group">
                    <label>
                        <img src="https://api.iconify.design/mdi:text-box.svg?color=%23667eea" width="18" height="18" style="vertical-align: middle; margin-right: 6px;" alt="">
                        应用描述
                    </label>
                    <textarea name="description" rows="4" placeholder="请输入应用描述（可选）"><?php echo htmlspecialchars($edit_app['description'] ?? ''); ?></textarea>
                </div>
                <div class="form-row">
                    <div class="form-group">
                        <label>
                            <img src="https://api.iconify.design/mdi:cash.svg?color=%2310b981" width="18" height="18" style="vertical-align: middle; margin-right: 6px;" alt="">
                            价格 (元) *
                        </label>
                        <div class="input-with-prefix">
                            <span class="prefix">¥</span>
                            <input type="number" name="price" step="0.01" required value="<?php echo $edit_app['price'] ?? 0; ?>" placeholder="0.00">
                        </div>
                    </div>
                    <div class="form-group">
                        <label>
                            <img src="https://api.iconify.design/mdi:calendar-clock.svg?color=%23f59e0b" width="18" height="18" style="vertical-align: middle; margin-right: 6px;" alt="">
                            授权期限 (天) *
                        </label>
                        <input type="number" name="duration_days" required value="<?php echo $edit_app['duration_days'] ?? 0; ?>" placeholder="0">
                        <small>
                            <img src="https://api.iconify.design/mdi:information.svg?color=%236b7280" width="14" height="14" style="vertical-align: middle; margin-right: 4px;" alt="">
                            0表示永久
                        </small>
                    </div>
                </div>
                <div class="form-group">
                    <label>
                        <img src="https://api.iconify.design/mdi:toggle-switch.svg?color=%23667eea" width="18" height="18" style="vertical-align: middle; margin-right: 6px;" alt="">
                        状态
                    </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">
                        <img src="https://api.iconify.design/mdi:content-save.svg?color=white" width="18" height="18" style="vertical-align: middle; margin-right: 6px;" alt="">
                        保存
                    </button>
                    <a href="?page=apps" class="btn btn-secondary">
                        <img src="https://api.iconify.design/mdi:close.svg?color=currentColor" width="18" height="18" style="vertical-align: middle; margin-right: 6px;" alt="">
                        取消
                    </a>
                </div>
            </form>
        </div>
    </div>
    
<?php else: ?>
    <!-- 应用列表 -->
    <div class="apps-manager">
        <div class="page-header">
            <h2>
                <img src="https://api.iconify.design/mdi:application-cog.svg?color=%23667eea" width="24" height="24" style="vertical-align: middle; margin-right: 8px;" alt="">
                应用管理
            </h2>
            <a href="?page=apps&action=add" class="btn btn-primary">
                <img src="https://api.iconify.design/mdi:plus.svg?color=white" width="18" height="18" style="vertical-align: middle; margin-right: 6px;" alt="">
                添加应用
            </a>
        </div>
        
        <?php if (empty($apps)): ?>
            <div class="empty-state">
                <img src="https://api.iconify.design/mdi:package-variant-closed.svg?color=%239ca3af" width="64" height="64" alt="">
                <p>暂无应用，点击上方按钮添加</p>
            </div>
        <?php else: ?>
            <div class="apps-grid">
                <?php foreach ($apps as $app): ?>
                    <div class="app-card">
                        <div class="app-card-header">
                            <div class="app-icon">
                                <img src="https://api.iconify.design/mdi:application.svg?color=%23667eea" width="32" height="32" alt="">
                            </div>
                            <div class="app-info">
                                <h3><?php echo htmlspecialchars($app['name']); ?></h3>
                                <code><?php echo htmlspecialchars($app['app_key']); ?></code>
                            </div>
                            <div class="app-status">
                                <span class="status-badge status-<?php echo $app['status'] ? 'active' : 'inactive'; ?>">
                                    <?php echo $app['status'] ? '启用' : '禁用'; ?>
                                </span>
                            </div>
                        </div>
                        <div class="app-card-body">
                            <?php if (!empty($app['description'])): ?>
                                <p class="app-description"><?php echo htmlspecialchars($app['description']); ?></p>
                            <?php else: ?>
                                <p class="app-description text-muted">暂无描述</p>
                            <?php endif; ?>
                            <div class="app-meta">
                                <div class="meta-item">
                                    <img src="https://api.iconify.design/mdi:cash.svg?color=%2310b981" width="16" height="16" alt="">
                                    <span>¥<?php echo number_format($app['price'], 2); ?></span>
                                </div>
                                <div class="meta-item">
                                    <img src="https://api.iconify.design/mdi:calendar-clock.svg?color=%23f59e0b" width="16" height="16" alt="">
                                    <span><?php echo $app['duration_days'] ? $app['duration_days'] . '天' : '永久'; ?></span>
                                </div>
                                <div class="meta-item">
                                    <img src="https://api.iconify.design/mdi:clock-outline.svg?color=%236b7280" width="16" height="16" alt="">
                                    <span><?php echo date('Y-m-d', strtotime($app['created_at'])); ?></span>
                                </div>
                            </div>
                        </div>
                        <div class="app-card-footer">
                            <a href="?page=apps&action=edit&id=<?php echo $app['id']; ?>" class="btn-icon" title="编辑">
                                <img src="https://api.iconify.design/mdi:pencil.svg?color=%23667eea" width="20" height="20" alt="">
                            </a>
                            <a href="?page=apps&action=delete&id=<?php echo $app['id']; ?>" class="btn-icon" onclick="return confirm('确定删除此应用吗？删除后相关授权也将失效。')" title="删除">
                                <img src="https://api.iconify.design/mdi:delete.svg?color=%23ef4444" width="20" height="20" alt="">
                            </a>
                        </div>
                    </div>
                <?php endforeach; ?>
            </div>
        <?php endif; ?>
    </div>
<?php endif; ?>

<style>
.form-container {
    max-width: 600px;
}
.form-card {
    background: var(--bg-primary);
    border-radius: 16px;
    padding: 30px;
    border: 1px solid var(--border-color);
    box-shadow: 0 2px 8px rgba(0,0,0,0.05);
}
.form-group {
    margin-bottom: 20px;
}
.form-group label {
    display: block;
    margin-bottom: 8px;
    font-weight: 500;
    color: var(--text-primary);
}
.form-group label img {
    display: inline-block;
}
.form-group input,
.form-group textarea,
.form-group select {
    width: 100%;
    padding: 12px 16px;
    border: 1px solid var(--border-color);
    border-radius: 10px;
    font-size: 14px;
    background: var(--bg-primary);
    color: var(--text-primary);
    transition: border-color 0.2s, box-shadow 0.2s;
}
.form-group input:focus,
.form-group textarea:focus,
.form-group select:focus {
    outline: none;
    border-color: var(--primary-color);
    box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
}
.form-group input[readonly] {
    background: var(--bg-secondary);
    cursor: not-allowed;
}
.form-group small {
    display: block;
    margin-top: 6px;
    font-size: 12px;
    color: var(--text-muted);
}
.form-group small img {
    display: inline-block;
}
.form-row {
    display: grid;
    grid-template-columns: 1fr 1fr;
    gap: 20px;
}
.input-with-prefix {
    display: flex;
    align-items: center;
    border: 1px solid var(--border-color);
    border-radius: 10px;
    overflow: hidden;
    transition: border-color 0.2s, box-shadow 0.2s;
}
.input-with-prefix:focus-within {
    border-color: var(--primary-color);
    box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
}
.input-with-prefix .prefix {
    padding: 12px 16px;
    background: var(--bg-secondary);
    color: var(--text-muted);
    font-weight: 500;
    border-right: 1px solid var(--border-color);
}
.input-with-prefix input {
    flex: 1;
    border: none !important;
    border-radius: 0 !important;
    padding: 12px 16px;
}
.input-with-prefix input:focus {
    outline: none;
    box-shadow: none;
}
.form-actions {
    margin-top: 30px;
    display: flex;
    gap: 12px;
}
.btn {
    display: inline-flex;
    align-items: center;
    padding: 10px 20px;
    border-radius: 10px;
    font-size: 14px;
    font-weight: 500;
    text-decoration: none;
    cursor: pointer;
    transition: all 0.2s;
    border: 1px solid transparent;
}
.btn img {
    display: inline-block;
}
.btn-primary {
    background: var(--primary-color);
    color: white;
}
.btn-primary:hover {
    background: var(--primary-hover);
    transform: translateY(-1px);
}
.btn-secondary {
    background: var(--bg-secondary);
    color: var(--text-primary);
    border-color: var(--border-color);
}
.btn-secondary:hover {
    background: var(--bg-primary);
}
.btn-icon {
    display: inline-flex;
    align-items: center;
    justify-content: center;
    width: 36px;
    height: 36px;
    border-radius: 10px;
    background: var(--bg-secondary);
    transition: all 0.2s;
}
.btn-icon:hover {
    background: var(--border-color);
    transform: translateY(-1px);
}
.alert {
    display: flex;
    align-items: center;
    padding: 14px 18px;
    border-radius: 12px;
    margin-bottom: 20px;
}
.alert-error {
    background: #fef2f2;
    border: 1px solid #fecaca;
    color: #991b1b;
}
.alert img {
    display: inline-block;
}

/* 应用卡片网格 */
.apps-grid {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(320px, 1fr));
    gap: 20px;
    margin-top: 20px;
}
.app-card {
    background: var(--bg-primary);
    border-radius: 16px;
    border: 1px solid var(--border-color);
    overflow: hidden;
    transition: all 0.2s;
    display: flex;
    flex-direction: column;
}
.app-card:hover {
    box-shadow: 0 4px 12px rgba(0,0,0,0.08);
    transform: translateY(-2px);
}
.app-card-header {
    display: flex;
    align-items: flex-start;
    padding: 20px 20px 16px;
    border-bottom: 1px solid var(--border-color);
}
.app-icon {
    width: 48px;
    height: 48px;
    background: linear-gradient(135deg, rgba(102,126,234,0.1) 0%, rgba(102,126,234,0.05) 100%);
    border-radius: 12px;
    display: flex;
    align-items: center;
    justify-content: center;
    margin-right: 12px;
}
.app-info {
    flex: 1;
    min-width: 0;
}
.app-info h3 {
    font-size: 16px;
    font-weight: 600;
    margin: 0 0 4px;
    color: var(--text-primary);
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
}
.app-info code {
    font-size: 12px;
    background: var(--bg-secondary);
    padding: 2px 6px;
    border-radius: 6px;
    color: var(--primary-color);
}
.app-status {
    flex-shrink: 0;
}
.status-badge {
    display: inline-block;
    padding: 4px 10px;
    border-radius: 20px;
    font-size: 12px;
    font-weight: 500;
}
.status-active {
    background: #d1fae5;
    color: #065f46;
}
.status-inactive {
    background: #fee2e2;
    color: #991b1b;
}
.app-card-body {
    padding: 16px 20px;
    flex: 1;
}
.app-description {
    font-size: 14px;
    color: var(--text-secondary);
    margin: 0 0 16px;
    line-height: 1.5;
    display: -webkit-box;
    -webkit-line-clamp: 2;
    -webkit-box-orient: vertical;
    overflow: hidden;
}
.text-muted {
    color: var(--text-muted);
    font-style: italic;
}
.app-meta {
    display: flex;
    flex-wrap: wrap;
    gap: 16px;
}
.meta-item {
    display: flex;
    align-items: center;
    gap: 6px;
    font-size: 13px;
    color: var(--text-secondary);
}
.meta-item img {
    opacity: 0.7;
}
.app-card-footer {
    display: flex;
    justify-content: flex-end;
    gap: 8px;
    padding: 12px 20px 20px;
    border-top: 1px solid var(--border-color);
}

/* 空状态 */
.empty-state {
    text-align: center;
    padding: 60px 20px;
    background: var(--bg-primary);
    border-radius: 16px;
    border: 1px solid var(--border-color);
    margin-top: 20px;
}
.empty-state img {
    opacity: 0.5;
    margin-bottom: 16px;
}
.empty-state p {
    color: var(--text-muted);
    font-size: 15px;
}

/* 页面头部 */
.page-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
}
.page-header h2 {
    display: flex;
    align-items: center;
    font-size: 24px;
    font-weight: 600;
    color: var(--text-primary);
    margin: 0;
}
.page-header h2 img {
    display: inline-block;
}

/* 响应式 */
@media (max-width: 768px) {
    .form-row {
        grid-template-columns: 1fr;
        gap: 0;
    }
    .apps-grid {
        grid-template-columns: 1fr;
    }
}
</style>