<?php
session_start();
include('../../includes/database.php');

// NiceUPI Gateway Configuration
$niceupi_token = "f140ca65f39a434a587ced6fa63e9272";
$niceupi_status_url = "https://qr.niceupi.com/api/check-order-status";

// Auto-migrate: add status and utr columns if missing
$col_check = mysqli_query($conn, "SHOW COLUMNS FROM `onlinepay` LIKE 'status'");
if(mysqli_num_rows($col_check) == 0){
    mysqli_query($conn, "ALTER TABLE `onlinepay` ADD COLUMN `status` VARCHAR(20) NOT NULL DEFAULT 'PENDING'");
    mysqli_query($conn, "ALTER TABLE `onlinepay` ADD COLUMN `utr` VARCHAR(50) DEFAULT NULL");
    mysqli_query($conn, "UPDATE `onlinepay` SET `status`='SUCCESS' WHERE `status`='PENDING'");
}

// Log all incoming params for debugging
$all_params = "CALLBACK HIT: " . date('Y-m-d H:i:s') . " | GET: " . json_encode($_GET) . " | POST: " . json_encode($_POST) . " | COOKIE: " . json_encode($_COOKIE) . " | SESSION: " . json_encode(isset($_SESSION['userid']) ? $_SESSION['userid'] : 'none') . "\n";
file_put_contents(__DIR__ . '/payment_log.txt', $all_params, FILE_APPEND | LOCK_EX);

// ========== STEP 1: Find order_id from multiple sources ==========

$order_id = '';

// Source 1: GET/POST parameters (NiceUPI may send in various key names)
$possible_keys = ['order_id', 'orderId', 'client_txn_id', 'txn_id', 'merchantTransactionId', 'txnId', 'orderid'];
foreach($possible_keys as $key){
    if(!empty($_GET[$key])){
        $order_id = trim($_GET[$key]);
        break;
    }
    if(!empty($_POST[$key])){
        $order_id = trim($_POST[$key]);
        break;
    }
}

// Source 2: Cookie (set by addwallet.php before redirect - survives cross-domain)
if(empty($order_id) && !empty($_COOKIE['pending_order_id'])){
    $order_id = trim($_COOKIE['pending_order_id']);
    file_put_contents(__DIR__ . '/payment_log.txt', "Got order_id from COOKIE: $order_id\n", FILE_APPEND | LOCK_EX);
}

// Source 3: Session (may be lost after external redirect, but try)
if(empty($order_id) && isset($_SESSION['userid'])){
    $uid = mysqli_real_escape_string($conn, $_SESSION['userid']);
    $res = mysqli_query($conn, "SELECT `or id` FROM onlinepay WHERE `user id`='$uid' AND `status`='PENDING' ORDER BY id DESC LIMIT 1");
    if($res && mysqli_num_rows($res) > 0){
        $row = mysqli_fetch_assoc($res);
        $order_id = $row['or id'];
        file_put_contents(__DIR__ . '/payment_log.txt', "Got order_id from SESSION user lookup: $order_id\n", FILE_APPEND | LOCK_EX);
    }
}

// Source 4: Cookie user fallback (session lost but cookie has user)
if(empty($order_id) && !empty($_COOKIE['pending_order_user'])){
    $cookie_user = mysqli_real_escape_string($conn, $_COOKIE['pending_order_user']);
    $res = mysqli_query($conn, "SELECT `or id` FROM onlinepay WHERE `user id`='$cookie_user' AND `status`='PENDING' ORDER BY id DESC LIMIT 1");
    if($res && mysqli_num_rows($res) > 0){
        $row = mysqli_fetch_assoc($res);
        $order_id = $row['or id'];
        file_put_contents(__DIR__ . '/payment_log.txt', "Got order_id from COOKIE user lookup: $order_id\n", FILE_APPEND | LOCK_EX);
    }
}

// Source 5: REMOVED - Unsafe fallback that could credit wrong user
// Previously picked any random PENDING order which is dangerous with multiple users

file_put_contents(__DIR__ . '/payment_log.txt', "Final resolved order_id: $order_id\n", FILE_APPEND | LOCK_EX);

if(empty($order_id)){
    file_put_contents(__DIR__ . '/payment_log.txt', "ERROR: No order_id found from any source\n", FILE_APPEND | LOCK_EX);
    header("Location: ../addwallet.php?txn_status=FAILED");
    exit;
}

// Sanitize order_id
$order_id_safe = mysqli_real_escape_string($conn, $order_id);

// Clear the cookies now that we have the order
setcookie('pending_order_id', '', time() - 3600, '/');
setcookie('pending_order_user', '', time() - 3600, '/');

// Check if this order already processed as SUCCESS (possibly by webhook)
$check = mysqli_query($conn, "SELECT * FROM onlinepay WHERE `or id`='$order_id_safe' AND `status`='SUCCESS'");
if($check && mysqli_num_rows($check) > 0){
    file_put_contents(__DIR__ . '/payment_log.txt', "Order $order_id already SUCCESS (credited by webhook)\n", FILE_APPEND | LOCK_EX);
    header("Location: ../addwallet.php?txn_status=SUCCESS");
    exit;
}

// ========== STEP 2: Check if NiceUPI sent status directly in redirect ==========
$direct_status = '';
if(!empty($_GET['txn_status'])) $direct_status = strtoupper(trim($_GET['txn_status']));
elseif(!empty($_GET['status'])) $direct_status = strtoupper(trim($_GET['status']));
elseif(!empty($_POST['txn_status'])) $direct_status = strtoupper(trim($_POST['txn_status']));
elseif(!empty($_POST['status'])) $direct_status = strtoupper(trim($_POST['status']));

// If NiceUPI directly says FAILED, no need to call API
if(in_array($direct_status, ['FAILED','TXN_FAILED','FAILURE','CANCELLED','CANCELED'])){
    mysqli_query($conn, "UPDATE onlinepay SET `status`='FAILED' WHERE `or id`='$order_id_safe' AND `status`='PENDING'");
    file_put_contents(__DIR__ . '/payment_log.txt', "DIRECT STATUS FAILED: $direct_status\n", FILE_APPEND | LOCK_EX);
    header("Location: ../addwallet.php?txn_status=FAILED");
    exit;
}

// ========== STEP 3: Call NiceUPI Check Order Status API with retries ==========
$retry_count = isset($_GET['retry']) ? intval($_GET['retry']) : 0;
$max_retries = 5;
$payment_confirmed = false;
$final_amount = 0;
$final_utr = '';
$final_userid = '';

for($attempt = 0; $attempt < 3; $attempt++){
    if($attempt > 0) sleep(3);
    
    $postData = array(
        "user_token" => $niceupi_token,
        "order_id"   => $order_id
    );
    
    $ch = curl_init($niceupi_status_url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($postData));
    curl_setopt($ch, CURLOPT_TIMEOUT, 30);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    $response = curl_exec($ch);
    $curl_err = curl_error($ch);
    curl_close($ch);
    
    file_put_contents(__DIR__ . '/payment_log.txt', "Attempt ".($attempt+1).": Response: $response | cURL_err: $curl_err\n", FILE_APPEND | LOCK_EX);
    
    if($curl_err) continue;
    
    $responseData = json_decode($response, true);
    if(!$responseData) continue;
    
    // Check outer status (boolean true, int 1, or string variations)
    $api_ok = false;
    if(isset($responseData["status"])){
        $s = $responseData["status"];
        if($s === true || $s === 1 || $s === "1" || (is_string($s) && in_array(strtoupper($s), ['TRUE','SUCCESS','COMPLETED','OK']))){
            $api_ok = true;
        }
    }
    
    if(!$api_ok){
        file_put_contents(__DIR__ . '/payment_log.txt', "API outer status not OK: " . json_encode($responseData["status"] ?? 'null') . "\n", FILE_APPEND | LOCK_EX);
        continue;
    }
    
    // Extract inner result data
    $result_data = array();
    if(isset($responseData["result"]) && is_array($responseData["result"])){
        $result_data = $responseData["result"];
    } elseif(isset($responseData["data"]) && is_array($responseData["data"])){
        $result_data = $responseData["data"];
    }
    
    // Get inner status
    $inner_status = '';
    if(isset($result_data["status"])) $inner_status = strtoupper(trim($result_data["status"]));
    elseif(isset($result_data["txnStatus"])) $inner_status = strtoupper(trim($result_data["txnStatus"]));
    elseif(isset($result_data["txn_status"])) $inner_status = strtoupper(trim($result_data["txn_status"]));
    
    file_put_contents(__DIR__ . '/payment_log.txt', "Inner status: $inner_status\n", FILE_APPEND | LOCK_EX);
    
    // If still pending, retry
    if(in_array($inner_status, ['PENDING','SCANNING','PROCESSING','INITIATED',''])){
        continue;
    }
    
    // If success
    if(in_array($inner_status, ['SUCCESS','COMPLETED','TXN_SUCCESS','PAID'])){
        $api_amount = 0;
        if(isset($result_data["amount"])) $api_amount = intval($result_data["amount"]);
        elseif(isset($result_data["txnAmount"])) $api_amount = intval($result_data["txnAmount"]);
        
        $api_utr = '';
        if(isset($result_data["utr"])) $api_utr = $result_data["utr"];
        elseif(isset($result_data["UTR"])) $api_utr = $result_data["UTR"];
        elseif(isset($result_data["bankTxnId"])) $api_utr = $result_data["bankTxnId"];
        
        if($api_amount > 0){
            $final_amount = $api_amount;
            $final_utr = $api_utr;
            $payment_confirmed = true;
        }
        break;
    }
    
    // If failed status from API
    if(in_array($inner_status, ['FAILED','TXN_FAILED','FAILURE','CANCELLED','CANCELED','EXPIRED'])){
        file_put_contents(__DIR__ . '/payment_log.txt', "API says FAILED: $inner_status\n", FILE_APPEND | LOCK_EX);
        mysqli_query($conn, "UPDATE onlinepay SET `status`='FAILED' WHERE `or id`='$order_id_safe' AND `status`='PENDING'");
        header("Location: ../addwallet.php?txn_status=FAILED");
        exit;
    }
    
    break; // Unknown status, don't retry
}

// ========== STEP 4: If payment still PENDING after API retries, auto-refresh page ==========
if(!$payment_confirmed && $retry_count < $max_retries){
    // Show a waiting page that auto-refreshes
    file_put_contents(__DIR__ . '/payment_log.txt', "Payment not confirmed yet, showing wait page (retry $retry_count/$max_retries)\n", FILE_APPEND | LOCK_EX);
    $next_retry = $retry_count + 1;
    $refresh_url = "callback.php?order_id=" . urlencode($order_id) . "&retry=" . $next_retry;
    ?>
    <!DOCTYPE html>
    <html><head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Verifying Payment...</title>
        <meta http-equiv="refresh" content="5;url=<?php echo htmlspecialchars($refresh_url, ENT_QUOTES, 'UTF-8'); ?>">
        <style>
            body { font-family: Arial, sans-serif; display: flex; justify-content: center; align-items: center; min-height: 100vh; margin: 0; background: #f0f2f5; }
            .box { background: #fff; padding: 40px; border-radius: 12px; text-align: center; box-shadow: 0 4px 15px rgba(0,0,0,0.1); max-width: 400px; }
            .spinner { border: 4px solid #f3f3f3; border-top: 4px solid #28a745; border-radius: 50%; width: 50px; height: 50px; animation: spin 1s linear infinite; margin: 0 auto 20px; }
            @keyframes spin { 0% { transform: rotate(0deg); } 100% { transform: rotate(360deg); } }
            .retry-info { color: #666; font-size: 14px; margin-top: 15px; }
        </style>
    </head><body>
        <div class="box">
            <div class="spinner"></div>
            <h2>Verifying Your Payment...</h2>
            <p>Please wait while we confirm your payment. Do not close this page.</p>
            <p class="retry-info">Checking... attempt <?php echo $next_retry; ?> of <?php echo $max_retries; ?></p>
        </div>
    </body></html>
    <?php
    exit;
}

// ========== STEP 5: Credit wallet if payment confirmed ==========
if($payment_confirmed){
    // Get order from DB - check PENDING and FAILED (webhook may have wrongly marked FAILED)
    $order_check = mysqli_query($conn, "SELECT * FROM onlinepay WHERE `or id`='$order_id_safe' AND `status` IN ('PENDING','FAILED')");
    
    if($order_check && mysqli_num_rows($order_check) > 0){
        $order_data = mysqli_fetch_assoc($order_check);
        $db_amount = intval($order_data['amount']);
        $userid = $order_data['user id'];
        $utr_safe = mysqli_real_escape_string($conn, $final_utr);
        
        // Update order status to SUCCESS
        $upd = mysqli_query($conn, "UPDATE onlinepay SET `status`='SUCCESS', `utr`='$utr_safe' WHERE `or id`='$order_id_safe' AND `status` IN ('PENDING','FAILED')");
        
        if($upd && mysqli_affected_rows($conn) > 0){
            // Credit wallet using prepared statement (safe)
            $stmt = mysqli_prepare($conn, "UPDATE usertable SET walletamount = walletamount + ? WHERE userid = ?");
            mysqli_stmt_bind_param($stmt, "is", $db_amount, $userid);
            mysqli_stmt_execute($stmt);
            mysqli_stmt_close($stmt);
            
            file_put_contents(__DIR__ . '/payment_log.txt', "SUCCESS: Wallet credited Rs.$db_amount for user $userid | UTR: $final_utr\n", FILE_APPEND | LOCK_EX);
            header("Location: ../addwallet.php?txn_status=SUCCESS");
            exit;
        } else {
            file_put_contents(__DIR__ . '/payment_log.txt', "DB UPDATE FAILED or 0 rows: " . mysqli_error($conn) . "\n", FILE_APPEND | LOCK_EX);
        }
    } else {
        // Order might have been already processed by webhook
        $already = mysqli_query($conn, "SELECT * FROM onlinepay WHERE `or id`='$order_id_safe' AND `status`='SUCCESS'");
        if($already && mysqli_num_rows($already) > 0){
            file_put_contents(__DIR__ . '/payment_log.txt', "Order already processed (likely by webhook)\n", FILE_APPEND | LOCK_EX);
            header("Location: ../addwallet.php?txn_status=SUCCESS");
            exit;
        }
        file_put_contents(__DIR__ . '/payment_log.txt', "ERROR: No PENDING/FAILED order found for $order_id_safe after confirmed payment\n", FILE_APPEND | LOCK_EX);
    }
}

// If we reach here, payment failed or verification failed
file_put_contents(__DIR__ . '/payment_log.txt', "FINAL: Redirecting to FAILED\n", FILE_APPEND | LOCK_EX);
header("Location: ../addwallet.php?txn_status=FAILED");
exit;
?>
