<?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 terminal_id, session_id FROM add_merchant WHERE user = ? AND merchant_name = 'HDFC'";
$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) {
$terminal_id = $merchantData['terminal_id'];
$session_id = $merchantData['session_id'];

// Step 11: Set the new API URL
$apiUrl = "https://smartupi.in.net/merchantapi/HDFCSoft/merchant-txn.php?tidList=$terminal_id&sessionid=$session_id&count=100&description=$orderid";

// Step 12: Make the API request using cURL
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $apiUrl);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // For testing only, remove in production
curl_setopt($ch, CURLOPT_TIMEOUT, 30);

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

// 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
$apiResponse = json_decode($response, true);

// Step 15: Check if we got a valid API response
if (!$apiResponse || !isset($apiResponse['status_code'])) {
echo json_encode([
'status_code' => 500,
'status' => 'Error',
'message' => 'Invalid API response',
'api_response' => $response
]);
exit;
}

// Handle different status codes from API
switch ($apiResponse['status_code']) {
case 3: // SUCCESS
// Verify that all required fields are present
if (!isset($apiResponse['data']['txnid']) || !isset($apiResponse['data']['amount']) || 
!isset($apiResponse['data']['txn_status']) || !isset($apiResponse['data']['utr_number'])) {
echo json_encode([
'status_code' => 500,
'status' => 'Error',
'message' => 'Missing required fields in API response',
'api_response' => $apiResponse
]);
exit;
}

// Extract data from API response
$apiTxnId = $apiResponse['data']['txnid'];
$apiAmount = $apiResponse['data']['amount'];
$apiTxnStatus = $apiResponse['data']['txn_status'];
$apiUtrNumber = $apiResponse['data']['utr_number'];
$apiReceivedFrom = isset($apiResponse['data']['received_from']) ? $apiResponse['data']['received_from'] : 'BharatQR-UPI';

// Compare with database values
if ($apiAmount != $orderData['amount']) {
echo json_encode([
'status_code' => 400,
'status' => 'Error',
'message' => 'Amount does not match',
'api_amount' => $apiAmount,
'db_amount' => $orderData['amount']
]);
exit;
}

// Update the database
$updateQuery = "UPDATE create_orders SET 
txn_status = ?, 
received_from = ?, 
amount = ?, 
utr_number = ?,
transactions_id = ?
WHERE orderid = ?";

$stmt = $conn->prepare($updateQuery);
$updateSuccess = $stmt->execute([
$apiTxnStatus, 
$apiReceivedFrom, 
$apiAmount, 
$apiUtrNumber,
$apiTxnId,
$orderid
]);

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

echo json_encode([
'status_code' => 200,
'status' => 'Success',
'message' => 'Transaction Successfully Updated',
'data' => [
'txn_id' => $apiTxnId,
'txn_status' => $apiTxnStatus,
'utr_number' => $apiUtrNumber,
'amount' => $apiAmount,
'received_from' => $apiReceivedFrom
]
]);
} else {
echo json_encode([
'status_code' => 500,
'status' => 'Error',
'message' => 'Failed to update database'
]);
}
break;

case 4: // FAILED
echo json_encode([
'status_code' => 400,
'status' => 'Failed',
'message' => isset($apiResponse['message']) ? $apiResponse['message'] : 'Transaction failed',
'orderid' => $orderid
]);
break;

case 2: // PENDING
default:
echo json_encode([
'status_code' => 201,
'status' => 'Pending',
'message' => isset($apiResponse['message']) ? $apiResponse['message'] : 'Waiting For Payment',
'orderid' => $orderid
]);
break;
}
} else {
echo json_encode([
'status_code' => 404,
'status' => 'Error',
'message' => 'Merchant data not found'
]);
}
}
} else {
// Order not found in the database
echo json_encode([
'status_code' => 404,
'status' => 'Error',
'message' => 'Order not found'
]);
}
?>