<?php

ini_set('display_errors', 1);
error_reporting(E_ALL);

// Include your database configuration file
require_once('../../database/config.php'); // Adjust the path as per your setup

// Step 1: Retrieve the base64-encoded data (from POST request)
$encodedData = isset($_POST['data']) ? $_POST['data'] : ''; // Base64-encoded data passed in POST under 'data'

// Step 2: Retrieve the UTR number (from POST request)
$utr_number = isset($_POST['utr_number']) ? $_POST['utr_number'] : ''; // User input for UTR number

// Step 3: Check if encoded data and UTR are available
if (empty($encodedData) || empty($utr_number)) {
echo json_encode(['status_code' => 400, 'status' => 'Error', 'message' => 'Encoded data or UTR number is missing', 'received_data' => $_POST]);
exit;
}

// Step 4: Check if the UTR number already exists in the create_orders table
$checkUtrQuery = "SELECT * FROM create_orders WHERE utr_number = ?";
$stmt = $conn->prepare($checkUtrQuery);
$stmt->execute([$utr_number]);
$existingUtr = $stmt->fetch(PDO::FETCH_ASSOC);

if ($existingUtr) {
// If UTR number already exists, return a message
echo json_encode([
'status_code' => 409,
'status' => 'Error',
'message' => 'UTR is Already Submitted'
]);
exit;
}

// Step 4: Decode the base64-encoded data
$decodedData = base64_decode($encodedData);

// Step 5: Check if decoding was successful
if ($decodedData === false) {
echo json_encode(['status_code' => 400, 'status' => 'Error', 'message' => 'Failed to decode base64 data']);
exit;
}

// Step 6: Parse the decoded data to extract parameters
parse_str($decodedData, $params); // This will convert the query string into an associative array

// Extract parameters
$orderid = isset($params['orderid']) ? $params['orderid'] : '';
$user_id = isset($params['user']) ? $params['user'] : '';

// Step 7: Check if required parameters are available
if (empty($orderid) || empty($user_id)) {
echo json_encode(['status_code' => 400, 'status' => 'Error', 'message' => 'Missing required parameters (orderid or user)', 'params' => $params]);
exit;
}

// Step 8: Check if the order exists in create_orders table and its txn_status
$checkOrderQuery = "SELECT * FROM create_orders WHERE orderid = ?";
$stmt = $conn->prepare($checkOrderQuery);
$stmt->execute([$orderid]);
$orderData = $stmt->fetch(PDO::FETCH_ASSOC);

if ($orderData) {
$txn_status = $orderData['txn_status'];
$order_amount = $orderData['amount']; // Fetch the amount from create_orders table

// Step 9: If txn_status is SUCCESS, return success response
if ($txn_status === 'SUCCESS') {
echo json_encode([
'status_code' => 201,
'status' => 'Success',
'message' => 'Transaction is already successful ' . $orderid
]);
exit;
}

// Step 10: If txn_status is PENDING, proceed with Bharatpe API request
if ($txn_status === 'PENDING') {
// Step 11: Fetch merchant data from the database for Bharatpe
$sql = "SELECT merchant_id, access_token FROM add_merchant WHERE user = ? AND merchant_name = 'Bharatpe'";
$stmt = $conn->prepare($sql);
$stmt->execute([$user_id]);

// Fetch merchant data
$merchantData = $stmt->fetch(PDO::FETCH_ASSOC);

if ($merchantData) {
$merchant_id = $merchantData['merchant_id'];
$access_token = $merchantData['access_token'];

// Step 12: Set API URL using the fetched data
$apiUrl = "https://smartupi.in.net/merchantapi/bharatpe/payment-status.php?merchant_id=$merchant_id&access_token=$access_token&bank_reference_no=$utr_number";

// Step 13: Make API request using cURL
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $apiUrl);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

// Execute API request
$response = curl_exec($ch);

// Step 14: Check for cURL errors
if (curl_errno($ch)) {
echo json_encode(['status_code' => 500, 'status' => 'Error', 'message' => 'cURL Error: ' . curl_error($ch)]);
exit;
}

// Close cURL session
curl_close($ch);

// Step 15: Decode API response
$apiResponse = json_decode($response, true);

// Step 16: Check if response indicates success or if no transaction found
if ($apiResponse && isset($apiResponse['status']) && $apiResponse['status'] == 'success') {
if (empty($apiResponse['bank_reference_no']) || empty($apiResponse['amount'])) {
// Handle "No Transactions Found" case
echo json_encode([
'status_code' => 404,
'status' => 'Error',
'message' => 'No Transactions Found',
'data' => $apiResponse
]);
exit;
}

// Extract necessary fields from API response
$txn_id = $apiResponse['transaction_id']; // Use 'transaction_id' from the API response
$txn_status = 'SUCCESS'; // Based on the response, transaction is successful
$received_from = $apiResponse['payer_handle']; // Payer name from the response
$payer_handle = $apiResponse['payer_handle']; // Payer handle (e.g., BHIM)
$amount = $apiResponse['amount']; // Transaction amount
$utr_number = $apiResponse['bank_reference_no']; // UTR number (bank reference number)
$payment_timestamp = $apiResponse['payment_timestamp']; // Payment timestamp

// Step 17: Compare the amounts and order numbers before saving the transaction
if ($amount != $order_amount) {
// If amounts do not match, return error
echo json_encode([
'status_code' => 409,
'status' => 'Error',
'message' => 'Amount mismatch.',
'data' => [
'order_amount' => $order_amount,
'api_amount' => $amount
]
]);
exit;
}

if ($orderid != $orderid) {
// If order numbers do not match, return error
echo json_encode([
'status_code' => 409,
'status' => 'Error',
'message' => 'Order number mismatch.',
'data' => [
'orderid' => $orderid,
'api_order_number' => $orderid
]
]);
exit;
}

// Step 18: Update create_orders table with new transaction details
$updateQuery = "UPDATE create_orders SET transactions_id = ?, api_txn_id = ?, txn_status = ?, received_from = ?, received_from = ?, amount = ?, utr_number = ?, created_at = ? WHERE orderid = ?";
$stmt = $conn->prepare($updateQuery);
$stmt->execute([$txn_id, $txn_id, $txn_status, $received_from, $payer_handle, $amount, $utr_number, $payment_timestamp, $orderid]);

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

// Return success response
echo json_encode([
'status_code' => 200,
'status' => 'Success',
'message' => 'Transaction Successfully Updated',
'data' => [
'api_txn_id' => $txn_id,
'txn_id' => $txn_id,
'txn_status' => $txn_status,
'utr_number' => $utr_number,
'amount' => $amount,
'received_from' => $received_from,
'payer_handle' => $payer_handle,
'payment_timestamp' => $payment_timestamp
]
]);
} else {
// Handle other API response scenarios
echo json_encode([
'status_code' => 202,
'status' => 'Pending',
'message' => 'Waiting For Payment'
]);
}
} else {
echo json_encode(['status_code' => 404, 'status' => 'Error', 'message' => 'Merchant data not found for Bharatpe']);
}
}
} else {
// Order not found in create_orders table
echo json_encode([
'status_code' => 404,
'status' => 'Error',
'message' => 'Order ID not found in create_orders table'
]);
}
?>
