<?php
// cron_fast.php — Fixed, Fast & Double-Refund Proof

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

// ===============================
// 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");
}

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
// ===============================
$sql = "SELECT id, mch_transfer_id, amount, user_id, status 
        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) {
    die("Query Error: " . $conn->error);
}

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

$count = 0;

// ===============================
// 🔥 HIGH SPEED cURL SETUP (Outside Loop)
// ===============================
$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);

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

    // Signature generate
    $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
    ];

    // Naye params set karo aur execute karo
    curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($params));
    $response = curl_exec($ch);

    if (curl_errno($ch)) {
        echo "ID $id: Network Error<br>";
        continue; // Agle loop me jao, curl_close mat karo
    }

    $json = json_decode($response, true);

    if (!$json) {
        echo "ID $id: Invalid JSON<br>";
        continue;
    }

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

        $tradeResult = $json['tradeResult'];

        // ===== SUCCESS =====
        if ($tradeResult == '1') {

            // Sirf tab update karo agar pehle se success nahi hai
            $stmt = $conn->prepare("UPDATE withdrawals SET status='success', updated_at=NOW() WHERE id=? AND status!='success'");
            $stmt->bind_param("i", $id);
            $stmt->execute();
            
            if ($stmt->affected_rows > 0) {
                echo "ID $id: ✅ Success<br>";
                $count++;
            }
            $stmt->close();
        }

        // ===== FAILED + REFUND =====
        elseif ($tradeResult == '2') {

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

            try {
                // UPDATE karo aur verify karo ki actually update hua hai (Double cron protection)
                $stmt1 = $conn->prepare("UPDATE withdrawals SET status='failed', remark='Gateway Failed', updated_at=NOW() WHERE id=? AND status IN ('pending', 'processing')");
                $stmt1->bind_param("i", $id);
                $stmt1->execute();
                $updated_rows = $stmt1->affected_rows;
                $stmt1->close();

                if ($updated_rows > 0) {
                    // Agar withdrawal sach me Update hua hai, tabhi refund do
                    $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++;
                } else {
                    // Agar already update ho chuka hai kisi aur process se
                    $conn->rollback();
                    echo "ID $id: ⚠️ Already Processed (Skipped Refund)<br>";
                }

            } catch (Exception $e) {
                $conn->rollback();
                echo "ID $id: 🚨 Refund DB Error<br>";
            }
        }
    }
}

// Sab records check hone ke baad end me cURL close karo
curl_close($ch);

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