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

// Ensure only admin access
if ($userdata['usertype'] != "mainadmin") {
    echo "<script>window.location.href='index.php';</script>";
    exit;
}

// Handle Status Updates
if (isset($_POST['update_status'])) {
    $req_id = $_POST['req_id'];
    $new_status = $_POST['status'];
    $utr = isset($_POST['utr']) ? $_POST['utr'] : '';
    
    // Update status AND UTR if provided
    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]);
    }
}

// Handle Auto Pay
if (isset($_POST['auto_pay'])) {
    $req_id = $_POST['req_id'];
    
    // 1. Fetch Request Details
    $stmt = $conn->prepare("SELECT * FROM payout_requests WHERE id = ?");
    $stmt->execute([$req_id]);
    $req = $stmt->fetch(PDO::FETCH_ASSOC);
    
    // 2. Fetch RSPay Credentials from Settings
    $set_stmt = $conn->prepare("SELECT * FROM settings LIMIT 1");
    $set_stmt->execute();
    $settings = $set_stmt->fetch(PDO::FETCH_ASSOC);
    
    $merchantId = $settings['rspay_merchant_id'] ?? '';
    $key = $settings['rspay_api_key'] ?? '';
    
    if (empty($merchantId) || empty($key)) {
        echo "<script>alert('RSPay Credentials not found in Site Settings!');</script>";
    } else {
        // 3. Prepare API Payload
        $domain = "https://api.rs-pay.cc"; // As per user
        $url = $domain . "/apii/out/createOrder";
        
        $params = [
            'merchantId' => $merchantId,
            'merchantOrderId' => $req['merchant_order_id'] ?? time().$req_id, // Use existing or gen new
            'amount' => number_format((float)$req['amount'], 2, '.', ''), // Two decimals
            'type' => 1, // 1: Bank card/Account
            'paymentCurrency' => 'INR',
            'notifyUrl' => $settings['weburl'] . "/partner/rspay/payout_callback.php", // Callback
            'ext' => 'payout_' . $req_id,
            'accountName' => $req['holder_name'],
            'accountNumber' => $req['bank_account'],
            'ifscCode' => $req['ifsc']
            // 'bankName' => $req['bank_name'] // Optional, usually not required for India if IFSC present
        ];
        
        // 4. Generate Signature
        ksort($params);
        $stringA = "";
        foreach ($params as $k => $v) {
            if ($v !== null && $v !== "") {
                $stringA .= $k . "=" . $v . "&";
            }
        }
        $stringA .= "key=" . $key;
        $params['sign'] = strtolower(hash("sha256", $stringA));
        
        // 5. Send Request
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($params));
        curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
        
        $response = curl_exec($ch);
        $httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);
        
        $res = json_decode($response, true);
        
        // 6. Handle Response
        if (isset($res['status']) && $res['status'] == '200') {
             // Success - Order Placed
             // Update status to PROCESSING (or SUCCESS if instant, but usually it's Processing first)
             // The API returns 'state': 2 (Processing)
             
             // Update UTR if available immediately? Usually not. Platform ID?
             $orderId = $res['data']['orderId'] ?? '';
             
             $upd = $conn->prepare("UPDATE payout_requests SET status = 'PROCESSING', platform_id = ? WHERE id = ?");
             $upd->execute([$orderId, $req_id]);
             
             echo "<script>alert('Auto Payout Initiated Successfully! Order ID: $orderId'); window.location.href='admin-payout-requests.php';</script>";
             
        } else {
             $msg = $res['message'] ?? 'Unknown Error';
             echo "<script>alert('Payout Failed: $msg');</script>";
        }
    }
}
?>

<div class="main-panel">
    <div class="content-wrapper">
        <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">
                <div class="table-responsive">
                    <table class="table table-bordered" id="dataTable" width="100%" cellspacing="0">
                        <thead>
                            <tr>
                                <th>ID</th>
                                <th>用户</th>
                                <th>银行</th>
                                <th>金额</th>
                                <th>持卡人姓名</th>
                                <th>账号</th>
                                <th>IFSC码</th>
                                <th>日期</th>
                                <th>状态</th>
                                <th>操作</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php
                            try {
                                $stmt = $conn->query("SELECT * FROM payout_requests ORDER BY id DESC");
                                while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
                                    $statusColor = 'info';
                                    if ($row['status'] == 'APPROVED' || $row['status'] == 'SUCCESS') $statusColor = 'success';
                                    if ($row['status'] == 'REJECTED' || $row['status'] == 'FAILED') $statusColor = 'danger';
                            ?>
                                <tr>
                                    <td><?php echo $row['id']; ?></td>
                                    <td><?php echo htmlspecialchars($row['user']); ?></td>
                                    <td><?php echo htmlspecialchars($row['bank_name'] ?? ''); ?></td>
                                    <td>₹<?php echo number_format($row['amount'], 2); ?></td>
                                    <td><?php echo htmlspecialchars($row['holder_name']); ?></td>
                                    <td><?php echo htmlspecialchars($row['bank_account']); ?></td>
                                    <td><?php echo htmlspecialchars($row['ifsc']); ?></td>
                                    <td><?php echo $row['created_at']; ?></td>
                                    <td><span class="badge badge-<?php echo $statusColor; ?>"><?php echo $row['status']; ?></span></td>
                                    <td>
                                        <?php if ($row['status'] == 'PENDING') { ?>
                                        <form method="POST" style="display:inline-block;" onsubmit="return confirm('确定要通过RSPay API自动付款吗？这将从您的商户账户中扣除资金。');">
                                            <input type="hidden" name="req_id" value="<?php echo $row['id']; ?>">
                                            <button type="submit" name="auto_pay" class="btn btn-warning btn-sm" style="color:#000;">自动支付</button>
                                        </form>
                                        
                                        <form method="POST" style="display:inline-block;">
                                            <input type="hidden" name="req_id" value="<?php echo $row['id']; ?>">
                                            <input type="hidden" name="status" value="SUCCESS">
                                            <input type="hidden" name="utr" id="utr_<?php echo $row['id']; ?>">
                                            <button type="submit" name="update_status" class="btn btn-success btn-sm" onclick="var u=prompt('请输入 UTR 订单号 #<?php echo $row['id']; ?>'); if(u){ document.getElementById('utr_<?php echo $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="<?php echo $row['id']; ?>">
                                            <input type="hidden" name="status" value="FAILED">
                                            <button type="submit" name="update_status" class="btn btn-danger btn-sm">拒绝</button>
                                        </form>
                                        <?php } else { echo "已完成"; } ?>
                                    </td>
                                </tr>
                            <?php
                                }
                            } catch (PDOException $e) {
                                echo "<tr><td colspan='9'>Table 'payout_requests' not found or empty.</td></tr>";
                            }
                            ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
    <!-- content-wrapper ends -->
    <?php require_once('../database/footer.php'); ?>
</div>
