<?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: Check if encoded data is available
if (empty($encodedData)) {
echo json_encode(['status_code' => 400, 'status' => 'Error', 'message' => 'Encoded data is missing', 'received_data' => $_POST]);
exit;
}

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

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

// Step 5: 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 6: 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 7: 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'];

// Step 8: If txn_status is SUCCESS, return success response
if ($txn_status === 'SUCCESS') {
echo json_encode([
'status_code' => 200,
'status' => 'Success',
'message' => 'Transaction is already successful  ' . $orderid,
'data' => [
'txn_id' => $orderData['transactions_id'],
'txn_status' => $txn_status,
'amount' => $orderData['amount'],
'received_from' => $orderData['received_from'],
'utr_number' => $orderData['utr_number']
]
]);
exit;
}

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

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

if ($merchantData) {
$ubid_acbin = $merchantData['ubid_acbin'];
$x_acbin = $merchantData['x_acbin'];
$at_acbin = $merchantData['at_acbin'];

// Step 11: Prepare data for the new API request
$apiUrl = 'https://smartupi.in.net/merchantapi/amazon/cheak-status-txn.php?txn_id=' . $orderid . '&ubid_acbin=' . $ubid_acbin . '&x_acbin=' . $x_acbin . '&at_acbin=' . $at_acbin;

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

// Execute API request
$response = curl_exec($ch);
//echo $apiUrl;
// Step 13: 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 14: Decode API response
$apiResponse = json_decode($response, true);

// Step 15: Check if response indicates success
if ($apiResponse && isset($apiResponse['status_code']) && $apiResponse['status_code'] == 200 && isset($apiResponse['transactions'][0]['txn_id'])) {
// Extract necessary fields from API response
$txn_id = $apiResponse['transactions'][0]['txn_id'];
$txn_status = isset($apiResponse['transactions'][0]['txn_status']) && $apiResponse['transactions'][0]['txn_status'] == 'success' ? 'SUCCESS' : 'PENDING';
//$received_from = isset($apiResponse['transactions'][0]['received_from']) ? $apiResponse['transactions'][0]['received_from'] : '';
$received_from = "UPI";
$amount = isset($apiResponse['transactions'][0]['amount']) ? $apiResponse['transactions'][0]['amount'] : '';
$utr_number = isset($apiResponse['transactions'][0]['utr_number']) ? $apiResponse['transactions'][0]['utr_number'] : '';

// Step 16: Validate that the amount from the API matches the amount in create_orders
if ($amount != $orderData['amount']) {
echo json_encode([
'status_code' => 400,
'status' => 'Error',
'message' => 'Amount mismatch: API amount does not match order amount'
]);
exit;
}

// Step 17: Update create_orders table with new transaction details
$updateQuery = "UPDATE create_orders SET transactions_id = ?, api_txn_id = ?, txn_status = ?, received_from = ?, amount = ?, utr_number = ? WHERE orderid = ?";
$stmt = $conn->prepare($updateQuery);
$stmt->execute([$txn_id, $txn_id, $txn_status, $received_from, $amount, $utr_number, $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
]
]);
} else {
// Handle other API response scenarios
echo json_encode([
'status_code' => 201,
'status' => 'Pending',
'message' => 'Waiting For Payment'
]);
}
} else {
echo json_encode(['status_code' => 404, 'status' => 'Error', 'message' => 'Merchant data not found']);
}
}
} 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'
]);
}
?>