<?php
ob_start();
require_once __DIR__ . '/../lib/config.php';
require_once __DIR__ . '/../lib/db_connect.php';
require_once __DIR__ . '/../includes/header.php';

// 验证用户登录状态
if (!isset($_SESSION['user_id'])) {
    header('Location: login.php');
    exit;
}

// 获取用户信息和当前积分
$stmt = $conn->prepare("SELECT name, points, wx_openid, reputation_score, reputation_level, alipay_name, alipay_account, alipay_qrcode, is_agent FROM users WHERE id = ?");
$stmt->bind_param("i", $_SESSION['user_id']);
$stmt->execute();
$result = $stmt->get_result();
$user = $result->fetch_assoc();
$stmt->close();

// 检查用户是否存在
if (!$user) {
    $_SESSION['error'] = "用户不存在或已被删除";
    header("Location: index.php");
    exit;
}

// 处理支付信息保存
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['save_payment_info'])) {
    $alipay_name = trim($_POST['alipay_name']);
    $alipay_account = trim($_POST['alipay_account']);
    
    // 验证必填字段
    if (empty($alipay_name) || empty($alipay_account)) {
        $_SESSION['error'] = "请填写完整的支付宝信息";
    } else {
        // 处理收款码上传
        $alipay_qrcode = $user['alipay_qrcode']; // 保持原有值
        
        if (isset($_FILES['alipay_qrcode']) && $_FILES['alipay_qrcode']['error'] === UPLOAD_ERR_OK) {
            $uploadDir = UPLOAD_DIR;
            $fileName = 'alipay_qrcode_' . uniqid() . '_' . time() . '.' . pathinfo($_FILES['alipay_qrcode']['name'], PATHINFO_EXTENSION);
            $targetPath = $uploadDir . $fileName;
            
            // 确保上传目录存在
            if (!file_exists($uploadDir)) {
                mkdir($uploadDir, 0755, true);
            }
            
            if (move_uploaded_file($_FILES['alipay_qrcode']['tmp_name'], $targetPath)) {
                // 删除旧的收款码
                if (!empty($user['alipay_qrcode']) && file_exists($uploadDir . $user['alipay_qrcode'])) {
                    unlink($uploadDir . $user['alipay_qrcode']);
                }
                $alipay_qrcode = $fileName;
            } else {
                $_SESSION['error'] = "收款码上传失败，请检查目录权限";
            }
        }
        
        if (!isset($_SESSION['error'])) {
            // 更新用户支付宝信息
            $stmt = $conn->prepare("UPDATE users SET alipay_name = ?, alipay_account = ?, alipay_qrcode = ? WHERE id = ?");
            $stmt->bind_param("sssi", $alipay_name, $alipay_account, $alipay_qrcode, $_SESSION['user_id']);
            
            if ($stmt->execute()) {
                $_SESSION['success'] = "支付宝信息保存成功";
                // 更新用户信息
                $user['alipay_name'] = $alipay_name;
                $user['alipay_account'] = $alipay_account;
                $user['alipay_qrcode'] = $alipay_qrcode;
            } else {
                $_SESSION['error'] = "保存失败: " . $stmt->error;
            }
            $stmt->close();
        }
    }
}

// 处理提现请求
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['submit_withdraw'])) {
    $amount = intval($_POST['amount']);
    $force_withdraw = isset($_POST['force_withdraw']) && $_POST['force_withdraw'] === '1';
    
    // 检查用户是否已设置支付宝信息
    if (empty($user['alipay_name']) || empty($user['alipay_account'])) {
        $_SESSION['error'] = "请先设置支付宝信息";
        header("Location: withdraw.php");
        exit;
    }
    
    // 验证提现金额
    if ($amount < 10) { // 最低提现10积分
        $_SESSION['error'] = "最低提现10积分";
    } elseif ($amount > 500) { // 最高提现500积分
        $_SESSION['error'] = "每次提现不能超过500积分";
    } elseif ($amount > $user['points']) {
        $_SESSION['error'] = "积分不足，无法申请提现";
    } else {
        // 检查当天提现次数
        $today = date('Y-m-d');
        $stmt = $conn->prepare("SELECT COUNT(*) as count FROM withdraw_requests WHERE user_id = ? AND DATE(created_at) = ?");
        $stmt->bind_param("is", $_SESSION['user_id'], $today);
        $stmt->execute();
        $result = $stmt->get_result();
        $todayWithdrawals = $result->fetch_assoc()['count'];
        $stmt->close();
        
        if ($todayWithdrawals >= 2) {
            $_SESSION['error'] = "每天只能提现2次，您今天已经提现了".$todayWithdrawals."次";
        } else {
            // 检查保留积分（代理用户保留100积分，普通用户保留60积分）
            $minReservedPoints = $user['is_agent'] ? 100 : 60;
            $remainingPoints = $user['points'] - $amount;
            
            // 检查预留积分是否足够 - 如果是强制提现则跳过此检查
            if ($remainingPoints < $minReservedPoints && !$force_withdraw) {
                $_SESSION['error'] = "因为出号慢且有封号情况，故需要留".$minReservedPoints."积分作为预扣积分";
            } else {
                $conn->begin_transaction();
                try {
                    // 准备更新用户积分
                    $deductAmount = $amount;
                    $userId = $_SESSION['user_id'];
                    
                    $stmt = $conn->prepare("UPDATE users SET points = points - ? WHERE id = ? AND points >= ?");
                    $stmt->bind_param("iii", $deductAmount, $userId, $deductAmount);
                    $execResult = $stmt->execute();
                    
                    if (!$execResult || $stmt->affected_rows === 0) {
                        throw new Exception("积分扣除失败，可能是积分不足或系统错误");
                    }
                    $stmt->close();

                    // 插入提现记录 - 添加 is_forced 字段
                    $payment_method = 'alipay';
                    $account_info = $user['alipay_name'] . '|' . $user['alipay_account'];
                    $receiptImage = $user['alipay_qrcode'] ?? '';
                    $status = 'pending';
                    $createdAt = date('Y-m-d H:i:s');
                    $is_forced = $force_withdraw ? 1 : 0; // 强制提现标记
                    
                    // 修改SQL，添加 is_forced 字段
                    $sql = "INSERT INTO withdraw_requests 
                           (user_id, amount, payment_method, account_info, receipt_image, status, created_at, wx_openid, is_forced) 
                           VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)";
                    
                    $stmt = $conn->prepare($sql);
                    if (!$stmt) {
                        throw new Exception("SQL准备失败: " . $conn->error);
                    }
                    
                    $wx_openid = $user['wx_openid'] ?? '';
                    
                    // 修改绑定参数，添加 is_forced
                    $stmt->bind_param("iissssssi", 
                        $userId, 
                        $amount, 
                        $payment_method, 
                        $account_info, 
                        $receiptImage, 
                        $status, 
                        $createdAt,
                        $wx_openid,  // 存储微信OpenID
                        $is_forced   // 新增：强制提现标记
                    );
                    
                    if (!$stmt->execute()) {
                        throw new Exception("提现记录创建失败: " . $stmt->error);
                    }
                    $withdrawId = $stmt->insert_id;
                    $stmt->close();

                    // 记录积分交易 - 确保状态为pending
                    $transactionType = 'withdrawal';
                    $transactionDesc = "积分提现申请 - 金额: {$amount} 积分";
                    if ($force_withdraw) {
                        $transactionDesc .= " (强制提现)";
                    }
                    $transactionStatus = 'pending';
                    
                    $negativeAmount = -$amount;
                    
                    $stmt = $conn->prepare("INSERT INTO point_transactions 
                                           (user_id, amount, type, description, related_id, status, created_at) 
                                           VALUES (?, ?, ?, ?, ?, ?, ?)");
                    
                    if (!$stmt) {
                        throw new Exception("积分交易SQL准备失败: " . $conn->error);
                    }
                    
                    $stmt->bind_param("iississ", 
                        $userId, 
                        $negativeAmount,
                        $transactionType, 
                        $transactionDesc, 
                        $withdrawId, 
                        $transactionStatus, 
                        $createdAt
                    );
                    
                    if (!$stmt->execute()) {
                        throw new Exception("积分交易记录失败: " . $stmt->error);
                    }
                    $stmt->close();

                    // 如果是强制提现，则取消该用户的全部权限词
                    if ($force_withdraw) {
                        $stmt = $conn->prepare("UPDATE users SET permissions = '' WHERE id = ?");
                        $stmt->bind_param("i", $userId);
                        if (!$stmt->execute()) {
                            throw new Exception("取消用户权限失败: " . $stmt->error);
                        }
                        $stmt->close();
                    }

                    // 提交事务
                    $conn->commit();
                    
                    // 更新会话中的积分
                    $_SESSION['points'] = $user['points'] - $amount;
                    
                    $_SESSION['success'] = "提现申请已提交，等待管理员审核";
                    if ($force_withdraw) {
                        $_SESSION['success'] .= " (本次为强制提现，预留积分不足，所有权限词已被取消)";
                    }
                    header("Location: withdraw.php");
                    exit;
                } catch (Exception $e) {
                    // 回滚事务
                    $conn->rollback();
                    $_SESSION['error'] = "提现申请失败: " . $e->getMessage();
                }
            }
        }
    }
}

// 分页设置
$perPage = 10; // 每页显示记录数
$currentPage = isset($_GET['page']) ? max(1, (int)$_GET['page']) : 1; // 当前页码，至少为1
$offset = ($currentPage - 1) * $perPage; // 计算偏移量

// 获取提现历史记录总数
$stmt = $conn->prepare("SELECT COUNT(*) AS total FROM withdraw_requests WHERE user_id = ?");
$stmt->bind_param("i", $_SESSION['user_id']);
$stmt->execute();
$result = $stmt->get_result();
$totalRecords = $result->fetch_assoc()['total'];
$stmt->close();

// 计算总页数
$totalPages = ceil($totalRecords / $perPage);

// 获取当前页的提现记录
$withdrawals = [];
$sql = "SELECT 
        wr.*, 
        u.name AS user_name,
        CONCAT('￥', FORMAT(wr.amount * " . (defined('POINT_TO_RMB_RATE') ? POINT_TO_RMB_RATE : '0.01') . ", 2)) AS amount_rmb 
        FROM withdraw_requests wr
        JOIN users u ON wr.user_id = u.id
        WHERE wr.user_id = ? 
        ORDER BY wr.created_at DESC
        LIMIT ? OFFSET ?";
        
$stmt = $conn->prepare($sql);
if ($stmt) {
    $stmt->bind_param("iii", $_SESSION['user_id'], $perPage, $offset);
    $stmt->execute();
    $result = $stmt->get_result();

    if ($result->num_rows > 0) {
        $withdrawals = $result->fetch_all(MYSQLI_ASSOC);
    }
    $stmt->close();
}

// 信誉等级样式映射 - 使用新的4级信誉系统
$reputation_levels = [
    '优质信誉' => ['class' => 'text-success', 'icon' => 'fas fa-gem'],
    '正常信誉' => ['class' => 'text-primary', 'icon' => 'fas fa-check-circle'],
    '略差信誉' => ['class' => 'text-warning', 'icon' => 'fas fa-exclamation-triangle'],
    '超差信誉' => ['class' => 'text-danger', 'icon' => 'fas fa-skull']
];

// 获取当前用户的信誉等级信息
$current_level_info = $reputation_levels[$user['reputation_level']] ?? $reputation_levels['正常信誉'];

// 检查用户是否已设置支付宝信息
$hasPaymentInfo = !empty($user['alipay_name']) && !empty($user['alipay_account']);

// 检查今天已提现次数
$today = date('Y-m-d');
$stmt = $conn->prepare("SELECT COUNT(*) as count FROM withdraw_requests WHERE user_id = ? AND DATE(created_at) = ?");
$stmt->bind_param("is", $_SESSION['user_id'], $today);
$stmt->execute();
$result = $stmt->get_result();
$todayWithdrawals = $result->fetch_assoc()['count'];
$stmt->close();

// 计算预留积分
$reservedPoints = $user['is_agent'] ? 100 : 60;
?>

<div class="main-content">
    <div class="d-flex justify-content-between align-items-center mb-4">
        <h4 class="mb-0">积分提现</h4>
        
        <!-- 信誉等级徽章 - 添加点击事件 -->
        <div class="d-flex align-items-center">
            <a href="javascript:void(0);" class="text-decoration-none" id="reputationBadge" data-bs-toggle="modal" data-bs-target="#reputationInfoModalWithdraw">
                <span class="badge bg-light text-dark border py-2 px-3 rounded-pill d-inline-flex align-items-center">
                    <i class="<?= $current_level_info['icon'] ?> <?= $current_level_info['class'] ?> me-2"></i>
                    <span class="<?= $current_level_info['class'] ?> fw-bold">
                        <?= $user['reputation_level'] ?>
                    </span>
                    <span class="ms-2">(<?= $user['reputation_score'] ?>分)</span>
                    <i class="fas fa-info-circle ms-2 text-info"></i>
                </span>
            </a>
        </div>
    </div>
    
    <?php if (isset($_SESSION['success'])): ?>
        <div class="alert alert-success alert-dismissible fade show" role="alert">
            <i class="fas fa-check-circle mr-2"></i>
            <?= $_SESSION['success'] ?>
            <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
        </div>
        <?php unset($_SESSION['success']); ?>
    <?php endif; ?>
    
    <?php if (isset($_SESSION['error'])): ?>
        <div class="alert alert-danger alert-dismissible fade show" role="alert">
            <i class="fas fa-exclamation-circle mr-2"></i>
            <?= $_SESSION['error'] ?>
            <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
        </div>
        <?php unset($_SESSION['error']); ?>
    <?php endif; ?>

    <div class="row">
        <div class="col-md-6">
            <div class="card mb-4">
                <div class="card-header bg-primary text-white">
                    <h5 class="mb-0">提现申请</h5>
                </div>
                <div class="card-body">
                    <?php if ($hasPaymentInfo): ?>
                        <!-- 已设置支付信息时的表单 -->
                        <div class="mb-4 p-3 bg-light rounded">
                            <h6>已保存的支付宝信息</h6>
                            <p class="mb-1"><strong>姓名:</strong> <?= htmlspecialchars($user['alipay_name']) ?></p>
                            <p class="mb-1"><strong>账号:</strong> <?= htmlspecialchars($user['alipay_account']) ?></p>
                            <?php if (!empty($user['alipay_qrcode'])): ?>
                                <p class="mb-2"><strong>收款码:</strong> 已上传</p>
                                <img src="<?= BASE_URL ?>uploads/<?= $user['alipay_qrcode'] ?>" class="img-fluid rounded" style="max-height: 150px;">
                            <?php endif; ?>
                            <div class="mt-3">
                                <button type="button" class="btn btn-sm btn-outline-primary" data-bs-toggle="modal" data-bs-target="#paymentInfoModal">
                                    <i class="fas fa-edit me-1"></i>修改支付信息
                                </button>
                            </div>
                        </div>
                        
                        <form method="POST" id="withdrawForm">
                            <input type="hidden" name="force_withdraw" value="0" id="forceWithdrawInput">
                            <div class="mb-3">
                                <label class="form-label">当前可用积分</label>
                                <div class="input-group">
                                    <input type="text" value="<?= number_format($user['points']) ?>" class="form-control bg-light" readonly>
                                    <span class="input-group-text">积分</span>
                                </div>
                                <div class="form-text">
                                    可兑换金额: <strong>￥<?= number_format($user['points'] * (defined('POINT_TO_RMB_RATE') ? POINT_TO_RMB_RATE : 0.01), 2) ?></strong>
                                </div>
                                <div class="form-text">
                                    预留积分要求: <strong><?= $reservedPoints ?> 积分</strong>
                                </div>
                            </div>
                            
                            <div class="mb-3">
                                <label class="form-label">提现金额</label>
                                <div class="input-group">
                                    <input type="text" name="amount" id="amountInput" class="form-control" placeholder="请输入提现金额" required>
                                    <span class="input-group-text">积分</span>
                                </div>
                                <div class="form-text">
                                    最低提现: 10 积分，最高提现: 500 积分，1积分 = <?= number_format(defined('POINT_TO_RMB_RATE') ? POINT_TO_RMB_RATE : 0.01, 2) ?>元
                                </div>
                                <div class="form-text text-warning">
                                    今日已提现: <?= $todayWithdrawals ?> 次 (每天最多2次)
                                </div>
                                <div class="form-text text-info" id="remainingPointsText">
                                    提现后剩余积分: <?= $user['points'] ?> 积分
                                </div>
                                <div class="form-text text-danger d-none" id="reservedPointsWarning">
                                    提现后剩余积分将低于预留积分要求 (<?= $reservedPoints ?> 积分)
                                </div>
                                <div class="form-text text-danger d-none" id="amountError">
                                    请输入有效的提现金额（10-500积分）
                                </div>
                            </div>
                            
                            <!-- 正常提现按钮 -->
                            <div class="d-grid mb-2">
                                <button type="submit" name="submit_withdraw" class="btn btn-primary btn-lg py-2" id="submitWithdrawBtn" <?= $todayWithdrawals >= 2 ? 'disabled' : '' ?>>
                                    <i class="fas fa-paper-plane me-2"></i>
                                    <?= $todayWithdrawals >= 2 ? '今日提现次数已用完' : '提交提现申请' ?>
                                </button>
                            </div>
                            
                            <!-- 强制提现按钮 - 初始隐藏 -->
                            <div class="d-grid mb-2 d-none" id="forceWithdrawSection">
                                <button type="button" class="btn btn-warning btn-lg py-2" id="forceWithdrawBtn" data-bs-toggle="modal" data-bs-target="#forceWithdrawModal">
                                    <i class="fas fa-exclamation-triangle me-2"></i>
                                    坚持提现
                                </button>
                                <div class="form-text text-warning text-center mt-1">
                                    <small>注意：预留积分不足可能会影响后续任务接取</small>
                                </div>
                            </div>
                        </form>
                    <?php else: ?>
                        <!-- 未设置支付信息时的表单 -->
                        <div class="alert alert-info">
                            <i class="fas fa-info-circle me-2"></i>请先设置支付宝信息，之后提现只需输入金额即可
                        </div>
                        
                        <form method="POST" enctype="multipart/form-data" id="mainPaymentForm">
                            <div class="mb-3">
                                <label class="form-label">支付宝姓名(务必真实名字)</label>
                                <input type="text" name="alipay_name" class="form-control" required>
                            </div>
                            
                            <div class="mb-3">
                                <label class="form-label">支付宝账号(务必准确支付宝账号)</label>
                                <input type="text" name="alipay_account" class="form-control" required>
                            </div>
                            
                            <div class="mb-3">
                                <label class="form-label">上传收款码 (可选)</label>
                                <input type="file" name="alipay_qrcode" class="form-control" accept="image/*">
                                <div class="form-text">
                                    上传收款码图片可加快审核速度，支持JPG、PNG格式
                                </div>
                            </div>
                            
                            <div class="d-grid">
                                <button type="submit" name="save_payment_info" class="btn btn-primary btn-lg py-2">
                                    <i class="fas fa-save me-2"></i>保存支付信息
                                </button>
                            </div>
                        </form>
                    <?php endif; ?>
                </div>
            </div>
        </div>
        
        <div class="col-md-6">
            <div class="card">
                <div class="card-header bg-info text-white">
                    <h5 class="mb-0">提现记录</h5>
                    <div class="d-flex justify-content-between align-items-center mt-2">
                        <small class="text-white-50">共 <?= $totalRecords ?> 条记录</small>
                        <small class="text-white-50">第 <?= $currentPage ?> 页/共 <?= $totalPages ?> 页</small>
                    </div>
                </div>
                <div class="card-body">
                    <?php if (empty($withdrawals)): ?>
                        <div class="text-center py-6">
                            <i class="fas fa-history text-gray-300 display-4 mb-3"></i>
                            <p class="text-gray-500">暂无提现记录</p>
                        </div>
                    <?php else: ?>
                        <div class="table-responsive">
                            <table class="table table-hover">
                                <thead>
                                    <tr>
                                        <th>申请时间</th>
                                        <th>金额</th>
                                        <th>方式</th>
                                        <th>状态</th>
                                        <th>操作</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php foreach ($withdrawals as $withdrawal): 
                                        // 准备详情数据 - 包含 is_forced 字段
                                        $details = [
                                            'id' => $withdrawal['id'],
                                            'user_name' => $withdrawal['user_name'],
                                            'amount' => $withdrawal['amount'],
                                            'payment_method' => $withdrawal['payment_method'],
                                            'status' => $withdrawal['status'],
                                            'formatted_created_at' => date('Y-m-d H:i', strtotime($withdrawal['created_at'])),
                                            'formatted_processed_at' => $withdrawal['processed_at'] ? date('Y-m-d H:i', strtotime($withdrawal['processed_at'])) : null,
                                            'admin_name' => $withdrawal['admin_name'] ?? null,
                                            'account_info' => $withdrawal['account_info'],
                                            'receipt_image' => $withdrawal['receipt_image'],
                                            'remark' => $withdrawal['remark'] ?? null,
                                            'wx_batch_no' => $withdrawal['wx_batch_no'] ?? null,
                                            'payment_no' => $withdrawal['payment_no'] ?? null,
                                            'payment_time' => $withdrawal['payment_time'] ?? null,
                                            'is_forced' => $withdrawal['is_forced'] ?? 0
                                        ];
                                    ?>
                                        <tr>
                                            <td><?= date('Y-m-d H:i', strtotime($withdrawal['created_at'])) ?></td>
                                            <td>
                                                <?= number_format($withdrawal['amount']) ?> 积分 
                                                <span class="text-muted">(<?= $withdrawal['amount_rmb'] ?>)</span>
                                                <?php if ($withdrawal['is_forced']): ?>
                                                    <span class="badge bg-warning ms-1" title="强制提现"><i class="fas fa-exclamation-triangle"></i></span>
                                                <?php endif; ?>
                                            </td>
                                            <td>
                                                <?php 
                                                if ($withdrawal['payment_method'] === 'alipay') echo '支付宝';
                                                elseif ($withdrawal['payment_method'] === 'wechat') echo '微信支付';
                                                else echo '银行卡';
                                                ?>
                                            </td>
                                            <td>
                                                <?php 
                                                if ($withdrawal['status'] === 'pending') {
                                                    echo '<span class="badge bg-warning"><i class="fas fa-clock me-1"></i> 待审核</span>';
                                                } elseif ($withdrawal['status'] === 'approved') {
                                                    echo '<span class="badge bg-success"><i class="fas fa-check-circle me-1"></i> 已通过</span>';
                                                } elseif ($withdrawal['status'] === 'rejected') {
                                                    echo '<span class="badge bg-danger"><i class="fas fa-times-circle me-1"></i> 已拒绝</span>';
                                                }
                                                ?>
                                            </td>
                                            <td>
                                                <button class="btn btn-sm btn-outline-primary view-details" 
                                                        data-bs-toggle="modal" 
                                                        data-bs-target="#detailsModal" 
                                                        data-details="<?= htmlspecialchars(json_encode($details), ENT_QUOTES, 'UTF-8') ?>">
                                                    <i class="fas fa-eye"></i> 查看
                                                </button>
                                            </td>
                                        </tr>
                                    <?php endforeach; ?>
                                </tbody>
                            </table>
                        </div>
                        
                        <!-- 分页导航 -->
                        <?php if ($totalPages > 1): ?>
                        <nav aria-label="提现记录分页导航">
                            <ul class="pagination justify-content-center">
                                <!-- 上一页 -->
                                <li class="page-item <?= $currentPage <= 1 ? 'disabled' : '' ?>">
                                    <a class="page-link" href="?page=<?= max(1, $currentPage - 1) ?>" aria-label="上一页">
                                        <span aria-hidden="true">&laquo;</span>
                                    </a>
                                </li>
                                
                                <!-- 页码 -->
                                <?php
                                // 显示页码范围（最多显示5个页码）
                                $startPage = max(1, min($currentPage - 2, $totalPages - 4));
                                $endPage = min($totalPages, max($currentPage + 2, 5));
                                
                                for ($i = $startPage; $i <= $endPage; $i++): 
                                ?>
                                    <li class="page-item <?= $i == $currentPage ? 'active' : '' ?>">
                                        <a class="page-link" href="?page=<?= $i ?>"><?= $i ?></a>
                                    </li>
                                <?php endfor; ?>
                                
                                <!-- 下一页 -->
                                <li class="page-item <?= $currentPage >= $totalPages ? 'disabled' : '' ?>">
                                    <a class="page-link" href="?page=<?= min($totalPages, $currentPage + 1) ?>" aria-label="下一页">
                                        <span aria-hidden="true">&raquo;</span>
                                    </a>
                                </li>
                            </ul>
                        </nav>
                        <?php endif; ?>
                    <?php endif; ?>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- 支付信息模态框 -->
<div class="modal fade" id="paymentInfoModal" tabindex="-1" aria-labelledby="paymentInfoModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">修改支付信息</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <form method="POST" enctype="multipart/form-data" id="paymentForm">
                <div class="modal-body">
                    <div class="mb-3">
                        <label class="form-label">支付宝姓名(务必真实名字)</label>
                        <input type="text" name="alipay_name" class="form-control" value="<?= htmlspecialchars($user['alipay_name'] ?? '') ?>" required>
                    </div>
                    
                    <div class="mb-3">
                        <label class="form-label">支付宝账号(务必正确支付宝账号)</label>
                        <input type="text" name="alipay_account" class="form-control" value="<?= htmlspecialchars($user['alipay_account'] ?? '') ?>" required>
                    </div>
                    
                    <div class="mb-3">
                        <label class="form-label">上传收款码 (可选)</label>
                        <input type="file" name="alipay_qrcode" class="form-control" accept="image/*">
                        <div class="form-text">
                            上传收款码图片可加快审核速度，支持JPG、PNG格式
                        </div>
                        <?php if (!empty($user['alipay_qrcode'])): ?>
                            <div class="mt-2">
                                <img src="<?= BASE_URL ?>uploads/<?= $user['alipay_qrcode'] ?>" class="img-fluid rounded" style="max-height: 100px;">
                                <div class="form-text">当前已上传的收款码</div>
                            </div>
                        <?php endif; ?>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                    <button type="submit" name="save_payment_info" class="btn btn-primary" id="savePaymentInfo">保存</button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- 详情模态框 -->
<div class="modal fade" id="detailsModal" tabindex="-1" aria-labelledby="detailsModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">提现申请详情</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body" id="detailsContent"></div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">关闭</button>
            </div>
        </div>
    </div>
</div>

<!-- 强制提现警告模态框 -->
<div class="modal fade" id="forceWithdrawModal" tabindex="-1" aria-labelledby="forceWithdrawModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header bg-warning">
                <h5 class="modal-title"><i class="fas fa-exclamation-triangle me-2"></i>强制提现警告</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <div class="alert alert-danger">
                    <h6 class="alert-heading"><i class="fas fa-ban me-2"></i>严重警告</h6>
                    <p class="mb-0">您当前的积分低于预留积分要求，强制提现将导致您的接单权限被取消！</p>
                </div>
                
                <div class="mb-3">
                    <p><strong>当前提现金额：</strong><span id="forceWithdrawAmount">0</span> 积分</p>
                    <p><strong>提现后剩余积分：</strong><span id="forceWithdrawRemaining">0</span> 积分</p>
                    <p><strong>预留积分要求：</strong><?= $reservedPoints ?> 积分</p>
                </div>
                
                <div class="border rounded p-3 bg-light">
                    <h6><i class="fas fa-info-circle me-2 text-primary"></i>后果说明</h6>
                    <ul class="mb-0">
                        <li>您的接单权限将被立即取消</li>
                        <li>后续可能无法恢复接单权限</li>
                        <li>将影响您的信誉评分</li>
                        <li>请谨慎考虑此操作</li>
                    </ul>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消提现</button>
                <button type="button" class="btn btn-danger" id="confirmForceWithdraw">
                    <i class="fas fa-exclamation-triangle me-2"></i>仍然坚持提现
                </button>
            </div>
        </div>
    </div>
</div>

<!-- 图片放大模态框 -->
<div class="modal fade" id="imageModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content bg-transparent border-0">
            <div class="modal-body text-center p-0">
                <img id="modalImage" src="" class="img-fluid" style="max-height: 80vh;">
            </div>
        </div>
    </div>
</div>

<!-- 信誉分级说明模态框 -->
<div class="modal fade" id="reputationInfoModalWithdraw" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title"><i class="fas fa-info-circle me-2"></i>信誉等级说明</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <div class="alert alert-info">
                    <p class="mb-0"><i class="fas fa-lightbulb me-2"></i>信誉分数初始为100分，通过任务+1分，扣回任务-5分</p>
                </div>
                
                <div class="row row-cols-1 row-cols-md-2 g-4">
                    <div class="col">
                        <div class="card h-100 border-0 shadow-sm">
                            <div class="card-header bg-success text-white">
                                <h6 class="mb-0"><i class="fas fa-gem me-2"></i>优质信誉</h6>
                            </div>
                            <div class="card-body">
                                <div class="d-flex align-items-center mb-3">
                                    <div class="bg-success bg-opacity-10 text-success rounded-circle d-flex align-items-center justify-content-center me-3" style="width: 40px; height: 40px;">
                                        <i class="fas fa-gem"></i>
                                    </div>
                                    <div>
                                        <h4 class="mb-0 fw-bold">110分以上</h4>
                                    </div>
                                </div>
                                <ul class="list-group list-group-flush">
                                    <li class="list-group-item"><i class="fas fa-check-circle text-success me-2"></i>可接取所有类型任务</li>
                                    <li class="list-group-item"><i class="fas fa-check-circle text-success me-2"></i>提现秒到-审核快</li>
                                
                                </ul>
                            </div>
                        </div>
                    </div>
                    
                    <div class="col">
                        <div class="card h-100 border-0 shadow-sm">
                            <div class="card-header bg-primary text-white">
                                <h6 class="mb-0"><i class="fas fa-check-circle me-2"></i>正常信誉</h6>
                            </div>
                            <div class="card-body">
                                <div class="d-flex align-items-center mb-3">
                                    <div class="bg-primary bg-opacity-10 text-primary rounded-circle d-flex align-items-center justify-content-center me-3" style="width: 40px; height: 40px;">
                                        <i class="fas fa-check-circle"></i>
                                    </div>
                                    <div>
                                        <h4 class="mb-0 fw-bold">100-109分</h4>
                                    </div>
                                </div>
                                <ul class="list-group list-group-flush">
                                    <li class="list-group-item"><i class="fas fa-check-circle text-primary me-2"></i>可接取大部分任务</li>
                                    <li class="list-group-item"><i class="fas fa-check-circle text-primary me-2"></i>审核快-提现24h内</li>
                              
                                </ul>
                            </div>
                        </div>
                    </div>
                    
                    <div class="col">
                        <div class="card h-100 border-0 shadow-sm">
                            <div class="card-header bg-warning text-dark">
                                <h6 class="mb-0"><i class="fas fa-exclamation-triangle me-2"></i>略差信誉</h6>
                            </div>
                            <div class="card-body">
                                <div class="d-flex align-items-center mb-3">
                                    <div class="bg-warning bg-opacity-10 text-warning rounded-circle d-flex align-items-center justify-content-center me-3" style="width: 40px; height: 40px;">
                                        <i class="fas fa-exclamation-triangle"></i>
                                    </div>
                                    <div>
                                        <h4 class="mb-0 fw-bold">80-99分</h4>
                                    </div>
                                </div>
                                <ul class="list-group list-group-flush">
                                    <li class="list-group-item"><i class="fas fa-exclamation-triangle text-warning me-2"></i>仅可接取部分任务</li>
                                    <li class="list-group-item"><i class="fas fa-exclamation-triangle text-warning me-2"></i>审核快-提现慢大约48h</li>
                                 
                                </ul>
                            </div>
                        </div>
                    </div>
                    
                    <div class="col">
                        <div class="card h-100 border-0 shadow-sm">
                            <div class="card-header bg-danger text-white">
                                <h6 class="mb-0"><i class="fas fa-skull me-2"></i>超差信誉</h6>
                            </div>
                            <div class="card-body">
                                <div class="d-flex align-items-center mb-3">
                                    <div class="bg-danger bg-opacity-10 text-danger rounded-circle d-flex align-items-center justify-content-center me-3" style="width: 40px; height: 40px;">
                                        <i class="fas fa-skull"></i>
                                    </div>
                                    <div>
                                        <h4 class="mb-0 fw-bold">80分以下</h4>
                                    </div>
                                </div>
                                <ul class="list-group list-group-flush">
                                    <li class="list-group-item"><i class="fas fa-times-circle text-danger me-2"></i>无法接取接单大厅任务</li>
                                    <li class="list-group-item"><i class="fas fa-times-circle text-danger me-2"></i>审核慢-提现极慢</li>
                       
                                </ul>
                            </div>
                        </div>
                    </div>
                </div>
                
                <div class="mt-4">
                    <div class="card border-0 bg-light">
                        <div class="card-body">
                            <h6><i class="fas fa-question-circle me-2 text-primary"></i>如何提升信誉分数？</h6>
                            <ul class="mb-0">
                                <li>认真完成每个任务，避免被扣回</li>
                                <li>遵守平台规则，不进行违规操作</li>
                                <li>保持活跃，持续完成高质量任务</li>
                                <li>避免提交虚假任务或低质量内容</li>
                            </ul>
                        </div>
                    </div>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">关闭</button>
            </div>
        </div>
    </div>
</div>

<script>
document.addEventListener('DOMContentLoaded', function() {
    // 检查是否首次访问提现页面
    if (!localStorage.getItem('withdrawPageVisited')) {
        // 首次访问，显示信誉等级说明模态框
        const reputationModal = new bootstrap.Modal(document.getElementById('reputationInfoModalWithdraw'));
        reputationModal.show();
        
        // 设置标记，表示已经访问过
        localStorage.setItem('withdrawPageVisited', 'true');
    }
    
    // 详情模态框处理 - 使用本地数据
    document.querySelectorAll('.view-details').forEach(btn => {
        btn.addEventListener('click', function() {
            const details = JSON.parse(this.getAttribute('data-details'));
            const content = document.getElementById('detailsContent');
            
            let html = `
                <div class="row mb-3">
                    <div class="col-md-6">
                        <p><strong>申请ID:</strong> ${details.id}</p>
                        <p><strong>用户姓名:</strong> ${details.user_name}</p>
                        <p><strong>申请时间:</strong> ${details.formatted_created_at}</p>
                        <p><strong>提现金额:</strong> ${details.amount} 积分</p>
                        ${details.is_forced ? '<p><strong>提现类型:</strong> <span class="badge bg-warning">强制提现</span></p>' : ''}
                    </div>
                    <div class="col-md-6">
                        <p><strong>支付方式:</strong> ${details.payment_method === 'alipay' ? '支付宝' : '微信支付'}</p>
                        <p><strong>状态:</strong> `;
            
            if (details.status === 'pending') {
                html += `<span class="badge bg-warning">待审核</span>`;
            } else if (details.status === 'approved') {
                html += `<span class="badge bg-success">已通过</span>`;
            } else if (details.status === 'rejected') {
                html += `<span class="badge bg-danger">已拒绝</span>`;
            }
            
            html += `</p>`;
            
            if (details.formatted_processed_at) {
                html += `<p><strong>处理时间:</strong> ${details.formatted_processed_at}</p>`;
            }
            
            if (details.admin_name) {
                html += `<p><strong>处理管理员:</strong> ${details.admin_name}</p>`;
            }
            
            html += `</div></div>`;
            
            // 账户信息
            const accountInfo = details.account_info ? details.account_info.split('|') : [];
            if (accountInfo.length >= 2) {
                html += `
                <div class="mb-3">
                    <h6>账户信息</h6>
                    <p><strong>姓名:</strong> ${accountInfo[0]}</p>
                    <p><strong>账号:</strong> ${accountInfo[1]}</p>
                </div>`;
            }
            
            // 收款码
            if (details.receipt_image) {
                html += `
                <div class="mb-3">
                    <h6>收款码</h6>
                    <img src="<?= BASE_URL ?>uploads/${details.receipt_image}" class="img-thumbnail receipt-image" style="max-height: 200px; cursor: pointer;" data-bs-toggle="modal" data-bs-target="#imageModal" onclick="document.getElementById('modalImage').src = this.src">
                </div>`;
            }
            
            // 备注 - 只有在状态不是待审核时才显示
            if (details.remark && details.status !== 'pending') {
                html += `
                <div class="mb-3">
                    <h6>备注</h6>
                    <p class="text-muted">${details.remark}</p>
                </div>`;
            }
            
            // 微信支付批次号
            if (details.wx_batch_no) {
                html += `<p><strong>微信批次号:</strong> ${details.wx_batch_no}</p>`;
            }
            
            // 支付单号
            if (details.payment_no) {
                html += `<p><strong>支付单号:</strong> ${details.payment_no}</p>`;
            }
            
            // 支付时间
            if (details.payment_time) {
                html += `<p><strong>支付时间:</strong> ${details.payment_time}</p>`;
            }
            
            content.innerHTML = html;
        });
    });
    
    // 表单验证
    const paymentForm = document.getElementById('paymentForm');
    if (paymentForm) {
        paymentForm.addEventListener('submit', function(e) {
            const nameInput = this.querySelector('input[name="alipay_name"]');
            const accountInput = this.querySelector('input[name="alipay_account"]');
            
            if (!nameInput.value.trim()) {
                e.preventDefault();
                alert('请输入支付宝姓名');
                nameInput.focus();
                return;
            }
            
            if (!accountInput.value.trim()) {
                e.preventDefault();
                alert('请输入支付宝账号');
                accountInput.focus();
                return;
            }
        });
    }
    
    const mainPaymentForm = document.getElementById('mainPaymentForm');
    if (mainPaymentForm) {
        mainPaymentForm.addEventListener('submit', function(e) {
            const nameInput = this.querySelector('input[name="alipay_name"]');
            const accountInput = this.querySelector('input[name="alipay_account"]');
            
            if (!nameInput.value.trim()) {
                e.preventDefault();
                alert('请输入支付宝姓名');
                nameInput.focus();
                return;
            }
            
            if (!accountInput.value.trim()) {
                e.preventDefault();
                alert('请输入支付宝账号');
                accountInput.focus();
                return;
            }
        });
    }
    
    // 提现金额输入限制和预留积分检查
    const amountInput = document.getElementById('amountInput');
    const submitWithdrawBtn = document.getElementById('submitWithdrawBtn');
    const forceWithdrawSection = document.getElementById('forceWithdrawSection');
    const forceWithdrawInput = document.getElementById('forceWithdrawInput');
    const remainingPointsText = document.getElementById('remainingPointsText');
    const reservedPointsWarning = document.getElementById('reservedPointsWarning');
    const amountError = document.getElementById('amountError');
    
    if (amountInput) {
        // 初始状态
        updateWithdrawButtonState();
        
        // 输入事件处理
        amountInput.addEventListener('input', function() {
            // 检查是否只读
            if (this.readOnly) {
                return;
            }
            
            // 移除非数字字符
            this.value = this.value.replace(/[^\d]/g, '');
            
            // 验证金额范围
            validateAmountInput();
        });
        
        // 失去焦点时验证
        amountInput.addEventListener('blur', function() {
            if (this.readOnly) {
                return;
            }
            validateAmountInput();
        });
    }
    
    function validateAmountInput() {
        const minAmount = 10;
        const maxAmount = 500;
        const value = parseInt(amountInput.value) || 0;
        
        // 隐藏错误信息
        amountError.classList.add('d-none');
        
        if (amountInput.value === '') {
            // 空值，不显示错误
            return false;
        }
        
        if (value < minAmount || value > maxAmount) {
            amountError.classList.remove('d-none');
            return false;
        }
        
        return true;
    }
    
    function updateWithdrawButtonState() {
        const minAmount = 10;
        const maxAmount = 500;
        const userPoints = <?= $user['points'] ?>;
        const reservedPoints = <?= $reservedPoints ?>;
        
        let value = parseInt(amountInput.value) || 0;
        
        // 验证输入是否有效
        const isValid = validateAmountInput();
        
        if (amountInput.value !== '' && (!isValid || value < minAmount || value > maxAmount)) {
            submitWithdrawBtn.disabled = true;
            submitWithdrawBtn.classList.remove('btn-primary');
            submitWithdrawBtn.classList.add('btn-secondary');
            return;
        }
        
        // 如果输入为空，使用最小值
        if (amountInput.value === '') {
            value = minAmount;
        }
        
        // 确保值在范围内
        if (value < minAmount) {
            value = minAmount;
            amountInput.value = minAmount;
        } else if (value > maxAmount) {
            value = maxAmount;
            amountInput.value = maxAmount;
        } else if (value > userPoints) {
            value = Math.min(userPoints, maxAmount);
            amountInput.value = value;
        }
        
        const remainingPoints = userPoints - value;
        remainingPointsText.textContent = `提现后剩余积分: ${remainingPoints} 积分`;
        
        // 检查预留积分
        if (remainingPoints < reservedPoints) {
            // 预留积分不足 - 设置输入框为只读，并设置为用户所有积分
            amountInput.readOnly = true;
            amountInput.value = userPoints; // 设置为所有积分
            
            // 更新剩余积分显示
            const newRemainingPoints = userPoints - userPoints;
            remainingPointsText.textContent = `提现后剩余积分: ${newRemainingPoints} 积分`;
            
            submitWithdrawBtn.disabled = true;
            submitWithdrawBtn.classList.remove('btn-primary');
            submitWithdrawBtn.classList.add('btn-secondary');
            
            reservedPointsWarning.classList.remove('d-none');
            forceWithdrawSection.classList.remove('d-none');
            
            // 更新强制提现按钮文本
            const forceWithdrawBtn = document.getElementById('forceWithdrawBtn');
            forceWithdrawBtn.innerHTML = `<i class="fas fa-exclamation-triangle me-2"></i>坚持提现 (全部${userPoints}积分)`;
            
            // 更新强制提现模态框中的数据
            document.getElementById('forceWithdrawAmount').textContent = userPoints;
            document.getElementById('forceWithdrawRemaining').textContent = newRemainingPoints;
        } else {
            // 预留积分足够 - 移除只读属性
            amountInput.readOnly = false;
            
            submitWithdrawBtn.disabled = <?= $todayWithdrawals >= 2 ? 'true' : 'false' ?>;
            submitWithdrawBtn.classList.remove('btn-secondary');
            submitWithdrawBtn.classList.add('btn-primary');
            
            reservedPointsWarning.classList.add('d-none');
            forceWithdrawSection.classList.add('d-none');
        }
    }
    
    // 强制提现按钮点击事件 - 显示警告模态框
    const forceWithdrawBtn = document.getElementById('forceWithdrawBtn');
    if (forceWithdrawBtn) {
        forceWithdrawBtn.addEventListener('click', function() {
            // 更新强制提现模态框中的数据 - 使用全部积分
            const userPoints = <?= $user['points'] ?>;
            const remainingPoints = 0;
            
            document.getElementById('forceWithdrawAmount').textContent = userPoints;
            document.getElementById('forceWithdrawRemaining').textContent = remainingPoints;
        });
    }
    
    // 确认强制提现按钮点击事件
    const confirmForceWithdraw = document.getElementById('confirmForceWithdraw');
    if (confirmForceWithdraw) {
        confirmForceWithdraw.addEventListener('click', function() {
            // 设置强制提现标记
            forceWithdrawInput.value = '1';
            
            // 关闭模态框
            const forceWithdrawModal = bootstrap.Modal.getInstance(document.getElementById('forceWithdrawModal'));
            forceWithdrawModal.hide();
            
            // 创建隐藏的表单并提交
            const form = document.getElementById('withdrawForm');
            const hiddenInput = document.createElement('input');
            hiddenInput.type = 'hidden';
            hiddenInput.name = 'submit_withdraw';
            hiddenInput.value = '1';
            form.appendChild(hiddenInput);
            
            // 提交表单
            form.submit();
        });
    }
    
    // 正常提现按钮点击事件 - 确保强制提现标记被清除
    if (submitWithdrawBtn) {
        submitWithdrawBtn.addEventListener('click', function() {
            forceWithdrawInput.value = '0';
        });
    }
    
    // 表单提交验证
    const withdrawForm = document.getElementById('withdrawForm');
    if (withdrawForm) {
        withdrawForm.addEventListener('submit', function(e) {
            const amount = parseInt(amountInput.value) || 0;
            const minAmount = 10;
            const maxAmount = 500;
            
            if (amount < minAmount || amount > maxAmount) {
                e.preventDefault();
                amountError.classList.remove('d-none');
                amountInput.focus();
                return false;
            }
            
            return true;
        });
    }
});
</script>

<?php
require_once __DIR__ . '/../includes/footer.php';
ob_end_flush();
?>