| Server IP : 13.126.101.145 / Your IP : 216.73.216.131 Web Server : Apache/2.4.52 (Ubuntu) System : Linux ip-11-115-0-196 6.8.0-1039-aws #41~22.04.1-Ubuntu SMP Thu Sep 11 10:54:48 UTC 2025 x86_64 User : www-data ( 33) PHP Version : 8.3.17 Disable Function : NONE MySQL : OFF | cURL : ON | WGET : ON | Perl : ON | Python : OFF | Sudo : ON | Pkexec : ON Directory : /var/www/html/rentals_updated/wp-content/plugins/api_manager/includes/ |
Upload File : |
<?php
class InvoicePostHandler {
public static function send_api_request($api_config, $invoice_data, $order_id) {
error_log("Sending API request for order_id: $order_id");
global $wpdb;
$sales_order_id = isset($invoice_data['id']) ? $invoice_data['id'] : null;
// Get Equipment number
$order = wc_get_order($order_id);
if (!$order) {
return 'Invalid order number.';
}
// Get the first item in the order
$items = $order->get_items();
if (empty($items)) {
return 'No products found in the order.';
}
// Since there's only one product, get the first item
$item = reset($items);
// Get the product ID
$product_id = $item->get_product_id();
// Retrieve the custom field value
$equipment_number = get_post_meta($product_id,'equipment_number', true);
$con_start_date = date('Y-m-d', strtotime(get_post_meta($order_id,'start_date', true)));
$con_end_date = date('Y-m-d', strtotime(get_post_meta($order_id,'end_date', true)));
$sap_contract = get_post_meta($order_id,'contract_id', true);
// fetch the tokens
$tokens_table = $wpdb->prefix . 'api_tokens';
$token_data = $wpdb->get_row($wpdb->prepare(
"SELECT token, cookies FROM $tokens_table WHERE order_id = %d AND token_type = 1 ORDER BY created_at DESC LIMIT 1",
$order_id
), ARRAY_A);
if (!empty($token_data)) {
if (!empty($token_data['token'])) {
$token= $token_data['token'];
}
if (!empty($token_data['cookies'])) {
$cookie= $token_data['cookies'];
}
} else {
error_log("No token data found for order ID: $order_id");
}
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => $api_config['request_url'],
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => '',
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 0,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => $api_config['request_method'],
CURLOPT_POSTFIELDS => '{
"ContractNumber": "' . $sap_contract . '",
"EquipmentNo": "' . $equipment_number . '",
"ScheduleStartDate": "' . $con_start_date . 'T00:00:00",
"ScheduleEndDate": "' . $con_end_date . 'T00:00:00",
"WorkHours": "30",
"Status": [{}],
"Details":[{}]
}',
// CURLOPT_POSTFIELDS => '{
// "ContractNumber": "6001708",
// "EquipmentNo": "8000050550",
// "ScheduleStartDate": "2025-01-12T00:00:00",
// "ScheduleEndDate": "2025-12-31T00:00:00",
// "WorkHours": "30",
// "Status": [{}],
// "Details":[{}]
// }',
CURLOPT_HTTPHEADER => array(
'X-CSRF-Token: ' . $token,
'Content-Type: application/json',
'Authorization: Basic b2RhdGFfZ3BxOkdtbWNvR1BRQDEyMw==',
'Cookie: ' . $cookie
),
));
$response = curl_exec($curl);
$http_code = curl_getinfo($curl, CURLINFO_HTTP_CODE);
$body = wp_remote_retrieve_body($response);
// $request_fields = json_encode($data);
// $header_rq = wp_remote_retrieve_header($response);
if (curl_errno($curl)) {
$error_message = curl_error($curl);
curl_close($curl);
error_log("cURL error for order_id $order_id: $error_message");
return ['success' => false, 'message' => 'cURL Error: ' . $error_message];
}
curl_close($curl);
// $status_code = wp_remote_retrieve_response_code($response);
// // Log response details for debugging
//error_log("API Response : $response");
error_log("URL: " . $api_config['request_url']);
error_log("Method: " . $api_config['request_method']);
// error_log("request Body: $request_fields ");
// error_log("Request Headers: " . print_r($headers, true));
// error_log("Payload: " . print_r($json_payload));
error_log("API Response Status: $http_code");
// error_log("Response Headers: " . print_r($header_rq));
error_log("Printing Response " . print_r($response, true));
if ($http_code === 201) {
// Initialize variables
$invoice_number = null;
$invoice_date = null;
$irnno = null;
$qrcode = null;
//print_r($extraction_methods);
// Extraction methods prioritizing XML parsing
$extraction_methods = [
'invoice_number' => [
['regex' => '/<d:InvoiceNumber>(.*?)<\/d:InvoiceNumber>/', 'index' => 1],
],
'invoice_date' => [
['regex' => '/<d:InvoiceDate>(.*?)<\/d:InvoiceDate>/', 'index' => 1],
],
'irnno' => [
['regex' => '/<d:IrnNo>(.*?)<\/d:IrnNo>/', 'index' => 1],
],
'qrcode' => [
['regex' => '/<d:QrCode>(.*?)<\/d:QrCode>/', 'index' => 1],
]
];
// Attempt to extract information using regex methods
foreach ($extraction_methods as $field => &$methods) {
foreach ($methods as $method) {
if (preg_match($method['regex'], $response, $matches)) {
${$field} = trim($matches[$method['index']]);
if (!empty(${$field})) {
break; // Stop if a value is found
}
}
}
}
// Fallback to JSON parsing
if (empty($invoice_number) || empty($invoice_date) ||
empty($irnno) || empty($qrcode)) {
$json_data = json_decode($response, true);
if ($json_data !== null) {
$invoice_number = $json_data['InvoiceNumber'] ?? $invoice_number;
$invoice_date = $json_data['InvoiceDate'] ?? $invoice_date;
$irnno = $json_data['IrnNo'] ?? $irnno;
$qrcode = $json_data['QrCode'] ?? $qrcode;
}
}
// Store the invoice information
if (!empty($invoice_number) || !empty($invoice_date) ||
!empty($irnno) || !empty($qrcode)) {
// $this->store_contract($contract_ID, $contract_po, $po_date, $order_id);
// Update database with extracted information
// $update_query = $wpdb->prepare(
// "UPDATE {$wpdb->prefix}order_invoice_details
// SET invoice_number = %s,
// invoice_date = %s,
// irnno = %s,
// qrcode = %s
// WHERE contract_id = %d",
// $invoice_number,
// $invoice_date,
// $irnno,
// $qrcode,
// $order_id,
// $sale_order_id
// );
// $date_obj = DateTime::createFromFormat('d-Y-m\TH:i:s', $invoice_date);
// $invoice_date = $date_obj->format('d-m-Y');
$invoice_date = date('d-m-Y', strtotime($invoice_date));
$update_query = $wpdb->prepare(
"UPDATE {$wpdb->prefix}sales_order
SET invoice_number = %s,
invoice_date = %s,
irnno = %s,
qrcode = %s
WHERE contract_id = %d AND id = %d",
$invoice_number,
$invoice_date,
$irnno,
$qrcode,
$order_id,
$sales_order_id
);
$update_result = $wpdb->query($update_query);
if ($update_result !== false) {
return [
'success' => true,
'message' => 'API request successful and database updated',
'invoice_number' => $invoice_number,
'invoice_date' => $invoice_date
];
} else {
return [
'success' => false,
'message' => 'API request successful but database update failed',
];
}
} else {
return [
'success' => false,
'message' => 'Unable to extract required information from API response' . $http_code,
];
}
} else {
return [
'success' => false,
'message' => 'API request failed with status code: ' . $http_code,
];
}
}
}
new InvoicePostHandler();