<?php
// cron_nekpay.php — Nekpayment Fast Status Checker & Telegram Alerts (Status String Fix)

// ===============================
// 1. DEBUG (Production me OFF kar dena)
// ===============================
error_reporting(E_ALL);
ini_set('display_errors', 1);
date_default_timezone_set('Asia/Kolkata');

// ===============================
// 2. DATABASE INCLUDE
// ===============================
if (file_exists("includes/config.php")) {
    require_once "includes/config.php";
} elseif (file_exists("../includes/config.php")) {
    require_once "../includes/config.php";
} else {
    die("Config missing");
}

if (!isset($conn) || $conn->connect_error) {
    die("Database connection failed");
}

// ==========================================
// 🚀 TELEGRAM BOT FUNCTION
// ==========================================
function sendTelegramMsg($message) {
    $botToken = "8672231993:AAH2A_Qvw9kwbgHlrfm_5iu440ylm8V19sk";
    $chatId = "-1003897973106";
    
    $url = "https://api.telegram.org/bot{$botToken}/sendMessage";
    $data = [
        'chat_id' => $chatId,
        'text' => $message,
        'parse_mode' => 'HTML'
    ];
    
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_TIMEOUT, 5); 
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_exec($ch);
    curl_close($ch);
}
// ==========================================

echo "🚀 Starting Nekpayment Fast Check...<br>";

// ===============================
// 3. NEKPAY GATEWAY SETTINGS
// ===============================
$merchant_id  = "100333234"; 
$merchant_key = "WFIWVNYBWCSZTHJAVKCVUO3BQ7GOVCSF"; 

$query_url    = "https://api.nekpayment.com/query/transfer"; 

// ===============================
// 4. FETCH PENDING ORDERS
// ===============================
$sql = "SELECT id, mch_transfer_id, amount, user_id, status 
        FROM withdrawals 
        WHERE status IN ('processing','pending') 
        AND mch_transfer_id LIKE 'NKOUT%' 
        ORDER BY id ASC 
        LIMIT 50";

$result = $conn->query($sql);

if (!$result) {
    die("Query Error: " . $conn->error);
}

if ($result->num_rows == 0) {
    die("✅ No pending Nekpayment transactions found.");
}

$count = 0;

// ===============================
// 🔥 HIGH SPEED cURL SETUP
// ===============================
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $query_url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
    'Content-Type: application/x-www-form-urlencoded'
));

// ===============================
// 5. PROCESS LOOP
// ===============================
while ($row = $result->fetch_assoc()) {

    $id = (int)$row['id'];
    $mch_transferId = $row['mch_transfer_id']; 
    $amount = (float)$row['amount'];
    $user_id = (int)$row['user_id'];

    $signStr = "mch_id={$merchant_id}&mch_transferId={$mch_transferId}&key={$merchant_key}";
    $sign = md5($signStr);

    $params = [
        'mch_id'         => $merchant_id,
        'mch_transferId' => $mch_transferId,
        'sign_type'      => 'MD5',
        'sign'           => $sign
    ];

    curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($params));
    $response = curl_exec($ch);

    if (curl_errno($ch)) {
        echo "ID $id: Network Error - " . curl_error($ch) . "<br>";
        continue;
    }

    $json = json_decode($response, true);

    if (!$json || !isset($json['respCode'])) {
        echo "ID $id: Invalid API Response.<br>";
        continue;
    }

    // ===============================
    // STATUS CHECK LOGIC
    // ===============================
    if ($json['respCode'] === 'SUCCESS' && isset($json['tradeResult'])) {
        
        $tradeResult = $json['tradeResult'];
        $tradeNo = isset($json['tradeNo']) ? $json['tradeNo'] : '';

        // ===== SUCCESS (1) =====
        if ($tradeResult == '1') {
            
            // 🔥 YAHAN FIX KIYA HAI: 'successful' ko 'success' kar diya taaki History me show ho
            $stmt = $conn->prepare("UPDATE withdrawals SET status='success', mch_transfer_id=?, updated_at=NOW() WHERE id=? AND status!='success'");
            $stmt->bind_param("si", $tradeNo, $id);
            $stmt->execute();
            
            if ($stmt->affected_rows > 0) {
                echo "ID $id: ✅ Success Updated<br>";
                $count++;

                // 🚀 TELEGRAM SUCCESS MESSAGE
                $msg = "✅ <b>NEKPAY PAYOUT SUCCESS</b>\n";
                $msg .= "━━━━━━━━━━━━━━━━━━\n";
                $msg .= "👤 <b>User ID:</b> " . $user_id . "\n";
                $msg .= "💰 <b>Amount:</b> ₹" . $amount . "\n";
                $msg .= "🆔 <b>Order No:</b> " . $mch_transferId . "\n";
                $msg .= "🕒 <b>Time:</b> " . date('d-M-Y H:i:s');
                sendTelegramMsg($msg);
            }
            $stmt->close();
        }

        // ===== FAILED / DECLINED (2 or 3) + REFUND =====
        elseif ($tradeResult == '2' || $tradeResult == '3') {

            $refund_amount = round($amount / 0.9, 2);
            $conn->begin_transaction();

            try {
                // 🔥 YAHAN FIX KIYA HAI: 'rejected' ko 'failed' kar diya
                $stmt1 = $conn->prepare("UPDATE withdrawals SET status='failed', mch_transfer_id=?, updated_at=NOW() WHERE id=? AND status IN ('pending', 'processing')");
                $stmt1->bind_param("si", $tradeNo, $id);
                $stmt1->execute();
                $updated_rows = $stmt1->affected_rows;
                $stmt1->close();

                if ($updated_rows > 0) {
                    $stmt2 = $conn->prepare("UPDATE users SET income_balance = income_balance + ? WHERE id=?");
                    $stmt2->bind_param("di", $refund_amount, $user_id);
                    $stmt2->execute();
                    $stmt2->close();

                    $conn->commit();
                    echo "ID $id: ❌ Failed (Refunded ₹{$refund_amount})<br>";
                    $count++;

                    // 🚀 TELEGRAM FAILED MESSAGE
                    $msg = "❌ <b>NEKPAY PAYOUT FAILED</b>\n";
                    $msg .= "━━━━━━━━━━━━━━━━━━\n";
                    $msg .= "👤 <b>User ID:</b> " . $user_id . "\n";
                    $msg .= "💰 <b>Withdrawal:</b> ₹" . $amount . "\n";
                    $msg .= "🔄 <b>Refunded to User:</b> ₹" . $refund_amount . "\n";
                    $msg .= "🆔 <b>Order No:</b> " . $mch_transferId . "\n";
                    $msg .= "⚠️ <b>Reason:</b> Bank/Gateway Failed\n";
                    $msg .= "🕒 <b>Time:</b> " . date('d-M-Y H:i:s');
                    sendTelegramMsg($msg);

                } else {
                    $conn->rollback();
                    echo "ID $id: ⚠️ Already Processed (Skipped Refund)<br>";
                }

            } catch (Exception $e) {
                $conn->rollback();
                echo "ID $id: 🚨 DB Refund Error: " . $e->getMessage() . "<br>";
            }
        }
        
        // ===== PROCESSING (0 or 4) =====
        else {
            echo "ID $id: ⏳ Still Processing (Status Code: $tradeResult)...<br>";
        }

    } else {
        $errorMsg = isset($json['errorMsg']) ? $json['errorMsg'] : 'Unknown API Error';
        echo "ID $id: ⚠️ Gateway Error ($errorMsg)<br>";
    }
}

curl_close($ch);
echo "<br>🏁 Batch Finished. Checked $count records.";
?>