<?php
// admin/adminpayout3.php — Nekpayment Payout Integration with Double-Click Protection
session_start();
error_reporting(E_ALL);
ini_set('display_errors', 1);
date_default_timezone_set('Asia/Kolkata');

// 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'];

// =========================================================================
// 🚀 NEKPAYMENT PAYOUT API CONFIGURATION
// =========================================================================
$mch_id       = "100333234"; // Aapki Nekpay Merchant ID
$merchant_key = "WFIWVNYBWCSZTHJAVKCVUO3BQ7GOVCSF"; // Aapki Nekpay Secret Key

$api_url      = "https://api.nekpayment.com/pay/transfer"; 

$domain = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http") . "://" . $_SERVER['HTTP_HOST'];
// Callback for Payouts
$back_url     = $domain . "/nekpay_payout_callback.php"; 
// =========================================================================

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

try {
    // 1. Fetch Withdrawal & User Bank Details with Row Lock (FOR UPDATE)
    $sql = "SELECT w.id, w.amount, w.status, u.id as uid, u.account_holder, u.account_number, u.ifsc 
            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!");
    }
    
    // STRICT CHECK: Sirf 'pending' wale hi aage jayenge.
    if ($req['status'] !== 'pending') {
        throw new Exception("This request is already processing, successful, or rejected.");
    }

    // 2. Mark as 'processing' immediately BEFORE hitting API
    $mch_transferId = "NKOUT" . time() . rand(1000, 9999);
    
    // ✅ FIX 1: order_no ki jagah mch_transfer_id laga diya hai
    $upd_initial = $conn->prepare("UPDATE withdrawals SET status='processing', mch_transfer_id=? WHERE id=? AND status='pending'");
    $upd_initial->bind_param("si", $mch_transferId, $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 = addslashes($e->getMessage());
    echo "<script>alert('{$error}'); window.location.href='withdraw.php';</script>";
    exit();
}
// --- 🔒 END LOCKING MECHANISM ---


// =========================================================================
// 🚀 NOW WE HIT THE NEKPAY API 
// =========================================================================

$amount = number_format((float)$req['amount'], 2, '.', ''); 
$apply_date = date("Y-m-d H:i:s");

// 💡 Nekpay Strict Rule: Name > 5 chars, NO numbers, NO special characters
$clean_name = preg_replace('/[^a-zA-Z\s]/', '', $req['account_holder']); // Sirf letters aur space bachenge
$clean_name = trim($clean_name);
if (strlen($clean_name) <= 5) {
    $clean_name = "Customer " . $clean_name; // Agar 5 letter se chota hai, toh "Customer" laga do
}

$data = array(
    'apply_date'      => $apply_date,
    'back_url'        => $back_url,
    'bank_code'       => 'IDPT0001', // Fixed value as per Nekpay Docs
    'mch_id'          => $mch_id,
    'mch_transferId'  => $mch_transferId,
    'receive_account' => $req['account_number'],
    'receive_name'    => $clean_name,
    'remark'          => $req['ifsc'], // IFSC code Nekpay mein remark field me jata hai
    'transfer_amount' => $amount
);

// 3. Generate Signature (Nekpay A-Z Sorting + key appending Rule)
ksort($data); 

$sign_string = "";
foreach($data as $key => $val) {
    if($val !== null && $val !== '') {
        $sign_string .= $key . "=" . $val . "&";
    }
}
$sign_string .= "key=" . $merchant_key; // Nekpay requires &key=...

// Add sign and sign_type back to data array for POST
$data['sign'] = md5($sign_string);
$data['sign_type'] = "MD5";

// 4. Send API Request via cURL (x-www-form-urlencoded format)
$ch = curl_init($api_url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data)); // HTTP_BUILD_QUERY is required for Nekpay
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 10.0; Win64; x64)'); 
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
    'Content-Type: application/x-www-form-urlencoded'
));
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);

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

if ($err) {
    // cURL failure
    // ✅ FIX 2: order_no ko mch_transfer_id se replace kiya
    $conn->query("UPDATE withdrawals SET status='pending', mch_transfer_id=NULL WHERE id={$withdraw_id}");
    file_put_contents('nekpay_payout_error.txt', date('[Y-m-d H:i:s] ') . "cURL Error for ID {$withdraw_id}: $err\n", FILE_APPEND);
    echo "<script>alert('❌ Connection Error with Nekpayment. Please try again.'); window.location.href='withdraw.php';</script>";
    exit();
}

$res_data = json_decode($response, true);

// 5. Handle Response
if ($res_data && isset($res_data['respCode']) && $res_data['respCode'] === 'SUCCESS') {
    
    // API Hit Success! 
    // ✅ FIX 3: Hum mch_transfer_id ko overwrite nahi kar rahe taaki Cron aur Callback hamara NKOUT id pakad sakein!
    
    echo "<script>alert('✅ Payout Sent to Nekpayment successfully! Status is Processing.'); window.location.href='withdraw.php';</script>";
} else {
    // API Failed - REVERT STATUS BACK TO PENDING
    // ✅ FIX 4: order_no ko mch_transfer_id se replace kiya
    $conn->query("UPDATE withdrawals SET status='pending', mch_transfer_id=NULL WHERE id={$withdraw_id}");

    $error_msg = isset($res_data['errorMsg']) ? addslashes($res_data['errorMsg']) : "Unknown Gateway Error";
    
    // Log error for debugging
    file_put_contents('nekpay_payout_error.txt', date('[Y-m-d H:i:s] ') . "Error for ID {$withdraw_id}: $response\n", FILE_APPEND);
    
    echo "<script>alert('❌ Nekpayment Error: {$error_msg}'); window.location.href='withdraw.php';</script>";
}
?>