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

header('Content-Type: application/json');

// 检查登录
if (!isLoggedIn()) {
    echo json_encode(['success' => false, 'message' => '请先登录']);
    exit;
}

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

// 获取邀请信息
if ($action === 'info') {
    // 生成邀请码（如果没有）
    if (empty($user['invite_code'])) {
        $invite_code = strtoupper(substr(md5($user['id'] . time()), 0, 8));
        $db->query("UPDATE users SET invite_code = '$invite_code' WHERE id = {$user['id']}");
        $user['invite_code'] = $invite_code;
    }
    
    // 获取邀请统计
    $invite_count = $db->fetchOne("SELECT COUNT(*) as cnt FROM invite_records WHERE inviter_id = {$user['id']}")['cnt'] ?? 0;
    $rebate_total = $db->fetchOne("SELECT SUM(amount) as total FROM rebate_records WHERE user_id = {$user['id']} AND status = 1")['total'] ?? 0;
    $pending_rebate = $db->fetchOne("SELECT SUM(amount) as total FROM rebate_records WHERE user_id = {$user['id']} AND status = 0")['total'] ?? 0;
    
    // 获取最近的返利记录
    $recent_rebates = $db->fetchAll("
        SELECT r.*, u.username as from_username 
        FROM rebate_records r
        LEFT JOIN users u ON r.from_user_id = u.id
        WHERE r.user_id = {$user['id']} AND r.status = 1
        ORDER BY r.id DESC LIMIT 10
    ");
    
    // 获取最近的邀请记录
    $recent_invites = $db->fetchAll("
        SELECT i.*, u.username as invitee_username
        FROM invite_records i
        LEFT JOIN users u ON i.invitee_id = u.id
        WHERE i.inviter_id = {$user['id']}
        ORDER BY i.id DESC LIMIT 10
    ");
    
    echo json_encode([
        'success' => true,
        'data' => [
            'invite_code' => $user['invite_code'],
            'invite_url' => SITE_URL . 'modules/home/register.php?code=' . $user['invite_code'],
            'invite_count' => $invite_count,
            'rebate_balance' => $user['rebate_balance'],
            'rebate_total' => $rebate_total,
            'pending_rebate' => $pending_rebate,
            'recent_rebates' => $recent_rebates,
            'recent_invites' => $recent_invites
        ]
    ]);
    exit;
}

// 申请提现
if ($action === 'withdraw') {
    $amount = floatval($_POST['amount'] ?? 0);
    
    if ($amount <= 0) {
        echo json_encode(['success' => false, 'message' => '金额错误']);
        exit;
    }
    
    if ($user['rebate_balance'] < $amount) {
        echo json_encode(['success' => false, 'message' => '余额不足']);
        exit;
    }
    
    $min_withdraw = 10; // 最低提现金额
    if ($amount < $min_withdraw) {
        echo json_encode(['success' => false, 'message' => "最低提现金额 ¥{$min_withdraw}"]);
        exit;
    }
    
    // 创建提现申请
    $db->query("INSERT INTO withdraw_records (user_id, amount) VALUES ({$user['id']}, $amount)");
    
    echo json_encode(['success' => true, 'message' => '提现申请已提交，请等待审核']);
    exit;
}