<?php
ob_start();
header('Content-Type: application/json');
require_once '../config.php';

if (!isLoggedIn()) {
    echo json_encode(['code' => 1, 'msg' => '请先登录']);
    exit;
}

$user = currentUser();
$action = $_GET['action'] ?? '';

switch ($action) {
    case 'home':
        // 获取用户拥有的应用（通过 licenses 表）
        $apps = $db->fetchAll("
            SELECT a.id, a.name, a.status,
                   COUNT(l.id) as license_count
            FROM licenses l
            JOIN apps a ON l.app_id = a.id
            WHERE l.user_id = {$user['id']}
            GROUP BY a.id
            ORDER BY MAX(l.created_at) DESC
            LIMIT 10
        ");
        echo json_encode(['code' => 0, 'apps' => $apps ?: []]);
        break;
        
    case 'licenses':
        $licenses = $db->fetchAll("
            SELECT l.*, a.name as app_name
            FROM licenses l
            LEFT JOIN apps a ON l.app_id = a.id
            WHERE l.user_id = {$user['id']}
            ORDER BY l.created_at DESC
            LIMIT 20
        ");
        echo json_encode(['code' => 0, 'licenses' => $licenses ?: []]);
        break;
        
    case 'orders':
        $orders = $db->fetchAll("
            SELECT o.*, 
                   CASE o.status 
                       WHEN 'pending' THEN '待支付'
                       WHEN 'paid' THEN '已支付'
                       WHEN 'cancelled' THEN '已取消'
                       ELSE '未知'
                   END as status_text
            FROM orders o
            WHERE o.user_id = {$user['id']}
            ORDER BY o.created_at DESC
            LIMIT 20
        ");
        echo json_encode(['code' => 0, 'orders' => $orders ?: []]);
        break;
        
    default:
        echo json_encode(['code' => 1, 'msg' => '无效操作']);
}
exit;