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

$requestIp = $_SERVER['REMOTE_ADDR'];
$requestMethod = $_SERVER['REQUEST_METHOD'];

// 获取 POST 数据
$postData = json_decode(file_get_contents('php://input'), true);
$requestData = json_encode($postData);

// 插入请求日志到 api_logs 表 
// 这段无用，可开可不开，根据需要决定，不然会多一段空数据
// $logSql = "INSERT INTO " . table('api_logs') . " (request_ip, request_method, request_data) VALUES (?, ?, ?)";
// $stmt = $conn->prepare($logSql);
// $stmt->bind_param("sss", $requestIp, $requestMethod, $requestData);
// $stmt->execute();
// $stmt->close();
if ($requestMethod === 'GET' || $requestMethod === 'PUT') {
    $logSql = "INSERT INTO " . table('api_logs') . " (request_ip, request_method, request_data) VALUES (?, ?, ?)";
    $stmt = $conn->prepare($logSql);
    $stmt->bind_param("sss", $requestIp, $requestMethod, $requestData);
    $stmt->execute();
    $stmt->close();
}
$apiKey = isset($apiCredentials['web_apikey']) ? $apiCredentials['web_apikey'] : null;

if (isset($currentSettings['api_status']) && $currentSettings['api_status'] == 0) {
    echo '访问被拒绝：API功能未开启。';
    exit();
}

$spdnsid = $postData['spdnsid']?? null;
$spdnskey = $postData['spdnskey']?? null;
//校验用户是否有API使用权限
if (isset($currentSettings['user_api_status']) && $currentSettings['user_api_status'] == 1) {
    $sql = "SELECT api_use_status FROM " . table('users') . " WHERE spdnsid = ? AND spdnskey = ?";
    if ($stmt = $conn->prepare($sql)) {
        $stmt->bind_param("ss", $spdnsid, $spdnskey); 
        $stmt->execute();
        $stmt->bind_result($api_use_status); 
        $stmt->fetch();
        $stmt->close();

        if ($api_use_status != 1) {
            echo '访问被拒绝：您没有API使用权限。';
            exit();
        }
    } else {
        echo "数据库查询失败：" . $conn->error;
        exit();
    }
}

if (isset($currentSettings['api_realname_status']) && $currentSettings['api_realname_status'] == 1) {
    $sql = "SELECT real_name_status FROM " . table('users') . " WHERE spdnsid = ? AND spdnskey = ?";
    if ($stmt = $conn->prepare($sql)) {
        $stmt->bind_param("ss", $spdnsid, $spdnskey);
        $stmt->execute();
        $stmt->bind_result($real_name_status);
        $stmt->fetch();
        $stmt->close();

        if ($real_name_status != 1) {
            echo '访问被拒绝：您没有还没有实名。';
            exit();
        }
    } else {
        echo "数据库查询失败：" . $conn->error;
        exit();
    }
}

//     // 查询数据库以验证用户的API使用权限
//     $sql = "SELECT api_use_status FROM api_users WHERE spdnsid = ? AND spdnskey = ?";
//     if ($stmt = $conn->prepare($sql)) {
//         $stmt->bind_param("ss", $spdnsid, $spdnskey);
//         $stmt->execute();
//         $stmt->bind_result($api_use_status);
//         $stmt->fetch();
//         $stmt->close();

//         if ($api_use_status != 1) {
//             echo '访问被拒绝：您没有API使用权限。';
//             exit();
//         }
//     } else {
//         echo "数据库查询失败：" . $conn->error;
//         exit();
//     }
// }

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (json_last_error() === JSON_ERROR_NONE && isset($postData['spdnsid'], $postData['spdnskey'], $postData['act'])) {
        $spdnsid = $conn->real_escape_string($postData['spdnsid']);
        $spdnskey = $conn->real_escape_string($postData['spdnskey']);
        $act = $conn->real_escape_string($postData['act']);

        $sqlUser = "SELECT group_id FROM " . table('users') . " WHERE spdnsid = '$spdnsid' AND spdnskey = '$spdnskey'";
        $resultUser = $conn->query($sqlUser);

        if ($resultUser->num_rows > 0) {
            $userInfo = $resultUser->fetch_assoc();
            $groupId = $userInfo['group_id'];

            switch ($act) {
                case 'getdomains':
                    $sqlDomains = "SELECT dl.domain_id, dl.domain, gd.price 
                                   FROM " . table('group_domains') . " gd
                                   JOIN " . table('domainlist') . " dl ON gd.domain_id = dl.id
                                   WHERE gd.group_id = '$groupId' AND gd.price IS NOT NULL";
                    $resultDomains = $conn->query($sqlDomains);

                    $domains = [];
                    while ($domainRow = $resultDomains->fetch_assoc()) {
                        $domains[] = [
                            'domain_id' => $domainRow['domain_id'],
                            'domain' => $domainRow['domain'],
                            'price' => $domainRow['price']
                        ];
                    }

                    $response = [
                        'status' => 'success',
                        'domains' => $domains
                    ];
                    echo json_encode($response);
                    $responseData = json_encode($response);

                    $logSql = "INSERT INTO ". table('api_logs') . " (request_ip, request_method, request_data, response_data) VALUES (?, ?, ?, ?)";
                    $stmt = $conn->prepare($logSql);
                    $stmt->bind_param("ssss", $requestIp, $requestMethod, $requestData, $responseData); // 绑定参数
                    $stmt->execute();
                    $stmt->close();
                    break;

                case 'adddnsrecord':
                    // 处理添加解析的逻辑
                    if (isset($postData['domain']) || isset($postData['domainId'])) {
                        $providerName = null;

                        if (isset($postData['domain_id'])) {
                            $domainId = $conn->real_escape_string($postData['domain_id']);
                            $sql = "SELECT dns_provider FROM " . table('domainlist') . " WHERE domain_id = '$domainId'";
                        } else {
                            $domain = $conn->real_escape_string($postData['domain']);
                            $sql = "SELECT dns_provider FROM " . table('domainlist') . " WHERE domain = '$domain'";
                        }

                        $result = $conn->query($sql);

                        if ($result && $result->num_rows > 0) {
                            $provider = $result->fetch_assoc();
                            $providerName = $provider['dns_provider'];

                            $userInfoSQL = "SELECT id AS user_id, group_id AS user_group_id, balance FROM " . table('users') . " WHERE spdnsid = '$spdnsid'";
                            $userInfoResult = $conn->query($userInfoSQL);

                            if ($userInfoResult && $userInfoResult->num_rows > 0) {
                                $userInfo = $userInfoResult->fetch_assoc();
                                $userId = $userInfo['user_id'];
                                $userGroupId = $userInfo['user_group_id'];
                                $userBalance = $userInfo['balance'];

                                $recordType = intval($postData['type']);
                                $hostRecord = $conn->real_escape_string($postData['host']);
                                $recordValue = $conn->real_escape_string($postData['data']);
                                $ttl = intval($postData['ttl']);

                                $domainPK = "SELECT id FROM " . table('domainlist') . " WHERE domain_id = '" . $postData['domain_id'] . "' OR domain = '" . $postData['domain'] . "'";
                                $resultDomainPK = $conn->query($domainPK);

                                if ($resultDomainPK && $resultDomainPK->num_rows > 0) {
                                    $domainInfo = $resultDomainPK->fetch_assoc();
                                    $actualDomainId = $domainInfo['id'];
                                } else {
                                    echo json_encode(['status' => 'error', 'message' => '未找到对应的域名或域名ID。']);
                                    return;
                                }

                                $priceSQL = "SELECT price FROM " . table('group_domains') . " WHERE group_id = '$userGroupId' AND domain_id = '$actualDomainId'";
                                $priceResult = $conn->query($priceSQL);

                                if (!$priceResult) {
                                    echo json_encode(['status' => 'error', 'message' => '查询出错: ' . $conn->error]);
                                    return;
                                }

                                $domainPrice = 0;

                                if ($priceResult->num_rows > 0) {
                                    $priceRow = $priceResult->fetch_assoc();
                                    $domainPrice = $priceRow['price'];
                                } else {
                                    echo json_encode(['status' => 'error', 'message' => '未获取到有效的域名价格。']);
                                    return;
                                }

                                $recordTypeMapping = [
                                    1 => 'A',
                                    2 => 'NS',
                                    5 => 'CNAME',
                                    15 => 'MX',
                                    16 => 'TXT',
                                    28 => 'AAAA',
                                    33 => 'SRV',
                                    257 => 'CAA',
                                    256 => 'URL转发'
                                ];

                                $recordTypeLetter = isset($recordTypeMapping[$recordType]) ? $recordTypeMapping[$recordType] : null;
                                if ($userBalance >= $domainPrice) {
                                    $apiData = [
                                        'act' => 'adddnsrecord',
                                        'spdnsid' => $postData['spdnsid'],
                                        'spdnskey' => $postData['spdnskey'],
                                        'domain' => $postData['domain'],
                                        'domainId' => $postData['domain_id'],
                                        'type' => $recordType,
                                        'host' => $hostRecord,
                                        'data' => $recordValue,
                                        'ttl' => $ttl,
                                        'groupId' => '',
                                        'lineId' => '',
                                        'preference' => 10,
                                        'weight' => 1,
                                        'dominant' => false
                                    ];

                                    $currentHost = $_SERVER['HTTP_HOST'];
                                    $currentScheme = $_SERVER['REQUEST_SCHEME'];
                                    $domain1 = $currentScheme . '://' . $currentHost;
                                    $url1 = $domain1 . '/other/dns/' . $providerName . '/add_dns.php?apikey=' . $apiKey;
                                    $ch = curl_init($url1);
                                    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
                                    curl_setopt($ch, CURLOPT_POST, true);
                                    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($apiData));
                                    curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);

                                    $response = curl_exec($ch);
                                    $httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
                                    curl_close($ch);

                                    if ($httpcode === 200) {
                                        $apiResponse = json_decode($response, true);
                                        if (isset($apiResponse['code']) && $apiResponse['code'] === 200) {
                                            $apiRecordId = $apiResponse['data']['id'];
                                            $insertSQL = "INSERT INTO " . table('dns_records') . " (domain_id, host_record, record_value, record_type, ttl, user_id, user_group_id, api_record_id) 
                                                          VALUES ('$domainId', '$hostRecord', '$recordValue', '$recordTypeLetter', '$ttl', '$userId', '$userGroupId', '$apiRecordId')";
                                            if ($conn->query($insertSQL) === TRUE) {
                                                $newBalance = $userBalance - $domainPrice;
                                                $updateBalanceSQL = "UPDATE " . table('users') . " SET balance = '$newBalance' WHERE id = '$userId'";

                                                if ($conn->query($updateBalanceSQL) === TRUE) {
                                                    $responseOutput = ['status' => 'success', 'provider' => $providerName, 'message' => 'DNS 记录添加成功，余额已扣除。', 'record_id' => $apiRecordId];
                                                } else {
                                                    $responseOutput = ['status' => 'error', 'message' => '更新用户余额失败: ' . $conn->error];
                                                }
                                            } else {
                                                $responseOutput = ['status' => 'error', 'message' => '添加 DNS 记录到数据库失败: ' . $conn->error];
                                            }
                                        } else {
                                            $responseOutput = ['status' => 'error', 'message' => 'API返回错误信息，未添加记录。', 'api_response' => $apiResponse];
                                        }
                                    } else {
                                        $responseOutput = ['status' => 'error', 'message' => '请求API返回错误，状态码: ' . $httpcode, 'response' => $response];
                                    }
                                } else {
                                    $responseOutput = ['status' => 'error', 'message' => '用户余额不足，无法添加 DNS 记录。'];
                                }
                            } else {
                                $responseOutput = ['status' => 'error', 'message' => '未找到对应的用户信息。'];
                            }
                        } else {
                            $responseOutput = ['status' => 'error', 'message' => '未找到对应的 DNS 服务商。'];
                        }
                    } else {
                        $responseOutput = ['status' => 'error', 'message' => '缺少必要的域名或域名ID。'];
                    }

                    echo json_encode($responseOutput);

                    $responseDataJson = json_encode($responseOutput);
                    $logSql = "INSERT INTO " . table('api_logs') . " (request_ip, request_method, request_data, response_data) VALUES (?, ?, ?, ?)";
                    $stmt = $conn->prepare($logSql);
                    $stmt->bind_param("ssss", $requestIp, $requestMethod, $requestData, $responseDataJson); // 绑定参数
                    $stmt->execute();
                    $stmt->close();
                    break;

                case 'moddnsrecord':
                    if (isset($postData['id'], $postData['data'], $postData['type'], $postData['host'], $postData['domain_id'])) {
                        $recordId = $conn->real_escape_string($postData['id']);
                        $recordValue = $conn->real_escape_string($postData['data']);
                        $recordType = intval($postData['type']);
                        $hostRecord = $conn->real_escape_string($postData['host']);

                        $spdnsid = $conn->real_escape_string($postData['spdnsid']);
                        $spdnskey = $conn->real_escape_string($postData['spdnskey']);

                        $userInfoSQL = "SELECT id AS user_id, group_id FROM " . table('users') . " WHERE spdnsid = '$spdnsid' AND spdnskey = '$spdnskey'";
                        $userInfoResult = $conn->query($userInfoSQL);

                        if ($userInfoResult && $userInfoResult->num_rows > 0) {
                            $userInfo = $userInfoResult->fetch_assoc();
                            $userGroupId = $userInfo['group_id'] ?? null;

                            if ($userGroupId === null) {
                                echo json_encode(['status' => 'error', 'message' => '用户组ID不存在。']);
                                return;
                            }

                            $domainId = $conn->real_escape_string($postData['domain_id']);
                            $sqlProvider = "SELECT dns_provider FROM " . table('domainlist') . " WHERE domain_id = '$domainId'";
                            $resultProvider = $conn->query($sqlProvider);

                            if ($resultProvider && $resultProvider->num_rows > 0) {
                                $provider = $resultProvider->fetch_assoc();
                                $providerName = $provider['dns_provider'];

                                $recordTypeMapping = [
                                    1 => 'A',
                                    2 => 'NS',
                                    5 => 'CNAME',
                                    15 => 'MX',
                                    16 => 'TXT',
                                    28 => 'AAAA',
                                    33 => 'SRV',
                                    257 => 'CAA',
                                    256 => 'URL转发'
                                ];

                                $recordTypeLetter = isset($recordTypeMapping[$recordType]) ? $recordTypeMapping[$recordType] : null;

                                if ($recordTypeLetter === null) {
                                    echo json_encode(['status' => 'error', 'message' => '无效的记录类型。']);
                                    return;
                                }

                                $apiData = [
                                    'act' => 'moddnsrecord',
                                    'spdnsid' => $spdnsid,
                                    'spdnskey' => $spdnskey,
                                    'domain' => $postData['domain'] ?? '',
                                    'domain_id' => $domainId,
                                    'id' => $recordId,
                                    'type' => $recordType,
                                    'host' => $hostRecord,
                                    'data' => $recordValue,
                                    'ttl' => intval($postData['ttl']),
                                    'groupId' => $userGroupId,
                                    'lineId' => $postData['lineId'] ?? '',
                                    'preference' => intval($postData['preference']),
                                    'weight' => intval($postData['weight']),
                                    'dominant' => filter_var($postData['dominant'], FILTER_VALIDATE_BOOLEAN)
                                ];

                                $currentHost = $_SERVER['HTTP_HOST'];
                                $currentScheme = $_SERVER['REQUEST_SCHEME'];
                                $url1 = $currentScheme . '://' . $currentHost . '/other/dns/' . $providerName . '/edit_dns.php?apikey=' . $apiKey;

                                $ch = curl_init($url1);
                                curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
                                curl_setopt($ch, CURLOPT_POST, true);
                                curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($apiData));
                                curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);

                                $response = curl_exec($ch);
                                $httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
                                curl_close($ch);

                                if ($httpcode === 200) {
                                    $apiResponse = json_decode($response, true);
                                    if (isset($apiResponse['code']) && $apiResponse['code'] === 200) {
                                        $updateSQL = "UPDATE " . table('dns_records') . " SET 
                                      host_record = '$hostRecord',
                                      record_value = '$recordValue',
                                      record_type = '$recordTypeLetter', 
                                      ttl = " . intval($postData['ttl']) . "
                                      WHERE api_record_id = '$recordId'";

                                        if ($conn->query($updateSQL) === TRUE) {
                                            $responseOutput = ['status' => 'success', 'message' => 'DNS 记录编辑成功。', 'record_id' => $recordId];
                                        } else {
                                            $responseOutput = ['status' => 'error', 'message' => '更新 DNS 记录到数据库失败: ' . $conn->error];
                                        }
                                    } else {
                                        $responseOutput = ['status' => 'error', 'message' => 'API返回错误信息，未编辑记录。', 'api_response' => $apiResponse];
                                    }
                                } else {
                                    $responseOutput = ['status' => 'error', 'message' => '请求API返回错误，状态码: ' . $httpcode, 'response' => $response];
                                }
                            } else {
                                $responseOutput = ['status' => 'error', 'message' => '未找到对应的 DNS 服务商。'];
                            }
                        } else {
                            $responseOutput = ['status' => 'error', 'message' => '用户不存在或凭证无效。'];
                        }
                    } else {
                        $responseOutput = ['status' => 'error', 'message' => '缺少必要的解析数据。'];
                    }

                    echo json_encode($responseOutput);

                    $responseDataJson = json_encode($responseOutput);
                    $logSql = "INSERT INTO " . table('api_logs') . " (request_ip, request_method, request_data, response_data) VALUES (?, ?, ?, ?)";
                    $stmt = $conn->prepare($logSql);
                    $stmt->bind_param("ssss", $requestIp, $requestMethod, $requestData, $responseDataJson); // 绑定参数
                    $stmt->execute();
                    $stmt->close();
                    break;

                // 删除解析部分
                case 'deldnsrecord':
                    if (isset($postData['domain_id']) && isset($postData['id'])) {
                        $domainId = $conn->real_escape_string($postData['domain_id']);
                        $recordId = $conn->real_escape_string($postData['id']);  // 使用记录ID

                        $spdnsid = $conn->real_escape_string($postData['spdnsid']);
                        $spdnskey = $conn->real_escape_string($postData['spdnskey']);

                        $userInfoSQL = "SELECT id AS user_id, group_id FROM " . table('users') . " WHERE spdnsid = '$spdnsid' AND spdnskey = '$spdnskey'";
                        $userInfoResult = $conn->query($userInfoSQL);

                        if ($userInfoResult && $userInfoResult->num_rows > 0) {
                            $userInfo = $userInfoResult->fetch_assoc();
                            $userId = $userInfo['user_id'];
                            $sqlProvider = "SELECT dns_provider FROM " . table('domainlist') . " WHERE domain_id = '$domainId'";
                            $resultProvider = $conn->query($sqlProvider);
                        }

                        if ($resultProvider && $resultProvider->num_rows > 0) {
                            $provider = $resultProvider->fetch_assoc();
                            $providerName = $provider['dns_provider'];
                            $apiData = [
                                'act' => 'deldnsrecord',
                                'spdnsid' => $spdnsid,
                                'spdnskey' => $spdnskey,
                                'domain' => $postData['domain'] ?? '',
                                'domain_id' => $domainId,
                            ];

                            $currentHost = $_SERVER['HTTP_HOST'];
                            $currentScheme = $_SERVER['REQUEST_SCHEME'];
                            $url1 = $currentScheme . '://' . $currentHost . '/other/dns/' . $providerName . '/del_dns.php?apikey=' . $apiKey;

                            $ch = curl_init($url1);
                            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
                            curl_setopt($ch, CURLOPT_POST, true);
                            curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($apiData));
                            curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);

                            $response = curl_exec($ch);
                            $httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
                            curl_close($ch);

                            if ($httpcode === 200) {
                                $apiResponse = json_decode($response, true);
                                if (isset($apiResponse['code']) && $apiResponse['code'] === 200) {
                                    $deleteSQL = "DELETE FROM " . table('dns_records') . " WHERE api_record_id = '$recordId'";
                                    if ($conn->query($deleteSQL) === TRUE) {
                                        $responseOutput = ['status' => 'success', 'message' => 'DNS 记录删除成功。'];
                                    } else {
                                        $responseOutput = ['status' => 'error', 'message' => '删除 DNS 记录从数据库失败: ' . $conn->error];
                                    }
                                } else {
                                    $responseOutput = ['status' => 'error', 'message' => 'API返回错误信息，未删除记录。', 'api_response' => $apiResponse];
                                }
                            } else {
                                $responseOutput = ['status' => 'error', 'message' => '请求API返回错误，状态码: ' . $httpcode, 'response' => $response];
                            }
                        } else {
                            $responseOutput = ['status' => 'error', 'message' => '用户不存在或凭证无效。'];
                        }
                    } else {
                        $responseOutput = ['status' => 'error', 'message' => '缺少必要的域名或记录ID。'];
                    }

                    echo json_encode($responseOutput);

                    $responseDataJson = json_encode($responseOutput);
                    $logSql = "INSERT INTO " . table('api_logs') . " (request_ip, request_method, request_data, response_data) VALUES (?, ?, ?, ?)";
                    $stmt = $conn->prepare($logSql);
                    $stmt->bind_param("ssss", $requestIp, $requestMethod, $requestData, $responseDataJson); // 绑定参数
                    $stmt->execute();
                    $stmt->close();
                    break;

                default:
                    echo json_encode(['status' => 'error', 'message' => '无效的操作类型。']);
                    break;
            }
        } else {
            echo json_encode(['status' => 'error', 'message' => '用户不存在或凭证无效']);
        }
    } else {
        echo json_encode(['status' => 'error', 'message' => '缺少参数或参数无效']);
    }
} else {
    echo json_encode(['status' => 'error', 'message' => '请求方法必须为POST']);
}

$conn->close();
?>