<?php
ob_start();
require_once __DIR__ . '/../../config.php';

if (!isAdmin()) {
    header('Location: /m/');
    exit;
}

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

// 处理删除
if ($action == 'delete' && $app_id > 0) {
    $check = $db->fetchOne("SELECT id FROM licenses WHERE app_id = $app_id LIMIT 1");
    if ($check) {
        echo '<script>alert("该应用存在关联授权码，无法删除"); location.href="?page=apps";</script>';
        exit;
    } else {
        $db->query("DELETE FROM apps WHERE id = $app_id");
        header('Location: ?page=apps');
        exit;
    }
}

// 处理保存
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'] ?? '');
    $edit_id = intval($_POST['id'] ?? 0);
    
    if (empty($name)) {
        $error = '应用名称不能为空';
    } elseif ($edit_id == 0 && empty($app_key)) {
        $error = '应用标识不能为空';
    } elseif ($edit_id == 0 && !preg_match('/^[a-zA-Z0-9_]+$/', $app_key)) {
        $error = '应用标识只能包含字母、数字和下划线';
    } else {
        if ($edit_id > 0) {
            $db->query("UPDATE apps SET name='$name', description='$description', price=$price, duration_days=$duration_days, status=$status WHERE id=$edit_id");
            header('Location: ?page=apps');
            exit;
        } else {
            $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')");
                header('Location: ?page=apps');
                exit;
            }
        }
    }
}

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

$apps = $db->fetchAll("SELECT * FROM apps ORDER BY id DESC");
?>

<?php if ($action == 'add' || $action == 'edit'): ?>
<!-- 添加/编辑表单 -->
<div class="card">
    <h3 style="margin-bottom: 16px; display: flex; align-items: center; gap: 8px;">
        <img src="https://api.iconify.design/mdi:<?php echo $edit_app ? 'pencil' : 'plus'; ?>.svg?color=%23667eea" width="20" height="20" alt="">
        <?php echo $edit_app ? '编辑应用' : '添加应用'; ?>
    </h3>
    
    <?php if ($error): ?>
    <div style="background: #fef2f2; color: #991b1b; padding: 12px; border-radius: 8px; margin-bottom: 16px;">
        <?php echo $error; ?>
    </div>
    <?php endif; ?>
    
    <form method="POST">
        <input type="hidden" name="id" value="<?php echo $edit_app['id'] ?? 0; ?>">
        
        <div style="margin-bottom: 16px;">
            <label style="display: block; margin-bottom: 6px; font-weight: 500;">应用名称 *</label>
            <input type="text" name="name" value="<?php echo htmlspecialchars($edit_app['name'] ?? ''); ?>" required 
                   style="width:100%; padding:12px; border:1px solid #e5e7eb; border-radius:8px; font-size:14px;">
        </div>
        
        <div style="margin-bottom: 16px;">
            <label style="display: block; margin-bottom: 6px; font-weight: 500;">应用标识 *</label>
            <input type="text" name="app_key" value="<?php echo htmlspecialchars($edit_app['app_key'] ?? ''); ?>" 
                   <?php echo $edit_app ? 'readonly' : 'required'; ?>
                   style="width:100%; padding:12px; border:1px solid #e5e7eb; border-radius:8px; font-size:14px; <?php echo $edit_app ? 'background:#f5f5f5;' : ''; ?>">
            <?php if (!$edit_app): ?>
            <small style="color:#999; font-size:12px;">唯一标识，只能包含字母、数字、下划线，创建后不可修改</small>
            <?php endif; ?>
        </div>
        
        <div style="margin-bottom: 16px;">
            <label style="display: block; margin-bottom: 6px; font-weight: 500;">应用描述</label>
            <textarea name="description" rows="3" 
                      style="width:100%; padding:12px; border:1px solid #e5e7eb; border-radius:8px; font-size:14px; resize:vertical;"><?php echo htmlspecialchars($edit_app['description'] ?? ''); ?></textarea>
        </div>
        
        <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 12px; margin-bottom: 16px;">
            <div>
                <label style="display: block; margin-bottom: 6px; font-weight: 500;">价格 (元) *</label>
                <input type="number" name="price" step="0.01" value="<?php echo $edit_app['price'] ?? 0; ?>" required
                       style="width:100%; padding:12px; border:1px solid #e5e7eb; border-radius:8px; font-size:14px;">
            </div>
            <div>
                <label style="display: block; margin-bottom: 6px; font-weight: 500;">授权期限 (天)</label>
                <input type="number" name="duration_days" value="<?php echo $edit_app['duration_days'] ?? 0; ?>"
                       style="width:100%; padding:12px; border:1px solid #e5e7eb; border-radius:8px; font-size:14px;">
                <small style="color:#999; font-size:12px;">0 表示永久</small>
            </div>
        </div>
        
        <div style="margin-bottom: 20px;">
            <label style="display: block; margin-bottom: 6px; font-weight: 500;">状态</label>
            <select name="status" style="width:100%; padding:12px; border:1px solid #e5e7eb; border-radius:8px; font-size:14px;">
                <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 style="display: flex; gap: 10px;">
            <button type="submit" class="btn btn-primary" style="flex:1;">
                <img src="https://api.iconify.design/mdi:content-save.svg?color=white" width="18" height="18" alt="">
                保存
            </button>
            <a href="?page=apps" class="btn" style="flex:1; background:#f5f5f5; text-align:center; text-decoration:none; color:#666;">
                <img src="https://api.iconify.design/mdi:close.svg?color=%23666" width="18" height="18" alt="">
                取消
            </a>
        </div>
    </form>
</div>

<?php else: ?>
<!-- 应用列表 -->
<div style="display: flex; justify-content: flex-end; margin-bottom: 16px;">
    <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" alt="">
        添加应用
    </a>
</div>

<?php foreach ($apps as $app): ?>
<div class="card">
    <div style="display: flex; align-items: center; gap: 12px; margin-bottom: 12px;">
        <img src="https://api.iconify.design/mdi:application.svg?color=%23667eea" width="40" height="40" alt="">
        <div style="flex:1;">
            <div style="font-weight: 600;"><?php echo htmlspecialchars($app['name']); ?></div>
            <code style="font-size: 11px; background: #f5f5f5; padding: 2px 6px; border-radius: 4px;"><?php echo htmlspecialchars($app['app_key']); ?></code>
        </div>
        <span style="padding: 4px 10px; border-radius: 20px; font-size: 12px; 
                     <?php echo $app['status'] ? 'background:#d1fae5;color:#065f46;' : 'background:#fee2e2;color:#991b1b;'; ?>">
            <?php echo $app['status'] ? '启用' : '禁用'; ?>
        </span>
    </div>
    <?php if ($app['description']): ?>
    <p style="font-size: 13px; color: #666; margin-bottom: 10px;"><?php echo htmlspecialchars($app['description']); ?></p>
    <?php endif; ?>
    <div style="display: flex; gap: 16px; font-size: 13px; color: #666; margin-bottom: 12px;">
        <span><img src="https://api.iconify.design/mdi:cash.svg?color=%2310b981" width="14" height="14" alt=""> ¥<?php echo number_format($app['price'], 2); ?></span>
        <span><img src="https://api.iconify.design/mdi:calendar.svg?color=%23f59e0b" width="14" height="14" alt=""> <?php echo $app['duration_days'] ? $app['duration_days'].'天' : '永久'; ?></span>
    </div>
    <div style="display: flex; gap: 8px;">
        <a href="?page=apps&action=edit&id=<?php echo $app['id']; ?>" style="flex:1; text-align: center; padding: 8px; background: #f5f5f5; border-radius: 8px; text-decoration: none; color: #666;">
            <img src="https://api.iconify.design/mdi:pencil.svg?color=%23666" width="16" height="16" alt=""> 编辑
        </a>
        <a href="?page=apps&action=delete&id=<?php echo $app['id']; ?>" onclick="return confirm('确定删除？')" style="flex:1; text-align: center; padding: 8px; background: #fef2f2; border-radius: 8px; text-decoration: none; color: #ef4444;">
            <img src="https://api.iconify.design/mdi:delete.svg?color=%23ef4444" width="16" height="16" alt=""> 删除
        </a>
    </div>
</div>
<?php endforeach; ?>

<?php if (empty($apps)): ?>
<div class="card" style="text-align: center; padding: 40px;">
    <img src="https://api.iconify.design/mdi:package-variant-closed.svg?color=%23999" width="48" height="48" alt="">
    <p style="color: #999;">暂无应用</p>
</div>
<?php endif; ?>

<?php endif; ?>