<?php
ini_set('display_errors', 1);
error_reporting(E_ALL);
// cron_fast.php — High Speed Auto-Check Script
// Isko Cron Job me 1-2 minute par set kar sakte ho.

// 1. Server Settings for Speed
error_reporting(E_ALL);
ini_set('display_errors', 0); // Errors chupao taaki log file na bhare
ini_set('max_execution_time', 0); // Script kabhi timeout nahi hoga
set_time_limit(0);

// 2. Database Include
// Path check kar lena
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");
}

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

// 3. Gateway Settings
$merchant_id   = "100888128"; 
$merchant_key  = "KOROZSWLYD8TI4JYGUNI72RWFJPZHQ1V"; 
$query_url     = "https://api.watchglb.com/query/transfer"; 

// 4. Fetch Pending Orders (Limit 50 to prevent crash)
$sql = "SELECT * FROM withdrawals WHERE status IN ('processing', 'pending') AND mch_transfer_id IS NOT NULL AND mch_transfer_id != '' ORDER BY id ASC LIMIT 50";
$result = $conn->query($sql);

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

$count = 0;

// 5. High Speed Loop
while ($row = $result->fetch_assoc()) {
    $id = $row['id'];
    $mch_transferId = $row['mch_transfer_id'];
    $amount = $row['amount'];
    
    // --- Signature Generation ---
    $signStr = "mch_id=" . $merchant_id . "&mch_transferId=" . $mch_transferId . "&key=" . $merchant_key;
    $sign = md5($signStr);

    $params = array(
        'mch_id' => $merchant_id,
        'mch_transferId' => $mch_transferId,
        'sign_type' => 'MD5',
        'sign' => $sign
    );

    // --- Optimized cURL ---
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $query_url);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($params));
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/x-www-form-urlencoded'));
    
    // 🔥 SPEED SETTINGS
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5); // 5 sec me connect na ho to chhor do
    curl_setopt($ch, CURLOPT_TIMEOUT, 10); // Total 10 sec se zyada wait mat karo
    
    $response = curl_exec($ch);
    $curl_errno = curl_errno($ch);
    curl_close($ch);
    
    if ($curl_errno) {
        echo "ID $id: Network Timeout (Skipped)<br>";
        continue; // Agle order par jao
    }

    $json = json_decode($response, true);

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

        if ($tradeResult == '1') {
            // SUCCESS
            $conn->query("UPDATE withdrawals SET status='success', updated_at=NOW() WHERE id=$id");
            echo "ID $id: <span style='color:green'>Success</span><br>";
            $count++;
            
        } elseif ($tradeResult == '2') {
            // FAILED - REFUND
            if (/* APKI FAILED CONDITION YAHAN HOGI */) {
            $conn->query("UPDATE withdrawals SET status='failed', remark='Gateway Failed' WHERE id=$id");
            
            // 10% cut hone ke baad wale gateway amount ko wapas 100% banana
            // Example: 180 / 0.9 = 200
            $refund_amount = round($amount / 0.9, 2); 
            
            // User ke wallet mein pura $refund_amount add karna
            $conn->query("UPDATE users SET income_balance = income_balance + $refund_amount WHERE id=" . $row['user_id']);
            
            echo "ID $id: <span style='color:red'>Failed (Refunded Full Amount: $refund_amount)</span><br>";
            $count++;
        } else {
            // Processing (Do nothing)
        }
    }
    
    // Note: No 'usleep' here for maximum speed
}

echo "<br>🏁 Batch Finished. Checked $count records.";
?>