<?php
require_once('../database/header.php');
?>
<?php
// Ensure columns exist for Payouts
try { $conn->exec("ALTER TABLE payout_requests ADD COLUMN utr VARCHAR(255)"); } catch(PDOException $e){}
try { $conn->exec("ALTER TABLE payout_requests ADD COLUMN handling_fee DECIMAL(10,2) DEFAULT 0.00"); } catch(PDOException $e){}
try { $conn->exec("ALTER TABLE payout_requests ADD COLUMN bank_name VARCHAR(255)"); } catch(PDOException $e){}
?>
<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="payout-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'>收款账户</th>
<th class='text-dark'>IFSC代码</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>
</tr>
</thead>
<tbody>
<?php if($userdata['usertype']=="mainadmin") {?>					
<?php
try {
    $sql = "SELECT * FROM payout_requests WHERE 1=1";
    $params = [];

    if (!empty($_GET['start_date'])) {
        $sql .= " AND created_at >= ?";
        $params[] = $_GET['start_date'] . ' 00:00:00';
    }
    if (!empty($_GET['end_date'])) {
        $sql .= " AND created_at <= ?";
        $params[] = $_GET['end_date'] . ' 23:59:59';
    }
    if (!empty($_GET['utr'])) {
        $sql .= " AND utr LIKE ?";
        $params[] = '%' . $_GET['utr'] . '%';
    }
    if (!empty($_GET['status'])) {
        $sql .= " AND status = ?";
        $params[] = $_GET['status'];
    }
    if (!empty($_GET['p_order'])) {
        $sql .= " AND id LIKE ?";
        $params[] = '%' . $_GET['p_order'] . '%';
    }

    // Handle Status Updates (Inline Admin Action)
    if (isset($_POST['update_status']) && $userdata['usertype'] == 'mainadmin') {
        $req_id = $_POST['req_id'];
        $new_status = $_POST['status'];
        $utr = isset($_POST['utr']) ? $_POST['utr'] : '';
        
        if($new_status == 'SUCCESS' && !empty($utr)) {
             $stmt = $conn->prepare("UPDATE payout_requests SET status = ?, utr = ? WHERE id = ?");
             $stmt->execute([$new_status, $utr, $req_id]);
        } else {
             $stmt = $conn->prepare("UPDATE payout_requests SET status = ? WHERE id = ?");
             $stmt->execute([$new_status, $req_id]);
        }
        echo "<script>window.location.href='payout-transactions.php';</script>";
        exit;
    }

    $sql .= " ORDER BY id DESC";
    $stmt = $conn->prepare($sql);
    $stmt->execute($params);
    $sl=1;
    while($row=$stmt->fetch()) {
        $statusVal = strtoupper($row['status']);
        $status = '<span class="badge badge-info text-white">待处理</span>'; // Lowercase text as requested
        $callback_state = "等待中"; 
        $result_msg = "-";
        
        if($statusVal == 'SUCCESS' || $statusVal == 'APPROVED'){
            $status = '<span class="badge badge-success">成功</span>';
            $callback_state = "回调成功";
            $result_msg = "付款成功";
        }
        if($statusVal == 'PENDING'){
            $status = '<span class="badge badge-info text-white">处理中</span>';
        }
        if($statusVal == 'FAILED' || $statusVal == 'REJECTED'){
            $status = '<span class="badge badge-danger">失败</span>';
            $callback_state = "回调失败"; // Or kept same if manual
            $result_msg = "付款失败";
        }

        $handling_fee = number_format(floatval($row['handling_fee'] ?? 0), 3); 
        $order_amount = number_format(floatval($row['amount']), 3);
        
        $utr = isset($row['utr']) ? $row['utr'] : '-';
        $merchant_order_no = !empty($row['merchant_order_id']) ? $row['merchant_order_id'] : 
                             (isset($row['order_id']) ? $row['order_id'] : ("ORD" . $row['id']));
        
        // Use stored platform_id if available, otherwise generate a consistent looking one based on ID or random for display
        $platform_order_no = !empty($row['platform_id']) ? $row['platform_id'] : (date('YmdHis', strtotime($row['created_at'])) . rand(10000,99999));
        
        $beneficiary = isset($row['holder_name']) ? $row['holder_name'] : '-'; 
        if($beneficiary == '-') $beneficiary = $row['bank_name'] ?? 'Bank';
        
        // Try to use updated_at if it exists, else created_at
        $mod_time = isset($row['updated_at']) ? $row['updated_at'] : $row['created_at'];

    
        echo "<tr>
        <td style='display:none;'>".$sl."</td>
        <td class='text-dark' style='font-size:13px'>".$row['created_at']."</td>
        <td class='text-dark' style='font-size:13px'>".$order_amount."</td>
        <td class='text-dark' style='font-size:13px'>".$handling_fee."</td>
        <td class='text-dark' style='font-size:13px'>".$beneficiary."</td>
        <td class='text-dark' style='font-size:13px'>".$row['bank_account']."</td>
        <td class='text-dark' style='font-size:13px'>".$row['ifsc']."</td>
        <td class='text-dark' style='font-size:13px'>".$utr."</td>
        <td class='text-dark' style='font-size:13px'>".$platform_order_no."</td>
        <td class='text-dark' style='font-size:13px'>".$merchant_order_no."</td>
        <td class='text-dark'>".$status."</td>
        <td class='text-dark' style='font-size:13px'>".$callback_state."</td>
        <td class='text-dark' style='font-size:13px'>".$result_msg."</td>
        <td class='text-dark' style='font-size:13px'>".$mod_time."</td>
        <td>
            <button class='btn btn-primary btn-sm mx-1 btn-details' data-orderid='".$row['id']."'>详情</button>";
            
            if ($statusVal == 'PENDING') {
                echo "
                <form method='POST' style='display:inline-block;'>
                    <input type='hidden' name='req_id' value='".$row['id']."'>
                    <input type='hidden' name='status' value='SUCCESS'>
                    <input type='hidden' name='utr' id='utr_".$row['id']."'>
                    <button type='submit' name='update_status' class='btn btn-success btn-sm mx-1' onclick=\"var u=prompt('请输入 UTR #".$row['id']."'); if(u){ document.getElementById('utr_".$row['id']."').value=u; return true; } else { return false; }\">批准</button>
                </form>
                <form method='POST' style='display:inline-block;'>
                    <input type='hidden' name='req_id' value='".$row['id']."'>
                    <input type='hidden' name='status' value='FAILED'>
                    <button type='submit' name='update_status' class='btn btn-danger btn-sm mx-1'>拒绝</button>
                </form>";
            }
            
        echo "</td>
        </tr>";
        $sl++;
    }
} catch (PDOException $e) {
    echo "<tr><td colspan='14' class='text-center'>No records found.</td></tr>";
}
?>					
<?php
}else{
?>
<?php
try {
    $sql = "SELECT * FROM payout_requests WHERE user = ?";
    $params = [$userdata['username']];

    if (!empty($_GET['start_date'])) {
        $sql .= " AND created_at >= ?";
        $params[] = $_GET['start_date'] . ' 00:00:00';
    }
    if (!empty($_GET['end_date'])) {
        $sql .= " AND created_at <= ?";
        $params[] = $_GET['end_date'] . ' 23:59:59';
    }
    if (!empty($_GET['utr'])) {
        $sql .= " AND utr LIKE ?";
        $params[] = '%' . $_GET['utr'] . '%';
    }
    if (!empty($_GET['status'])) {
        $sql .= " AND status = ?";
        $params[] = $_GET['status'];
    }
    if (!empty($_GET['p_order'])) {
        $sql .= " AND id LIKE ?";
        $params[] = '%' . $_GET['p_order'] . '%';
    }

    $sql .= " ORDER BY id DESC";
    $stmt = $conn->prepare($sql);
    $stmt->execute($params);
    $sl=1;
    while($row=$stmt->fetch()) {
        $statusVal = strtoupper($row['status']);
        $status = '<span class="badge badge-info text-white">待处理</span>';
        $callback_state = "等待中";
        $result_msg = "-";

        if($statusVal == 'SUCCESS' || $statusVal == 'APPROVED'){
            $status = '<span class="badge badge-success">成功</span>';
            $callback_state = "回调成功";
            $result_msg = "付款成功";
        }
        if($statusVal == 'PENDING'){
            $status = '<span class="badge badge-info text-white">处理中</span>';
        }
        if($statusVal == 'FAILED' || $statusVal == 'REJECTED'){
            $status = '<span class="badge badge-danger">失败</span>';
            $callback_state = "回调失败";
            $result_msg = "付款失败";
        }

        $handling_fee = number_format(floatval($row['handling_fee'] ?? 0), 3); 
        $order_amount = number_format(floatval($row['amount']), 3);
        
        $utr = isset($row['utr']) ? $row['utr'] : '-';
        
        // Use stored specific merchant order ID, or order_id, or fallback to generated one
        // Check 'merchant_order_id' column first
        $merchant_order_no = !empty($row['merchant_order_id']) ? $row['merchant_order_id'] : 
                             (isset($row['order_id']) ? $row['order_id'] : (strtotime($row['created_at']) . rand(10000000,99999999)));
        
        // Use stored platform_id if available, otherwise generate a consistent looking one based on ID or random for display
        $platform_order_no = !empty($row['platform_id']) ? $row['platform_id'] : (date('YmdHis', strtotime($row['created_at'])) . rand(10000,99999));
        
        $beneficiary = isset($row['holder_name']) ? $row['holder_name'] : '-';
        if($beneficiary == '-') $beneficiary = $row['bank_name'] ?? 'Bank';
        
        $mod_time = isset($row['updated_at']) ? $row['updated_at'] : $row['created_at'];

        echo "<tr>
        <td style='display:none;'>".$sl."</td>
        <td class='text-dark' style='font-size:13px'>".$row['created_at']."</td>
        <td class='text-dark' style='font-size:13px'>".$order_amount."</td>
        <td class='text-dark' style='font-size:13px'>".$handling_fee."</td>
        <td class='text-dark' style='font-size:13px'>".$beneficiary."</td>
        <td class='text-dark' style='font-size:13px'>".$row['bank_account']."</td>
        <td class='text-dark' style='font-size:13px'>".$row['ifsc']."</td>
        <td class='text-dark' style='font-size:13px'>".$utr."</td>
        <td class='text-dark' style='font-size:13px'>".$platform_order_no."</td>
        <td class='text-dark' style='font-size:13px'>".$merchant_order_no."</td>
        <td class='text-dark'>".$status."</td>
        <td class='text-dark' style='font-size:13px'>".$callback_state."</td>
        <td class='text-dark' style='font-size:13px'>".$result_msg."</td>
        <td class='text-dark' style='font-size:13px'>".$mod_time."</td>
        <td><button class='btn btn-primary btn-sm btn-details' data-orderid='".$row['id']."'>详情</button></td>
        </tr>";
        $sl++;
    }
} catch (PDOException $e) {
     echo "<tr><td colspan='14' class='text-center'>No records found.</td></tr>";
}
?>
<?php
}
?>
</tbody>
</table>
</div>
</div>
</div>

</div>
<!-- /.container-fluid -->

<!-- Detailed Payout Modal -->
<div class="modal fade" id="payoutDetailModal" tabindex="-1" role="dialog" aria-labelledby="payoutDetailModalLabel" 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="payoutDetailModalLabel">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="payoutDetailContent">
                <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() {
    // Event delegation for dynamically generated buttons or normal bind
    $('body').on('click', '.btn-details', function() { // specific class for payout details
        var orderid = $(this).data('orderid');
        
        // Show Modal with Loader
        $('#payoutDetailModal').modal('show');
        $('#payoutDetailContent').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_payout_details.php',
            type: 'POST',
            data: { orderid: orderid },
            success: function(response) {
                $('#payoutDetailContent').html(response);
            },
            error: function() {
                $('#payoutDetailContent').html('<div class="alert alert-danger">Failed to load details.</div>');
            }
        });
    });
});
</script>

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