<?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 the txn_status in the create_orders table for the given orderid
$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' => 202,
'status' => 'Success',
'message' => 'Transaction is already successful',
'data' => [
'txn_id' => $orderData['transactions_id'],
'txn_status' => $txn_status,
'amount' => $orderData['amount'],
'received_from' => $orderData['received_from'],
'utr_number' => $orderData['utr_number']
]
]);
exit;
}

// If txn_status is 'PENDING', proceed with further logic
if ($txn_status == 'PENDING') {
// Proceed to fetch merchant data and perform the rest of the logic
// Step 8: Use user_id to fetch only the app_fc field from the database
$sql = "SELECT app_fc FROM add_merchant WHERE user = ? AND merchant_name = 'Freecharge'";
$stmt = $conn->prepare($sql);
$stmt->execute([$user_id]);

// Step 9: Fetch merchant data from the database
$merchantData = $stmt->fetch(PDO::FETCH_ASSOC);

// Step 10: Check if merchant data is found and retrieve the app_fc field
if ($merchantData) {
// Extract app_fc data
$app_fc = $merchantData['app_fc'];

// Step 11: Set the new API URL
$apiUrl = 'https://smartupi.in.net/merchantapi/freecharge_new/cheak-status-txn.php?app_fc=' . urlencode($app_fc) . '&order_id=' . urlencode($orderid);
//echo $apiUrl;
// Step 12: Make the API request using cURL
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $apiUrl); // Set the URL of the API
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // Return the response as a string

// Execute the 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 the cURL session
curl_close($ch);

// Step 14: Decode the response from the API (assuming the response is in JSON format)
$apiResponse = json_decode($response, true);

// Step 15: Check if the response indicates success
if ($apiResponse && isset($apiResponse['status_code']) && $apiResponse['status_code'] == 200) {
// Extract necessary fields from the API response
$apiTxnId = $apiResponse['data']['TxnId']; // Assuming TxnId is the key in the API response
$apiAmount = $apiResponse['data']['amount'];

// Step 16: Compare the API response with the database values
if ($apiAmount != $orderData['amount']) {
// If amounts do not match, return an error message
echo json_encode([
'status_code' => 400,
'status' => 'Error',
'message' => 'Amount does not match',
'api_amount' => $apiAmount,
'db_amount' => $orderData['amount']
]);
exit;
}

if ($apiTxnId != $orderData['orderid']) {
// If order IDs do not match, return an error message
echo json_encode([
'status_code' => 400,
'status' => 'Error',
'message' => 'Order ID does not match',
'api_txn_id' => $apiTxnId,
'db_orderid' => $orderData['orderid']
]);
exit;
}

// If both match, update the database
$txn_status = $apiResponse['data']['status'];
//$received_from = $apiResponse['data']['TxnType'];
$received_from = "UPI";

$utr_number = $apiResponse['data']['UTR'];


// Step 17: Update the transactions_id and other fields in the create_orders table
$updateQuery = "UPDATE create_orders SET txn_status = ?, received_from = ?, amount = ?, utr_number = ? WHERE orderid = ?";
$stmt = $conn->prepare($updateQuery);
$stmt->execute([$txn_status, $received_from, $apiAmount, $utr_number, $orderid]);

// Return success response
echo json_encode([
'status_code' => 200,
'status' => 'Success',
'message' => 'Transaction Successfully Updated',
'data' => [
'txn_status' => $txn_status,
'utr_number' => $utr_number,
'amount' => $apiAmount,
'received_from' => $received_from
]
]);
} else {
// Handle any other response from the API
echo json_encode([
'status_code' => 201,
'status' => 'Pending',
'message' => 'Waiting For Payment'
]);
}
}
}
} else {
// Order not found in the database
echo json_encode([
'status_code' => 404,
'status' => 'Error',
'message' => 'Order not found'
]);
}

?>