<?php
// cron_toppay.php — TopPay Fast Status Checker & Auto-Refund (WITH HTTPS & DEBUG 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");
}

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

// ===============================
// 3. TOPPAY GATEWAY SETTINGS
// ===============================
$merchant_id = 191; 
$secret_key  = "77b900bc099a80be6d2c8ec96d4ee0d1"; 

// 🔥 HTTPS FIX: HTTP ko HTTPS kar diya hai 🔥
$query_url   = "https://api.toppay-app.com/api/pay/query/order"; 

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

// ===============================
// 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 'OUT%' 
        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 TopPay 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, 15); // Timeout thoda badha diya hai
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

// 🔥 REDIRECT FIX: Agar server redirect kare toh cURL follow karega 🔥
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); 

// 🔥 IP BINDING APPLIED 🔥
curl_setopt($ch, CURLOPT_INTERFACE, $server_ip); 

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

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

    // TopPay Request Data for Inquiry
    $data = array(
        'type'            => 1, // 1 = Payout Order Inquiry
        'merchantId'      => (int)$merchant_id,
        'merchantOrderNo' => $mchOrderNo
    );

    // 🚀 STRICT SIGNATURE GENERATION 🚀
    $sign_data = array();
    foreach($data as $key => $val) {
        if($val !== null && $val !== '') {
            $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);

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

    // Send JSON Request exactly as needed
    $payload = json_encode($data, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
    
    // Headers setup inside loop to maintain correct dynamic Content-Length
    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)
    ));
    
    curl_setopt($ch, CURLOPT_POSTFIELDS, $payload);

    $response = curl_exec($ch);
    
    // 🔥 HTTP STATUS LOGGER 🔥
    $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);

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

    $json = json_decode($response, true);

    // 🔥 DETAILED ERROR PRINTING 🔥
    if (!$json || !isset($json['code'])) {
        echo "ID $id: Invalid API Response. HTTP Status: <b>$http_code</b> | Raw Response: ($response)<br>";
        continue;
    }

    // ===============================
    // STATUS CHECK LOGIC
    // ===============================
    if ($json['code'] == 200 && isset($json['data']['status'])) {
        
        $status = (int)$json['data']['status'];
        $count++;

        // ===== SUCCESS (1 or 4) =====
        if ($status === 1 || $status === 4) {
            
            $stmt = $conn->prepare("UPDATE withdrawals SET status='successful' WHERE id=? AND status!='successful'");
            $stmt->bind_param("i", $id);
            $stmt->execute();
            
            if ($stmt->affected_rows > 0) {
                echo "ID $id: ✅ Success Updated<br>";
            } else {
                echo "ID $id: ✅ Already Successful in DB<br>";
            }
            $stmt->close();
        }

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

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

            try {
                $stmt1 = $conn->prepare("UPDATE withdrawals SET status='rejected' 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) {
                    $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>";
                } else {
                    $conn->rollback();
                    echo "ID $id: ⚠️ Already Processed (Skipped Refund)<br>";
                }

            } catch (Exception $e) {
                $conn->rollback();
                echo "ID $id: 🚨 DB Refund Error<br>";
            }
        }
        
        // ===== PROCESSING (0) =====
        elseif ($status === 0) {
            echo "ID $id: ⏳ Still Processing at TopPay end...<br>";
        }

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

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