<?php
// 禁用缓存
// 禁用缓存
header("Cache-Control: no-store, no-cache, must-revalidate, max-age=0");
header("Pragma: no-cache");
header("Expires: -1");




// 设置允许的跨域请求头
header("Access-Control-Allow-Origin: *"); // 允许所有来源
header("Access-Control-Allow-Methods: GET, POST, OPTIONS"); // 允许的请求方法
header("Access-Control-Allow-Headers: Content-Type, Authorization"); // 允许的请求头
header("Content-Type: application/json; charset=UTF-8"); // 返回JSON格式

if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    http_response_code(200);
    exit();
}


// 数据库连接设置
class DB {
    private static $conn;

    public static function getConnection() {
        if (self::$conn == null) {
            // 修改这里，添加端口号 6306
            self::$conn = new mysqli("localhost", "mall", "hZ5TiP3HzHmmeNfz", "mall", 6306);
            
            if (self::$conn->connect_error) {
                die("Connection failed: " . self::$conn->connect_error);
            }
        }
        return self::$conn;
    }
}

// API处理类
class WalletAPI {
    // 查询 t_kyc 表
    public function getKYCInfo($partyId) {
        $conn = DB::getConnection();
        $stmt = $conn->prepare("SELECT UUID, PARTY_ID, IDNUMBER, IDNAME, NAME, SELLER_NAME, SELLER_ADDRESS FROM t_kyc WHERE PARTY_ID = ?");
        $stmt->bind_param("s", $partyId);
        $stmt->execute();
        $result = $stmt->get_result();
        
        if ($result->num_rows > 0) {
            $kycInfo = $result->fetch_assoc();  // 获取 KYC 信息
            
            // 查询 t_wallet 表，获取余额信息
            $walletInfo = $this->getWalletBalance($partyId);
            if ($walletInfo) {
                $kycInfo['MONEY'] = $walletInfo['MONEY'];  // 合并余额信息
            } else {
                $kycInfo['MONEY'] = 0;  // 如果没有找到钱包信息，余额默认为 0
            }
            
            return $kycInfo;  // 返回合并后的 KYC 信息
        } else {
            return null;  // 如果没有找到 KYC 数据
        }
    }

    // 查询 t_wallet 表获取余额
    private function getWalletBalance($partyId) {
        $conn = DB::getConnection();
        $stmt = $conn->prepare("SELECT MONEY FROM t_wallet WHERE PARTY_ID = ?");
        $stmt->bind_param("s", $partyId);
        $stmt->execute();
        $result = $stmt->get_result();
        
        if ($result->num_rows > 0) {
            return $result->fetch_assoc();  // 返回余额信息
        }
        return null;  // 如果没有找到余额信息
    }

    // 查询 t_wallet_private 表
// 查询 t_wallet_private 表
// 查询 t_wallet_private 表
public function getWalletInfo($partyId) {
    $conn = DB::getConnection();
    $stmt = $conn->prepare("SELECT UUID, PARTY_ID, BALANCE, CREATED_AT, EXTRACTED_AT, EXTRACTED, ORDER_ID,TIME_PERIOD FROM t_wallet_private WHERE PARTY_ID = ?");
    $stmt->bind_param("s", $partyId);
    $stmt->execute();
    $result = $stmt->get_result();
    
    $walletInfo = [];
    while ($row = $result->fetch_assoc()) {
        
        // 获取当前的利率
        $timePeriod =  $this->getWithdrawableTime(); // 假设利率是基于28天
        $interestRate = $this->getInterestRate($timePeriod);
        //echo $timePeriod;

        // 计算预计利息（预计利息 = 当前余额 * 利率）
        $estimatedInterest = $row['BALANCE'] * $interestRate;

        // 将预计利息加入到返回数据中
        $row['estimatedInterest'] = $estimatedInterest;
        
                // 计算可取款时间
        $withdrawableAt = $this->calculateWithdrawableTime($row['CREATED_AT']);
        $row['withdrawable_at'] = $withdrawableAt;  // 将可取款时间添加到结果中

        // 将每个记录添加到数组
        $walletInfo[] = $row;
    }
    return $walletInfo;
}


public function getAccumulatedInterest($partyId) {
    // 获取数据库连接
    $conn = DB::getConnection();
    
    // 准备查询语句
    $stmt = $conn->prepare("SELECT INTEREST FROM t_wallet_private WHERE PARTY_ID = ?");
    $stmt->bind_param("s", $partyId);
    $stmt->execute();
    $result = $stmt->get_result();
    
    // 初始化累计收益变量
    $accumulatedInterest = 0;

    // 遍历查询结果并累加 INTEREST
    while ($row = $result->fetch_assoc()) {
        $accumulatedInterest += $row['INTEREST'];
    }

    // 返回包含累计收益（INTEREST）的JSON格式结果
    return json_encode([
        'INTEREST' => $accumulatedInterest
    ]);
}



// 计算可取款时间
private function calculateWithdrawableTime($createdAt) {
    $conn = DB::getConnection();
    $stmt = $conn->prepare("SELECT TIME_PERIOD FROM t_wallet_private_config LIMIT 1"); // 假设时间周期配置是统一的
    $stmt->execute();
    $result = $stmt->get_result();
    
    if ($result->num_rows > 0) {
        $config = $result->fetch_assoc();
        $timePeriod = $config['TIME_PERIOD'];
        
        // 计算可取款时间
        $withdrawableAt = strtotime("+$timePeriod days", strtotime($createdAt));
        return date("Y-m-d H:i:s", $withdrawableAt);  // 返回可取款时间
    }
    
    return null;  // 如果没有找到时间配置，返回null
}

// 计算可取款时间
function getWithdrawableTime() {
    // 连接数据库
    $conn = DB::getConnection();
    
    // 预备查询语句
    $stmt = $conn->prepare("SELECT TIME_PERIOD FROM t_wallet_private_config LIMIT 1");
    
    if ($stmt === false) {
        return null; // 如果准备语句失败，返回 null
    }

    // 执行查询
    $stmt->execute();
    
    // 获取查询结果
    $result = $stmt->get_result();
    
    // 检查是否有数据返回
    if ($result->num_rows > 0) {
        $config = $result->fetch_assoc();
        $timePeriod = $config['TIME_PERIOD'];
        
        // 返回从数据库查询到的可取款时间周期
        return $timePeriod;  
    }
    
    // 如果没有返回值，则返回默认值
    return 365;  
}


    // 获取 t_wallet_private_config 表的利率信息
    public function getInterestRate($timePeriod) {
        
        $conn = DB::getConnection();
        $stmt = $conn->prepare("SELECT INTEREST_RATE FROM t_wallet_private_config WHERE TIME_PERIOD = ?");
        $stmt->bind_param("i", $timePeriod);
        $stmt->execute();
        $result = $stmt->get_result();
        
        if ($result->num_rows > 0) {
            
            $config = $result->fetch_assoc();
            
            return $config['INTEREST_RATE'];
        }
       
        return null;  // 如果没有找到配置
    }

    // 检查是否符合取款时间
    public function checkWithdrawTime($createdAt) {
        $conn = DB::getConnection();
        $stmt = $conn->prepare("SELECT TIME_PERIOD FROM t_wallet_private_config");
        $stmt->execute();
        $result = $stmt->get_result();
        
        $currentTimestamp = time(); // 获取当前时间戳
        while ($config = $result->fetch_assoc()) {
            $timePeriod = $config['TIME_PERIOD'];
            $withdrawalTimeLimit = strtotime("+$timePeriod days", strtotime($createdAt));

            if ($currentTimestamp >= $withdrawalTimeLimit) {
                return true; // 符合取款时间
            }
        }
        return false;  // 不符合取款时间
    }

public function depositFunds($partyId, $amount, $orderId,$timePeriod) {
    //存入资金
    $conn = DB::getConnection();

    // 先查询余额
    $walletInfo = $this->getWalletBalance($partyId);
    $balance = 0;
    if ($walletInfo) {
        $balance = $walletInfo['MONEY'];  // 获取实际余额字段 'MONEY'
    }

    //$timePeriod = 7;
    // 判断余额是否足够
    if ($balance >= $amount) {
        // 更新余额
        $newBalance = $balance - $amount;

        // 开始事务，确保更新和插入的原子性
        $conn->begin_transaction();

        try {
            // 更新 t_wallet 表中的余额
            $stmt = $conn->prepare("UPDATE t_wallet SET MONEY = ? WHERE PARTY_ID = ?");
            $stmt->bind_param("ds", $newBalance, $partyId);
            if (!$stmt->execute()) {
                throw new Exception("Error during wallet balance update");
            }

            // 插入一条新记录到 t_wallet_private 表
            $uuid = uniqid('', true);  // 使用唯一标识符生成 UUID
            $stmt = $conn->prepare("INSERT INTO t_wallet_private (UUID, PARTY_ID, BALANCE, CREATED_AT, ORDER_ID,TIME_PERIOD) VALUES (?, ?, ?, CURRENT_TIMESTAMP, ?,?)");
            $stmt->bind_param("ssisi", $uuid, $partyId, $amount, $orderId,$timePeriod);
            if (!$stmt->execute()) {
                throw new Exception("Error during insert into t_wallet_private");
            }

            // 提交事务
            $conn->commit();

            return json_encode(["status" => "success", "message" => "Funds deposited successfully","data" => ["TIME_PERIOD" => $timePeriod,"amount" => $amount,"orderid" => $orderId]]);
        } catch (Exception $e) {
            // 发生异常时回滚事务
            $conn->rollback();
            return json_encode(["status" => "error", "message" => $e->getMessage()]);
        }
    } else {
        return json_encode(["status" => "error", "message" => "Insufficient balance"]);
    }
}

// 取出资金
public function withdrawFunds($partyId, $amount, $orderId) {
    $conn = DB::getConnection();

    // 查询 t_wallet_private 表中的配置
    $walletInfo = $this->getWalletInfo($partyId);

    // 初始化变量
    $balance = 0;
    $extracted = 0;
    $createdAt = ''; // 记录创建时间

    // 获取当前订单的相关记录
    $currentWalletInfo = null;

    foreach ($walletInfo as $info) {
        if ($info['ORDER_ID'] === $orderId) {
            $currentWalletInfo = $info;
            break;
        }
    }

    // 如果找到了当前订单的记录
    if ($currentWalletInfo) {
        $balance = $currentWalletInfo['BALANCE'];
        $extracted = $currentWalletInfo['EXTRACTED'];  // 提取标记
        $createdAt = $currentWalletInfo['CREATED_AT'];  // 获取创建时间
        $timePeriod = $currentWalletInfo['TIME_PERIOD'];  // 获取创建时间
    } else {
        return json_encode([
            "status" => "error",
            "message" => "未找到当前订单的相关信息"
        ]);
    }
    //echo $timePeriod;

    // 判断是否满足取出条件
    if ($extracted == 1 && $balance >= $amount) {
        // 获取利率信息，检查取款条件
        //$timePeriod = $this->getWithdrawableTime(); // 默认为28天
        //$timePeriod = $this->getWithdrawableTime();
        $interestRate = $this->getInterestRate($timePeriod);

        if (!$this->checkWithdrawTime($createdAt)) {
            return json_encode(["status" => "error", "message" => "取款时间尚未到达","TIME_PERIOD" => $timePeriod]);
        }

        // 计算利息
        //$interest = $amount * $interestRate; // 利息 = 取款金额 * 利率
        //$totalAmount = $amount + $interest;  // 最终取款金额 = 本金 + 利息
        
        
        // 计算利息
        $interest = $amount * $interestRate * ($timePeriod / 365);  // 利息 = 本金 * 年利率 * (存款天数 / 365)
        $totalAmount = $amount + $interest;  // 最终金额 = 本金 + 利息

        // 更新余额
        $newBalance = $balance - $amount;
        // 修正：使用's'来绑定字符串类型的orderId
        $stmt = $conn->prepare("UPDATE t_wallet_private SET BALANCE = ?,INTEREST = ? , EXTRACTED = 0, EXTRACTED_AT = CURRENT_TIMESTAMP WHERE ORDER_ID = ?");
        $stmt->bind_param("dss", $newBalance,$interest, $orderId);  // 'd' 为数字类型, 's' 为字符串类型

        if ($stmt->execute()) {
            return json_encode([
                "status" => "success", 
                "message" => "资金取出成功", 
                "principal" => $amount,  // 本金
                "interest" => $interest,  // 利息
                "totalAmount" => $totalAmount,  // 最终取款金额
                "interestRate" => $interestRate,  // 利率
                "timePeriod" => $timePeriod,  // 利率
                "orderId" => $orderId
            ]);
        } else {
            // 输出错误信息，帮助调试
            return json_encode([
                "status" => "error", 
                "message" => "取款过程中发生错误", 
                "error" => $stmt->error
            ]);
        }
    } else {
        return json_encode([
            "status" => "error", 
            "message" => "无法取出资金，余额不足或未满足取款条件[$orderId][$balance][$amount][$interest][$newBalance]"
        ]);
    }
}



// 查询 t_wallet_private_config 表中的 TIME_PERIOD 和 INTEREST_RATE 配置

public function getConfig() {
    $conn = DB::getConnection();
    $stmt = $conn->prepare("SELECT TIME_PERIOD, INTEREST_RATE FROM t_wallet_private_config");
    $stmt->execute();
    $result = $stmt->get_result();
    
    // 如果查询到结果
    if ($result->num_rows > 0) {
        // 使用 fetch_all 获取所有数据
        $configs = $result->fetch_all(MYSQLI_ASSOC);
        
        // 返回查询结果
        $response = [
            "status" => "success",
            "message" => "配置查询成功",
            "data" => $configs
        ];
    } else {
        // 如果没有查询到数据
        $response = [
            "status" => "error",
            "message" => "没有配置数据",
            "data" => 2
        ];
    }
    
    // 返回JSON响应
    return ($response);
}



// 修改 t_wallet_private_config 表中的 TIME_PERIOD 和 INTEREST_RATE 配置
public function updateConfig($timePeriod, $interestRate) {
    switch ($timePeriod) {
        case 28:
            $ids = 1;
            break;
        case 7:
            $ids = 2;
            break;
        default:
            // 默认值或错误处理
            $ids = 0; // 假设默认值为0
            break;
    }
    // 如果 $ids 为 0，表示处理失败

    
    if ($ids == 0) {
        // 返回错误响应
        $response = [
            "status" => "error",
            "message" => "配置更新失败: 未知的时间段",
            "data" => [
                "TIME_PERIOD" => $timePeriod,
                "INTEREST_RATE" => $interestRate
            ]
        ];
        return $response;  // 直接返回响应
    }


    
    $conn = DB::getConnection();
    
    // 使用事务来保证数据一致性
    $conn->begin_transaction();
    
    try {
        // 更新 TIME_PERIOD 字段
        $stmt = $conn->prepare("UPDATE t_wallet_private_config SET TIME_PERIOD = ? WHERE ID = $ids");
        $stmt->bind_param("i", $timePeriod);
        $stmt->execute();
        
        // 更新 INTEREST_RATE 字段
        $stmt = $conn->prepare("UPDATE t_wallet_private_config SET INTEREST_RATE = ? WHERE ID = $ids");
        $stmt->bind_param("d", $interestRate);  // INTEREST_RATE 是浮动类型
        $stmt->execute();
        
        // 提交事务
        $conn->commit();
        
        // 返回成功响应
        $response = [
            "status" => "success",
            "message" => "配置更新成功",
            "data" => [
                "TIME_PERIOD" => $timePeriod,
                "INTEREST_RATE" => $interestRate
            ]
        ];
    } catch (Exception $e) {
        // 回滚事务
        $conn->rollback();
        
        // 返回错误响应
        $response = [
            "status" => "error",
            "message" => "配置更新失败: " . $e->getMessage(),
            "data" => null
        ];
    }
    
    // 返回JSON响应
     return ($response);
}



// 设置公告内容
public function setAnnouncement($title, $content) {
    $conn = DB::getConnection();

    // 对标题和内容进行URL编码
    $encodedTitle = urlencode($title);
    $encodedContent = urlencode($content);

    $stmt = $conn->prepare("INSERT INTO t_announcements (title, content, created_at) VALUES (?, ?, NOW())");
    $stmt->bind_param("ss", $encodedTitle, $encodedContent);

    if ($stmt->execute()) {
        return ["status" => "success", "message" => "公告内容已成功添加"];
    } else {
        return ["status" => "error", "message" => "添加公告失败：" . $stmt->error];
    }
}

// 获取公告内容
public function getAnnouncement() {
    $conn = DB::getConnection();
    $stmt = $conn->prepare("SELECT title, content, created_at FROM t_announcements ORDER BY created_at DESC LIMIT 10;");
    $stmt->execute();
    $result = $stmt->get_result();

    $announcements = [];
    while ($row = $result->fetch_assoc()) {
        // 对标题和内容进行URL解码 urldecode
        $row['title'] = $row['title'];
        $row['content'] = $row['content'];
        $announcements[] = $row;
    }

    return $announcements;
}


}

// 获取请求的 JSON 数据
$request = json_decode(file_get_contents("php://input"), true);

$inputData = json_decode(file_get_contents('php://input'), true);

if (json_last_error() !== JSON_ERROR_NONE) {
    echo json_encode(["status" => "error", "message" => "Invalid Body( NEED JSON )","body"=>$inputData,"tips"=>"请使用 api.jfhyebbd66.shop 作为API域名"]);
    

// 判断是否为 POST 请求
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // 输出所有的 POST 参数
    echo '<pre>';
    print_r($_POST);
    echo '</pre>';
} else {
    echo "当前不是 POST 请求。";
}


    
    exit();
}
//print_r($inputData) ;




// 确认请求数据
if (!isset($request['action'])) {
    echo json_encode(["status" => "error", "message" => "No action specified"]);
    exit;
}

$walletAPI = new WalletAPI();
$response = null;

switch ($request['action']) {
    case 'getKYCInfo':
        if (isset($request['partyId'])) {
            $response = $walletAPI->getKYCInfo($request['partyId']);
        } else {
            $response = ["status" => "error", "message" => "Missing partyId"];
        }
        break;
    case 'getWalletInfo':
        if (isset($request['partyId'])) {
            $response = $walletAPI->getWalletInfo($request['partyId']);
        } else {
            $response = ["status" => "error", "message" => "Missing partyId"];
        }
        break;
    case 'getAccumulatedInterest':
        if (isset($request['partyId'])) {
            $response = $walletAPI->getAccumulatedInterest($request['partyId']);
        } else {
            $response = ["status" => "error", "message" => "Missing partyId"];
        }
        break;
    case 'depositFunds':
        if (isset($request['partyId']) && isset($request['amount']) && isset($request['orderId']) && isset($request['timePeriod'])) {
            $response = $walletAPI->depositFunds($request['partyId'], $request['amount'], $request['orderId'], $request['timePeriod']);
        } else {
            $response = ["status" => "error", "message" => "Missing parameters"];
        }
        break;
    case 'withdrawFunds':
        if (isset($request['partyId']) && isset($request['amount']) && isset($request['orderId'])) {
            $response = $walletAPI->withdrawFunds($request['partyId'], $request['amount'], $request['orderId']);
        } else {
            $response = ["status" => "error", "message" => "Missing parameters"];
        }
        break;
     case 'getConfig':
        $response = $walletAPI->getConfig();
        break;
    case 'setAnnouncement':
        if (isset($request['title']) && isset($request['content'])) {
            $response = $walletAPI->setAnnouncement($request['title'], $request['content']);
        } else {
            $response = ["status" => "error", "message" => "Missing parameters"];
        }
        break;
    case 'getAnnouncement':
            $response = $walletAPI-> getAnnouncement();
        break;
    case 'updateConfig':
        // 处理配置更新请求
        if (isset($request['timePeriod']) && isset($request['interestRate'])) {
            $timePeriod = $request['timePeriod'];
            $interestRate = $request['interestRate'];
            $response = $walletAPI->updateConfig($timePeriod, $interestRate);
        } else {
            $response = ["status" => "error", "message" => "Missing parameters for updateConfig"];
        }
        break;
    default:
        $response = ["status" => "error", "message" => "Invalid action"];
        break;
}

echo json_encode($response);
?>
