<?php
// tpcron.php — TopPay Auto Status Checker & 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 TopPay Cron Check...<br><br>";

// ===============================
// 3. TOPPAY GATEWAY SETTINGS
// ===============================
$merchant_id   = 191; // YAHAN APNI MERCHANT ID DAALEIN
$secret_key    = "77b900bc099a80be6d2c8ec96d4ee0d1"; // YAHAN APNA SECRET KEY DAALEIN
$query_url     = "http://api.toppay-app.com/api/pay/query/order"; 

// ===============================
// 4. FETCH PENDING PAYOUTS
// ===============================
// Hum un payouts ko check karenge jo 'processing' me hain aur jinka order_no (TopPay ID) hai
$sql = "SELECT id, order_no, amount, user_id, status 
        FROM withdrawals 
        WHERE status = 'processing' 
        AND order_no IS NOT NULL 
        AND order_no != '' 
        ORDER BY id ASC 
        LIMIT 50"; // Ek baar mein max 50 records taaki load na pade

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

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

if ($result->num_rows == 0) {
    die("✅ No pending TopPay payouts 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);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));

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

    $id = (int)$row['id'];
    $mch_order_no = $row['order_no'];
    $amount = (float)$row['amount'];
    $user_id = (int)$row['user_id'];

    // --- Prepare Payload for Order Inquiry ---
    $data = array(
        'type'            => 1, // 1 for Payout
        'merchantId'      => (int)$merchant_id,
        'merchantOrderNo' => $mch_order_no
    );

    // --- Signature logic (A-Z sorting without empty vals) ---
    $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=" . $secret_key;
    
    $data['sign'] = strtolower(md5($sign_string));

    // Send JSON Request
    $payload = json_encode($data);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $payload);
    $response = curl_exec($ch);

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

    $json = json_decode($response, true);

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

    // ===============================
    // STATUS CHECK BASED ON TOPPAY DOCS
    // ===============================
    if (isset($json['code']) && $json['code'] == 200 && isset($json['data']['status'])) {
        
        // As per Section 1.5 of TopPay docs (Payout status):
        // 0 = Payment, 1 = Order matched but no callback, 2 = Payment failed, 3 = Dismissed/Rejection, 4 = Successful
        $tp_status = (int)$json['data']['status'];

        // ===== SUCCESS (Status 4 or 1 can be considered success depending on gateway logic, usually 4 is final success) =====
        if ($tp_status == 4 || $tp_status == 1) {

            $stmt = $conn->prepare("UPDATE withdrawals SET status='successful', updated_at=NOW() WHERE id=? AND status='processing'");
            $stmt->bind_param("i", $id);
            $stmt->execute();
            
            if ($stmt->affected_rows > 0) {
                echo "ID $id (Order $mch_order_no): ✅ Successful<br>";
                $count++;
            }
            $stmt->close();
        }

        // ===== FAILED / REJECTED (Status 2 or 3) -> DO REFUND =====
        elseif ($tp_status == 2 || $tp_status == 3) {

            $refund_amount = round($amount / 0.9, 2); // 10% tax adjustment if you took it earlier
            $conn->begin_transaction();

            try {
                // UPDATE karo aur verify karo ki actually update hua hai (Double cron protection)
                $stmt1 = $conn->prepare("UPDATE withdrawals SET status='rejected', updated_at=NOW() WHERE id=? AND status='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 (Order $mch_order_no): ❌ Failed/Rejected (Refunded ₹$refund_amount)<br>";
                    $count++;
                } else {
                    $conn->rollback();
                    echo "ID $id: ⚠️ Already Processed (Skipped Refund)<br>";
                }

            } catch (Exception $e) {
                $conn->rollback();
                echo "ID $id: 🚨 Refund DB Error<br>";
            }
        } else {
            // Status 0 = Still paying/processing
            echo "ID $id (Order $mch_order_no): ⏳ Still Processing...<br>";
        }
    } else {
         $msg = $json['message'] ?? 'Unknown Error';
         echo "ID $id: ⚠️ API Error - $msg<br>";
    }
}

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

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