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

if (!isset($_SESSION['username'])) {
    echo "未授权";
    exit;
}

if (!isset($_POST['orderid'])) {
    echo "无效请求";
    exit;
}

$orderid = $_POST['orderid'];
$username = $_SESSION['username'];

// 1. Fetch Order Details from create_orders
$stmt = $conn->prepare("SELECT * FROM create_orders WHERE orderid = ?");
$stmt->execute([$orderid]);
$order = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$order) {
    echo "未找到订单";
    exit;
}

// Security Check: If not admin, ensure order belongs to user
$is_admin = false;
// Fetch user details to check type
$ustmt = $conn->prepare("SELECT usertype FROM loginusers WHERE username = ?");
$ustmt->execute([$username]);
$u_res = $ustmt->fetch();
if ($u_res && $u_res['usertype'] == 'mainadmin') {
    $is_admin = true;
}

if (!$is_admin && $order['user'] != $username) {
    echo "拒绝访问";
    exit;
}

// 2. Fetch User Details (Link through user field in order)
// The order has 'user' column which corresponds to username in loginusers
$stmt_user = $conn->prepare("SELECT * FROM loginusers WHERE username = ?");
$stmt_user->execute([$order['user']]);
$user_data = $stmt_user->fetch(PDO::FETCH_ASSOC);

// 3. Fetch Callback Log
$stmt_log = $conn->prepare("SELECT * FROM callback_logs WHERE order_id = ? ORDER BY id DESC LIMIT 1");
$stmt_log->execute([$order['orderid']]);
$log = $stmt_log->fetch(PDO::FETCH_ASSOC);

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

// Fee Calculation Logic (Copied/Adapted from transactions.php)
// Fee Calculation Logic (Copied/Adapted from transactions.php)
if (stripos($order['merchant_name'], 'Bank UPI') !== false) {
    // Bank UPI Logic
    $total_percent = floatval($settings['bank_upi_commission'] ?? 0);
    $total_fixed = floatval($settings['bank_upi_fixed'] ?? 0);
} else {
    // RSPay / Default Logic
    $global_payin_base = floatval($settings['rspay_payin_base'] ?? 0);
    $global_payin_fixed_base = floatval($settings['rspay_payin_fixed'] ?? 0);

    $usr_payin_margin = 0; // Default
    if (isset($user_data['payin_commission'])) {
         $usr_payin_margin = floatval($user_data['payin_commission']);
    } elseif (isset($settings['payin_commission'])) {
         $usr_payin_margin = floatval($settings['payin_commission']);
    }

    $total_percent = $global_payin_base + $usr_payin_margin;

    $usr_fixed_margin = 0;
    if (isset($user_data['payin_fixed'])) {
        $usr_fixed_margin = floatval($user_data['payin_fixed']);
    } elseif (isset($settings['payin_fixed'])) {
        $usr_fixed_margin = floatval($settings['payin_fixed']);
    }
    $total_fixed = $global_payin_fixed_base + $usr_fixed_margin;
}

$amount = floatval($order['amount']);
$fee_amount = ($amount * ($total_percent / 100)) + $total_fixed;


// PREPARE DATA FOR DISPLAY

// Mappings
$merchant_order_no = $order['orderid'];
$platform_order_no = $order['transactions_id'] ? $order['transactions_id'] : ($order['api_txn_id'] ?? ''); // Fallback with null coalescing
$status_str = strtolower($order['txn_status']); 
$status_display = "processing";
if($status_str == 'success') $status_display = '<span class="text-success">成功</span>';
elseif($status_str == 'failed') $status_display = '<span class="text-danger">失败</span>';
elseif($status_str == 'pending') $status_display = '<span class="text-warning">待处理</span>';
else $status_display = $status_str;

$callback_state = (($order['callback_sent'] ?? 0) == 1) ? "回调成功" : "等待回调";
if($status_str == 'failed') $callback_state = "回调失败 (或未发送)";
// Overwrite if log exists
if($log) {
    if($log['http_code'] == 200) $callback_state = "回调成功";
    else $callback_state = "回调失败 (HTTP {$log['http_code']})";
}

$order_amount = number_format($amount, 3);
$payment_amount = number_format($amount, 3); // Assuming full payment
$currency = "Indian Rupee - INR (₹)";

// Merchants ID? Use a dummy or fetch from add_merchant if needed. 
// User screenshot 'INR222836'. Let's check 'add_merchant' or just use 'user' column prefixed or similar
$merchants_display = strtoupper($order['user']); 
// Try to get specific merchant ID from add_merchant
$m_stmt = $conn->prepare("SELECT merchant_id FROM add_merchant WHERE user = ? LIMIT 1");
$m_stmt->execute([$order['user']]);
$m_row = $m_stmt->fetch();
if($m_row && $m_row['merchant_id']) {
    $merchants_display = $m_row['merchant_id'];
}

$merchant_rates = number_format($total_percent, 4);
$merchant_txn_fees = number_format($amount * ($total_percent/100), 3);
$merchant_fixed_fee = number_format($total_fixed, 3);

$notify_address = $user_data['callback_url'] ?? 'N/A';
$redirect_address = 'N/A'; // Usually passed dynamically, maybe not stored. Just placeholder or check logs.
// Log sent_data might have redirect_url?
$req_msg = "";
$cb_msg = "";
$cb_time = "N/A";
$cb_info = "N/A";

if($log) {
    if(isset($log['sent_data'])) {
        $cb_msg = $log['sent_data'];
        $json_cb = json_decode($cb_msg, true);
        if(isset($json_cb['notifyUrl'])) $notify_address = $json_cb['notifyUrl'];
        // if(isset($json_cb['redirectUrl'])) $redirect_address = $json_cb['redirectUrl']; // If it existed in outgoing payload
    }
    $cb_time = $log['created_at'];
    $cb_info = $log['http_code'] . "|" . ($log['http_code']==200 ? 'success' : 'failed');
}

// Construct a fake/reconstructed Request Message if actual one isn't stored
$req_complete_msg_arr = [
    "merchantId" => $merchants_display,
    "merchantOrderId" => $merchant_order_no,
    "amount" => $order_amount,
    "type" => 2,
    "paymentCurrency" => "INR",
    "userName" => $order['user'],
    "sign" => "****************" 
];
$req_complete_msg = json_encode($req_complete_msg_arr);


$utr = ($status_str == 'success' || $status_str == 'active') ? ($order['utr_number'] ?? 'N/A') : 'N/A';
$payment_time = ($order['txn_status'] == 'SUCCESS') ? $order['date'] : 'N/A'; // Or use modified column if exists
$creation_time = $order['date'];
$modified_time = $order['date']; // Often same in simple schemas unless 'updated_at' exists.

?>

<style>
    .detail-row {
        display: flex;
        padding: 5px 0;
        border-bottom: 1px solid #eee;
    }
    .detail-label {
        width: 35%;
        font-weight: 500;
        color: #555;
    }
    .detail-value {
        width: 65%;
        color: #333;
        word-break: break-word;
        overflow-wrap: break-word;
    }
    .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%;
    }
</style>

<div class="container-fluid">
    <div class="row">
        <!-- Left Column -->
        <div class="col-md-6">
            <h6 class="text-primary mb-3">订单详情</h6>
            
            <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_display; ?></div>
            </div>
             <div class="detail-row">
                <div class="detail-label">订单信息</div>
                <div class="detail-value"><?php echo !empty($order['customer_name']) ? $order['customer_name'] : '-'; ?></div>
            </div>
             <div class="detail-row">
                <div class="detail-label">支付金额</div>
                <div class="detail-value"><?php echo $payment_amount; ?></div>
            </div>
             <div class="detail-row">
                <div class="detail-label">商户</div>
                <div class="detail-value"><?php echo $merchants_display; ?></div>
            </div>
             <div class="detail-row">
                <div class="detail-label">商户交易费用</div>
                <div class="detail-value"><?php echo $merchant_txn_fees; ?></div>
            </div>
             <div class="detail-row">
                <div class="detail-label">通知地址</div>
                <div class="detail-value"><?php echo $notify_address; ?></div>
            </div>
             <div class="detail-row"> // Add Params
                <div class="detail-label">附加参数</div>
                <div class="detail-value">test</div>
            </div>
            
        </div>
        
        <!-- Right Column -->
        <div class="col-md-6 text-right-md-custom"> 
             <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 $order_amount; ?></div>
            </div>
             <div class="detail-row">
                <div class="detail-label">货币</div>
                <div class="detail-value"><?php echo $currency; ?></div>
            </div>
             <div class="detail-row">
                <div class="detail-label">商户费率</div>
                <div class="detail-value"><?php echo $merchant_rates; ?></div>
            </div>
             <div class="detail-row">
                <div class="detail-label">商户单笔手续费</div>
                <div class="detail-value"><?php echo $merchant_fixed_fee; ?></div>
            </div>
             <div class="detail-row">
                <div class="detail-label">重定向地址</div>
                <div class="detail-value"><?php echo $redirect_address; ?></div>
            </div>
        </div>
    </div>
    
    <div class="row mt-3">
        <div class="col-md-12">
            <h6 class="text-primary mb-3">消息</h6>
            
            <div class="mb-3">
                <div class="detail-label mb-1">请求完成消息</div>
                <div class="json-box"><?php echo $req_complete_msg; ?></div>
            </div>
            
             <div class="mb-3">
                <div class="detail-label mb-1">回调消息</div>
                <div class="json-box"><?php echo $cb_msg ? htmlspecialchars($cb_msg) : '{}'; ?></div>
            </div>
        </div>
    </div>
    
    <div class="row mt-3">
        <div class="col-md-6">
            <div class="detail-row">
                <div class="detail-label">回调信息</div>
                <div class="detail-value"><?php echo $cb_info; ?></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 $modified_time; ?></div>
            </div>
        </div>
        <div class="col-md-6">
             <div class="detail-row">
                <div class="detail-label">回调时间</div>
                <div class="detail-value"><?php echo $cb_time; ?></div>
            </div>
             <div class="detail-row">
                <div class="detail-label">UTR</div>
                <div class="detail-value"><?php echo $utr; ?></div>
            </div>
             <div class="detail-row">
                <div class="detail-label">创建时间</div>
                <div class="detail-value"><?php echo $creation_time; ?></div>
            </div>
        </div>
    </div>

    <div class="row mt-3">
        <?php if ($is_admin): ?>
        <div class="col-md-12 text-center">
            <h6 class="text-primary mb-3">管理员操作</h6>
            <!-- Only show actions for pending/processing transactions -->
            <?php if (strtolower($status_str) == 'pending' || strtolower($status_str) == 'processing'): ?>
                <button class="btn btn-success mr-2" onclick="updateStatus('SUCCESS')">批准 (Approve)</button>
                <button class="btn btn-danger" onclick="updateStatus('FAILED')">拒绝 (Reject)</button>
            <?php else: ?>
                <div class="alert alert-secondary">此订单已处理 (<?php echo $status_str; ?>)</div>
            <?php endif; ?>
        </div>
        
        <script>
        function updateStatus(newStatus) {
            if(!confirm('确定要更改状态为 ' + newStatus + '?')) return;
            
            $.ajax({
                url: 'update_transaction_status.php',
                type: 'POST',
                data: {
                    orderid: '<?php echo $orderid; ?>',
                    status: newStatus
                },
                dataType: 'json',
                success: function(data) {
                    if(data.status == 'success') {
                        alert('更新成功!');
                        window.location.reload(true); // Force reload
                    } else {
                        alert('更新失败: ' + (data.message || '未知错误'));
                    }
                },
                error: function(xhr, status, error) {
                    console.error(xhr.responseText);
                    alert('网络错误: ' + error);
                }
            });
        }
        </script>
        <?php endif; ?>
    </div>

</div>
