<?php
// paytm_webhook_receiver_optimized.php

error_reporting(E_ALL);
ini_set('display_errors', 0); // Production mein errors display nahi hone chahiye
ini_set("log_errors", 1);
ini_set("error_log", __DIR__ . "/webhook_error_log.txt");

// --- Configuration Includes (Ensure these paths are correct) ---
define('ROOT_DIR', realpath(dirname(__FILE__)) . '/');
include ROOT_DIR . 'pages/dbFunctions.php';
include ROOT_DIR . 'auth/config.php';
include ROOT_DIR . 'pages/dbInfo.php'; 
// ---------------------------------------------------------------

date_default_timezone_set('Asia/Kolkata');
$currentdt=date('Y-m-d H:i:s');
$d=date('d');
$m=date('m');
$y=date('Y');
$webhookLogFile = "webhook_transaction_log.txt";

// --- STEP 1: IMMEDIATELY SEND 200 OK TO PAYTM ---
// This is the CRITICAL step to prevent 30-60 minute delays due to Retries.
if (isset($_SERVER['REQUEST_METHOD']) && $_SERVER['REQUEST_METHOD'] === 'POST') {
    http_response_code(200);
    header('Connection: close');
    header('Content-Length: 0');
    // Buffer flush: Ensures the header is sent to the client (Paytm) right away.
    if (ob_get_level()) {
        ob_end_flush();
    }
    flush();
} else {
    // Only process POST requests
    exit;
}

// Webhook Data प्राप्त करें
$postData = file_get_contents("php://input");
$receivedData = json_decode($postData, true);

if (empty($receivedData)) {
    file_put_contents($webhookLogFile, date("Y-m-d H:i:s") . " - No valid JSON received." . PHP_EOL, FILE_APPEND);
    exit;
}

// Log the incoming data
file_put_contents($webhookLogFile, date("Y-m-d H:i:s") . " - Received: " . $postData . PHP_EOL, FILE_APPEND);


// --- STEP 2: BACKGROUND PROCESSING STARTS HERE ---
try {
    // Necessary Transaction Data
    $orderId = mysqli_real_escape_string($conn, $receivedData['ORDERID'] ?? null);
    $paytmTxnStatus = $receivedData['STATUS'] ?? null;
    $bankTxnId = mysqli_real_escape_string($conn, $receivedData['BANKTXNID'] ?? null);
    $txnAmount = (float)($receivedData['TXNAMOUNT'] ?? 0);

    if ($paytmTxnStatus !== "TXN_SUCCESS") {
        // Log Non-Success status and exit early to save processing time
        file_put_contents($webhookLogFile, date("Y-m-d H:i:s") . " - Order $orderId: Status is not SUCCESS ($paytmTxnStatus). Skipping wallet update." . PHP_EOL, FILE_APPEND);
        // DB update for FAILED/PENDING can happen here if needed, but not crediting wallet.
        exit; 
    }
    
    // --- A. Update Order Status in DB (orders table) ---
    // Note: Assuming your 'orders' table is in the $conn database or is accessible.
    $sqlOrderUpdate = "UPDATE orders SET status='SUCCESS', utr='$bankTxnId', update_time=NOW() WHERE order_id='$orderId' AND status != 'SUCCESS'";
    $conn->query($sqlOrderUpdate);
    
    if ($conn->affected_rows === 0) {
        // If 0 affected rows, the order was already SUCCESS or ORDERID was wrong/missing.
        file_put_contents($webhookLogFile, date("Y-m-d H:i:s") . " - Order $orderId: Already credited or not found. Exiting." . PHP_EOL, FILE_APPEND);
        exit; 
    }
    
    // --- B. Fetch User details for Wallet Credit ---
    // Find the user token/mobile from the order (You may need to adjust this query)
    $sqlFetchUser = "SELECT user_token, amount, customer_mobile FROM orders WHERE order_id='$orderId'";
    $orderRes = $conn->query($sqlFetchUser)->fetch_assoc();
    
    if (!$orderRes) {
        file_put_contents($webhookLogFile, date("Y-m-d H:i:s") . " - Error: Order data not found for $orderId after update." . PHP_EOL, FILE_APPEND);
        exit;
    }
    
    // ⚠️ CRITICAL STEP: Call your dedicated wallet-adding function/script
    
    // Assuming you move the logic from payment.php into a function or include a dedicated file:
    // This is where you would call your wallet credit logic, which should ensure no duplicate entries.
    
    // --- DUMMY WALLET ADD (Replace with your optimized payment.php logic) ---
    /*
    include 'payment_wallet_logic.php'; 
    $wallet_credited = credit_user_wallet_and_log($orderRes['customer_mobile'], $txnAmount, $orderId, $bankTxnId);
    */
    
    // Since you want full copy-paste, we use a simplified version for wallet update:
    // --- 4. FIND UID using customer_mobile (Assuming users table is in $conn) ---
    $customer_mobile = mysqli_real_escape_string($conn, $orderRes['customer_mobile']);
    $sqlFindUID = "SELECT uid FROM users WHERE uid2='$customer_mobile'";
    $userRes = $conn->query($sqlFindUID)->fetch_assoc();
    $uid = $userRes['uid'] ?? null;
    
    if ($uid) {
        // --- 5. Add to Wallet and Transaction Log ---
        // Wallet Update
        $sqlWallet = "INSERT INTO walletb (uid, amount) VALUES ('$uid', $txnAmount)
                      ON DUPLICATE KEY UPDATE amount = amount + $txnAmount";
        $conn->query($sqlWallet);
        
        // Transaction Log Update (Simplified version)
        $sqlTrans = "INSERT INTO transaction (uid, title, type, amount, date_time, ORD, UTR)
                     VALUES ('$uid', 'Add-Fund (Webhook)', 3, $txnAmount, NOW(), '$orderId', '$bankTxnId')";
        $conn->query($sqlTrans);
        
        file_put_contents($webhookLogFile, date("Y-m-d H:i:s") . " - Order $orderId: Wallet credited successfully via Webhook (UID: $uid, Amt: $txnAmount)." . PHP_EOL, FILE_APPEND);
    } else {
        file_put_contents($webhookLogFile, date("Y-m-d H:i:s") . " - Warning: UID not found for mobile $customer_mobile. Status updated, but wallet not credited." . PHP_EOL, FILE_APPEND);
    }
    
} catch (Throwable $e) {
    file_put_contents(__DIR__ . "/webhook_error_log.txt", date("Y-m-d H:i:s") . " - Exception: " . $e->getMessage() . " (Order $orderId)" . PHP_EOL, FILE_APPEND);
}

$conn->close();
?>