<?php
// admin/adminpayout2.php — TopPay Payout Integration with IP Binding & Signature Fix
session_start();
error_reporting(E_ALL);
ini_set('display_errors', 1);

// Config Path
if (file_exists("includes/config.php")) {
    require_once "includes/config.php";
} else {
    require_once "../includes/config.php";
}

// Admin Check
if (!isset($_SESSION['admin_id'])) {
    header("Location: login.php");
    exit();
}

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

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

// =========================================================================
// 🚀 TOPPAY PAYOUT API CONFIGURATION
// =========================================================================
$merchant_id = 191; 
$secret_key  = "77b900bc099a80be6d2c8ec96d4ee0d1"; 

$api_url     = "https://api.toppay-app.com/api/pay/create/order"; 

$protocol = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on') ? "https" : "http";
$domain = $protocol . "://" . $_SERVER['HTTP_HOST'];
$notify_url  = $domain . "/payout_callback.php"; 

// 🔥 SERVER IP BINDING 🔥
$server_ip   = "187.127.128.155"; 
// =========================================================================

// --- 🔒 PREVENT DOUBLE PAYOUT (LOCKING MECHANISM) ---
$conn->begin_transaction();

try {
    $sql = "SELECT w.id, w.amount, w.status, u.id as uid, u.mobile, u.account_holder, u.account_number, u.ifsc, u.bank_name 
            FROM withdrawals w 
            JOIN users u ON w.user_id = u.id 
            WHERE w.id = ? FOR UPDATE";

    $stmt = $conn->prepare($sql);
    $stmt->bind_param("i", $withdraw_id);
    $stmt->execute();
    $req = $stmt->get_result()->fetch_assoc();
    $stmt->close();

    if (!$req) {
        throw new Exception("Withdrawal request not found!");
    }
    
    if ($req['status'] !== 'pending') {
        throw new Exception("This request is already processing, successful, or rejected.");
    }

    $order_no = "OUT" . time() . rand(1000, 9999);
    
    $upd_initial = $conn->prepare("UPDATE withdrawals SET status='processing', mch_transfer_id=? WHERE id=? AND status='pending'");
    $upd_initial->bind_param("si", $order_no, $withdraw_id);
    $upd_initial->execute();
    
    if ($upd_initial->affected_rows === 0) {
        throw new Exception("Failed to acquire lock for processing.");
    }
    $upd_initial->close();

    $conn->commit();

} catch (Exception $e) {
    $conn->rollback();
    $error = $e->getMessage();
    echo "<script>alert('{$error}'); window.location.href='withdraw.php';</script>";
    exit();
}
// --- 🔒 END LOCKING MECHANISM ---


// =========================================================================
// 🚀 PREPARE EXACT 1:1 PAYLOAD & SIGNATURE
// =========================================================================

// Is se extra zeroes hat jayenge (e.g. 100.00 -> 100), aur json_encode bhi wahi karega
$amount = $req['amount'] + 0; 

// TopPay Data Structure 
$data = array(
    'type'            => 1, 
    'merchantId'      => (int)$merchant_id,
    'merchantOrderNo' => trim($order_no),
    'orderAmount'     => $amount, 
    'accountName'     => trim($req['account_holder']),
    'cardNumber'      => trim($req['account_number']),
    'ifsc'            => trim($req['ifsc']),
    'bankName'        => trim($req['bank_name'] ?: "Bank"),
    'notifyUrl'       => trim($notify_url),
    'phone'           => trim($req['mobile']),
    'email'           => trim($req['mobile']) . "@gmail.com",
    'extra'           => "" // Hamesha empty rakho jaisa docs ke example mein hai
);

// 3. Generate Signature (A-Z Sorting)
$sign_data = array();
foreach($data as $key => $val) {
    // Sirf unhi ko sign karo jo empty na hon
    if($val !== null && $val !== '' && $key !== 'sign') {
        $sign_data[$key] = $val; 
    }
}
ksort($sign_data); 

$sign_string = "";
foreach($sign_data as $key => $val) {
    $sign_string .= $key . "=" . $val . "&";
}
$sign_string .= "secret=" . trim($secret_key); 

// MD5 Hash
$data['sign'] = strtolower(md5($sign_string));

// =========================================================================
// 🚀 SEND REQUEST VIA CURL (WITH IP BINDING)
// =========================================================================
$ch = curl_init($api_url);
$payload = json_encode($data, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);

// Ek baar logs me print karne ke liye taaki check ho sake ki exact kya gaya
file_put_contents('toppay_last_request.txt', date('[Y-m-d H:i:s]') . "\nStr: $sign_string\nJSON: $payload\n\n", FILE_APPEND);

curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $payload);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_INTERFACE, $server_ip); 
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_TIMEOUT, 15);

curl_setopt($ch, CURLOPT_HTTPHEADER, array(
    'Content-Type: application/json',
    'Accept: application/json',
    'User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64)',
    'Content-Length: ' . strlen($payload)
));

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

// =========================================================================
// 🚀 HANDLE RESPONSE
// =========================================================================
if ($err) {
    file_put_contents('toppay_payout_error.txt', date('[Y-m-d H:i:s] ') . "cURL Error: $err\n", FILE_APPEND);
    echo "<script>alert('⚠️ Network Error: Request sent but confirmation pending.'); window.location.href='withdraw.php';</script>";
    exit();
}

$res_data = json_decode($response, true);

if ($res_data && isset($res_data['code']) && $res_data['code'] == 200) {
    echo "<script>alert('✅ Payout Sent successfully!'); window.location.href='withdraw.php';</script>";
} else {
    $error_msg = isset($res_data['message']) ? addslashes($res_data['message']) : "Gateway Connection Error";
    
    // Explicit rejection -> Revert to pending
    $conn->query("UPDATE withdrawals SET status='pending', mch_transfer_id=NULL WHERE id={$withdraw_id}");
    file_put_contents('toppay_payout_error.txt', date('[Y-m-d H:i:s] ') . "Error: $response\n", FILE_APPEND);
    
    echo "<script>alert('❌ TopPay Error: {$error_msg}'); window.location.href='withdraw.php';</script>";
}
?>