<?php
// admin_payout.php — Final Fixed Version
error_reporting(E_ALL);
ini_set('display_errors', 1);

session_start();
// Apne config file ka path check kar lena
include __DIR__ . "/includes/config.php"; 

if (!isset($_SESSION['admin_id'])) { die("Access Denied"); }
if (!isset($_GET['id'])) { die("Invalid Request"); }

$id = (int)$_GET['id'];

// 1. Fetch Request from DB
$stmt = $conn->prepare("SELECT * FROM withdrawals WHERE id=? LIMIT 1");
$stmt->bind_param("i", $id);
$stmt->execute();
$result = $stmt->get_result();
$row = $result->fetch_assoc();

if (!$row) { die("Request not found."); }

if ($row['status'] != 'pending') {
    die("<h3 style='color:red; text-align:center;'>❌ Transaction Already Processed!</h3><a href='withdraw_requests.php'>Go Back</a>");
}

// ==========================================
// 2. CONFIGURATION (Set your details)
// ==========================================
$merchant_id   = "100888128"; 
$merchant_key  = "KOROZSWLYD8TI4JYGUNI72RWFJPZHQ1V"; 
$payout_url    = "https://api.watchglb.com/pay/transfer"; // Check if this URL is correct
$notify_url    = "https://yjedukxqf-most-stable-app.com/payout_callback.php"; 

// ==========================================
// 3. DATA PREPARATION
// ==========================================
$mch_transferId = "WD" . date("YmdHis") . $id; // Unique Order ID
$apply_date     = date('Y-m-d H:i:s');

// Amount Formatting (Ensure 2 decimal places or integer based on gateway requirement)
$amt = (float)$row['amount'];
$transfer_amount = number_format($amt, 2, '.', ''); // Sending as 100.00

// Bank & User Details
// Note: 'bank_code' gateway ke hisaab se hona chahiye. 
// Agar user ka bank code DB me hai to waha se lo, nahi to default.
$bank_code       = "IDPT0001"; 
$receive_account = trim($row['account_number']);
$receive_name    = trim($row['account_holder']);
$remark          = trim($row['ifsc']); // Using IFSC as remark (Optional)

// ==========================================
// 4. SIGNATURE GENERATION (Crucial Step)
// ==========================================

// Order matters! Check doc if 'remark' is needed in signature.
// Adding params to string:
$signStr = "";
$signStr .= "apply_date=" . $apply_date . "&";
$signStr .= "bank_code=" . $bank_code . "&";
$signStr .= "mch_id=" . $merchant_id . "&";
$signStr .= "mch_transferId=" . $mch_transferId . "&";

// NOTE: Notify URL is NOT signed (to avoid mismatch), but sent in POST
// $signStr .= "notify_url=" . $notify_url . "&"; <--- Commented out intentionally

$signStr .= "receive_account=" . $receive_account . "&";
$signStr .= "receive_name=" . $receive_name . "&";
$signStr .= "remark=" . $remark . "&";  
$signStr .= "transfer_amount=" . $transfer_amount;

// Append Key and Hash
$sign = md5($signStr . "&key=" . $merchant_key);

// ==========================================
// 5. SEND REQUEST (cURL)
// ==========================================

$postdata = array(
    'apply_date'      => $apply_date,
    'bank_code'       => $bank_code,
    'mch_id'          => $merchant_id,
    'mch_transferId'  => $mch_transferId,
    'notify_url'      => $notify_url, // ✅ Bheja ja raha hai (Not signed)
    'receive_account' => $receive_account,
    'receive_name'    => $receive_name,
    'remark'          => $remark,
    'transfer_amount' => $transfer_amount,
    'sign_type'       => 'MD5',
    'sign'            => $sign
);

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $payout_url);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($ch, CURLOPT_POST, true);
// Force header to form-urlencoded
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/x-www-form-urlencoded'));
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($postdata));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

$response = curl_exec($ch);
$err = curl_error($ch);
curl_close($ch);

// ==========================================
// 6. HANDLE RESPONSE
// ==========================================

if ($err) {
    echo "cURL Error: $err";
} else {
    $json = json_decode($response, true);
    
    // Debugging: Uncomment line below to see raw response if it fails
    // var_dump($response); 

    // Check for SUCCESS
    if (isset($json['respCode']) && strtoupper($json['respCode']) == 'SUCCESS') {
        
        // --- SUCCESS LOGIC ---
        // 1. Update DB to 'processing'
        // Make sure your table has 'mch_transfer_id' column
        $update = $conn->prepare("UPDATE withdrawals SET status='processing', mch_transfer_id=?, updated_at=NOW() WHERE id=?");
        $update->bind_param("si", $mch_transferId, $id);
        $update->execute();

        echo "<div style='font-family:sans-serif; padding:20px; text-align:center;'>";
        echo "<h2 style='color:green;'>✅ Request Sent Successfully!</h2>";
        echo "<p>Status: <b>Processing</b></p>";
        echo "<p>Transfer ID: $mch_transferId</p>";
        echo "<p>Redirecting...</p>";
        echo "</div>";
        
        echo "<script>setTimeout(function(){ window.location.href='withdrawal.php'; }, 2000);</script>";

    } else {
        // --- FAILURE LOGIC ---
        $msg = isset($json['errorMsg']) ? $json['errorMsg'] : (isset($json['tradeMsg']) ? $json['tradeMsg'] : 'Unknown Error');
        
        echo "<div style='font-family:sans-serif; padding:20px; text-align:center;'>";
        echo "<h3 style='color:red;'>Transaction Failed: $msg</h3>";
        // Auto Refund Logic
$conn->begin_transaction();

try {

    // 1. Mark withdrawal as failed
    $stmt = $conn->prepare("UPDATE withdrawals SET status='failed', remark=? WHERE id=?");
    $stmt->bind_param("si", $msg, $id);
    $stmt->execute();
    $stmt->close();

    // 2. Calculate original amount before 10% deduction
    $refund_amount = round($row['amount'] / 0.9, 2);

    // 3. Refund Balance to User
    $stmt = $conn->prepare("UPDATE users SET income_balance = income_balance + ? WHERE id=?");
    $stmt->bind_param("di", $refund_amount, $row['user_id']);
    $stmt->execute();
    $stmt->close();

    // 4. Commit transaction
    $conn->commit();

    echo "<p style='color:blue;'><b>Amount Refunded to User Wallet automatically.</b></p>";

} catch (Exception $e) {

    // Rollback if error
    $conn->rollback();
    echo "<p>Error processing refund: " . $e->getMessage() . "</p>";

}

echo "<br><a href='withdraw_requests.php'>Go Back</a>";
echo "<br><br><details><summary>Debug Info</summary><pre>$response</pre></details>";
echo "</div>";
}
}
?>
       