<?php
// tp_deposit_cron.php — TopPay Auto Deposit/Recharge Checker (Missed Webhook Fallback)

// ===============================
// 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 Deposit 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     = "https://api.toppay-app.com/api/pay/query/order"; 

// ===============================
// 4. FETCH PENDING DEPOSITS
// ===============================
// Hum sirf pending deposits check karenge jo humne (TOP) se generate kiye the
// Aur jo pichle 1 ghante ke andar bane hain (bohut purane check karne ka fayda nahi)
$sql = "SELECT id, order_no, amount, user_id, status 
        FROM deposits 
        WHERE status = 'pending' 
        AND order_no LIKE 'TOP%' 
        AND created_at >= NOW() - INTERVAL 1 HOUR
        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 deposits found in the last 1 hour.");
}

$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_HTTPHEADER, array('Content-Type: application/json'));
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

// ===============================
// 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'            => 0, // 0 = Collection/Deposit (Important)
        'merchantId'      => (int)$merchant_id,
        'merchantOrderNo' => $mch_order_no
    );

    // --- Signature logic (A-Z sorting) ---
    $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 (Collection status):
        // 0 = Pre-built, 1 = In Cashier, 2 = Payment Successful, 3 = Timeout, 4 = Successful Processing
        $tp_status = (int)$json['data']['status'];

        // ===== SUCCESS (Status 2 or 4 means user paid) =====
        if ($tp_status == 2 || $tp_status == 4) {

            $conn->begin_transaction();
            try {
                // Lock and Update Status (Double Addition Protection)
                $stmt1 = $conn->prepare("UPDATE deposits SET status='successful', updated_at=NOW() WHERE id=? AND status='pending'");
                $stmt1->bind_param("i", $id);
                $stmt1->execute();
                $updated_rows = $stmt1->affected_rows;
                $stmt1->close();

                if ($updated_rows > 0) {
                    // Update user's deposit balance only if deposit row was actually updated right now
                    $stmt2 = $conn->prepare("UPDATE users SET deposit_balance = deposit_balance + ? WHERE id=?");
                    $stmt2->bind_param("di", $amount, $user_id);
                    $stmt2->execute();
                    $stmt2->close();

                    $conn->commit();
                    echo "ID $id (Order $mch_order_no): ✅ Payment Found! Added ₹$amount to UID $user_id.<br>";
                    $count++;
                } else {
                    $conn->rollback();
                    echo "ID $id: ⚠️ Already Processed via Webhook.<br>";
                }
            } catch (Exception $e) {
                $conn->rollback();
                echo "ID $id: 🚨 DB Error while adding balance.<br>";
            }
        }

        // ===== TIMEOUT / FAILED (Status 3) =====
        elseif ($tp_status == 3) {
            $stmt = $conn->prepare("UPDATE deposits SET status='rejected', updated_at=NOW() WHERE id=? AND status='pending'");
            $stmt->bind_param("i", $id);
            $stmt->execute();
            $stmt->close();
            echo "ID $id (Order $mch_order_no): ❌ Timeout/Expired.<br>";
        } else {
            // Status 0 or 1 = User is still on payment page / hasn't paid yet
            echo "ID $id (Order $mch_order_no): ⏳ Waiting for user to pay...<br>";
        }
    } else {
         $msg = $json['message'] ?? 'Unknown Error';
         echo "ID $id: ⚠️ API Error - $msg<br>";
    }
}

// Close cURL
curl_close($ch);

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