<?php
require_once __DIR__ . '/layout.php';

$db = db();

// Helper to check permissions
if (!hasPermission('audit_finance')) {
    echo "权限不足";
    exit;
}

// Handle Approval
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action'])) {
    $id = (int)$_POST['request_id'];
    $stmt = $db->prepare("SELECT r.* FROM finance_requests r JOIN users u ON r.user_id = u.id WHERE r.id = ? " . ($admin['is_agent'] ? "AND u.agent_id = ?" : ""));
    $params = [$id];
    if ($admin['is_agent']) $params[] = $admin['id'];
    $stmt->execute($params);
    $req = $stmt->fetch();
    
    if (!$req) {
        header("Location: finance.php?error=invalid");
        exit;
    }
    
    if ($_POST['action'] === 'approve') {
        $db->beginTransaction();
        try {
            // Check if already approved to avoid double adding balance
            if ($req['status'] === '3') {
                header("Location: finance.php?error=" . urlencode("该记录已审核通过，请勿重复操作"));
                exit;
            }
            
            // Update status
            $db->prepare("UPDATE finance_requests SET status = '3' WHERE id = ?")->execute([$id]);
            
            // If recharge, add to balance
            if ($req['type'] === 'recharge') {
                $final_amount = (float)($_POST['final_amount'] ?? $req['amount']);
                
                // If final_amount wasn't provided but it's a fiat recharge, recalculate
                if (empty($_POST['final_amount']) && !empty($req['fiat_amount']) && !empty($req['fiat_currency'])) {
                    require_once __DIR__ . '/../includes/exchange.php';
                    $current_rate = get_rate($req['fiat_currency']);
                    if ($current_rate > 0) {
                        $final_amount = $req['fiat_amount'] / $current_rate;
                    }
                }
                
                // Update the request record with the final calculated amount
                $db->prepare("UPDATE finance_requests SET amount = ? WHERE id = ?")->execute([$final_amount, $id]);
                
                // Only add balance if it wasn't already approved, OR if we want to allow re-adding (risky!)
                // Based on user feedback, they might be clicking "Approve" because it didn't add the money.
                // So I will allow it but maybe we should have a log.
                
                $stmt = $db->prepare("SELECT * FROM user_balances WHERE user_id = ? AND symbol = ?");
                $stmt->execute([$req['user_id'], $req['symbol']]);
                $bal = $stmt->fetch();
                
                if ($bal) {
                    $db->prepare("UPDATE user_balances SET available = available + ? WHERE id = ?")
                       ->execute([$final_amount, $bal['id']]);
                } else {
                    $db->prepare("INSERT INTO user_balances (user_id, symbol, available) VALUES (?, ?, ?)")
                       ->execute([$req['user_id'], $req['symbol'], $final_amount]);
                }
                
                // Add to transactions history with the final amount
                $db->prepare("INSERT INTO transactions (user_id, type, amount, symbol, status) VALUES (?, 'recharge', ?, ?, 'completed')")
                   ->execute([$req['user_id'], $final_amount, $req['symbol']]);

                // Update user total_recharge and vip_level based on cumulative approved recharges
                $totalRecharge = getUserTotalRecharge($req['user_id']);
                $newVipLevel = getAutoVipLevel($totalRecharge);
                $db->prepare("UPDATE users SET total_recharge = ?, vip_level = ? WHERE id = ?")
                   ->execute([$totalRecharge, $newVipLevel, $req['user_id']]);
            }
            
            // If withdrawal, update transaction status
            if ($req['type'] === 'withdrawal') {
                $db->prepare("UPDATE transactions SET status = 'completed' WHERE user_id = ? AND type = 'withdrawal' AND amount = ? AND symbol = ? AND status = 0 ORDER BY created_at DESC LIMIT 1")
                   ->execute([$req['user_id'], $req['amount'], $req['symbol']]);
            }
            
            $db->commit();
            header("Location: finance.php?msg=approved");
        } catch (Exception $e) {
            $db->rollBack();
            header("Location: finance.php?error=" . urlencode($e->getMessage()));
        }
        exit;
    }
    
    if ($_POST['action'] === 'reject') {
        $reason = $_POST['reason'] ?? '';
        $db->beginTransaction();
        try {
            $db->prepare("UPDATE finance_requests SET status = '4', rejection_reason = ? WHERE id = ?")
               ->execute([$reason, $id]);
            
            // If withdrawal, return balance
            if ($req['type'] === 'withdrawal') {
                $db->prepare("UPDATE user_balances SET available = available + ? WHERE user_id = ? AND symbol = ?")
                   ->execute([$req['amount'], $req['user_id'], $req['symbol']]);
                   
                $db->prepare("UPDATE transactions SET status = 4 WHERE user_id = ? AND type = 'withdrawal' AND amount = ? AND symbol = ? AND status = 0 ORDER BY created_at DESC LIMIT 1")
                   ->execute([$req['user_id'], $req['amount'], $req['symbol']]);
            }
            
            $db->commit();
            header("Location: finance.php?msg=rejected");
        } catch (Exception $e) {
            $db->rollBack();
            header("Location: finance.php?error=" . urlencode($e->getMessage()));
        }
        exit;
    }
}

$title = '充提管理';
ob_start();

$type = $_GET['type'] ?? 'recharge';
$user_id = isset($_GET['user_id']) ? (int)$_GET['user_id'] : null;

$sql = "SELECT r.*, u.username, u.uid FROM finance_requests r LEFT JOIN users u ON r.user_id = u.id WHERE r.type = ?";
$params = [$type];

if ($admin['is_agent']) {
    $sql .= " AND u.agent_id = ?";
    $params[] = $admin['id'];
}

if ($user_id) {
    $sql .= " AND r.user_id = ?";
    $params[] = $user_id;
}
$sql .= " ORDER BY r.created_at DESC";

$stmt = $db->prepare($sql);
$stmt->execute($params);
$requests = $stmt->fetchAll();
?>

<div class="d-flex justify-content-between align-items-center mb-4">
    <div class="d-flex align-items-center gap-3">
        <a href="<?= $user_id ? 'users.php' : 'index.php' ?>" class="btn btn-outline-secondary btn-sm"><i class="bi bi-arrow-left"></i> 返回</a>
        <h4 class="mb-0"><?= $type === 'recharge' ? '充值审核' : '提现审核' ?> <?= $user_id ? "(用户ID: $user_id)" : "" ?></h4>
        <span class="badge bg-secondary"><?= count($requests) ?> 条记录</span>
    </div>
    <div class="btn-group">
        <a href="?type=recharge" class="btn <?= $type === 'recharge' ? 'btn-primary' : 'btn-outline-primary' ?>">充值审核</a>
        <a href="?type=withdrawal" class="btn <?= $type === 'withdrawal' ? 'btn-primary' : 'btn-outline-primary' ?>">提现审核</a>
    </div>
</div>

<div class="card p-3 mb-4 border-0 shadow-sm card-dismissible card-auto-dismiss" data-card-id="finance_instructions">
    <h6 class="fw-bold mb-2"><i class="bi bi-info-circle me-2"></i>充提管理说明</h6>
    <p class="small text-muted mb-0">在此页面您可以审核用户的充值和提现申请。通过充值申请会自动增加用户余额；通过提现申请则完成资产扣除；拒绝提现申请会自动退回冻结金额。</p>
</div>

<?php if (isset($_GET['msg'])): ?>
    <div class="alert alert-success mb-4">操作成功！</div>
<?php endif; ?>
<?php if (isset($_GET['error'])): ?>
    <div class="alert alert-danger mb-4">错误: <?= htmlspecialchars($_GET['error']) ?></div>
<?php endif; ?>

<div class="table-container">
    <table class="table table-hover align-middle">
        <thead>
            <tr class="text-muted small">
                <th>编号</th>
                <th>用户信息</th>
                <th>金额</th>
                <th>支付信息/详情</th>
                <th>IP地址</th>
                <th>时间</th>
                <th>状态</th>
                <th class="text-end">操作</th>
            </tr>
        </thead>
        <tbody>
            <?php foreach ($requests as $r): ?>
            <tr>
                <td><?= $r['id'] ?></td>
                <td>
                    <div><?= htmlspecialchars($r['username'] ?? '未知用户') ?></div>
                    <code class="small"><?= htmlspecialchars($r['uid'] ?? '---') ?></code>
                </td>
                <td>
                    <?php
                    $display_amount = $r['amount'];
                    $is_recalculated = false;
                    // Only recalculate for pending/matched/account_sent statuses. 
                    // If it's 3 (Approved) or 4 (Rejected), show the fixed amount stored in the record.
                    if ($r['type'] === 'recharge' && !in_array($r['status'], ['3', '4']) && $r['fiat_amount'] > 0 && $r['fiat_currency']) {
                        require_once __DIR__ . '/../includes/exchange.php';
                        $current_rate = get_rate($r['fiat_currency']);
                        if ($current_rate > 0) {
                            $display_amount = $r['fiat_amount'] / $current_rate;
                            $is_recalculated = true;
                        }
                    }
                    ?>
                    <span class="fw-bold <?= $r['type'] === 'recharge' ? 'text-success' : 'text-danger' ?>">
                        <?= $r['type'] === 'recharge' ? '+' : '-' ?> <?= number_format($display_amount, 2) ?> <?= $r['symbol'] ?>
                    </span>
                    <?php if ($is_recalculated): ?>
                        <i class="bi bi-info-circle-fill text-primary" style="font-size: 10px; cursor: help;" title="当前汇率: 1 USDT ≈ <?= $current_rate ?> <?= $r['fiat_currency'] ?>。此金额按实时汇率动态计算，审核通过时将以操作时刻的汇率重新核准。"></i>
                    <?php endif; ?>
                    <?php if ($r['fiat_amount']): ?>
                        <div class="text-muted small">
                            ≈ <?= number_format($r['fiat_amount'], 2) ?> <?= $r['fiat_currency'] ?>
                        </div>
                    <?php endif; ?>
                </td>
                <td>
                    <?php if ($r['type'] === 'recharge'): ?>
                        <div class="small">方法: <?= htmlspecialchars($r['payment_method'] ?? 'USDT') ?></div>
                        <div class="text-muted small">哈希/备注: <?= htmlspecialchars($r['tx_hash'] ?? '无') ?></div>
                    <?php else: ?>
                        <div class="small">提现地址: <code><?= htmlspecialchars($r['payment_details'] ?? '未知') ?></code></div>
                    <?php endif; ?>
                    <?php if ($r['rejection_reason']): ?>
                        <div class="text-danger small mt-1">理由: <?= htmlspecialchars($r['rejection_reason']) ?></div>
                    <?php endif; ?>
                </td>
                <td>
                    <span class="badge bg-light text-dark shadow-sm" style="font-size: 11px;">
                        <i class="bi bi-geo-alt-fill me-1 text-primary"></i><?= htmlspecialchars($r['ip_address'] ?? '---') ?>
                    </span>
                </td>
                <td><small class="text-muted"><?= $r['created_at'] ?></small></td>
                <td>
                    <?php if ($r['status'] === '0' || $r['status'] === 'pending'): ?>
                        <span class="badge bg-secondary">待匹配</span>
                    <?php elseif ($r['status'] === '1' || $r['status'] === 'matched'): ?>
                        <span class="badge bg-info">匹配成功/待发账号</span>
                    <?php elseif ($r['status'] === '2' || $r['status'] === 'account_sent'): ?>
                        <span class="badge bg-warning text-dark">已发账号/待转账</span>
                    <?php elseif ($r['status'] === 'finished'): ?>
                        <span class="badge bg-primary">用户已转账/待审核</span>
                    <?php elseif ($r['status'] === '3' || $r['status'] === 'completed'): ?>
                        <span class="badge bg-success">已通过</span>
                    <?php elseif ($r['status'] === '4' || $r['status'] === 'rejected'): ?>
                        <span class="badge bg-danger">已拒绝</span>
                    <?php else: ?>
                        <span class="badge bg-dark"><?= htmlspecialchars($r['status']) ?></span>
                    <?php endif; ?>
                </td>
                <td>
                    <?php if ($r['status'] === '3' || $r['status'] === '4' || $r['status'] === 'completed' || $r['status'] === 'rejected'): ?>
                        <span class="badge bg-light text-muted border"><?= in_array($r['status'], ['4', 'rejected']) ? '已拒绝' : '已通过' ?></span>
                    <?php else: ?>
                        <div class="btn-group btn-group-sm">
                            <?php if ($r['type'] === 'recharge'): ?>
                                <?php if ($r['status'] === '0' || $r['status'] === 'pending'): ?>
                                    <button type="button" class="btn btn-primary" onclick="submitMatchOnly(<?= $r['id'] ?>)">
                                        匹配成功
                                    </button>
                                <?php elseif ($r['status'] === '1' || $r['status'] === 'matched'): ?>
                                    <button type="button" class="btn btn-info text-white" onclick="showSendModal(<?= $r['id'] ?>, '<?= htmlspecialchars($r['account_bank'] ?? '') ?>', '<?= htmlspecialchars($r['account_name'] ?? '') ?>', '<?= htmlspecialchars($r['account_number'] ?? '') ?>')">
                                        发送账户
                                    </button>
                                <?php elseif ($r['status'] === '2' || $r['status'] === 'account_sent'): ?>
                                    <span class="badge bg-light text-muted border d-flex align-items-center px-2">等待用户转账...</span>
                                <?php elseif ($r['status'] === 'finished'): ?>
                                    <button type="button" class="btn btn-outline-success fw-bold" 
                                        onclick="showApproveModal(<?= $r['id'] ?>, <?= $r['fiat_amount'] ?: 0 ?>, '<?= $r['fiat_currency'] ?: 'USDT' ?>', <?= $display_amount ?>)">
                                        通过
                                    </button>
                                    <button class="btn btn-outline-danger fw-bold ms-1" onclick="showRejectModal(<?= $r['id'] ?>)">拒绝</button>
                                <?php else: ?>
                                    <span class="badge bg-light text-muted border"><?= htmlspecialchars($r['status']) ?></span>
                                <?php endif; ?>
                            <?php else: /* Withdrawal */ ?>
                                <?php if ($r['status'] === '0' || $r['status'] === 'pending' || $r['status'] === 'finished'): ?>
                                    <form method="POST" class="d-inline">
                                        <input type="hidden" name="request_id" value="<?= $r['id'] ?>">
                                        <input type="hidden" name="action" value="approve">
                                        <button type="submit" class="btn btn-outline-success fw-bold" onclick="return confirm('确定要通过该提现申请吗？')">
                                            通过
                                        </button>
                                    </form>
                                    <button class="btn btn-outline-danger fw-bold ms-1" onclick="showRejectModal(<?= $r['id'] ?>)">拒绝</button>
                                <?php else: ?>
                                    <span class="badge bg-light text-muted border"><?= htmlspecialchars($r['status']) ?></span>
                                <?php endif; ?>
                            <?php endif; ?>
                        </div>
                    <?php endif; ?>
                </td>
            </tr>
            <?php endforeach; ?>
            <?php if (empty($requests)): ?>
            <tr><td colspan="8" class="text-center p-5 text-muted">暂无记录</td></tr>
            <?php endif; ?>
        </tbody>
    </table>
</div>

<!-- Send Modal -->
<div class="modal fade" id="sendModal" tabindex="-1">
    <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"></button>
            </div>
            <div class="modal-body">
                <input type="hidden" id="send_id">
                <div class="alert alert-info py-2 small">点击确认后，用户手机端将立即显示以下收款信息。</div>
                <div class="mb-3">
                    <label class="form-label">银行/机构</label>
                    <input type="text" id="send_bank" class="form-control">
                </div>
                <div class="mb-3">
                    <label class="form-label">收款人姓名</label>
                    <input type="text" id="send_name" class="form-control">
                </div>
                <div class="mb-3">
                    <label class="form-label">收款账号</label>
                    <input type="text" id="send_account" class="form-control">
                </div>
                <div class="mb-3">
                    <label class="form-label">备注 (可选)</label>
                    <textarea id="send_note" class="form-control" rows="2" placeholder="转账时请备注用户UID..."></textarea>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                <button type="button" class="btn btn-info text-white" onclick="submitSend()">确认发送</button>
            </div>
        </div>
    </div>
</div>

<!-- Reject Modal -->
<div class="modal fade" id="rejectModal" tabindex="-1">
    <div class="modal-dialog">
        <form class="modal-content" method="POST">
            <input type="hidden" name="action" value="reject">
            <input type="hidden" name="request_id" id="reject_request_id">
            <div class="modal-header">
                <h5 class="modal-title">拒绝请求</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <div class="mb-3">
                    <label class="form-label">拒绝理由</label>
                    <textarea name="reason" class="form-control" rows="3" required placeholder="请填写拒绝理由..."></textarea>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                <button type="submit" class="btn btn-danger">确认拒绝</button>
            </div>
        </form>
    </div>
</div>

<!-- Approve Modal -->
<div class="modal fade" id="approveModal" tabindex="-1">
    <div class="modal-dialog">
        <form class="modal-content" method="POST">
            <input type="hidden" name="action" value="approve">
            <input type="hidden" name="request_id" id="approve_request_id">
            <div class="modal-header">
                <h5 class="modal-title">审核通过并入账</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <div class="alert alert-info py-2 small">
                    <i class="bi bi-info-circle me-1"></i> 请核实用户实际到账金额，确认后资金将立即增加到用户余额。
                </div>
                <div id="approve_fiat_section" style="display:none;">
                    <div class="mb-3">
                        <label class="form-label small text-muted">用户支付 (法币)</label>
                        <div class="input-group">
                            <input type="text" id="approve_fiat_display" class="form-control bg-light" readonly>
                            <span class="input-group-text" id="approve_currency_label"></span>
                        </div>
                    </div>
                </div>
                <div class="mb-3">
                    <label class="form-label fw-bold">到账金额 (USDT)</label>
                    <input type="number" name="final_amount" id="approve_final_amount" class="form-control form-control-lg text-success fw-bold" step="0.01" required>
                    <div class="form-text mt-2" id="approve_rate_info"></div>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                <button type="submit" class="btn btn-success">确认通过并入账</button>
            </div>
        </form>
    </div>
</div>

<script>
async function submitMatchOnly(id) {
    if(!confirm('确定标记为匹配成功吗？')) return;
    const formData = new FormData();
    formData.append('id', id);
    const resp = await fetch('../api/admin_recharge.php?action=match_success', { method: 'POST', body: formData });
    const data = await resp.json();
    if(data.success) location.reload(); else alert(data.error || '操作失败');
}

function showSendModal(id, bank, name, account) {
    document.getElementById('send_id').value = id;
    document.getElementById('send_bank').value = bank;
    document.getElementById('send_name').value = name;
    document.getElementById('send_account').value = account;
    new bootstrap.Modal(document.getElementById('sendModal')).show();
}

async function submitSend() {
    const id = document.getElementById('send_id').value;
    const bank = document.getElementById('send_bank').value;
    const name = document.getElementById('send_name').value;
    const account = document.getElementById('send_account').value;
    const note = document.getElementById('send_note').value;
    
    if(!bank || !name || !account) return alert('请完整填写信息');
    
    const formData = new FormData();
    formData.append('id', id);
    formData.append('bank', bank);
    formData.append('name', name);
    formData.append('account', account);
    formData.append('note', note);
    
    const resp = await fetch('../api/admin_recharge.php?action=send_account', { method: 'POST', body: formData });
    const data = await resp.json();
    if(data.success) location.reload(); else alert(data.error || '操作失败');
}

function showRejectModal(id) {
    document.getElementById('reject_request_id').value = id;
    new bootstrap.Modal(document.getElementById('rejectModal')).show();
}

function showApproveModal(id, fiatAmount, currency, currentUSDT) {
    document.getElementById('approve_request_id').value = id;
    if (fiatAmount > 0) {
        document.getElementById('approve_fiat_section').style.display = 'block';
        document.getElementById('approve_fiat_display').value = Number(fiatAmount).toLocaleString(undefined, {minimumFractionDigits: 2});
        document.getElementById('approve_currency_label').innerText = currency;
        let rate = Number(fiatAmount) / Number(currentUSDT);
        document.getElementById('approve_rate_info').innerText = `参考汇率: 1 USDT ≈ ${rate.toFixed(4)} ${currency}`;
    } else {
        document.getElementById('approve_fiat_section').style.display = 'none';
        document.getElementById('approve_rate_info').innerText = '';
    }
    document.getElementById('approve_final_amount').value = Number(currentUSDT).toFixed(2);
    
    new bootstrap.Modal(document.getElementById('approveModal')).show();
}
</script>

<?php
$content = ob_get_clean();
renderAdminPage($content, $title);
?>
