<?php
require '../include/common.php';

session_name('user_session');
session_start();

if (!isset($_SESSION['user_id'])) {
    echo json_encode(['status' => 'error', 'message' => '用户未登录。']);
    exit;
}

$userId = $_SESSION['user_id'];

if (isset($_POST['action']) && $_POST['action'] === 'purchase') {
    $groupId = intval($_POST['group_id']);
    $price = floatval($_POST['price']);

    // 检查用户余额
    $stmt = $conn->prepare("SELECT balance FROM " . table('users') . " WHERE id = ?");
    $stmt->bind_param("i", $userId);
    $stmt->execute();
    $result = $stmt->get_result();
    $user = $result->fetch_assoc();

    if ($user && $user['balance'] >= $price) {
        // 扣款
        $newBalance = $user['balance'] - $price;
        $stmt = $conn->prepare("UPDATE " . table('users') . " SET balance = ? WHERE id = ?");
        $stmt->execute([$newBalance, $userId]);

        $expiryDate = date('Y-m-d H:i:s', strtotime('+1 month'));
        $stmt = $conn->prepare("UPDATE " . table('users') . " SET group_id = ?, group_expiry = ? WHERE id = ?");
        $stmt->execute([$groupId, $expiryDate, $userId]);

        $reason = "购买会员组 ID: $groupId";
        $stmt = $conn->prepare("INSERT INTO " . table('balance_logs') . " (user_id, change_amount, new_balance, reason) VALUES (?, ?, ?, ?)");
        $stmt->execute([$userId, -$price, $newBalance, $reason]);

        echo json_encode(['status' => 'success']);
        exit;
    } else {
        echo json_encode(['status' => 'error', 'message' => '余额不足或用户不存在。']);
        exit;
    }
}


$sqlUserGroup = "SELECT group_id FROM " . table('users') . " WHERE id = ?";
$stmtUserGroup = $conn->prepare($sqlUserGroup);
$stmtUserGroup->bind_param("i", $userId);
$stmtUserGroup->execute();
$resultUserGroup = $stmtUserGroup->get_result();

$userGroupIds = [];
if ($resultUserGroup && $resultUserGroup->num_rows > 0) {
    $userRow = $resultUserGroup->fetch_assoc();
    $userGroupIds[] = $userRow['group_id'];
}

$sqlAllGroups = "SELECT id, group_name, group_price FROM " . table('user_groups') . "";
$stmtAllGroups = $conn->prepare($sqlAllGroups);
$stmtAllGroups->execute();
$resultAllGroups = $stmtAllGroups->get_result();

$stmtUserGroup->close();
$stmtAllGroups->close();
?>

<?php include 'header.php'; ?>
<!DOCTYPE html>
<html lang="zh-CN">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <title>会员组信息</title>
    <style>
        .domain-list {
            display: none;
            position: absolute;
            background: white;
            border: 1px solid #ccc;
            border-radius: 5px;
            padding: 10px;
            z-index: 1000;
            box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
        }

        .domain-container {
            position: relative;
            margin-bottom: 20px;
        }

        .btn-info {
            margin-bottom: 10px;
        }
        .domain-list {
    list-style-type: none; 
    padding: 0;            
    margin: 0;  
}

    </style>
</head>

<body>
    <div class="main-content">
        <div class="page-content">
            <div class="container-fluid">
                <h1>会员组信息</h1>

                <div class="row">
                    <?php
                    if (!empty($userGroupIds)) {
                        foreach ($userGroupIds as $groupId) {
                            $sqlGroup = "SELECT id, group_name FROM " . table('user_groups') . " WHERE id = ?";
                            $stmtGroup = $conn->prepare($sqlGroup);
                            $stmtGroup->bind_param("i", $groupId);
                            $stmtGroup->execute();
                            $resultGroup = $stmtGroup->get_result();

                            if ($resultGroup && $resultGroup->num_rows > 0) {
                                while ($row = $resultGroup->fetch_assoc()) {
                                    echo '<p>您所在的会员组: ' . htmlspecialchars($row['group_name']) . '</p>';
                                }
                            }
                            $stmtGroup->close();
                        }
                    } else {
                        echo '<div class="alert alert-warning" role="alert">当前用户未找到会员组信息。</div>';
                    }
                    ?>
                </div>

                <h2>所有会员组</h2>
                <div class="row">
                    <?php
                    if ($resultAllGroups && $resultAllGroups->num_rows > 0) {
                        while ($row = $resultAllGroups->fetch_assoc()) {
                            echo '<div class="col-md-4">';
                            echo '    <div class="card mb-4 shadow-sm">';
                            echo '        <div class="card-body">';
                            echo '            <h5 class="font-size-16">' . htmlspecialchars($row['group_name']) . '</h5>';
                            echo '            <h1 class="mt-3">￥' . htmlspecialchars($row['group_price']) .  '<span class="text-muted font-size-16 fw-medium">/ 月</span></h1>';
                            echo '            <button class="btn btn-outline-primary w-100" onclick="purchaseGroup(' . htmlspecialchars($row['id']) . ', ' . htmlspecialchars($row['group_price']) . ')">购买</button>'; 
                    
                            $sqlDomain = "SELECT d.domain, gd.price FROM " . table('group_domains') . " gd JOIN " . table('domainlist') . " d ON gd.domain_id = d.id WHERE gd.group_id = ?";
                            $stmtDomain = $conn->prepare($sqlDomain);
                            $stmtDomain->bind_param("i", $row['id']);
                            $stmtDomain->execute();
                            $resultDomain = $stmtDomain->get_result();

                            echo '            <div class="domain-container">';
                            echo '                <br>';
                            echo '                <button class="btn btn-info" onmouseover="showDomains(this)" onmouseout="hideDomains(this)">显示可解析域名</button>';
                            echo '                <div class="domain-list">';
                            if ($resultDomain && $resultDomain->num_rows > 0) {
                                while ($domainRow = $resultDomain->fetch_assoc()) {
                                    echo '<li><i class="mdi mdi-check-circle text-secondary font-size-18 me-2"></i>' . htmlspecialchars($domainRow['domain']) . ' (价格: ' . htmlspecialchars($domainRow['price']) . ' 元)</li>';

                                }
                            } else {
                                echo '<li>无可解析域名</li>'; 
                            }
                            echo '                </div>'; 
                            echo '            </div>';
                    
                            echo '        </div>';
                            echo '    </div>';
                            echo '</div>';

                            $stmtDomain->close();
                        }
                    } else {
                        echo '<div class="alert alert-warning" role="alert">未找到任何会员组信息。</div>';
                    }
                    ?>
                </div>
            </div>
        </div>
    </div>
    <script>
        function purchaseGroup(groupId, price) {
            if (confirm('确定要购买此会员组吗？')) {
                $.ajax({
                    url: '',
                    type: 'POST',
                    data: {
                        action: 'purchase',
                        group_id: groupId,
                        price: price
                    },
                    success: function (response) {
                        const result = JSON.parse(response);
                        if (result.status === 'success') {
                            alert('购买成功！');
                            location.reload();
                        } else {
                            alert('购买失败：' + result.message);
                        }
                    },
                    error: function () {
                        alert('请求失败，请重试。');
                    }
                });
            }
        }

        function showDomains(button) {
            const domainList = button.nextElementSibling;
            domainList.style.display = 'block';
        }

        function hideDomains(button) {
            const domainList = button.nextElementSibling;
            domainList.style.display = 'none';
        }
    </script>
</body>

</html>