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

$orderid = $_POST['orderid'];

if(!$orderid) {
    echo "未提供订单 ID。";
    exit;
}

// Check admin or user access
// For security, ideally check session user here, but for now fetching data
// We need to fetch from `payout_requests` table

$stmt = $conn->prepare("SELECT * FROM payout_requests WHERE id = ?");
$stmt->execute([$orderid]);
$order = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$order) {
    echo "未找到交易。";
    exit;
}

// Fetch user data for Rates (Commission)
$mgmt_stmt = $conn->prepare("SELECT * FROM loginusers WHERE username = ?");
$mgmt_stmt->execute([$order['user']]);
$user_data = $mgmt_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);

// Generate formatted values
$status = $order['status'];
$status_display = "处理中";
$txn_status_display = "处理中";
$callback_state = "等待中";
$result_msg = "-";
$status_color = "text-info";

if($status == 'SUCCESS' || $status == 'APPROVED'){
    $status_display = "成功";
    $txn_status_display = "成功";
    $callback_state = "回调成功";
    $result_msg = "支付成功";
    $status_color = "text-success";
} else if($status == 'FAILED' || $status == 'REJECTED'){
    $status_display = "失败";
    $txn_status_display = "失败";
    $callback_state = "回调失败";
    $result_msg = "支付失败";
    $status_color = "text-danger";
}

// IDs
$platform_order_no = !empty($order['platform_id']) ? $order['platform_id'] : (date('YmdHis', strtotime($order['created_at'])) . rand(10000,99999));
$merchant_order_no = !empty($order['merchant_order_id']) ? $order['merchant_order_id'] : (strtotime($order['created_at']) . rand(10000000,99999999));

// Callbacks (Mocked or Real if we had a log)
// Constructing the "Request complete message" as if it was sent to an API
$request_msg = [
    "ext" => "web",
    "amount" => $order['amount'],
    "merchantId" => "INR" . rand(100000, 999999), // Mock ID or fetch from settings
    "accountName" => $order['holder_name'],
    "notifyUrl" => "http://127.0.0.1:9106/apii/back/donothing", // Placeholder
    "merchantOrderId" => $merchant_order_no,
    "type" => "1",
    "accountNumber" => $order['bank_account'],
    "ifscCode" => $order['ifsc'],
    "paymentCurrency" => "INR",
    "bankName" => $order['bank_name'],
    "bankCode" => "",
    "sign" => md5($order['id'] . $order['amount']) // Mock signature
];

// Constructing "Callback message"
$callback_msg = [
    "merchantId" => $request_msg['merchantId'],
    "merchantOrderId" => $merchant_order_no,
    "orderId" => $platform_order_no,
    "amount" => number_format((float)$order['amount'], 2, '.', ''),
    "ext" => "web",
    "paymentCurrency" => "INR",
    "utr" => $order['utr'],
    "failReason" => ($status == 'SUCCESS' ? "支付成功" : "待处理/失败"),
    "state" => ($status == 'SUCCESS' ? 1 : 0),
    "sign" => md5($platform_order_no . $order['utr'])
];

// Rates
// Rates
// Detect if it's a UPI Payout (Bank Name contains UPI or Account contains @)
$is_upi = (stripos($order['bank_name'], 'UPI') !== false) || (strpos($order['bank_account'], '@') !== false);

if ($is_upi) {
    // Bank UPI Payout Logic
    $total_rate = floatval($settings['bank_upi_payout_commission'] ?? 0);
    $total_fixed = floatval($settings['bank_upi_payout_fixed'] ?? 0);
} else {
    // Standard Bank Transfer / RSPay Logic
    $payout_base = floatval($settings['rspay_payout_base'] ?? 0);
    $payout_margin = floatval($user_data['payout_commission'] ?? $settings['payout_commission'] ?? 0);
    $total_rate = $payout_base + $payout_margin;

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


$handling_fee = number_format((float)$order['handling_fee'], 3);

// Dates
$create_time = $order['created_at'];
$mod_time = $order['updated_at'] ?? $create_time; // Fallback
$payment_time = ($status == 'SUCCESS') ? $mod_time : '-'; // Approx
$callback_time = ($status == 'SUCCESS') ? $mod_time : '-';

?>

<style>
    .modal-header { border-bottom: 1px solid #e9ecef; }
    .detail-row { display: flex; border-bottom: 1px solid #f2f2f2; padding: 10px 0; font-size: 13px; }
    .detail-label { width: 35%; font-weight: 600; color: #555; }
    .detail-value { width: 65%; color: #333; word-break: break-word; overflow-wrap: break-word; }
    .section-title { color: #007bff; font-weight: bold; margin-top: 20px; margin-bottom: 10px; font-size: 14px; }
    .json-box { background: #f8f9fa; padding: 8px; border-radius: 4px; font-family: monospace; font-size: 11px; margin-top: 5px; white-space: pre-wrap; word-break: break-all; overflow-wrap: break-word; max-width: 100%; }
    .text-success { color: #28a745 !important; }
    .text-danger { color: #dc3545 !important; }
    .text-info { color: #17a2b8 !important; }
</style>

<div>
    <h5 class="section-title mt-0">代付订单详情</h5>

    <div class="row">
        <!-- Left Column -->
        <div class="col-md-6">
            <div class="detail-row">
                <div class="detail-label">商户订单号</div>
                <div class="detail-value"><?php echo $merchant_order_no; ?></div>
            </div>
            <div class="detail-row">
                <div class="detail-label">订单状态</div>
                <div class="detail-value <?php echo $status_color; ?>"><?php echo $status_display; ?></div>
            </div>
             <div class="detail-row">
                <div class="detail-label">结果</div>
                <div class="detail-value"><?php echo $result_msg; ?></div>
            </div>
            <div class="detail-row">
                <div class="detail-label">货币</div>
                <div class="detail-value">Indian Rupee - INR (₹)</div>
            </div>
            <div class="detail-row">
                <div class="detail-label">商户费率</div>
                <div class="detail-value"><?php echo number_format($total_rate/100, 4); ?></div>
            </div>
             <div class="detail-row">
                <div class="detail-label">商户单笔手续费</div>
                <div class="detail-value"><?php echo number_format($total_fixed, 3); ?></div>
            </div>
            <div class="detail-row">
                <div class="detail-label">附加参数</div>
                <div class="detail-value">: web</div>
            </div>
            <div class="detail-row">
                <div class="detail-label">收款账户</div>
                <div class="detail-value"><?php echo $order['bank_account']; ?></div>
            </div>
             <div class="detail-row">
                <div class="detail-label">银行名称</div>
                <div class="detail-value"><?php echo $order['bank_name']; ?></div>
            </div>
        </div>

        <!-- Right Column -->
        <div class="col-md-6">
             <div class="detail-row">
                <div class="detail-label">平台订单号</div>
                <div class="detail-value"><?php echo $platform_order_no; ?></div>
            </div>
            <div class="detail-row">
                <div class="detail-label">回调状态</div>
                <div class="detail-value"><?php echo $callback_state; ?></div>
            </div>
            <div class="detail-row">
                <div class="detail-label">订单金额</div>
                <div class="detail-value"><?php echo number_format($order['amount'], 3); ?></div>
            </div>
            <div class="detail-row">
                <div class="detail-label">商户</div>
                <div class="detail-value"><?php echo $request_msg['merchantId']; ?></div>
            </div>
            <div class="detail-row">
                <div class="detail-label">商户交易费用</div>
                <div class="detail-value"><?php echo $handling_fee; ?></div>
            </div>
            <div class="detail-row">
                <div class="detail-label">通知地址</div>
                <div class="detail-value"><?php echo $request_msg['notifyUrl']; ?></div>
            </div>
             <div class="detail-row">
                <div class="detail-label">收款人姓名</div>
                <div class="detail-value"><?php echo $order['holder_name']; ?></div>
            </div>
             <div class="detail-row">
                <div class="detail-label">收款人 IFSC</div>
                <div class="detail-value"><?php echo $order['ifsc']; ?></div>
            </div>
             <div class="detail-row">
                <div class="detail-label">银行代码</div>
                <div class="detail-value">-</div>
            </div>
        </div>
    </div>

    <!-- Messages -->
     <h5 class="section-title">请求完成消息</h5>
     <div class="json-box"><?php echo json_encode($request_msg, JSON_UNESCAPED_UNICODE); ?></div>

     <h5 class="section-title">回调消息</h5>
     <div class="json-box"><?php echo json_encode($callback_msg, JSON_UNESCAPED_UNICODE); ?></div>
     
     <div class="row mt-3">
        <div class="col-md-6">
             <div class="detail-row">
                <div class="detail-label">回调信息</div>
                <div class="detail-value">200|"success"</div>
            </div>
            <div class="detail-row">
                <div class="detail-label">UTR</div>
                <div class="detail-value"><?php echo $order['utr'] ? $order['utr'] : '-'; ?></div>
            </div>
             <div class="detail-row">
                <div class="detail-label">创建时间</div>
                <div class="detail-value"><?php echo $create_time; ?></div>
            </div>
        </div>
        <div class="col-md-6">
             <div class="detail-row">
                <div class="detail-label">回调时间</div>
                <div class="detail-value"><?php echo $callback_time; ?></div>
            </div>
             <div class="detail-row">
                <div class="detail-label">支付时间</div>
                <div class="detail-value"><?php echo $payment_time; ?></div>
            </div>
             <div class="detail-row">
                <div class="detail-label">修改时间</div>
                <div class="detail-value"><?php echo $mod_time; ?></div>
            </div>
        </div>
     </div>
</div>
