<?php
ini_set('display_errors', 0); // Suppress errors to ensure clean JSON
error_reporting(E_ALL);
header('Content-Type: application/json');

require_once('../../database/config.php');

// Output Buffering to prevent unwanted output
ob_start();

try {
    $encodedData = $_POST['data'] ?? '';
    $utr_number = $_POST['utr_number'] ?? '';

    if (empty($encodedData) || empty($utr_number)) {
        throw new Exception('Encoded data or UTR number is missing', 400);
    }

    // 1. Check if UTR exists
    $stmt = $conn->prepare("SELECT id FROM create_orders WHERE utr_number = ? AND txn_status = 'SUCCESS'");
    $stmt->execute([$utr_number]);
    if ($stmt->fetch()) {
        throw new Exception('UTR is already used for a successful transaction', 409);
    }

    // 2. Decode Data
    $decodedData = base64_decode($encodedData);
    if ($decodedData === false) {
        throw new Exception('Failed to decode data', 400);
    }
    parse_str($decodedData, $params);
    $orderid = $params['orderid'] ?? '';
    
    // Log decoded params for debugging (optional, can be removed)
    // file_put_contents(__DIR__ . '/submit_debug.log', "Decoded: " . print_r($params, true));

    if (empty($orderid)) {
        throw new Exception('Invalid Order Data', 400);
    }

    // 3. Fetch Order
    $stmt = $conn->prepare("SELECT * FROM create_orders WHERE orderid = ?");
    $stmt->execute([$orderid]);
    $order = $stmt->fetch(PDO::FETCH_ASSOC);

    if (!$order) {
        throw new Exception('Order not found', 404);
    }

    if ($order['txn_status'] == 'SUCCESS') {
        ob_clean();
        echo json_encode(['status_code' => 200, 'status' => 'Success', 'message' => 'Order already successful']);
        exit;
    }

    $order_amount = $order['amount'];
    $current_upi_id = $order['upi_id'];

    // 4. Identify Merchant and Attempt Verification
    $verification_status = 'PENDING';
    $verified_amount = 0;
    $txn_id = '';
    $api_response_msg = 'Verification skipped or not available';

    // Check for BharatPe logic...
    // Removed check by upi_id as the column might not exist or be reliable
    $bpStmt = $conn->prepare("SELECT * FROM add_merchant WHERE user = ? AND merchant_name = 'Bharatpe' AND status = 'Active'");
    $bpStmt->execute([$order['user']]);
    $bpMerchant = $bpStmt->fetch(PDO::FETCH_ASSOC);

    // Check for Paytm logic...
    $ptStmt = $conn->prepare("SELECT * FROM add_merchant WHERE user = ? AND merchant_name = 'Paytm' AND status = 'Active'");
    $ptStmt->execute([$order['user']]);
    $ptMerchant = $ptStmt->fetch(PDO::FETCH_ASSOC);

    if ($bpMerchant) {
        // BharatPe Verification
        if (!function_exists('curl_init')) {
            throw new Exception('cURL extension missing');
        }
        $merchant_id = $bpMerchant['merchant_id'];
        $access_token = $bpMerchant['access_token'];
        $apiUrl = "https://smartupi.in.net/merchantapi/bharatpe/payment-status.php?merchant_id=$merchant_id&access_token=$access_token&bank_reference_no=$utr_number";
        
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $apiUrl);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        $response = curl_exec($ch);
        $curl_err = curl_error($ch);
        curl_close($ch);
        
        if (!$curl_err) {
            $apiResponse = json_decode($response, true);
            if ($apiResponse && isset($apiResponse['status']) && $apiResponse['status'] == 'success') {
                $api_amount = $apiResponse['amount'] ?? 0;
                if (floatval($api_amount) >= floatval($order_amount)) {
                    $verification_status = 'SUCCESS';
                    $verified_amount = $api_amount;
                    $txn_id = $apiResponse['transaction_id'] ?? $utr_number;
                    $api_response_msg = 'BharatPe Verification Successful';
                } else {
                    $api_response_msg = "Amount Mismatch: Order $order_amount vs API $api_amount";
                }
            } else {
                 $api_response_msg = isset($apiResponse['message']) ? $apiResponse['message'] : 'BharatPe API returned failure';
            }
        }
    } elseif ($ptMerchant) {
        // Paytm Verification
        if (!function_exists('curl_init')) {
            throw new Exception('cURL extension missing');
        }
        $paytm_mid = $ptMerchant['paytm_mid'];
        $apiUrl = 'https://smartupi.in.net/merchantapi/paytm/payment-status.php';
        $data = ['mid' => $paytm_mid, 'order_id' => $orderid];
        
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $apiUrl);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data)); // Ensure http_build_query usage
        $response = curl_exec($ch);
        $curl_err = curl_error($ch);
        curl_close($ch);
        
        if (!$curl_err) {
            $apiResponse = json_decode($response, true);
            if ($apiResponse && isset($apiResponse['status_code']) && $apiResponse['status_code'] == 200 && isset($apiResponse['transactionId'])) {
                $api_utr = $apiResponse['UTR'] ?? '';
                $api_amount = $apiResponse['amount'] ?? 0;
                if ($api_utr == $utr_number) {
                    if (floatval($api_amount) >= floatval($order_amount)) {
                        $verification_status = 'SUCCESS';
                        $verified_amount = $api_amount;
                        $txn_id = $apiResponse['transactionId'];
                        $api_response_msg = 'Paytm Verification Successful';
                    } else {
                         $api_response_msg = "Amount Mismatch";
                    }
                } else {
                    $api_response_msg = "UTR Mismatch: API has $api_utr, User entered $utr_number";
                }
            }
        }
    }

    // 5. Update Database
    if ($verification_status == 'SUCCESS') {
        $update = $conn->prepare("UPDATE create_orders SET utr_number = ?, txn_status = 'SUCCESS', transactions_id = ?, amount = ? WHERE orderid = ?");
        if ($update->execute([$utr_number, $txn_id, $verified_amount, $orderid])) {
            
            // Update UPI Pool
            $poolManagerPath = '../../database/UpiPoolManager.php';
            if (file_exists($poolManagerPath)) {
                require_once($poolManagerPath);
                if (class_exists('UpiPoolManager')) {
                    try {
                        $upiManager = new UpiPoolManager($conn);
                        $upiManager->updateTransactionStatus($orderid, 'success');
                    } catch (Exception $e) {}
                }
            }

            // Send Callback
            $callbackFile = __DIR__ . '/../../partner/send_callback.php';
            if (file_exists($callbackFile)) {
                require_once($callbackFile);
                if (function_exists('sendCallback')) {
                    sendCallback($conn, $orderid, 'SUCCESS');
                }
            }

            ob_clean();
            echo json_encode(['status_code' => 200, 'status' => 'Success', 'message' => 'Transaction Verified and Updated Successfully']);
        } else {
            throw new Exception('Database Update Failed', 500);
        }
    } else {
        // Set Pending
        $update = $conn->prepare("UPDATE create_orders SET utr_number = ?, txn_status = 'PENDING' WHERE orderid = ?");
        if ($update->execute([$utr_number, $orderid])) {
            ob_clean();
            echo json_encode(['status_code' => 200, 'status' => 'Pending', 'message' => 'UTR Submitted. Verification Pending. ' . $api_response_msg]);
        } else {
            throw new Exception('Database Update Failed', 500);
        }
    }

} catch (Exception $e) {
    ob_clean();
    $code = $e->getCode() ?: 500;
    echo json_encode(['status_code' => $code, 'status' => 'Error', 'message' => $e->getMessage()]);
}
?>
