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

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

$global_payin_base = floatval($settings['rspay_payin_base'] ?? 0);
$global_payin_fixed_base = floatval($settings['rspay_payin_fixed'] ?? 0);
?>
<div class="main-panel">
<div class="content-wrapper">

 
<!-- DataTales Example -->
<div class="card shadow mb-4">
<div class="card-header py-3 bg-primary">
<h6 class="m-0 font-weight-bold text-white">交易记录</h6>
</div>
<div class="card-body">
        <form method="GET" action="">
            <div class="row mb-3">
                <div class="col-md-3">
                    <label>开始日期</label>
                    <input type="date" name="start_date" class="form-control" value="<?php echo $_GET['start_date'] ?? ''; ?>">
                </div>
                <div class="col-md-3">
                    <label>结束日期</label>
                    <input type="date" name="end_date" class="form-control" value="<?php echo $_GET['end_date'] ?? ''; ?>">
                </div>
                <div class="col-md-3">
                    <label>UTR</label>
                    <input type="text" name="utr" class="form-control" placeholder="Enter UTR" value="<?php echo $_GET['utr'] ?? ''; ?>">
                </div>
                <div class="col-md-3">
                    <label>状态</label>
                    <select name="status" class="form-control">
                        <option value="">All</option>
                        <option value="SUCCESS" <?php echo (isset($_GET['status']) && $_GET['status']=='SUCCESS') ? 'selected' : ''; ?>>Success</option>
                        <option value="PENDING" <?php echo (isset($_GET['status']) && $_GET['status']=='PENDING') ? 'selected' : ''; ?>>Pending</option>
                        <option value="FAILED" <?php echo (isset($_GET['status']) && $_GET['status']=='FAILED') ? 'selected' : ''; ?>>Failed</option>
                    </select>
                </div>
            </div>
            <div class="row mb-3">
                 <div class="col-md-3">
                    <label>平台订单号</label>
                    <input type="text" name="p_order" class="form-control" placeholder="Platform Order No" value="<?php echo $_GET['p_order'] ?? ''; ?>">
                </div>
                <div class="col-md-3">
                    <label>商户订单号</label>
                    <input type="text" name="m_order" class="form-control" placeholder="Merchant Order ID" value="<?php echo $_GET['m_order'] ?? ''; ?>">
                </div>
                <div class="col-md-3 pt-4">
                    <button type="submit" class="btn btn-primary mr-2">查询</button>
                    <a href="transactions.php" class="btn btn-light">重置</a>
                </div>
            </div>
        </form>
<div class="table-responsive">
<table class="table table-bordered" id="order-listing" width="100%" cellspacing="0">
<thead>
<tr>
<th style='display:none;'>SL No.</th>
<th class='text-dark'>创建时间</th>
<th class='text-dark'>订单金额</th>
<th class='text-dark'>支付金额</th>
<th class='text-dark'>手续费</th>
<th class='text-dark'>UTR</th>
<th class='text-dark'>订单状态</th>
<th class='text-dark'>结算状态</th>
<th class='text-dark'>回调状态</th>
<th class='text-dark'>平台订单号</th>
<th class='text-dark'>商户订单号</th>
<th class='text-dark'>订单信息</th>
<th class='text-dark'>支付时间</th>
<th class='text-dark'>回调时间</th>
<th class='text-dark'>操作</th>
</tr>
</thead>
<tbody>
<?php if($userdata['usertype']=="mainadmin") {?>					
<?php
// Join with loginusers to get commission rates
// Join with loginusers to get commission rates - REMOVE specific columns if they don't exist
// Fallback: Select all user columns or just ignore if column names are unknown
$sql = "SELECT co.* 
        FROM create_orders co 
        WHERE 1=1";
$params = [];

if (!empty($_GET['start_date'])) {
    $sql .= " AND co.date >= ?";
    $params[] = $_GET['start_date'] . ' 00:00:00';
}
if (!empty($_GET['end_date'])) {
    $sql .= " AND co.date <= ?";
    $params[] = $_GET['end_date'] . ' 23:59:59';
}
if (!empty($_GET['utr'])) {
    $sql .= " AND co.utr_number LIKE ?";
    $params[] = '%' . $_GET['utr'] . '%';
}
if (!empty($_GET['status'])) {
    $sql .= " AND co.txn_status = ?";
    $params[] = $_GET['status'];
}
if (!empty($_GET['p_order'])) {
    $sql .= " AND co.transactions_id LIKE ?";
    $params[] = '%' . $_GET['p_order'] . '%';
}
if (!empty($_GET['m_order'])) {
    $sql .= " AND co.orderid LIKE ?";
    $params[] = '%' . $_GET['m_order'] . '%';
}

$sql .= " ORDER BY co.id DESC";
$stmt = $conn->prepare($sql);
$stmt->execute($params);

$sl=1;
while($row=$stmt->fetch()) {
    $status = '<span class="badge badge-info">待处理</span>';
    $callback_state = '等待回调';
    $settlement = '<span class="badge badge-secondary">未结算</span>';
    
    if($row['txn_status']== 'Active'){
        $status = '<span class="badge badge-success">活跃</span>';
        $settlement = '<span class="badge badge-success">已结算</span>';
    }
    if($row['txn_status']== 'SUCCESS'){
        $status = '<span class="badge badge-success">成功</span>';
        $callback_state = '<span class="text-success">回调成功</span>';
        $settlement = '<span class="badge badge-success">已结算</span>';
    }
    if($row['txn_status']== 'PENDING'){
        $status = '<span class="badge badge-info">待处理</span>';
    }
    if($row['txn_status']== 'FAILED'){
        $status = '<span class="badge badge-danger">失败</span>';
        $callback_state = '回调失败';
    }

    // Calculate Handling Fee
    // Calculate Handling Fee
    if (stripos($row['merchant_name'], 'Bank UPI') !== false) {
        // Bank UPI Logic
        $b_comm = floatval($settings['bank_upi_commission'] ?? 0);
        $b_fixed = floatval($settings['bank_upi_fixed'] ?? 0);
        $amount = floatval($row['amount']);
        $handling_fee_val = ($amount * ($b_comm / 100)) + $b_fixed;
    } else {
        // RSPay / Default Logic
        $usr_payin_margin = floatval($row['payin_commission'] ?? 0);
        if ($usr_payin_margin == 0 && isset($settings['payin_commission'])) {
             $usr_payin_margin = floatval($settings['payin_commission']);
        }
    
        $total_percent = $global_payin_base + $usr_payin_margin;
        
        // Fixed fee
        $usr_fixed_margin = floatval($row['payin_fixed'] ?? 0); 
        if ($usr_fixed_margin == 0 && isset($settings['payin_fixed'])) {
            $usr_fixed_margin = floatval($settings['payin_fixed']);
        }
        $total_fixed = $global_payin_fixed_base + $usr_fixed_margin;
    
        $amount = floatval($row['amount']);
        $handling_fee_val = ($amount * ($total_percent / 100)) + $total_fixed;
    }
    
    // Only show fee if status is SUCCESS or Active, or always? Usually always based on potential.
    // Format to 3 decimal places as requested
    $handling_fee = number_format($handling_fee_val, 3);
    
    $m_order = $row['orderid']; 
    $p_order = !empty($row['transactions_id']) ? $row['transactions_id'] : (!empty($row['api_txn_id']) ? $row['api_txn_id'] : '-');
    $order_info = !empty($row['customer_name']) ? $row['customer_name'] : '-';

    echo "<tr>
    <td style='display:none;'>".$sl."</td>
    <td class='text-dark' style='font-size:13px'>".$row['date']."</td>
    <td class='text-dark' style='font-size:13px'>".number_format($amount, 2)."</td>
    <td class='text-dark' style='font-size:13px'>".number_format($amount, 2)."</td>
    <td class='text-dark' style='font-size:13px'>".$handling_fee."</td>
    <td class='text-dark' style='font-size:13px'>".(($row['txn_status'] == 'SUCCESS' || $row['txn_status'] == 'Active') ? ($row['utr_number'] ?? '-') : '-')."</td>
    <td class='text-dark'>".$status."</td>
    <td class='text-dark' style='font-size:13px'>".$settlement."</td>
    <td class='text-dark' style='font-size:13px'>".$callback_state."</td>
    <td class='text-dark' style='font-size:13px'>".$p_order."</td>
    <td class='text-dark' style='font-size:13px'>".$m_order."</td>
    <td class='text-dark' style='font-size:13px'>".$order_info."</td>
    <td class='text-dark' style='font-size:13px'>".($row['txn_status'] == 'SUCCESS' ? $row['date'] : '-')."</td>
    <td class='text-dark' style='font-size:13px'>".($row['txn_status'] == 'SUCCESS' ? $row['date'] : '-')."</td>
    <td><button class='btn btn-primary btn-sm btn-details' data-orderid='".$row['orderid']."'>详情</button></td>
    </tr>";
    $sl++;
}							
?>					
<?php
}else{
?>
<?php
// For specific user
// Join with loginusers to get commission rates - REMOVE specific columns if they don't exist
// Fallback: Select all user columns or just ignore if column names are unknown
$sql = "SELECT co.* 
        FROM create_orders co 
        WHERE co.user = ?";
$params = [$userdata['username']];

if (!empty($_GET['start_date'])) {
    $sql .= " AND co.date >= ?";
    $params[] = $_GET['start_date'] . ' 00:00:00';
}
if (!empty($_GET['end_date'])) {
    $sql .= " AND co.date <= ?";
    $params[] = $_GET['end_date'] . ' 23:59:59';
}
if (!empty($_GET['utr'])) {
    $sql .= " AND co.utr_number LIKE ?";
    $params[] = '%' . $_GET['utr'] . '%';
}
if (!empty($_GET['status'])) {
    $sql .= " AND co.txn_status = ?";
    $params[] = $_GET['status'];
}
if (!empty($_GET['p_order'])) {
    $sql .= " AND co.transactions_id LIKE ?";
    $params[] = '%' . $_GET['p_order'] . '%';
}
if (!empty($_GET['m_order'])) {
    $sql .= " AND co.orderid LIKE ?";
    $params[] = '%' . $_GET['m_order'] . '%';
}

$sql .= " ORDER BY co.id DESC";
$stmt = $conn->prepare($sql);
$stmt->execute($params);

$sl=1;
while($row=$stmt->fetch()) {
    $status = '<span class="badge badge-info">待处理</span>';
    $callback_state = '等待回调';
    $settlement = '<span class="badge badge-secondary">未结算</span>';
    
    if($row['txn_status']== 'Active'){
        $status = '<span class="badge badge-success">活跃</span>';
        $settlement = '<span class="badge badge-success">已结算</span>';
    }
    if($row['txn_status']== 'SUCCESS'){
        $status = '<span class="badge badge-success">成功</span>';
        $callback_state = '<span class="text-success">回调成功</span>';
        $settlement = '<span class="badge badge-success">已结算</span>';
    }
    if($row['txn_status']== 'PENDING'){
        $status = '<span class="badge badge-info">待处理</span>';
    }
    if($row['txn_status']== 'FAILED'){
        $status = '<span class="badge badge-danger">失败</span>';
        $callback_state = '回调失败';
    }
    
    // Calculate Handling Fee - Fallback to global settings only since user column failed
    // Or try to fetch user margin another way if needed, but for now safe default
    
    // Calculate Handling Fee
    if (stripos($row['merchant_name'], 'Bank UPI') !== false) {
        // Bank UPI Logic
        $b_comm = floatval($settings['bank_upi_commission'] ?? 0);
        $b_fixed = floatval($settings['bank_upi_fixed'] ?? 0);
        $amount = floatval($row['amount']);
        $handling_fee_val = ($amount * ($b_comm / 100)) + $b_fixed;
    } else {
        // RSPay / Default Logic
        $usr_payin_margin = 0;
        // Check global default margin
        if (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($settings['payin_fixed'])) {
            $usr_fixed_margin = floatval($settings['payin_fixed']);
        }
        $total_fixed = $global_payin_fixed_base + $usr_fixed_margin;
    
        $amount = floatval($row['amount']);
        $handling_fee_val = ($amount * ($total_percent / 100)) + $total_fixed;
    }
    $handling_fee = number_format($handling_fee_val, 3);
    
    $m_order = $row['orderid']; 
    $p_order = !empty($row['transactions_id']) ? $row['transactions_id'] : (!empty($row['api_txn_id']) ? $row['api_txn_id'] : '-');
    $order_info = !empty($row['customer_name']) ? $row['customer_name'] : '-';

    echo "<tr>
    <td style='display:none;'>".$sl."</td>
    <td class='text-dark' style='font-size:13px'>".$row['date']."</td>
    <td class='text-dark' style='font-size:13px'>".number_format($amount, 2)."</td>
    <td class='text-dark' style='font-size:13px'>".number_format($amount, 2)."</td>
    <td class='text-dark' style='font-size:13px'>".$handling_fee."</td>
    <td class='text-dark' style='font-size:13px'>".(($row['txn_status'] == 'SUCCESS' || $row['txn_status'] == 'Active') ? ($row['utr_number'] ?? '-') : '-')."</td>
    <td class='text-dark'>".$status."</td>
    <td class='text-dark' style='font-size:13px'>".$settlement."</td>
    <td class='text-dark' style='font-size:13px'>".$callback_state."</td>
    <td class='text-dark' style='font-size:13px'>".$p_order."</td>
    <td class='text-dark' style='font-size:13px'>".$m_order."</td>
    <td class='text-dark' style='font-size:13px'>".$order_info."</td>
    <td class='text-dark' style='font-size:13px'>".($row['txn_status'] == 'SUCCESS' ? $row['date'] : '-')."</td>
    <td class='text-dark' style='font-size:13px'>".($row['txn_status'] == 'SUCCESS' ? $row['date'] : '-')."</td>
    <td><button class='btn btn-primary btn-sm btn-details' data-orderid='".$row['orderid']."'>详情</button></td>
    </tr>";
    $sl++;
}							
?>
<?php
}
?>
</tbody>
</table>
</div>
</div>
</div>

</div>
<!-- /.container-fluid -->
<!-- End of Main Content -->


<!-- Detailed Transaction Modal -->
<div class="modal fade" id="transactionDetailModal" tabindex="-1" role="dialog" aria-labelledby="transactionDetailModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-lg" role="document" style="max-width: 800px;">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="transactionDetailModalLabel">Order details</h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <div class="modal-body" id="transactionDetailContent">
                <div class="text-center py-5">
                    <div class="spinner-border text-primary" role="status">
                        <span class="sr-only">Loading...</span>
                    </div>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
            </div>
        </div>
    </div>
</div>

<!-- Scripts -->
<script>
document.addEventListener('DOMContentLoaded', function() {
    // We use jQuery because it's already loaded in the admin template usually
    $('.btn-details').on('click', function() {
        var orderid = $(this).data('orderid');
        
        // Show Modal with Loader
        $('#transactionDetailModal').modal('show');
        $('#transactionDetailContent').html('<div class="text-center py-5"><div class="spinner-border text-primary" role="status"><span class="sr-only">Loading...</span></div></div>');
        
        // AJAX Fetch
        $.ajax({
            url: 'get_transaction_details.php',
            type: 'POST',
            data: { orderid: orderid },
            success: function(response) {
                $('#transactionDetailContent').html(response);
            },
            error: function() {
                $('#transactionDetailContent').html('<div class="alert alert-danger">Failed to load details.</div>');
            }
        });
    });
});
</script>

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