<?php
// NiceUPI Webhook Handler - Auto-credit wallet on successful payment
include('../../includes/database.php');

// 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'");
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // ===== STEP 1: Extract data from POST (top-level fields) =====
    $status    = isset($_POST['status']) ? strtoupper(trim($_POST['status'])) : '';
    $order_id  = isset($_POST['order_id']) ? $_POST['order_id'] : '';
    if(empty($order_id)) $order_id = isset($_POST['orderId']) ? $_POST['orderId'] : '';
    if(empty($order_id)) $order_id = isset($_POST['client_txn_id']) ? $_POST['client_txn_id'] : '';
    $amount    = isset($_POST['amount']) ? intval($_POST['amount']) : 0;
    $utr       = isset($_POST['utr']) ? $_POST['utr'] : (isset($_POST['UTR']) ? $_POST['UTR'] : '');
    $remark1   = isset($_POST['remark1']) ? $_POST['remark1'] : '';

    // ===== STEP 2: NiceUPI sends amount/utr/remark1 INSIDE 'result' object =====
    // This was the ROOT CAUSE bug - data is nested, not at top level!
    $result_data = null;
    if(isset($_POST['result'])){
        if(is_array($_POST['result'])){
            $result_data = $_POST['result'];
        } elseif(is_string($_POST['result'])){
            $result_data = json_decode($_POST['result'], true);
        }
    }
    // Also try reading raw JSON body (some gateways send JSON content-type)
    if($result_data === null && empty($amount)){
        $raw_body = file_get_contents('php://input');
        if(!empty($raw_body)){
            $json_body = json_decode($raw_body, true);
            if($json_body && isset($json_body['result'])){
                $result_data = $json_body['result'];
                if(empty($status) && isset($json_body['status'])) $status = strtoupper(trim($json_body['status']));
                if(empty($order_id) && isset($json_body['order_id'])) $order_id = $json_body['order_id'];
            }
        }
    }

    // Extract nested data if top-level is empty
    if($result_data && is_array($result_data)){
        if($amount <= 0 && isset($result_data['amount'])) $amount = intval(floatval($result_data['amount']));
        if(empty($utr)){
            if(isset($result_data['utr'])) $utr = $result_data['utr'];
            elseif(isset($result_data['UTR'])) $utr = $result_data['UTR'];
            elseif(isset($result_data['bankTxnId'])) $utr = $result_data['bankTxnId'];
        }
        if(empty($remark1) && isset($result_data['remark1'])) $remark1 = $result_data['remark1'];
        if(empty($order_id)){
            if(isset($result_data['orderId'])) $order_id = $result_data['orderId'];
            elseif(isset($result_data['order_id'])) $order_id = $result_data['order_id'];
        }
        // Also check inner txnStatus for status confirmation
        if(isset($result_data['txnStatus'])){
            $inner_status = strtoupper(trim($result_data['txnStatus']));
            if(in_array($inner_status, ['COMPLETED','SUCCESS','TXN_SUCCESS','PAID']) && !in_array($status, ['SUCCESS','COMPLETED','TXN_SUCCESS','PAID'])){
                $status = 'SUCCESS';
            }
        }
    }

    // Log webhook data for debugging
    $log_data = date('Y-m-d H:i:s') . " | ALL_POST: " . json_encode($_POST) . " | status: $status | order_id: $order_id | amount: $amount | utr: $utr | remark1: $remark1\n";
    file_put_contents(__DIR__ . '/webhook_log.txt', $log_data, FILE_APPEND | LOCK_EX);

    if (in_array($status, ['SUCCESS','COMPLETED','TXN_SUCCESS','PAID']) && !empty($order_id)) {
        $order_id_safe = mysqli_real_escape_string($conn, $order_id);
        
        // Check if this order exists and is PENDING or wrongly marked FAILED
        $check = mysqli_query($conn, "SELECT * FROM onlinepay WHERE `or id`='$order_id_safe' AND `status` IN ('PENDING','FAILED')");
        
        if($check && mysqli_num_rows($check) > 0){
            $order_data = mysqli_fetch_assoc($check);
            $db_amount = intval($order_data['amount']);
            $userid = $order_data['user id'];
            
            // If amount from webhook is 0, use database amount (trusted)
            if($amount <= 0) $amount = $db_amount;
            
            // Update order status to SUCCESS
            $utr_safe = mysqli_real_escape_string($conn, $utr);
            mysqli_query($conn, "UPDATE onlinepay SET `status`='SUCCESS', `utr`='$utr_safe' WHERE `or id`='$order_id_safe' AND `status` IN ('PENDING','FAILED')");
            
            // Credit wallet using prepared statement (use DB amount - more trustworthy)
            $stmt = mysqli_prepare($conn, "UPDATE usertable SET walletamount = walletamount + ? WHERE userid = ?");
            mysqli_stmt_bind_param($stmt, "is", $db_amount, $userid);
            mysqli_stmt_execute($stmt);
            $affected = mysqli_stmt_affected_rows($stmt);
            mysqli_stmt_close($stmt);
            
            file_put_contents(__DIR__ . '/webhook_log.txt', "CREDITED: Rs.$db_amount to user $userid (affected:$affected) | UTR:$utr\n", FILE_APPEND | LOCK_EX);
            
            http_response_code(200);
            echo json_encode(["status" => "success", "message" => "Wallet credited successfully"]);
        } else {
            // Check if already processed as SUCCESS
            $already = mysqli_query($conn, "SELECT * FROM onlinepay WHERE `or id`='$order_id_safe' AND `status`='SUCCESS'");
            if($already && mysqli_num_rows($already) > 0){
                http_response_code(200);
                echo json_encode(["status" => "ok", "message" => "Order already processed"]);
            } else {
                http_response_code(200);
                echo json_encode(["status" => "ok", "message" => "Order not found"]);
            }
        }
    } else {
        // Payment genuinely failed (status is FAILED/FAILURE etc)
        // Only mark as FAILED if status is explicitly a failure status
        if(!empty($order_id) && in_array($status, ['FAILED','TXN_FAILED','FAILURE','CANCELLED','CANCELED','EXPIRED'])){
            $order_id_safe = mysqli_real_escape_string($conn, $order_id);
            mysqli_query($conn, "UPDATE onlinepay SET `status`='FAILED' WHERE `or id`='$order_id_safe' AND `status`='PENDING'");
            file_put_contents(__DIR__ . '/webhook_log.txt', "MARKED FAILED: order=$order_id status=$status\n", FILE_APPEND | LOCK_EX);
        } else {
            // Unknown status or missing data - DO NOT mark as failed, leave as PENDING
            file_put_contents(__DIR__ . '/webhook_log.txt', "SKIPPED: order=$order_id status=$status amount=$amount (not marking failed)\n", FILE_APPEND | LOCK_EX);
        }
        http_response_code(200);
        echo json_encode(["status" => "received", "message" => "Webhook processed"]);
    }
} else {
    http_response_code(405);
    echo json_encode(["status" => "error", "message" => "Method not allowed"]);
}
?>
