<?php
session_name('user_session');
session_start();
require '../include/common.php';
require '../include/function.php';

// 获取当前用户的用户组
$userId = $_SESSION['user_id'];

// 获取用户的实名状态
$stmt = $pdo->prepare("SELECT real_name_status FROM " . table('users') . " WHERE id = :id");
$stmt->execute(['id' => $userId]);
$realNameStatus = $stmt->fetchColumn(); // 获取实名状态

// 检查用户是否已登录，普通用户和管理员都可以访问
if (!isset($_SESSION['role']) || ($_SESSION['role'] != 1 && $_SESSION['role'] != 0)) {
    header("Location: login.php");
    exit();
}
// 获取当前用户的用户组
$userId = $_SESSION['user_id'];
// 获取用户组
$stmt = $pdo->prepare("SELECT group_id FROM " . table('users') . " WHERE id = :id");
$stmt->execute(['id' => $userId]);
$userGroup = $stmt->fetchColumn();



// 处理新增解析
if (isset($_POST['add_dns'])) {
    $hostRecord = $_POST['host_record'];
    $recordType = $_POST['record_type'];
    $domainId = $_POST['domain_id'];
    $recordValue = $_POST['record_value']; // 获取记录值
    $ttl = $_POST['ttl'];

    // 获取域名的主键ID
    $stmt = $pdo->prepare("SELECT id FROM " . table('domainlist') . " WHERE domain_id = :domain_id");
    $stmt->execute(['domain_id' => $domainId]);
    $actualDomainId = $stmt->fetchColumn();

    if ($actualDomainId === false) {
        echo "<script>alert('找不到对应的域名，请检查域名设置。'); window.history.go(-1);</script>";
        exit();
    }

    // 获取解析费用
    $stmt = $pdo->prepare("SELECT price FROM " . table('group_domains') . " WHERE domain_id = :domain_id AND group_id = :group_id");
    $stmt->execute(['domain_id' => $actualDomainId, 'group_id' => $userGroup]);
    $priceData = $stmt->fetchColumn();

    if ($priceData === false) {
        echo "<script>alert('找不到对应的解析费用，请检查域名设置。'); window.history.go(-1);</script>";
        exit();
    }

    $cost = (float) $priceData; // 解析费用

    // 查询用户余额
    $stmt = $pdo->prepare("SELECT balance FROM " . table('users') . " WHERE id = :user_id");
    $stmt->execute(['user_id' => $userId]);
    $userBalance = $stmt->fetchColumn();

    // 检查余额是否足够
    if ($userBalance < $cost) {
        echo "<script>alert('余额不足，无法添加解析。'); window.history.go(-1);</script>";
        exit();
    }

    // 扣除用户余额
    $stmt = $pdo->prepare("UPDATE " . table('users') . " SET balance = balance - :cost WHERE id = :user_id");
    $stmt->execute(['cost' => $cost, 'user_id' => $userId]);

    // 将记录类型转换为对应的整数值
    $typeMapping = [
        'A' => 1,
        'NS' => 2,
        'CNAME' => 5,
        'MX' => 15,
        'TXT' => 16,
        'AAAA' => 28,
        'SRV' => 33,
        'CAA' => 257,
        'URL转发' => 256
    ];

    $type = isset($typeMapping[$recordType]) ? $typeMapping[$recordType] : null;

    if ($type === null) {
        echo "<script>alert('无效的记录类型');</script>"; // 弹窗显示错误信息
        exit();
    }

    // 获取 dns_provider
    $stmt = $pdo->prepare("SELECT dns_provider FROM " . table('domainlist') . " WHERE domain_id = :domain_id");
    $stmt->execute(['domain_id' => $domainId]);
    $dnsProvider = $stmt->fetchColumn();

    if (!$dnsProvider) {
        echo "<script>alert('无效的域名，无法找到 DNS 提供者。');</script>";
        exit();
    }

    // 获取域名字符串
    $domain = ''; // 存储域名
    $stmt = $pdo->prepare("SELECT domain FROM " . table('domainlist') . " WHERE domain_id = :domain_id");
    $stmt->execute(['domain_id' => $domainId]);
    $domain = $stmt->fetchColumn();

    // 获取当前域名和前缀
    $currentHost = $_SERVER['HTTP_HOST'];
    $currentScheme = $_SERVER['REQUEST_SCHEME'];
    $domain1 = $currentScheme . '://' . $currentHost;
    $web_apikey = $apiCredentials['web_apikey'] ?? '';
    $url = $domain1 . '/other/dns/' . $dnsProvider . '/add_dns.php' . '?apikey=' . $web_apikey;

    // 准备要发送的 JSON 数据
    $postData = [
        'domain' => $domain,
        'domainId' => $domainId,
        'type' => $type,
        'host' => $hostRecord,
        'data' => $recordValue,
        'ttl' => (int) $ttl,
        'groupId' => "",
        'lineId' => "",
        'preference' => 10,
        'weight' => 1,
        'dominant' => false
    ];
    // echo "<pre>";
    // echo json_encode($postData);    
    // echo "</pre>";
    // 带有 CURL 的 POST 请求
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($postData));
    curl_setopt($ch, CURLOPT_HTTPHEADER, [
        'Content-Type: application/json'
    ]);

    // 执行 CURL 请求并处理响应
    $response = curl_exec($ch);
    if ($response === false) {
        echo 'Curl error: ' . curl_error($ch);
        exit();
    } else {
        $apiResponse = json_decode($response, true);

        // 检查返回结果并提取 ID
        if (isset($apiResponse['code']) && $apiResponse['code'] === 200 && isset($apiResponse['data']['id'])) {
            $insertedId = $apiResponse['data']['id'];
            // 在成功添加解析后，记录余额变动日志
            $stmt = $pdo->prepare("INSERT INTO " . table('balance_logs') . " (user_id, change_amount, new_balance, reason) VALUES (:user_id, :change_amount, :new_balance, :reason)");
            $stmt->execute([
                'user_id' => $userId,
                'change_amount' => -$cost, // 变动的金额为负
                'new_balance' => $userBalance - $cost, // 扣款后的新余额
                'reason' => "添加域名解析（记录ID: " . $insertedId . "）"
            ]);
            // 插入数据到数据库，确保 record_value 字段也被写入
            $stmt = $pdo->prepare("INSERT INTO " . table('dns_records') . " (host_record, record_type, domain_id, record_value, ttl, user_group_id, user_id, api_record_id) VALUES (:host_record, :record_type, :domain_id, :record_value, :ttl, :user_group_id, :user_id, :api_record_id)");
            $stmt->execute([
                'host_record' => $hostRecord,
                'record_type' => $recordType,
                'domain_id' => $domainId,
                'record_value' => $recordValue, // 确保记录值也被写入
                'ttl' => $ttl,
                'user_group_id' => $userGroup,
                'user_id' => $userId,
                'api_record_id' => $insertedId // 使用API返回的ID
            ]);
        } else {
            echo "<script>alert('未能成功添加DNS记录，返回信息：" . json_encode($apiResponse) . "');</script>";
        }
    }

    curl_close($ch);

    // 重定向以刷新
    header("Location: dns.php");
    exit();
}

if (isset($_GET['delete_id'])) {
    // 获取要删除的 DNS 记录 ID
    $dnsId = $_GET['delete_id'];

    // 获取 api_record_id 和 domain_id
    $stmt = $pdo->prepare("SELECT api_record_id, domain_id FROM " . table('dns_records') . " WHERE id = :id");
    $stmt->execute(['id' => $dnsId]);  // 使用 $dnsId 作为参数
    $recordData = $stmt->fetch(PDO::FETCH_ASSOC);

    // 检查记录是否存在
    if (!$recordData) {
        echo "<script>alert('记录不存在。');</script>";
        exit();
    }

    // 获取对应的 api_record_id 和 domain_id
    $apiRecordId = $recordData['api_record_id'];
    $domainId = $recordData['domain_id']; // 确保定义 domainId

    // 获取 dns_provider
    $stmt = $pdo->prepare("SELECT dns_provider FROM " . table('domainlist') . " WHERE domain_id = :domain_id");
    $stmt->execute(['domain_id' => $domainId]);
    $dnsProvider = $stmt->fetchColumn();

    // 获取当前域名和前缀
    $currentHost = $_SERVER['HTTP_HOST'];
    $currentScheme = $_SERVER['REQUEST_SCHEME'];
    $domain2 = $currentScheme . '://' . $currentHost;
    $web_apikey = $apiCredentials['web_apikey'] ?? '';
    $deleteUrl = $domain2 . '/other/dns/' . $dnsProvider . '/del_dns.php' . '?apikey=' . $web_apikey;

    // 准备 POST 数据
    $deletePostData = [
        'id' => $apiRecordId, // 将 api_record_id 加入到 POST 数据
        'domain_id' => $domainId // 将 domain_id 加入到 POST 数据
    ];
    // 打印要发送的 JSON 数据（可用于调试）
    // echo "<pre>";
    // echo json_encode($deletePostData, JSON_PRETTY_PRINT);

    // 发送删除请求的函数
    function sendDeleteRequest($url, $postData)
    {
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($postData));
        curl_setopt($ch, CURLOPT_HTTPHEADER, [
            'http_build_query($postData'
        ]);

        $response = curl_exec($ch);
        curl_close($ch);
        return $response;
    }

    // 发送删除请求
    $deleteResponse = sendDeleteRequest($deleteUrl, $deletePostData);
    $deleteApiResponse = json_decode($deleteResponse, true);

    // 检查删除的响应结果
    if (isset($deleteApiResponse['code']) && $deleteApiResponse['code'] === 200) {
        // 删除数据库中的 DNS 记录
        $stmt = $pdo->prepare("DELETE FROM " . table('dns_records') . " WHERE id = :id AND user_id = :user_id");
        $stmt->execute(['id' => $dnsId, 'user_id' => $userId]); // 确保只能删除自己的记录
        echo "<script>alert('DNS记录删除成功。');</script>";
    } else {
        echo "<script>alert('未能成功删除DNS记录，返回信息：" . json_encode($deleteApiResponse) . "');</script>";
    }

    // 重定向以刷新
    header("Location: dns.php");
    exit();
}

// 获取当前用户组的域名解析列表
if ($_SESSION['role'] == 0) { // 管理员
    $stmt = $pdo->prepare("SELECT * FROM " . table('dns_records') . " WHERE user_group_id = :user_group_id");
    $stmt->execute(['user_group_id' => $userGroup]);
} else { // 普通用户
    $stmt = $pdo->prepare("SELECT * FROM " . table('dns_records') . " WHERE user_group_id = :user_group_id AND user_id = :user_id");
    $stmt->execute(['user_group_id' => $userGroup, 'user_id' => $userId]);
}
$dnsRecords = $stmt->fetchAll();

// 根据用户组获取可用域名及对应的价格
$stmt = $pdo->prepare("SELECT d.id, d.domain, d.domain_id, g.price FROM " . table('group_domains') . " g 
                        JOIN " . table('domainlist') . " d ON g.domain_id = d.id 
                        WHERE g.group_id = :group_id");
$stmt->execute(['group_id' => $userGroup]);
$availableDomains = $stmt->fetchAll();
?>

<?php include 'header.php';
// 检查实名功能是否开启
if (isset($currentSettings['realname_status']) && $currentSettings['realname_status'] == 1) {
    // 检查用户是否已实名
    if ($realNameStatus != 1) { // 是否实名
echo '<div class="page-content">';
echo '<div class="page-content">';
echo '<div class="container-fluid">';
echo '    <div class="alert alert-danger text-center" role="alert">';
echo '        <h3>提示： 已开启实名功能，请先完成实名验证。</h3>';
echo '    </div>';
echo '</div>';
echo '<div style="margin: 20px; text-align: center;">';
echo '    <button class="btn btn-primary" onclick="location.href=\'profile.php?realname\';">立即实名</button>';
echo '</div>';
echo '</div>';
echo '</div>';
        exit();
    }
}
?>

<div class="main-content">
    <div class="page-content">
        <div class="container-fluid">
    <h1>域名解析管理</h1>

    <!-- 新增解析的按钮 -->
    <button class="btn btn-success" data-bs-toggle="modal" data-bs-target="#addDnsModal">新增解析</button>

    <!-- 新增解析的模态框 -->
    <div class="modal fade" id="addDnsModal" tabindex="-1" aria-labelledby="addDnsModalLabel" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="addDnsModalLabel">新增域名解析</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <form method="POST" action="dns.php">
                        <div class="mb-3">
                            <label for="host_record" class="form-label">主机记录</label>
                            <input type="text" class="form-control" name="host_record" required>
                        </div>
                        <div class="mb-3">
                            <label for="record_type" class="form-label">记录类型</label>
                            <select class="form-select" name="record_type" id="record_type" required
                                onchange="showFields()">
                                <option value="A">A</option>
                                <option value="NS">NS</option>
                                <option value="CNAME">CNAME</option>
                                <option value="MX">MX</option>
                                <option value="TXT">TXT</option>
                                <option value="AAAA">AAAA</option>
                                <option value="SRV">SRV</option>
                                <option value="CAA">CAA</option>
                                <option value="URL转发">URL转发</option>
                            </select>
                        </div>
                        <div class="mb-3">
                            <label for="domain_id" class="form-label">选择域名</label>
                            <select class="form-select" name="domain_id" id="domain_id" required
                                onchange="updateCost()">
                                <option value="">请选择</option>
                                <?php foreach ($availableDomains as $domain): ?>
                                    <option value="<?php echo $domain['domain_id']; ?>"
                                        data-price="<?php echo $domain['price']; ?>">
                                        <?php echo $domain['domain']; ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        <div class="mb-3">
                            <label for="record_value" class="form-label">记录值</label>
                            <input type="text" class="form-control" name="record_value" required>
                        </div>
                        <div class="mb-3">
                            <label for="ttl" class="form-label">TTL</label>
                            <input type="number" class="form-control" name="ttl" required value="600">
                        </div>
                        <div class="mb-3">
                            <label for="cost" class="form-label">解析费用</label>
                            <input type="number" class="form-control" name="cost" id="cost" required readonly>
                        </div>
                        <div class="mb-3" id="preference_field" style="display: none;">
                            <label for="preference" class="form-label">优先级 (1-55)</label>
                            <input type="number" class="form-control" name="preference" min="1" max="55">
                        </div>
                        <div class="mb-3" id="weight_field" style="display: none;">
                            <label for="weight" class="form-label">权重 (1-10)</label>
                            <input type="number" class="form-control" name="weight" min="1" max="10">
                        </div>
                        <div class="mb-3" id="dominant_field" style="display: none;">
                            <label for="dominant" class="form-label">是否显性 URL 转发</label>
                            <select class="form-select" name="dominant">
                                <option value="0">否</option>
                                <option value="1">是</option>
                            </select>
                        </div>
                        <button type="submit" name="add_dns" class="btn btn-success">新增解析</button>
                    </form>
                </div>
            </div>
        </div>
    </div>
    </div>
    </div>
    <script>
        function showFields() {
            const recordType = document.getElementById('record_type').value;
            const preferenceField = document.getElementById('preference_field');
            const weightField = document.getElementById('weight_field');
            const dominantField = document.getElementById('dominant_field');

            preferenceField.style.display = (recordType === 'MX') ? 'block' : 'none'; // 只有MX记录显示优先级
            weightField.style.display = (['A', 'CNAME', 'AAAA', 'URL转发'].includes(recordType)) ? 'block' : 'none'; // A、CNAME、AAAA、URL转发显示权重
            dominantField.style.display = (recordType === 'URL转发') ? 'block' : 'none'; // 只有URL转发显示显性选择
        }

        function updateCost() {
            const domainSelect = document.getElementById('domain_id');
            const costField = document.getElementById('cost');

            const selectedOption = domainSelect.options[domainSelect.selectedIndex];
            const price = selectedOption ? selectedOption.getAttribute('data-price') : 0;

            costField.value = price ? parseFloat(price).toFixed(2) : 0; // 显示获取到的价格，保留两位小数
        }
    </script>

<div style="overflow-x: auto;">
        <table class="table table-bordered table-striped mt-3">
        <thead>
            <tr>
                <th>ID</th>
                <th>主机记录</th>
                <th>记录类型</th>
                <th>域名</th>
                <th>记录值</th>
                <th>TTL</th>
                <?php if ($_SESSION['role'] == 0): ?> <!-- 只有管理员才显示用户 ID -->
                    <th>用户 ID</th>
                <?php endif; ?>
                <th>操作</th>
            </tr>
        </thead>
        <tbody>
            <?php foreach ($dnsRecords as $record): ?>
                <tr>
                    <td><?php echo $record['id']; ?></td>
                    <td><?php echo $record['host_record']; ?></td>
                    <td><?php echo $record['record_type']; ?></td>
                    <td><?php
                    // 获取域名
                    $stmt = $pdo->prepare("SELECT domain FROM " . table('domainlist') . " WHERE domain_id = :domain_id");
                    $stmt->execute(['domain_id' => $record['domain_id']]);
                    $domain = $stmt->fetchColumn();
                    echo $domain; ?></td>
                    <td><?php echo $record['record_value']; ?></td>
                    <td><?php echo $record['ttl']; ?></td>
                    <?php if ($_SESSION['role'] == 0): ?> <!-- 仅管理员显示用户 ID -->
                        <td><?php echo $record['user_id']; ?></td>
                    <?php endif; ?>
                    <td>
                        <button class="btn btn-primary" data-bs-toggle="modal"
                            data-bs-target="#editDnsModal<?php echo $record['id']; ?>">编辑</button>
                        <a href="?delete_id=<?php echo $record['id']; ?>" class="btn btn-danger"
                            onclick="return confirm('确定删除此解析吗？');">删除</a>
                    </td>
                </tr>

                <!-- 编辑域名解析的模态框 -->
                <div class="modal fade" id="editDnsModal<?php echo $record['id']; ?>" tabindex="-1"
                    aria-labelledby="editDnsModalLabel" aria-hidden="true">
                    <div class="modal-dialog">
                        <div class="modal-content">
                            <div class="modal-header">
                                <h5 class="modal-title" id="editDnsModalLabel">编辑域名解析</h5>
                                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                            </div>
                            <div class="modal-body">
                                <form method="POST" action="">
                                    <input type="hidden" name="record_id" value="<?php echo $record['id']; ?>">
                                    <!-- 隐藏记录 ID -->
                                    <div class="mb-3">
                                        <label for="host_record" class="form-label">主机记录</label>
                                        <input type="text" class="form-control" name="host_record"
                                            value="<?php echo $record['host_record']; ?>" required>
                                    </div>
                                    <div class="mb-3">
                                        <label for="record_type" class="form-label">记录类型</label>
                                        <select class="form-select" name="record_type" required>
                                            <option value="A" <?php if ($record['record_type'] == 'A')
                                                echo 'selected'; ?>>A
                                            </option>
                                            <option value="NS" <?php if ($record['record_type'] == 'NS')
                                                echo 'selected'; ?>>
                                                NS</option>
                                            <option value="CNAME" <?php if ($record['record_type'] == 'CNAME')
                                                echo 'selected'; ?>>CNAME</option>
                                            <option value="MX" <?php if ($record['record_type'] == 'MX')
                                                echo 'selected'; ?>>
                                                MX</option>
                                            <option value="TXT" <?php if ($record['record_type'] == 'TXT')
                                                echo 'selected'; ?>>TXT</option>
                                            <option value="AAAA" <?php if ($record['record_type'] == 'AAAA')
                                                echo 'selected'; ?>>AAAA</option>
                                            <option value="SRV" <?php if ($record['record_type'] == 'SRV')
                                                echo 'selected'; ?>>SRV</option>
                                            <option value="CAA" <?php if ($record['record_type'] == 'CAA')
                                                echo 'selected'; ?>>CAA</option>
                                            <option value="URL转发" <?php if ($record['record_type'] == 'URL转发')
                                                echo 'selected'; ?>>URL转发</option>
                                        </select>
                                    </div>
                                    <div class="mb-3">
                                        <label for="record_value" class="form-label">记录值</label>
                                        <input type="text" class="form-control" name="record_value"
                                            value="<?php echo $record['record_value']; ?>" required>
                                    </div>
                                    <div class="mb-3">
                                        <label for="ttl" class="form-label">TTL</label>
                                        <input type="number" class="form-control" name="ttl"
                                            value="<?php echo $record['ttl']; ?>" required>
                                    </div>
                                    <button type="submit" name="edit_dns" class="btn btn-primary">保存更改</button>
                                </form>
                            </div>
                        </div>
                    </div>
                </div>
                </div>
            <?php endforeach; ?>
        </tbody>
    </table>
</div>
</body>

</html>