<?php
require_once('../database/header.php');
require_once('../database/config.php');

// Fetch User Data (Logged In User)
$uid = $userdata['id'];
$stmt = $conn->prepare("SELECT * FROM loginusers WHERE id = ?");
$stmt->execute([$uid]);
$usrrow = $stmt->fetch(PDO::FETCH_ASSOC);

// Fetch Merchant Data for RSPay
$merch_stmt = $conn->prepare("SELECT * FROM add_merchant WHERE user = ? AND merchant_name='RSPay'");
$merch_stmt->execute([$usrrow['username']]); 
$merch_data = $merch_stmt->fetch(PDO::FETCH_ASSOC);

// Fetch Global Settings
$set_stmt = $conn->prepare("SELECT * FROM settings LIMIT 1");
$set_stmt->execute();
$settings = $set_stmt->fetch(PDO::FETCH_ASSOC);

// Rate Display Logic based on Gateway
$current_gateway = $settings['default_gateway'] ?? 'rspay';

if ($current_gateway == 'bank_upi') {
    // Show Bank UPI Rates
    $total_payin = floatval($settings['bank_upi_commission'] ?? 0);
    $total_payin_fixed = floatval($settings['bank_upi_fixed'] ?? 0);
    
    $total_payout = floatval($settings['bank_upi_payout_commission'] ?? 0);
    $total_payout_fixed = floatval($settings['bank_upi_payout_fixed'] ?? 0);
} else {
    // RSPay / Default Logic: Base + Margin
    $payin_base = floatval($settings['rspay_payin_base'] ?? 0);
    $payin_margin = floatval($usrrow['payin_commission'] ?? $settings['payin_commission'] ?? 0);
    $total_payin = $payin_base + $payin_margin;

    $payout_base = floatval($settings['rspay_payout_base'] ?? 0);
    $payout_margin = floatval($usrrow['payout_commission'] ?? $settings['payout_commission'] ?? 0);
    $total_payout = $payout_base + $payout_margin;

    // Fixed Fees Calculation
    $payin_fixed_base = floatval($settings['rspay_payin_fixed'] ?? 0);
    $payin_fixed_margin = floatval($settings['payin_fixed'] ?? 0);
    $total_payin_fixed = $payin_fixed_base + $payin_fixed_margin;

    $payout_fixed_base = floatval($settings['rspay_payout_fixed'] ?? 0);
    $payout_fixed_margin = floatval($settings['payout_fixed'] ?? 0);
    $total_payout_fixed = $payout_fixed_base + $payout_fixed_margin;
}

    // --- DYNAMIC BALANCE CALCULATION ---
    // 1. Calculate Net Payins
    $stmt_orders = $conn->prepare("SELECT amount FROM create_orders WHERE txn_status = 'SUCCESS' AND user_id = ?");
    $stmt_orders->execute([$usrrow['id']]);
    
    $sum_payin_net = 0;
    while($ord = $stmt_orders->fetch(PDO::FETCH_ASSOC)) {
         $amt = floatval($ord['amount']);
         $fee = ($amt * ($total_payin / 100)) + $total_payin_fixed;
         $sum_payin_net += ($amt - $fee);
    }
    
    // 2. Calculate Gross Payouts (Amount only - matching index.php logic)
    $sum_payout_deduction = 0;
    try {
        $stmt_payout = $conn->prepare("SELECT SUM(amount) FROM payout_requests WHERE user = ? AND status NOT IN ('REJECTED', 'FAILED')");
        $stmt_payout->execute([$usrrow['username']]);
        $sum_payout_deduction = $stmt_payout->fetchColumn() ?: 0;
    } catch(Exception $e) {
        $sum_payout_deduction = 0;
    }

    $available_balance = $sum_payin_net - $sum_payout_deduction;

// Mask Key
$full_key = $merch_data['access_token'] ?? $usrrow['api_key'] ?? 'N/A';
$masked_key = (strlen($full_key) > 8) ? substr($full_key, 0, 3) . '*****' . substr($full_key, -3) : $full_key;
?>

<div class="main-panel">
    <div class="content-wrapper">
        
        <div class="card shadow-sm border-0 mb-4" style="background:#fff;">
            <div class="card-body">
                <h4 class="card-title text-dark mb-1">
                    <?php echo strtoupper($usrrow['username']); ?> - 信息
                </h4>
                <p class="text-muted small mb-4">pay2inr</p>

                <div class="row">
                    <!-- Column 1 -->
                    <div class="col-md-6 col-lg-4 mb-4">
                        <h6 class="text-secondary small mb-1">账户名称：</h6>
                        <div class="text-dark font-weight-bold"><?php echo htmlspecialchars($usrrow['owner_name'] ?: $usrrow['username']); ?></div>
                    </div>

                    <div class="col-md-6 col-lg-4 mb-4">
                        <h6 class="text-secondary small mb-1">账户余额：</h6>
                        <div class="text-dark font-weight-bold"><?php echo number_format($available_balance ?? 0, 5); ?></div>
                    </div>

                    <div class="col-md-6 col-lg-4 mb-4">
                        <h6 class="text-secondary small mb-1">冻结金额：</h6>
                        <div class="text-dark font-weight-bold">0.00000</div>
                    </div>

                    <!-- Column 2 (Collection Info + Key) -->
                    <div class="col-md-6 col-lg-4 mb-4">
                        <h6 class="text-info small mb-1">收款费率：</h6>
                        <div class="text-dark font-weight-bold"><?php echo htmlspecialchars($total_payin); ?>%</div>
                    </div>
                    
                    <div class="col-md-6 col-lg-4 mb-4">
                        <h6 class="text-info small mb-1">收款固定费：</h6>
                        <div class="text-dark font-weight-bold"><?php echo number_format($total_payin_fixed, 3); ?></div>
                    </div>

                    <div class="col-md-6 col-lg-4 mb-4">
                        <h6 class="text-secondary small mb-1">账户密钥：</h6>
                        <div class="text-dark font-weight-bold"><?php echo htmlspecialchars($masked_key); ?></div>
                    </div>
                    
                    <!-- Column 3 (Payout Info + Telegram) -->
                    <div class="col-md-6 col-lg-4 mb-4">
                        <h6 class="text-danger small mb-1">代付费率：</h6>
                        <div class="text-dark font-weight-bold"><?php echo htmlspecialchars($total_payout); ?>%</div>
                    </div>

                    <div class="col-md-6 col-lg-4 mb-4">
                        <h6 class="text-danger small mb-1">代付固定费：</h6>
                        <div class="text-dark font-weight-bold"><?php echo number_format($total_payout_fixed, 3); ?></div> 
                    </div>

                    <div class="col-md-6 col-lg-4 mb-4">
                        <h6 class="text-secondary small mb-1">Telegram 群组 ID：</h6>
                        <div class="text-dark font-weight-bold"><?php echo htmlspecialchars($usrrow['telegram_id'] ?? '-'); ?></div>
                    </div>

                    <!-- Column 4 (Others) -->
                    <div class="col-md-6 col-lg-4 mb-4">
                        <h6 class="text-secondary small mb-1">代付 IP 白名单：</h6>
                        <div class="text-dark font-weight-bold"><?php echo htmlspecialchars($merch_data['callback_ip'] ?? '未设置'); ?></div>
                    </div>

                    <div class="col-md-6 col-lg-4 mb-4">
                        <h6 class="text-secondary small mb-1">更新时间：</h6>
                        <div class="text-dark font-weight-bold"><?php echo htmlspecialchars($merch_data['last_sync'] ?? $usrrow['date_time']); ?></div>
                    </div>
                    
                    <div class="col-md-6 col-lg-4 mb-4">
                        <h6 class="text-secondary small mb-1">用户类型：</h6>
                        <div class="text-dark font-weight-bold"><?php echo strtoupper($usrrow['usertype']); ?></div>
                    </div>
                </div>

            </div>
        </div>
    </div>
<?php require_once('../database/footer.php'); ?>