| Server IP : 13.126.101.145 / Your IP : 216.73.217.47 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-phone/ |
Upload File : |
<?php
// Customer application APIs
function addToCartf($request)
{
$parametresen = $request->get_body_params() ?? array();
$parametres = decryptdaata($parametresen['params']);
$prodId = $parametres['prodId'];
$user_id = $parametres['user_id'];
$t = $parametres['type'];
$getWishId = get_user_meta($user_id, 'cartlistId', true);
$wishIdlist = explode(",", $getWishId);
// die(json_encode($wishIdlist));
$wishIdlistt = array_merge( $wishIdlist , $prodId); // $wishIdlist + $prodId;
// $integerIDs = array_map('intval', $wishIdlistt);
$integerIDss = array_unique($wishIdlistt);
// $integerIDss = array_map('trim', $integerIDss);
$integerIDss = array_filter($integerIDss, 'strlen');
if ($t == 'r') {
$integerIDss = array_diff($integerIDss, $prodId);
}
$sid = implode(",", $integerIDss);
update_user_meta($user_id, 'cartlistId', $sid);
$resulta = array("data" => $sid, 'ex' => $getWishId, 'success' => 1);
$encrypted = encryptdaata($resulta);
return new WP_REST_Response($encrypted, 200);
// $variationdata = array("date"=>date('y-m-d H:i:s'), 'user_id'=>$user_id,);
// global $wpdb;
// global $woocommerce;
// /**pending: map with user id */
// if($t=='r'){
// // $c_cart = new WC_Cart();
// // WC()->session->set($user_id, $c_cart);
// // $c_cart->add_to_cart($productId);
// $woocommerce->cart->remove_cart_item($productId);
// }else{
// $woocommerce->cart->add_to_cart($productId, $quantity,$user_id,$variationdata);
// }
// $cartsids = $woocommerce->cart->get_cart();
// $resulta = array("data" => $cartsids, 'success' => 1);
// $encrypted = encryptdaata($resulta);
// return new WP_REST_Response($encrypted, 200);
}
/** request_quote insert and update */
function rfqf($request)
{
$parametresen = $request->get_body_params() ?? array();
$parametres = decryptdaata($parametresen['params']);
if (!is_array($parametres)) {
die(json_encode(['message' => 'Please pass required parameters']));
}
$start_date = $parametres["start_date"];
$end_date = $parametres["end_date"];
$shift = intval($parametres["shift"]);
$product_id = intval($parametres["product_id"]);
$location = sanitize_text_field($parametres["location"]);
$application = $parametres["application"];
$user_id = intval($parametres["user_id"]);
$user_info = get_userdata($user_id);
$user_name = $user_info->first_name . " " . $user_info->last_name;
$user_email = $user_info->user_email;
$region = _getRegionLeads(strtolower($location));
$product = wc_get_product($product_id);
if ($product) {
$product_name = $product->get_name();
} else {
$resultdata = array("message" => "Product not found", 'success' => 0);
$encrypted = encryptdaata($resultdata);
return new WP_REST_Response($encrypted, 400);
}
global $wpdb;
$table_name = $wpdb->prefix . "request_quote";
if (array_key_exists("rmsId", $parametres)) {
$rfq_id = intval($parametres["rfq_id"]);
$calculated_price = $parametres["calculated_price"];
$rfq_status = $parametres["rfq_status"];
// Remove everything except numbers, decimal point, and minus sign
$price = str_replace(',', '', $calculated_price);
$insertData = [
"user_id" => $user_id,
"user_name" => $user_name,
"user_email" => $user_email,
"product_id" => $product_id,
"product_name" => $product_name,
"start_date" => $start_date,
"end_date" => $end_date,
"shift" => $shift,
"region" => $region,
"calculated_price" => $price,
"rfq_status" => $rfq_status
];
$result = $wpdb->update($table_name, $insertData, ['id' => $rfq_id]);
if ($result) {
// $ch = curl_init();
// 9148313859
// $rfqdata = array(
// "user_id" => $user_id,
// "user_name" => $user_name,
// "user_email" => $user_email,
// "product_id" => $product_id,
// "product_name" => $product_name,
// "start_date" => $start_date,
// "end_date" => $end_date,
// "shift" => $shift,
// "calculated_price" => $price,
// "rfq_status" => $rfq_status,
// 'id' => $rfq_id
// );
// $email_instance = new WC_Custom_Email_Rfq();
// $email_instance->trigger($rfq_id, $rfqdata);
// --- add to cart ----
// -- end to add cart ------
$request_quote_id = $wpdb->insert_id;
$inserted_id = $wpdb->insert_id;
customAddToCart_mob($insertData); // woocommerce cart
/** mob cart */
$getWishId = get_user_meta($user_id, 'cartlistId', true);
$wishIdlist = explode(",", $getWishId);
$wishIdlistt = array_merge( $wishIdlist , ["$inserted_id"]);// $wishIdlist + [$inserted_id];
$integerIDss = array_unique($wishIdlistt);
$integerIDss = array_filter($integerIDss, 'strlen');
$sid = implode(",", $integerIDss);
update_user_meta($user_id, 'cartlistId', $sid);
// ---- mob cart ----
$ajax_url = admin_url("admin-ajax.php");
$nonce = wp_create_nonce("send_rfq_email_nonce");
$reqdata = [
'action' => 'send_rfq_email',
'user_id' => $user_id,
'nonce' => $nonce
];
$response = wp_remote_post($ajax_url, [
'method' => 'POST',
'body' => $reqdata
]);
$edit_url = admin_url('admin.php?page=edit-quote&id=' . $request_quote_id);
create_notification(
'User Requested For Quote',
'User "' . $user_name . '" has requested a quote for product "' . $product_name . '". <a target="_blank" href="' . $edit_url . '" style="color: blue; text-decoration: underline;">Click here</a> to view/edit.',
array(
'meta_input' => array(
'user_id' => $user_id,
'action' => 'request_for_quote',
'request_quote_id' => $request_quote_id,
)
)
);
$resultdata = array("message" => "Quatation updated. The team will contact you soon.", 'success' => 1, 'cartId' => $sid);
$encrypted = encryptdaata($resultdata);
return new WP_REST_Response($encrypted, 200);
} else {
$resultdata = array("message" => "Unable to save your request changes.", 'success' => 0, 'reaso' => $wpdb->last_error);
$encrypted = encryptdaata($resultdata);
return new WP_REST_Response($encrypted, 200);
}
} else {
$base_price = $product->get_price();
if (($base_price ?? 0) < 1) {
$resultdata = array("message" => "This equipment price is not mensioned.", 'success' => 0, 'reaso' => $wpdb->last_error);
return new WP_REST_Response($resultdata, 400);
}
$max_value = $wpdb->get_var("SELECT MAX(id) FROM $table_name");
// If no value found, default to 0
if (is_null($max_value)) {
$max_value = 0;
}
// Increment the value by 1
$rmsID = $max_value + 1;
// Calculate the price based on selected shifts and date range
$start_date_obj = new DateTime($start_date);
$end_date_obj = new DateTime($end_date);
$interval = $start_date_obj->diff($end_date_obj);
$days = $interval->days + 1; // Include the end date
$hours_per_day = 8; // Default hours per shift
$total_hours = $days * $shift * $hours_per_day;
$calculated_price = ($total_hours / 8) * $base_price;
$insertData = [
"user_id" => $user_id,
"rmsID" => "RMS00" . $rmsID,
"user_name" => $user_name,
"user_email" => $user_email,
"product_id" => $product_id,
"product_name" => $product_name,
"start_date" => $start_date,
"end_date" => $end_date,
"shift" => $shift,
"location" => $location,
"application" => $application,
"region" => $region,
"calculated_price" => $calculated_price,
"requested_on" => date('Y-m-d H:i:s'),
];
$result = $wpdb->insert($table_name, $insertData);
$inserted_id = $wpdb->insert_id;
if ($result) {
$resultCart = customAddToCart_mob($insertData); // woocommerce cart
/** mob cart */
$getWishId = get_user_meta($user_id, 'cartlistId', true);
$getwidth = "";
if ($getWishId) {
$getwidth = "getwish";
$wishIdlist = explode(",", $getWishId);
$wishIdlistt = array_merge( $wishIdlist , ["$inserted_id"]);// $wishIdlist + ["$inserted_id"];
$integerIDss = array_unique($wishIdlistt);
$integerIDss = array_filter($integerIDss, 'strlen');
$sid = implode(",", $integerIDss);
} else {
$getwidth = "getwithno";
$sid = "$inserted_id";
}
$isUpdateSid = update_user_meta($user_id, 'cartlistId', $sid);
// if(!$isUpdateSid){
// add_user_meta($user_id,'cartlisttId',$inserted_id);
// }
// ---- mob cart ----
$ajax_url = admin_url("admin-ajax.php");
$nonce = wp_create_nonce("send_rfq_email_nonce");
$reqdata = [
'action' => 'send_rfq_email',
'user_id' => $user_id,
'nonce' => $nonce
];
$response = wp_remote_post($ajax_url, [
'method' => 'POST',
'body' => $reqdata
]);
// $rfqdata = array(
// "user_id" => $user_id,
// "user_name" => $user_name,
// "user_email" => $user_email,
// "product_id" => $product_id,
// "product_name" => $product_name,
// "start_date" => $start_date,
// "end_date" => $end_date,
// "shift" => $shift,
// "calculated_price" => $calculated_price,
// 'id' => $insertid
// );
// $email_instance = new WC_Custom_Email_Rfq();
// $email_instance->trigger($insertid, $rfqdata);
$resultdata = array("message" => "Quatation request sent to Gmmco team. The team will contact you soon.", 'success' => 1, 'cartId' => $sid, '$isUpdateSid' => $isUpdateSid, ' $getwidth ' => $getwidth, 'emailResponse' => $response);
$encrypted = encryptdaata($resultdata);
return new WP_REST_Response($encrypted, 200);
} else {
$resultdata = array("message" => "Unable to save your request quote", 'success' => 0, 'reaso' => $wpdb->last_error);
return new WP_REST_Response($resultdata, 400);
}
}
}
/**download standard quote in RFQ */
function rfq_downloadQuotef($request)
{
$parametresen = $request->get_body_params() ?? array();
$parametres = decryptdaata($parametresen['params']);
if (!is_array($parametres)) {
die(json_encode(['message' => 'Please pass required parameters']));
}
$start_date = $parametres["start_date"];
$end_date = $parametres["end_date"];
$shift = intval($parametres["shift"]);
$product_id = intval($parametres["product_id"]);
$location = sanitize_text_field($parametres["location"]);
$application = intval($parametres["application"]);
$user_id = intval($parametres["user_id"]);
$user_info = get_userdata($user_id);
$user_name = $user_info->first_name . " " . $user_info->last_name;
$user_email = $user_info->user_email;
$region = _getRegionLeads(strtolower($location));
$product = wc_get_product($product_id);
if ($product) {
$product_name = $product->get_name();
$base_price = $product->get_price();
} else {
$resultdata = array("message" => "Product not found", 'success' => 0);
$encrypted = encryptdaata($resultdata);
return new WP_REST_Response($encrypted, 400);
}
global $wpdb;
$start_date_obj = new DateTime($start_date);
$end_date_obj = new DateTime($end_date);
$interval = $start_date_obj->diff($end_date_obj);
$days = $interval->days + 1; // Include the end date
$hours_per_day = 8; // Default hours per shift
$total_hours = $days * $shift * $hours_per_day;
$calculated_price = ($total_hours / 8) * $base_price;
$table_name = $wpdb->prefix . "download_std_ratecard";
$result = $wpdb->insert($table_name, [
"user_id" => $user_id,
"user_name" => $user_name,
"user_email" => $user_email,
"product_id" => $product_id,
"product_name" => $product_name,
"start_date" => $start_date,
"end_date" => $end_date,
"shift" => $shift,
"location" => $location,
"region" => $region,
"calculated_price" => $calculated_price,
"downloaded_on" => date('Y-m-d H:i:s'),
]);
$gmmcoAdress = [
"GMMCO Limited.",
"No.6, G.S.T Road,",
"ST Thomas Mount,",
"Chennai - 600 016",
"GSTIN :27AABCG0949C1ZX",
"Phone: +91 44 2267 6000",
"Email: contact@gmmco.in",
];
$termslist = [
"The rental charges for the above-mentioned machine will be for a minimum billing of 240 hours per month for 26 working days.",
"Customer will pay extra charges @ Prorate Basis for every additional hour used beyond 240 hrs.",
"GST as applicable will be charged separately on the invoice value and will be payable by the Customer extra at actual.",
"Customer shall pay an amount of two months' rental charges as a security deposit along with the Work Order, which shall be adjusted against the last two months' rental charges.",
"To & Fro Transportation will be borne by Customer Scope. In case of rental duration for more than 6 months, one side transportation will be Gmmco's scope.",
"Order confirmation will be subject to equipment availability of stock.",
"Transit insurance and third-party insurance will be Gmmco's responsibility.",
"Gmmco will dispatch the machine after getting a confirmed order along with the security deposit.",
"One Operator for Single Shift Operation is considered in the above price and the same will be borne by Gmmco.",
"If you want extra Operator, anadditional charge will need to be paid",
"Food, accommodation, and transportation for the Operators to the site will be borne by the Customer.",
"Uncontaminated High-Speed Diesel required for the operation of the equipment shall be provided by the Customer at the site at his costs.",
"GET & Oils shall be organized by the customer as per OEM recommendation.",
"Repair and Maintenance of the equipment will be under Gmmco's scope.",
"The Rental charges shall be paid by the Customer within ten days from the date of invoice submission, by way of RTGS in favor of Gmmco Limited.",
"Gmmco will dehire the machine in case payment is not received within fifteen days from the date of Invoice.",
"Gmmco will raise invoices for utilization of the Equipment for each calendar month and submit the same to the customer based on Log sheets.",
"Customer will use the equipment only for the purpose it is hired and shall not misuse or abuse the equipment or use the Equipment for any unlawful or illegal purposes.",
"Prices are subject to change without notice.",
"Customer will ensure the safe custody of the equipment by providing necessary security, parking bay, etc., and will be liable for any loss or damage or destruction to the machine at prevailing prices, taxes, freight, etc. Customer shall ensure safe procedures and practices at the site.",
"In case the customer dehires the machines before the contract period, then both mobilization and demobilization will be the customer's account.",
"Any terms and conditions missing in the above shall be mutually agreed upon at the time of signing the contract.",
"All above indicated T & C, actually may vary as per contracts and site conditions.",
];
if ($result) {
$dated = date('Y-m-d H:i:s');
$duration = "$days days";
$resultdataa = array(
"message" => "Quatation downloading... The GMMCO team will contact you soon.",
'success' => 1,
'gmmcoAdress' => $gmmcoAdress,
'date' => $dated,
'price' => $calculated_price,
'termslist' => $termslist,
'duration' => $duration,
);
if ($parametres['type'] == 'justDownload') {
$resultdataa['rentprice'] = $base_price;
}
create_notification(
'User Downloaded Std Rate card',
'User "' . $user_info->user_login . '" has downloaded standard rate card for product ' . $product_name . ' ',
array(
'meta_input' => array(
'user_id' => $user_id,
'action' => 'std_rate_card_download',
)
)
);
$encrypted = encryptdaata($resultdataa);
return new WP_REST_Response($encrypted, 200);
} else {
$resultdata = array("message" => "Unable to save your request quote", 'success' => 0, 'reaso' => $wpdb->last_error);
return new WP_REST_Response($resultdata, 400);
}
}
/**download quotation function */
function quote_downloadQuotef($request)
{
$parametresen = $request->get_body_params() ?? array();
$parametres = decryptdaata($parametresen['params']);
if (!is_array($parametres)) {
die(json_encode(['message' => 'Please pass required parameters']));
}
global $wpdb;
$quotation_id = intval($parametres['quotation_id']);
$quotation_table = 'wp_quotation';
$terms_conditions_table = 'wp_terms_conditions';
$custom_logo_id = get_theme_mod('custom_logo');
$logo_url = wp_get_attachment_image_url($custom_logo_id, 'full');
// Fetch product_name, dynamic_terms_1, dynamic_terms_2, shift, final_price, user_name, and user_email from the wp_quotation table
$quotationres = $wpdb->get_row($wpdb->prepare("SELECT * FROM $quotation_table WHERE id = %d", $quotation_id));
if ($quotationres) {
$product_name = esc_html($quotationres->product_name);
$assign_location_id = esc_html($quotationres->assign_location_id);
$location_name = $wpdb->get_results(
$wpdb->prepare(
"SELECT * FROM wp_zone_address WHERE id = %d",
$assign_location_id
),
OBJECT
);
$assign_location_name = esc_attr($location_name[0]->address);
$assign_location_gst = esc_attr($location_name[0]->gst_no);
$version_number = esc_html($quotationres->revised_count - 1);
$dynamic_terms = wp_kses_post($quotationres->dynamic_terms_1);
$dynamic_terms_2 = wp_kses_post($quotationres->dynamic_terms_2);
$shift = esc_html($quotationres->shift);
$final_price = esc_html($quotationres->final_price);
// $user_email = esc_html($quotationres->user_email);
$user_name = esc_html($quotationres->user_name);
// Logic for total hours
$start_date = esc_html(date('Y-m-d', strtotime($quotationres->start_date)));
$end_date = esc_html(date('Y-m-d', strtotime($quotationres->end_date)));
// Number of shifts per day
$shifts_per_day = $shift;
// Define shift duration (8 hours per shift)
$shift_duration = 8; // Hours
// Convert to DateTime objects
$start = new DateTime($start_date);
$end = new DateTime($end_date);
// Calculate the difference in days between the dates (include the end date by adding 1 day)
$interval = $start->diff($end);
$total_days = $interval->days + 1; // Adding 1 to include the end date
// Calculate total duration in hours based on the number of shifts per day
$total_hours = $total_days * $shifts_per_day * $shift_duration;
// gst calculation
$gst_percentage = 18;
$gst_amount = ($final_price * $gst_percentage) / 100;
// Calculate the final price including GST
$final_price_with_gst = $final_price + $gst_amount;
$final_price_with_gst = round($final_price_with_gst);
// User billing address
$user_id = esc_html($quotationres->user_id);
// Get user data
$user_info = get_userdata($user_id);
// Retrieve the first name
$user_name = $user_info->first_name . " " . $user_info->last_name;
$quote_date = date('d.m.Y');
$quote_number = $quotationres->id;
$billing_company = get_user_meta($user_id, 'billing_company', true);
$billing_address_1 = get_user_meta($user_id, 'billing_address_1', true);
$billing_address_2 = get_user_meta($user_id, 'billing_address_2', true);
$billing_city = get_user_meta($user_id, 'billing_city', true);
$billing_postcode = get_user_meta($user_id, 'billing_postcode', true);
$billing_state = get_user_meta($user_id, 'billing_state', true);
$countrycode = get_user_meta($user_id, 'billing_country', true);
$contries = new WC_Countries();
$states = $contries->get_states($countrycode);
$state = $states[$billing_state];
// Combine address fields to match the desired format
$billing_address = '';
if (!empty($billing_company)) {
$billing_address .= $billing_company . "\n";
}
if (!empty($billing_address_1)) {
$billing_address .= $billing_address_1;
}
if (!empty($billing_address_2)) {
$billing_address .= " " . $billing_address_2;
}
if (!empty($billing_city)) {
$billing_address .= "\n" . $billing_city . ' ' . $billing_postcode;
}
if (!empty($billing_state)) {
$billing_address .= "\n" . strtoupper($state);
}
// Output the address
$billing_address = nl2br($billing_address);
$total_price_in_words = convert_number_to_words_mf($final_price_with_gst);
$final_price_with_gst = number_format($final_price_with_gst, 2);
$resultdataa = array(
"message" => "Quatation loaded... ",
'success' => 1,
'logo_url' => $logo_url,
'assign_location_name' => $assign_location_name,
'assign_location_gst' => $assign_location_gst,
'upid' => 'GMMCOLTD34959@HDFCBANK',
'user_name' => $user_name,
'billing_address' => $billing_address,
'quote_number' => $quote_number,
'quote_date' => $quote_date,
'version_number' => $version_number,
'product_name' => $product_name,
'total_hours' => $total_hours,
'final_price' => $final_price,
'total_price_in_words' => $total_price_in_words,
'gst_amount' => $gst_amount,
'dynamic_terms' => $dynamic_terms,
'dynamic_terms_2' => $dynamic_terms_2,
);
$encrypted = encryptdaata($resultdataa);
return new WP_REST_Response($encrypted, 200);
} else {
$resultdata = array("message" => "Unable to download your quotation", 'success' => 0, 'reaso' => $wpdb->last_error);
return new WP_REST_Response($resultdata, 400);
}
}
/** show all request quote in admin */
function showRfqf($request)
{
$parametresen = $request->get_body_params() ?? array();
$parametres = decryptdaata($parametresen['params']);
$date1 = $parametres['start_date'];
$date2 = $parametres['end_date'];
$user_id = $parametres['user_id'];
$page = $parametres['page'] ?? 1;
$perpage = $parametres['perpage'] ?? 10;
$limit = " limit $perpage";
$daterange = "";
if ($page > 1) {
$perpage1 = $page * $perpage;
$perpage1 = ($perpage1 - $perpage);
$limit = " limit $perpage1,$perpage";
}
$datesBetween = "";
if (!empty($date1) && !empty($date2)) {
$limit = "";
$datesBetween = " AND date(a.requested_on) between '$date1' and '$date2' ";
}
// if (!empty($user_id)) {
$whereuserid = " a.user_id='$user_id' ";
// }
global $wpdb;
$table_name = "wp_request_quote";
$tableOrder = $wpdb->prefix . "quotation";
$rfqquery = "SELECT a.*,b.qt_status from $table_name a left join $tableOrder b on a.id = b.rfq_id WHERE $whereuserid $datesBetween order by a.id desc $limit";
// die($rfqquery);
$count = $wpdb->query("SELECT count(*) as count from `wp_request_quote` WHERE $whereuserid ");
// die("connttt $count");
$results = $wpdb->get_results($rfqquery, ARRAY_A);
if ($wpdb->last_error) {
$resultdata = array("message" => "something went wrong.", 'reson' => $wpdb->last_error);
return new WP_REST_Response($resultdata, 400);
}
if (count($results ?? []) > 0) {
$results = $results ?? [];
for ($i = 0; $i < count($results); $i++) {
$res = (object) $results[$i];
$image = wp_get_attachment_image_src(get_post_thumbnail_id($res->product_id), 'thumbnail'); //'single-post-thumbnail');
$results[$i]['image'] = $image;
$qtstatus = $res->qt_status;
if ($qtstatus == 'Quote Send to Coustmer') {
$statusDisplay = 'Quote Generated';
} elseif ($qtstatus == 'Revised') {
$statusDisplay = 'Completed';
} elseif ($qtstatus == 'Accepted') {
$statusDisplay = 'Completed';
} elseif ($qtstatus == 'Cancelled') {
$statusDisplay = 'Request Cancelled';
} else {
$statusDisplay = $qtstatus; // Default to the original status if no conditions are met
}
$results[$i]['qt_status'] = $statusDisplay;
}
$resulta = array("data" => $results ?? [], 'success' => 1);
$encrypted = encryptdaata($resulta);
return new WP_REST_Response($encrypted, 200);
} else {
if ($page > 1) {
$resulta = array("data" => $results ?? [], 'success' => 1);
$encrypted = encryptdaata($resulta);
return new WP_REST_Response($encrypted, 200);
}
$resultdata = array("message" => "No RFQ requested yet. Raise a request request for Quote.", 'success' => 1);
return new WP_REST_Response($resultdata, 400);
}
}
function getCategories($request)
{
$type = $request['type'];
$producCateAr = [];
if ($type == 'rent') {
$parentId = 100;
$woo_cat_args = array('taxonomy' => 'product_cat', 'orderby' => 'id', 'parent' => $parentId, 'hide_empty' => false,); // 'category__in' => get_queried_object()->term_id,);
$woo_categories = get_categories($woo_cat_args);
$parentId2 = 133;
$woo_cat_args2 = array('taxonomy' => 'product_cat', 'orderby' => 'id', 'parent' => $parentId2, 'hide_empty' => false, 'category__in' => get_queried_object()->term_id,);
$woo_categories2 = get_categories($woo_cat_args2);
if (count($woo_categories2) > 0) {
$woo_categories3 = array_merge((array)$woo_categories, (array)$woo_categories2);
}
}
// echo count($woo_categories3) . "\n";
$producCateAr[] = ['parent' => $parentId, 'child' => $woo_categories3];
die(json_encode($producCateAr));
}
function getProductsByIdsf($request)
{
$parametersen = $request->get_body_params();
$parameters = decryptdaata($parametersen['params']);
$idss = $parameters['productsIds'] ?? '';
$ids = explode(",", $idss);
for ($i = 0; $i < count($ids); $i++) {
try {
$proid = $ids[$i];
$products = wc_get_product($proid);
$product = (object)$products->get_data();
// $product->wp_getvis;
// $product->post_excerpt;
$image = wp_get_attachment_image_src(get_post_thumbnail_id($product->id), 'medium'); //'single-post-thumbnail');
$thumbnail = wp_get_attachment_image_src(get_post_thumbnail_id($product->id), 'thumbnail'); //'single-post-thumbnail');
// $excerpt = get_the_excerpt($product->ID);
$product->thumbnail = $thumbnail;
$product->image = $image;
$productsAr[] = $product;
} catch (\Throwable $th) {
}
}
$encrypeddata = encryptdaata(['data' => $productsAr]);
return new WP_REST_Response($encrypeddata);
}
function getProductsf($request)
{
$parametersen = $request->get_body_params();
$parameters = decryptdaata($parametersen['params']);
$prod_categories = explode(",", $parameters['parentId']);
$page = $parameters['page'] ?? 1;
$posts_per_page = $parameters['perpage'] ?? 10;
// $tax_query = array(
// 'taxonomy' => 'product_cat',
// 'field' => 'slug',
// 'terms' => $slug,
// );
$args = array(
'limit' => -1,
'orderby' => 'id',
'order' => 'ASC',
'status' => 'publish',
'tax_query' => array(
'RELATION' => "AND",
array(
'taxonomy' => 'product_cat',
'field' => 'id',
'terms' => $prod_categories,
'operator' => 'IN'
),
),
'meta_query' => array(
array(
'key' => 'purpose_of_listing',
'value' => 'Display',
'compare' => '='
)
)
);
// echo "\n" . json_encode($args) . "\n";
$productsAr = [];
$query = new WC_Product_Query($args);
$products = $query->get_products();
foreach ($products as $product) {
$productsAr[] = [
'name' => $product->name,
'id' => $product->id,
'image' => wp_get_attachment_image_src(get_post_thumbnail_id($product->id), 'medium'),
'short_description' => $product->short_description,
'price' => $product->price,
'regular_price' => $product->regular_price,
'sale_price' => $product->sale_price,
'stock_status' => $product->stock_status,
'asset_id' => $product->get_sku(),
// 'image' => wp_get_attachment_thumb_url($product->get_image_id())
];
// echo " thisProducts " . $value2->name . " pro: " . $product->get_name() . ' slug:'. $product->get_slug . "\n";
// $productsAr[] = $productdata;
}
$encrypeddata = encryptdaata(['data' => $productsAr]);
return new WP_REST_Response($encrypeddata);
}
function mainPageProductGrid($request)
{
$parametresen = $request->get_body_params();
$parameters = decryptdaata($parametresen['params']);
// $parametres = decryptdaata($parametresen['params']);
$type = $parameters['type'];
$productsAr = [];
$parentId = 0;
if ($type == 'rent') {
$parentId = 100;
$woo_cat_args = array(
'post_type' => 'product',
'post_status' => 'publish',
'taxonomy' => 'product_cat',
'orderby' => 'id',
'parent' => $parentId,
'category' => 'rent',
'hide_empty' => false,
'category__in' => get_queried_object()->term_id,
);
$woo_categories1 = get_categories($woo_cat_args);
$parentId2 = 133;
$woo_cat_args2 = array('taxonomy' => 'product_cat', 'orderby' => 'id', 'parent' => $parentId2, 'hide_empty' => false, 'category__in' => get_queried_object()->term_id,);
$woo_categories2 = get_categories($woo_cat_args2);
$woo_categories = (array)$woo_categories1;
if (count($woo_categories2) > 0) {
$woo_categories = array_merge((array)$woo_categories1, (array)$woo_categories2);
}
// echo count($woo_categories);
foreach ($woo_categories as $key => $value) {
$woo_cat_args = array(
'taxonomy' => 'product_cat',
'orderby' => 'id',
'post_status' => 'publish',
'parent' => $value->term_id,
'hide_empty' => false,
'category__in' => get_queried_object()->term_id,
);
$productsCount = 0;
$woo_categories2 = get_categories($woo_cat_args);
$woo_categories2count = count($woo_categories2);
if ($woo_categories2count > 0) {
$thisProduct = [];
for ($i = 0; $i < $woo_categories2count; $i++) {
$value2 = $woo_categories2[$i];
$limit = 2;
if ($i == 0 && $woo_categories2count == 1) {
$limit = 5;
} else if ($productsCount < 2 && $woo_categories2count <= 3) {
$limit = 4;
} else if ($i == ($woo_categories2count - 1) && $productsCount < 4) {
$limit = 5 - $productsCount;
}
try {
$args = array(
'limit' => $limit,
'orderby' => 'name',
'order' => 'DESC',
'status' => 'publish',
'tax_query' => array(
array(
'taxonomy' => 'product_cat',
'field' => 'id',
'terms' => $value2->term_id,
),
),
'meta_query' => array(
array(
'key' => 'purpose_of_listing',
'value' => 'Display',
'compare' => '='
)
)
);
// echo "\n" . json_encode($args) . "\n";
$query = new WC_Product_Query($args);
$products = $query->get_products();
$productsCount += count($products);
$thisProducts = [];
foreach ($products as $product) {
$thisProducts[] = ['name' => $product->name, 'id' => $product->id, 'image' => wp_get_attachment_thumb_url($product->get_image_id())];
// echo " thisProducts " . $value2->name . " pro: " . $product->get_name() . ' slug:'. $product->get_slug . "\n";
}
$thisProduct[] = ['catId' => $value->term_id, 'catname' => $value->name, 'subcatname' => $value2->name, 'subcatId' => $value2->term_id, 'products' => $thisProducts];
} catch (Throwable $th) {
// echo $th->getMessage();
}
}
$productsAr[] = $thisProduct;
} else {
$limit = 5;
try {
$args = array(
'limit' => $limit,
'orderby' => 'name',
'order' => 'DESC',
'status' => 'publish',
'tax_query' => array(
array(
'taxonomy' => 'product_cat',
'field' => 'id',
'terms' => $value->term_id,
),
),
'meta_query' => array(
array(
'key' => 'purpose_of_listing',
'value' => 'Display',
'compare' => '='
)
)
);
// echo "\n" . json_encode($args) . "\n";
$query = new WC_Product_Query($args);
$products = $query->get_products();
$productsCount += count($products);
$thisProducts = [];
foreach ($products as $product) {
$thisProducts[] = ['name' => $product->name, 'id' => $product->id, 'image' => wp_get_attachment_thumb_url($product->get_image_id())];
}
$thisProduct = ['catId' => $value->term_id, 'catname' => $value->name, 'products' => $thisProducts];
// echo json_encode($thisProducts);
// echo "--- enc -- \n";
$productsAr[] = $thisProduct;
// echo "\n thisProducts". json_encode($thisProducts). "\n";
} catch (Throwable $th) {
// echo $th->getMessage();
}
}
}
} else if ($type == 'buy') {
// $parentId = 137; // all buy categories
$parentId = 140; // only Used equipment buy categories
// } else {
// $resultdata = array("message" => "Invalid request");
// return new WP_REST_Response($resultdata, 400);
// }
$woo_cat_args = array(
'post_type' => 'product',
'post_status' => 'publish',
'taxonomy' => 'product_cat',
'orderby' => 'id',
'parent' => $parentId,
// 'category' => 'used equipment to buy',
'hide_empty' => false,
'category__in' => get_queried_object()->term_id,
);
$woo_categories1 = get_categories($woo_cat_args);
$woo_categories = (array)$woo_categories1;
// $parentId2 = 133;
// $woo_cat_args2 = array('taxonomy' => 'product_cat', 'orderby' => 'id', 'parent' => $parentId2, 'hide_empty' => false, 'category__in' => get_queried_object()->term_id,);
// $woo_categories2 = get_categories($woo_cat_args2);
// if (count($woo_categories2) > 0) {
// $woo_categories = array_merge((array)$woo_categories1, (array)$woo_categories2);
// }
// echo count($woo_categories);
foreach ($woo_categories as $key => $value) {
$woo_cat_args = array(
'taxonomy' => 'product_cat',
'orderby' => 'id',
'parent' => $value->term_id,
'hide_empty' => false,
'category__in' => get_queried_object()->term_id,
);
$productsCount = 0;
$woo_categories2 = get_categories($woo_cat_args);
$woo_categories2count = count($woo_categories2);
if ($woo_categories2count > 0) {
$thisProduct = [];
for ($i = 0; $i < $woo_categories2count; $i++) {
$value2 = $woo_categories2[$i];
$limit = 2;
if ($i == 0 && $woo_categories2count == 1) {
$limit = 5;
} else if ($productsCount < 2 && $woo_categories2count <= 3) {
$limit = 4;
} else if ($i == ($woo_categories2count - 1) && $productsCount < 4) {
$limit = 5 - $productsCount;
}
try {
$args = array(
'limit' => $limit,
'orderby' => 'name',
'order' => 'DESC',
'status' => 'publish',
'tax_query' => array(
array(
'taxonomy' => 'product_cat',
'field' => 'id',
'terms' => $value2->term_id,
),
),
'meta_query' => array(
array(
'key' => 'purpose_of_listing',
'value' => 'Display',
'compare' => '='
)
)
);
// echo "\n" . json_encode($args) . "\n";
$query = new WC_Product_Query($args);
$products = $query->get_products();
$productsCount += count($products);
$thisProducts = [];
foreach ($products as $product) {
$thisProducts[] = ['name' => $product->name, 'id' => $product->id, 'image' => wp_get_attachment_thumb_url($product->get_image_id())];
// echo " thisProducts " . $value2->name . " pro: " . $product->get_name() . ' slug:'. $product->get_slug . "\n";
}
if (!empty($thisProducts)) {
$thisProduct[] = ['catId' => $value->term_id, 'catname' => $value->name, 'subcatname' => $value2->name, 'subcatId' => $value2->term_id, 'products' => $thisProducts];
}
} catch (Throwable $th) {
// echo $th->getMessage();
}
}
// if (!empty($thisProducts)) {
$productsAr[] = $thisProduct;
// }
// $productsAr[] = $thisProduct;
} else {
$limit = 5;
try {
$args = array(
'limit' => $limit,
'orderby' => 'name',
'status' => 'publish',
'order' => 'DESC',
'tax_query' => array(
array(
'taxonomy' => 'product_cat',
'field' => 'id',
'terms' => $value->term_id,
),
),
'meta_query' => array(
array(
'key' => 'purpose_of_listing',
'value' => 'Display',
'compare' => '='
)
)
);
// echo "\n" . json_encode($args) . "\n";
$query = new WC_Product_Query($args);
$products = $query->get_products();
$productsCount += count($products);
$thisProducts = [];
foreach ($products as $product) {
$thisProducts[] = ['name' => $product->name, 'id' => $product->id, 'image' => wp_get_attachment_thumb_url($product->get_image_id())];
}
$thisProduct = ['catId' => $value->term_id, 'catname' => $value->name, 'products' => $thisProducts];
// echo json_encode($thisProducts);
// echo "--- enc -- \n";
if (!empty($thisProducts)) {
$productsAr[] = $thisProduct;
}
// echo "\n thisProducts". json_encode($thisProducts). "\n";
} catch (Throwable $th) {
// echo $th->getMessage();
}
}
}
} else {
$resultdata = array("message" => "Invalid request");
return new WP_REST_Response($resultdata, 400);
}
$encrypeddata = encryptdaata(['data' => $productsAr]);
return new WP_REST_Response($encrypeddata);
}
function getProductByIdf($request)
{
$parametresen = $request->get_body_params();
$parametres = decryptdaata($parametresen['params']);
$productId = $parametres['productId'];
// echo $productId . "\n";
// $_pf = new WC_Product_Factory();
$product = wc_get_product($productId);
$pdroductdata = (object) $product->get_data();
// echo $pdroductdata->description;
$relatedProductId = wc_get_related_products($productId, 4);
$relatedProductsa = [];
foreach ($relatedProductId as $key => $value) {
$relProduct = wc_get_product($value);
$relatedProductsa[] = ['name' => $relProduct->name, 'id' => $value, 'image' => wp_get_attachment_thumb_url($relProduct->get_image_id())];
}
$galleryImageId = $product->get_gallery_image_ids();
$gallerImages = [];
foreach ($galleryImageId as $key => $value) {
$gallerImages[] = wp_get_attachment_image_url($value, 'medium');
}
$_image = wp_get_attachment_image_src(get_post_thumbnail_id($productId), 'medium'); //'single-post-thumbnail');
$pdroductdata->image = $_image;
$pdroductdata->related_ids = $relatedProductId;
$pdroductdata->galleryImages = $gallerImages;
$pdroductdata->relatedProducts = $relatedProductsa;
$pdroductdata->categories = [];
// $pdroductdata->attribuites = wc_display_product_attributes ($product) ;
$encrypeddata = encryptdaata(['data' => $pdroductdata]);
return new WP_REST_Response($encrypeddata);
}
function showMyQuotesListf($request)
{
$parametresen = $request->get_body_params() ?? array();
$parametres = decryptdaata($parametresen['params']);
$date1 = $parametres['start_date'];
$date2 = $parametres['end_date'];
$user_id = $parametres['user_id'];
$page = $parametres['page'] ?? 1;
$perpage = $parametres['perpage'] ?? 10;
$limit = " limit $perpage";
$daterange = "";
if ($page > 1) {
$perpage1 = $page * $perpage;
$perpage1 = ($perpage1 - $perpage);
$limit = " limit $perpage1,$perpage";
}
$datesBetween = "";
if (!empty($date1) && !empty($date2)) {
$limit = "";
$datesBetween = " AND date(a.requested_on) between '$date1' and '$date2' ";
}
$whereuserid = '';
if (!empty($user_id)) {
$whereuserid = " a.user_id='$user_id' ";
} else {
$resultdata = array("message" => "Not a valid request.", 'success' => 0);
return new WP_REST_Response($resultdata, 400);
}
global $wpdb;
$table_name = "wp_quotation";
$table_namerfq = "wp_request_quote";
// $whereQuery = $whereuserid . (!empty($datesBetween) && !empty($user_id)) ? " and $datesBetween " : $whereuserid;
// $whereQuery = !empty(trim($whereQuery)) ? " where $whereQuery " : "";
$qquery = "SELECT a.*,b.location,b.application from $table_name a LEFT JOIN $table_namerfq b on a.rfq_id=b.id WHERE $whereuserid AND a.cs_view != '0' $datesBetween order by a.id desc $limit";
// die($rfqquery);
$count = $wpdb->query("SELECT count(*) as count from $table_name WHERE $whereuserid ");
// die("connttt $count");
$results = $wpdb->get_results($qquery, ARRAY_A);
if ($wpdb->last_error) {
$resultdata = array("message" => "something went wrong.", 'reson' => $wpdb->last_error);
return new WP_REST_Response($resultdata, 400);
}
if (count($results ?? []) > 0) {
$results = $results ?? [];
for ($i = 0; $i < count($results); $i++) {
// $res = (object) $results[$i];
$image = wp_get_attachment_image_src(get_post_thumbnail_id($results[$i]['product_id']), 'thumbnail'); //'single-post-thumbnail');
$results[$i]['image'] = $image;
unset($results[$i]['dynamic_terms_1'], $results[$i]['dynamic_terms_2'], $results[$i]['assign_terms_conditions']);
$qtstatus = trim($results[$i]['qt_status']);
if ($qtstatus != 'Requested For Revision') {
// unset( $results[$i]['comments']);
}
$results[$i]['qt_status'] = $qtstatus === 'Quote Send to Coustmer' ? 'In Progress' : $qtstatus;
}
$resulta = array("data" => $results ?? [], 'success' => 1);
$encrypted = encryptdaata($resulta);
return new WP_REST_Response($encrypted, 200);
} else {
if ($page > 1) {
$resulta = array("data" => [], 'success' => 1);
$encrypted = encryptdaata($resulta);
return new WP_REST_Response($encrypted, 200);
}
$resultdata = array("message" => "No Qoutes created yet. Raise a request for Quote.", 'success' => 0);
return new WP_REST_Response($resultdata, 400);
}
}
function acceptMyQuotef($request)
{
$parametresen = $request->get_body_params() ?? array();
$parametres = decryptdaata($parametresen['params']);
$_wpnonce = $parametres['_wpnonce'];
$user_id = intval($parametres['user_id']);
$quotation_id = intval($parametres['quotation_id']);
// if (!isset($_POST['_wpnonce']) || !wp_verify_nonce($_POST['_wpnonce'], 'accept_quotation_nonce')) {
// wc_add_notice('Nonce verification failed.', 'error');
// return;
// }
if ($_wpnonce != 'accept_quotation_nonce') {
$resultdata = array("message" => "Invalid request.", 'success' => 0);
return new WP_REST_Response($resultdata, 400);
}
global $wpdb;
$table_name = $wpdb->prefix . 'quotation';
$updated = $wpdb->update(
$table_name,
array(
'qt_status' => 'Accepted'
),
array('id' => $quotation_id, 'user_id' => $user_id)
);
if ($updated !== false) {
$edit_url = admin_url('admin.php?page=edit-quotation&id=' . $quotation_id);
create_notification(
'Customer accepted quotation',
'Customer accepted quotation for "' . $quotation_id . '". <a target="_blank" href="' . $edit_url . '" style="color: blue; text-decoration: underline;">Click here</a> to view/edit.',
array(
'meta_input' => array(
'user_id' => $user_id,
'action' => 'qt accepted',
)
)
);
$resulta = array("message" => "Quotation accepted.", 'qt_status' => 'Accepted', 'success' => 1);
$encrypted = encryptdaata($resulta);
return new WP_REST_Response($encrypted, 200);
} else {
$resultdata = array("message" => "Unable to accept the quote.", 'success' => 0);
return new WP_REST_Response($resultdata, 400);
}
}
function showMyAgreementsf($request)
{
$parametresen = $request->get_body_params() ?? array();
$parametres = decryptdaata($parametresen['params']);
$date1 = $parametres['start_date'];
$date2 = $parametres['end_date'];
$user_id = $parametres['user_id'];
$page = $parametres['page'] ?? 1;
$perpage = $parametres['perpage'] ?? 10;
$limit = " limit $perpage";
$daterange = "";
if ($page > 1) {
$perpage1 = $page * $perpage;
$perpage1 = ($perpage1 - $perpage);
$limit = " limit $perpage1,$perpage";
}
$datesBetween = "";
if (!empty($date1) && !empty($date2)) {
$limit = "";
$datesBetween = " date(a.at_created_at) between '$date1' and '$date2' ";
}
if (!empty($user_id)) {
$whereuserid = " b.user_id='$user_id' ";
}
global $wpdb;
$table_name1 = "wp_agreement";
$table_name2 = "wp_quotation";
$whereQuery = $datesBetween . (!empty($datesBetween) && !empty($user_id)) ? " and $whereuserid " : $whereuserid;
$whereQuery = !empty(trim($whereQuery)) ? " where $whereQuery " : "";
$rfqquery = "select * from $table_name1 $whereQuery order by id desc $limit";
// die($rfqquery);
$count = $wpdb->query("SELECT count(*) as count from $table_name1 $whereQuery ");
// die("connttt $count");
$results = $wpdb->get_results("SELECT * from $table_name1 a left join $table_name2 b on a.qt_id=b.id $whereQuery order by a.agreement_id desc $limit", ARRAY_A);
if ($wpdb->last_error) {
$resultdata = array("message" => "something went wrong.");
return new WP_REST_Response($resultdata, 400);
}
if (count($results ?? []) > 0) {
$results = $results ?? [];
for ($i = 0; $i < count($results); $i++) {
$res = (object) $results[$i];
$image = wp_get_attachment_image_src(get_post_thumbnail_id($res->product_id), 'thumbnail'); //'single-post-thumbnail');
$results[$i]['image'] = $image;
unset($results[$i]['dynamic_terms_1'], $results[$i]['dynamic_terms_2'], $results[$i]['revision_details']);
}
$resulta = array("data" => $results ?? [], 'success' => 1);
$encrypted = encryptdaata($resulta);
return new WP_REST_Response($encrypted, 200);
} else {
if ($page > 1) {
$resulta = array("data" => [], 'success' => 1);
$encrypted = encryptdaata($resulta);
return new WP_REST_Response($encrypted, 200);
}
$resultdata = array("message" => "No Agreement generated yet. Raise a request for Quote to create Qoutes and Agreement or contact to GMMCO team.", 'success' => 1);
return new WP_REST_Response($resultdata, 400);
}
}
function uploadMySignedPdff($request)
{
$parametresen = $request->get_body_params();
$parameters = decryptdaata($parametresen['params']);
$id = intval($parameters['id']);
$agreement_id = intval($parameters['agreement_id']);
global $wpdb;
global $host;
$upload_dir = wp_upload_dir();
$foldername = "/pdfuploads-cus/";
$upload_path = $upload_dir['basedir'] . $foldername;
// Ensure the uploads directory exists
if (!is_dir($upload_path)) {
wp_mkdir_p($upload_path);
}
$file_name1 = $_FILES['images']['name'];
$file_tmp_name = $_FILES['images']['tmp_name'];
$file_type = wp_check_filetype($file_name1);
if ($file_type['ext'] !== 'pdf') {
$resultdata = array("message" => "Only PDF file allowed.");
return new WP_REST_Response($resultdata, 400);
}
$filenameext = rtrim($file_name1, '.pdf');
$filenameext = rtrim($filenameext, '.PDF');
$randnnum = rand(10, 99);
$file_name = $filenameext . $randnnum . '.pdf';
$file_url = "$host/wp-content/uploads$foldername$file_name";
// $file_url_up = $upload_dir['baseurl'] . '/pdfuploads-cus/' . $file_name1;
$file_url_up = $upload_path . $file_name;
$user = get_userdata($id);
// $first_name = get_user_meta($id, 'first_name', true);
// $first_name = get_user_meta($id, 'first_name', true);
// die($file_url);
if (move_uploaded_file($file_tmp_name, $file_url_up)) {
$isUpdated = $wpdb->update(
'wp_agreement',
array('upload_pdf_cus' => $file_url),
array('agreement_id' => $agreement_id),
array('%s'),
array('%d')
);
create_notification(
'User uploaded signed PDF',
'User "' . $user->first_name . '" uploaded signed PDF. Email id "' . $user->user_email . '" ',
array(
'meta_input' => array(
'user_id' => $id,
'action' => 'User submited offer',
)
)
);
} else {
$resultdata = array("message" => "Unable to upload. Please try later.");
return new WP_REST_Response($resultdata, 400);
}
$encrypted = encryptdaata(array('message' => 'Agreement file saved.', 'success' => 1));
return new WP_REST_Response($encrypted);
}
function requestForRevisionf($request)
{
$parametresen = $request->get_body_params();
$parameters = decryptdaata($parametresen['params']);
$user_id = intval($parameters['user_id']);
$quotation_id = intval($parameters['id']);
global $wpdb;
$table_name = $wpdb->prefix . 'quotation';
$quotation_id = intval($quotation_id);
$user_id = intval($user_id);
$comments = sanitize_text_field($parameters['comment']);
// Update the quotation comments
$updated = $wpdb->update($table_name, array('comments' => $comments, 'qt_status' => 'Requested For Revision'), array('id' => $quotation_id, 'user_id' => $user_id));
if ($updated) {
$encrypted = encryptdaata(array('message' => 'Your Request has been sent.', 'qt_status' => 'Requested For Revision', 'success' => 1));
return new WP_REST_Response($encrypted);
} else {
$resultdata = array("message" => "Unable to update your request. Please try later.", 'reason' => $wpdb->last_error);
return new WP_REST_Response($resultdata, 400);
}
}
function showOrdersListf($request)
{
$parametresen = $request->get_body_params() ?? array();
$parametres = decryptdaata($parametresen['params']);
$date1 = $parametres['start_date'];
$date2 = $parametres['end_date'];
$user_id = $parametres['user_id'];
$page = $parametres['page'] ?? 1;
$perpage = $parametres['perpage'] ?? 10;
$rfqlistr = $parametres['rfqlistr'];
$pargs = array(
'limit' => 15,
// 'type' => 'shop_order'
); //,'customer_id'=>$user_id
if (!empty($date1) && !empty($date2)) {
$limit = "";
// $datesBetween = " date(requested_on) between '$date1' and '$date2' ";
$pargs['date_created'] = strtotime($date1) . '...' . strtotime($date2 . " 23:59");
$pargs['limit'] = -1;
}
// if (!empty($user_id)) {
// $whereuserid = " user_id='$user_id' ";
// }
global $wpdb;
// $args = array('status' => array('wc-completed'), 'limit' => -1, 'type' => 'shop_order');
// die(json_encode($args));
// $results = wc_get_orders($args);
// $tableName = $wpdb->prefix . "wc_orders";
// $queryRO = "SELECT count(*) as cnt FROM `wp_wc_orders` WHERE `customer_id` =$user_id AND `status` IN ('wc-renewal_status', 'wc-contract-renewed')";
// $customerRenewalOrder = $wpdb->get_var($queryRO);
$args2 = array(
'limit' => -1,
// 'status' => array('wc-completed'),
'status' => array('wc-renewal_status', 'wc-contract-renewed'),
'orderby' => 'date',
'order' => 'DESC',
'customer_id' => $user_id
);
$orderData2 = [];
$contries = new WC_Countries();
$states = $contries->get_states("IN");
if ($rfqlistr == 0) {
$orders2 = wc_get_orders($args2);
foreach ($orders2 as $order2) {
if ($order2 instanceof WC_Order) {
// $order = wc_get_order($order->ID);
$order_items2 = $order2->get_items();
$orderDatta2 = (object) $order2->get_data();
try {
unset($orderDatta2->shipping, $orderDatta2->cart_hash, $orderDatta2->customer_user_agent, $orderDatta2->download_permissions_granted, $orderDatta2->tax_lines);
} catch (\Throwable $th) {
}
try {
$billingdata2 = (object) $orderDatta2->billing;
$statef2 = $states[$billingdata2->state];
$billingdata2->statef = strtoupper($statef2);
$orderDatta2->billing = $billingdata2;
} catch (\Throwable $th) {
}
$orderData12['orderdata'] = $orderDatta2;
// $orderData1['status'] = $order->get_status();
$order_status2 = wc_get_order_status_name($order2->get_status());
$orderData12['status'] = $order_status2;
$orderData12['orderNum'] = $order2->get_order_number();
foreach ($order_items2 as $order_item2) {
$product_item2 = $order_item2->get_data();
$image2 = wp_get_attachment_image_src(get_post_thumbnail_id(intval($product_item2['product_id'])), 'thumbnail'); //'single-post-thumbnail');
$product_item2['image'] = $image2;
$orderData12['orderItems'] = $product_item2;
}
$orderData2[] = $orderData12;
}
}
}
$args = array(
// 'limit' => -1,
'limit' => $perpage,
'paged' => $page,
// 'status' => array('wc-completed'),
'status' => array('wc-work_order', 'wc-completed', 'wc-processing', 'wc-pending', 'wc-sdp', 'wc-opassigned', 'wc-equipmentassigned'),
'orderby' => 'date',
'order' => 'DESC',
'customer_id' => $user_id
);
$orderData = [];
$orders = wc_get_orders($args);
foreach ($orders as $order) {
if ($order instanceof WC_Order) {
// $order = wc_get_order($order->ID);
$order_items = $order->get_items();
$orderDatta = (object) $order->get_data();
try {
// unset($orderDatta->shipping, $orderDatta->cart_hash, $orderDatta->customer_user_agent, $orderDatta->download_permissions_granted, $orderDatta->tax_lines);
} catch (\Throwable $th) {
}
try {
$billingdata = (object) $orderDatta->billing;
$statef = $states[$billingdata->state];
$billingdata->statef = strtoupper($statef);
$orderDatta->billing = $billingdata;
} catch (\Throwable $th) {
}
// try {
// $metadata = (array) $orderDatta->meta_data;
// foreach ($metadata as $mkey => $mvaluemap) {
// if(array_key_exists("start_date", $mvaluemap)){
// $stdt = $mvaluemap['value'];
// $isdateList = explode("-",$stdt);
// if(is_array($isdateList)){
// if(strlen($isdateList[0]) == 2){
// $stdt = implode('-', array_reverse(explode('-', $stdt)));
// $mvaluemap['value'] = $stdt;
// $metadata[$mkey] = $mvaluemap;
// }
// } }else if(array_key_exists("end_date", $mvaluemap)){
// $enddt = $mvaluemap['value'];
// $isdateList = explode("-",$enddt);
// if(is_array($isdateList)){
// if(strlen($isdateList[0]) == 2){
// $enddt = implode('-', array_reverse(explode('-', $enddt)));
// $mvaluemap['value'] = $enddt;
// $metadata[$mkey] = $mvaluemap;
// }
// } }
// }
// } catch (\Throwable $th) {
// //throw $th;
// }
$orderData1['orderdata'] = $orderDatta;
// $orderData1['status'] = $order->get_status();
$order_status = wc_get_order_status_name($order->get_status());
$orderData1['status'] = $order_status;
$orderData1['orderNum'] = $order->get_order_number();
foreach ($order_items as $order_item) {
$product_item = $order_item->get_data();
$image = wp_get_attachment_image_src(get_post_thumbnail_id(intval($product_item['product_id'])), 'thumbnail'); //'single-post-thumbnail');
$product_item['image'] = $image;
$orderData1['orderItems'] = $product_item;
}
$orderData[] = $orderData1;
}
}
if (count($orderData ?? []) > 0) {
$resulta = array('renewal' => $orderData2, "data" => $orderData, 'success' => 1);
$encrypted = encryptdaata($resulta);
return new WP_REST_Response($encrypted, 200);
} else {
if ($page > 1) {
$resulta = array('renewal' => $orderData2, "data" => $orderData, 'success' => 1);
$encrypted = encryptdaata($resulta);
return new WP_REST_Response($encrypted, 200);
}
$resultdata = array("message" => "No orders have been created yet. Please raise a Request-For-Quote to initiate a rental order.", 'success' => 1);
return new WP_REST_Response($resultdata, 400);
}
}
function getDashCountf($request)
{
$parametresen = $request->get_body_params() ?? array();
$parametres = decryptdaata($parametresen['params']);
$user_id = $parametres['user_id'];
$lead_phone = $parametres['lead_phone'] ?? '';
global $wpdb;
$whereuserid = " user_id='$user_id' ";
$whereuserid_lead = " user_id='$user_id' ";
if ($lead_phone != "") {
// $whereuserid_lead .= " or lead_phone='$lead_phone' ";
$whereuserid_lead .= " or (lead_phone='$lead_phone' and IFNULL(user_id,0)=0)";
}
$cartlistId = get_user_meta($user_id, 'cartlistId', true);
$wishIdlist = explode(",", $cartlistId);
// die(json_encode($wishIdlist));
// $integerIDs = array_map('intval', $wishIdlistt);
$integerIDss = array_unique($wishIdlist);
// $integerIDss = array_map('trim', $integerIDss);
$cartlistIdIDss = array_filter($integerIDss, 'strlen');
$table_name_quotation = "wp_quotation";
$res1 = $wpdb->get_var("SELECT count(*) as count from $table_name_quotation WHERE $whereuserid ");
// $result1 = $wpdb->get_results($res1);
$table_name_rfq = "wp_request_quote";
$res2 = $wpdb->get_var("SELECT count(*) as count from $table_name_rfq WHERE $whereuserid ");
// $result2 = $wpdb->get_results($res2);
$table_name_leads = "wp_leads";
$query3 = "SELECT count(*) as count from $table_name_leads WHERE $whereuserid_lead ";
// echo $query3;
$res3 = $wpdb->get_var($query3);
// $result3 = $wpdb->get_results($res3);
// if($wpdb->last_error){
// $resultdata = array("message" => "something went wrong. $table_name_leads". $wpdb->last_error);
// return new WP_REST_Response($resultdata, 400);
// }
$whereuseridaggrement = " b.user_id='$user_id' ";
global $wpdb;
$table_name1 = "wp_agreement";
$table_name2 = "wp_quotation";
$queryAgrr = "SELECT count(*) count from $table_name1 a left join $table_name2 b on a.qt_id=b.id WHERE $whereuseridaggrement ";
$res4 = $wpdb->get_var($queryAgrr);
$tableNameOrders = $wpdb->prefix . "wc_orders";
$query5 = "SELECT count(*) as count from $tableNameOrders WHERE customer_id=$user_id ";
$res5 = $wpdb->get_var($query5);
$query6 = "SELECT count(*) as count from wp_logsheet WHERE order_id in(SELECT id from $tableNameOrders WHERE customer_id=$user_id) ";
$res6 = $wpdb->get_var($query6);
// $table_name_logs = "wp_logsheet";
// $query = "SELECT count(id) FROM $table_name_logs WHERE user_id=$user_id ";
$resulta = array("data" => ['quotes' => $res1, 'rfq' => $res2, 'leads' => $res3, 'agreement' => $res4, 'orders' => $res5, 'logs' => $res6,'cartid'=>$cartlistIdIDss], 'success' => 1);
$encrypted = encryptdaata($resulta);
return new WP_REST_Response($encrypted, 200);
}
function addWishlistf($request)
{
$parametresen = $request->get_body_params() ?? array();
$parametres = decryptdaata($parametresen['params']);
$prodId = $parametres['prodId'];
$user_id = $parametres['user_id'];
$t = $parametres['type'];
$getWishId = get_user_meta($user_id, 'wishlistId', true);
$wishIdlist = explode(",", $getWishId);
$wishIdlistt = $wishIdlist + $prodId;
// $integerIDs = array_map('intval', $wishIdlistt);
$integerIDss = array_unique($wishIdlistt);
// $integerIDss = array_map('trim', $integerIDss);
$integerIDss = array_filter($integerIDss, 'strlen');
if ($t == 'r') {
$integerIDss = array_diff($integerIDss, $prodId);
}
$sid = implode(",", $integerIDss);
update_user_meta($user_id, 'wishlistId', $sid);
$resulta = array("data" => $sid, 'ex' => $getWishId, 'success' => 1);
$encrypted = encryptdaata($resulta);
return new WP_REST_Response($encrypted, 200);
}
function addCartlistf($request)
{
$parametresen = $request->get_body_params() ?? array();
$parametres = decryptdaata($parametresen['params']);
$prodId = $parametres['prodId'];
$user_id = $parametres['user_id'];
$t = $parametres['type'];
$getWishId = get_user_meta($user_id, 'wishlistId', true);
$wishIdlist = explode(",", $getWishId);
$wishIdlistt = $wishIdlist + $prodId;
// $integerIDs = array_map('intval', $wishIdlistt);
$integerIDss = array_unique($wishIdlistt);
// $integerIDss = array_map('trim', $integerIDss);
$integerIDss = array_filter($integerIDss, 'strlen');
if ($t == 'r') {
$integerIDss = array_diff($integerIDss, $prodId);
}
$sid = implode(",", $integerIDss);
update_user_meta($user_id, 'wishlistId', $sid);
$resulta = array("data" => $sid, 'ex' => $getWishId, 'success' => 1);
$encrypted = encryptdaata($resulta);
return new WP_REST_Response($encrypted, 200);
}
function convert_number_to_words_mf($number)
{
$hyphen = '-';
$conjunction = ' and ';
$separator = ', ';
$negative = 'negative ';
$decimal = ' point ';
$dictionary = [
0 => 'Zero',
1 => 'One',
2 => 'Two',
3 => 'Three',
4 => 'Four',
5 => 'Five',
6 => 'Six',
7 => 'Seven',
8 => 'Eight',
9 => 'Nine',
10 => 'Ten',
11 => 'Eleven',
12 => 'Twelve',
13 => 'Thirteen',
14 => 'Fourteen',
15 => 'Fifteen',
16 => 'Sixteen',
17 => 'Seventeen',
18 => 'Eighteen',
19 => 'Nineteen',
20 => 'Twenty',
30 => 'Thirty',
40 => 'Forty',
50 => 'Fifty',
60 => 'Sixty',
70 => 'Seventy',
80 => 'Eighty',
90 => 'Ninety',
100 => 'Hundred',
1000 => 'Thousand',
100000 => 'Lakh',
10000000 => 'Crore'
];
if (!is_numeric($number)) {
return false;
}
if (($number >= 0 && (int) $number < 0) || (int) $number < 0 - PHP_INT_MAX) {
// Overflow
// trigger_error(
// 'convert_number_to_words_mf only accepts numbers between -' . PHP_INT_MAX . ' and ' . PHP_INT_MAX,
// E_USER_WARNING
// );
return false;
}
if ($number < 0) {
return $negative . convert_number_to_words_mf(abs($number));
}
$string = $fraction = null;
if (strpos($number, '.') !== false) {
list($number, $fraction) = explode('.', $number);
}
switch (true) {
case $number < 21:
$string = $dictionary[$number];
break;
case $number < 100:
$tens = ((int) ($number / 10)) * 10;
$units = $number % 10;
$string = $dictionary[$tens];
if ($units) {
$string .= $hyphen . $dictionary[$units];
}
break;
case $number < 1000:
$hundreds = $number / 100;
$remainder = $number % 100;
$string = $dictionary[(int) $hundreds] . ' ' . $dictionary[100];
if ($remainder) {
$string .= $conjunction . convert_number_to_words_mf($remainder);
}
break;
case $number < 100000:
$thousands = $number / 1000;
$remainder = $number % 1000;
$string = convert_number_to_words_mf((int) $thousands) . ' ' . $dictionary[1000];
if ($remainder) {
$string .= $remainder < 100 ? $conjunction : $separator;
$string .= convert_number_to_words_mf($remainder);
}
break;
case $number < 10000000:
$lakhs = $number / 100000;
$remainder = $number % 100000;
$string = convert_number_to_words_mf((int) $lakhs) . ' ' . $dictionary[100000];
if ($remainder) {
$string .= $remainder < 100 ? $conjunction : $separator;
$string .= convert_number_to_words_mf($remainder);
}
break;
default:
$crores = $number / 10000000;
$remainder = $number % 10000000;
$string = convert_number_to_words_mf((int) $crores) . ' ' . $dictionary[10000000];
if ($remainder) {
$string .= $remainder < 100 ? $conjunction : $separator;
$string .= convert_number_to_words_mf($remainder);
}
break;
}
if (null !== $fraction && is_numeric($fraction)) {
$string .= $decimal;
$words = [];
foreach (str_split((string) $fraction) as $number) {
$words[] = $dictionary[$number];
}
$string .= implode(' ', $words);
}
return $string;
}
function getNotificationf($request)
{
$parametresen = json_decode($request->get_body(), true); // <-- safest way
$paramData = $parametresen['params'] ?? [];
if (is_array($paramData)) {
$parametres = $paramData;
} else {
$parametres = decryptdaata($paramData); // if you're using encryption
}
// $parametresen = $request->get_body_params() ?? array();
// $parametres = decryptdaata($parametresen['params']);
$user_id = $parametres['user_id'];
global $wpdb;
// $args = array(
// 'meta_query' => array(
// array(
// 'key' => 'user_id',
// 'value' => $user_id
// )
// ),
// 'post_type' => 'notifications',
// 'posts_per_page' => 15,
// 'orderby'=>'ID',
// 'order'=>'DESC'
// // 'paged'=>1,
// );
// $postss = new WP_Query($args);
// $posts = $postss->posts ;
// $posts = $wpdb->get_results("SELECT a.ID,a.post_date,a.post_content,a.post_title, b.meta_key,b.meta_value FROM wp_posts a left join `wp_postmeta` b on a.ID=b.post_id where a.post_type='notifications' and a.post_status='publish' and b.post_id IN(SELECT post_id from wp_postmeta where b.meta_key='user_id' and b.meta_value='$user_id') group by a.post_title ORDER by a.ID DESC;");
// // echo "length " . count($posts);
// // die(json_encode($posts));
// if($posts){
// $resulta = array("data" => $posts, 'success' => 1);
// $encrypted = encryptdaata($resulta);
// return new WP_REST_Response($encrypted, 200);
// }
// Fetch the latest agreement id and status based on the most recent update_at timestamp
$agreement = $wpdb->get_row($wpdb->prepare("SELECT agreement_id, agreement_id,upload_pdf_cus,`status`,updated_at, notification_status FROM wp_agreement WHERE ag_user_id = %d ORDER BY updated_at DESC LIMIT 1", $user_id));
// print_r( $agreement);
// Check if a quotation exists and if the status is "Revised" or "Quote Send to Customer"
// if ($agreement && ($agreement->status === "PDF Uploaded" || $agreement->status === "Order Created")) {
// Generate message based on status
$data = [];
$agd = [];
if ($agreement) {
$agd['time'] = $agreement->updated_at;
$agd['id'] = $agreement->agreement_id;
$agd['notification_status'] = $agreement->notification_status;
if (($agreement->status === "PDF Uploaded") && ($agreement->upload_pdf_cus == null)) {
$agd['title'] = "New Document from GMMCO";
$agd['message'] = "PDF uploaded by GMMCO";
$agd['page'] = "agreement";
} elseif ($agreement->status === "Order Created") {
$agd['title'] = "You're All Set! New Contract Ready";
$agd['message'] = "A new contract generated.";
$agd['page'] = "agreement";
}
$agd['type'] = 'agreement';
$data[] = $agd;
}
// print_r($agreement);
// print_r($agd);
// exit();
// ----------
$contract_ids = $wpdb->get_row(
$wpdb->prepare(
"SELECT id, contract_id,updated_at, notification_status FROM {$wpdb->prefix}contract_renewal
WHERE user_id = %d AND reminder_sent = 1 AND extended_date_by_user IS NULL
ORDER BY updated_at DESC LIMIT 1",
$user_id
)
);
$contract_renewal = $wpdb->get_row(
$wpdb->prepare(
"SELECT * FROM wp_contract_renewal WHERE user_id = %d AND extended_date_by_admin IS NOT NULL
ORDER BY updated_at DESC LIMIT 1",
$user_id
)
);
$agd = [];
$contract_message = '';
// if (!empty($contract_ids) || !empty($contract_renewal))
if (!empty($contract_renewal)) {
$agd['time'] = $contract_renewal->updated_at;
$agd['id'] = $contract_renewal->id;
$agd['title'] = "Contract Period Extended by Gmmco";
$agd['message'] = "Gmmco extended your contract renewal date.";
$agd['page'] = 'contract_renewal';
$agd['notification_status'] = $contract_renewal->notification_status;
$agd['type'] = 'contract renewal';
$data[] = $agd;
}
// Check if contract IDs exist
if (!empty($contract_ids)) {
$agd['time'] = $contract_ids->updated_at;
$agd['id'] = $contract_ids->id;
$agd['title'] = "Renewal Pending – Action Needed";
$agd['message'] = "Gmmco sends reminder to extend your contract.";
$agd['page'] = 'contract_renewal';
$agd['notification_status'] = $contract_ids->notification_status;
$agd['type'] = 'contract renewal';
$data[] = $agd;
}
// ----------
// Fetch the latest quotation id and qt_status based on the most recent update_at timestamp
$quotation = $wpdb->get_row($wpdb->prepare("SELECT id, qt_status,updated_at, notification_status FROM wp_quotation WHERE user_id = %d
AND cs_view = 1
ORDER BY updated_at DESC
LIMIT 1
", $user_id));
$agd = [];
// Check if a quotation exists and if the status is "Revised" or "Quote Send to Customer"
if ($quotation && ($quotation->qt_status === "Revised" || $quotation->qt_status === "Quote Send to Customer")) {
// Generate message based on status
$agd['page'] = 'quotation';
$agd['time'] = $quotation->updated_at;
$agd['id'] = $quotation->id;
$agd['type'] = 'quotation';
if ($quotation->qt_status === "Quote Send to Customer") {
$agd['title'] = "Your Quotation is Ready";
$agd['message'] = "New qutation is created";
} elseif ($quotation->qt_status === "Revised") {
$agd['title'] = "Review Revised Quotation";
$agd['message'] = "Qutation is revised";
}
$agd['notification_status'] = $quotation->notification_status;
$data[] = $agd;
}
$quotation = $wpdb->get_row($wpdb->prepare("SELECT id, qt_status,updated_at, notification_status FROM wp_quotation AND cs_view = 1
ORDER BY updated_at DESC
LIMIT 1", $user_id));
$agd = [];
// Check if a quotation exists and if the status is "Revised" or "Quote Send to Customer"
if ($quotation && ($quotation->qt_status === "Revised" || $quotation->qt_status === "Quote Send to Customer")) {
// Generate message based on status
if ($quotation->qt_status === "Quote Send to Customer") {
$agd['id'] = $quotation->id;
$agd['title'] = "Your Quotation is Ready";
$agd['notification_status'] = $quotation->notification_status;
$agd['message'] = "New qutation is created";
} elseif ($quotation->qt_status === "Revised") {
$agd['id'] = $quotation->id;
$agd['title'] = "Review Revised Quotation";
$agd['notification_status'] = $quotation->notification_status;
$agd['message'] = "Qutation is revised";
}
$agd['type'] = 'quotation';
$agd['page'] = 'quotation';
$agd['time'] = $quotation->updated_at;
$data[] = $agd;
}
//----------
$work_order = $wpdb->get_row($wpdb->prepare(
"SELECT id, contract_id , updated_at
FROM wp_work_orders
WHERE wo_type = 'First work order'
AND is_work_order_generated = 1
ORDER BY updated_at DESC
LIMIT 1",
$user_id
));
$agd = [];
if ($work_order) {
// Check if a 'Monthly Work Order' exists for the same contract_id
$monthly_work_order = $wpdb->get_var($wpdb->prepare(
"SELECT COUNT(*)
FROM wp_work_orders
WHERE wo_type = 'Monthly Work Order'
AND contract_id = %d",
$work_order->contract_id
));
// Show notification only if no 'Monthly Work Order' exists
if ($monthly_work_order == 0) {
$agd['id'] = $work_order->id;
$agd['type'] = 'work order';
$agd['message'] = "First work order created and Equipement Shipped Successfully.";
$agd['time'] = $work_order->updated_at;
$agd['page'] = 'contracts';
$agd['title'] = "Your First Order is on the Way";
$agd['notification_status'] = $work_order->notification_status;
$data[] = $agd;
}
}
// Daily reminder for log sheet - pseudo logic
$today_date = date('Y-m-d');
$logsheet_count = $wpdb->get_var($wpdb->prepare(
"SELECT COUNT(*) FROM wp_logsheet WHERE operator_id = %d AND log_date >= %s AND notification_status = 0",
$user_id, $today_date));
if (intval($logsheet_count) === 0) {
$data[] = [
'time' => current_time('mysql'),
'id' => 'N/A',
'title' => "Daily Reminder: Submit Log Sheet",
'message' => "Please submit your log sheet for today to keep records updated.",
'page' => 'logs',
'type' => 'logsheet_daily_reminder',
];
}
// Assignment and machine assignment notification
// Check if operator has a machine assigned (in assign_operators_contracts)
$assignment = $wpdb->get_row($wpdb->prepare(
"SELECT id, meachine_id, contract_id, created_on FROM wp_assign_operators_contracts WHERE operator_id = %d ORDER BY created_on DESC LIMIT 1",
$user_id));
if ($assignment) {
//$machine_post = get_post($machine_id);
$machine_post = get_post($assignment->meachine_id);
$machine_title = $machine_post ? $machine_post->post_title : '';
$data[] = [
'time' => $assignment->created_on,
'id' => $assignment->id,
'title' => "Machine Assignment Notification",
'message' => "You have been assigned to machine $machine_title.",
'page' => 'assignment',
'type' => 'assignment',
];
}
// Initial inspection pending notification
// Check for initial inspection record for operator's assigned machine/order
if ($assignment) {
$machine_id = $assignment->meachine_id;
$contract_id = $assignment->contract_id;
$inspection = $wpdb->get_row($wpdb->prepare(
"SELECT * FROM wp_service_request WHERE operator_id = %d AND equipment_id = %d AND order_id = %d AND stype = 1 ORDER BY created_on DESC LIMIT 1",
$user_id, $machine_id, $contract_id));
if (!$inspection) {
$data[] = [
'time' => current_time('mysql'),
'id' => 'N/A',
'title' => "Initial Inspection Pending",
'message' => "Please complete the initial inspection for your assigned equipment.",
'page' => 'inspection',
'type' => 'Initial inspection',
];
}
}
// Job closure / Contract completion notification
// Check the contract end date and if today is near or past end date and no closure notification sent yet
if ($assignment) {
$contract_id = $assignment->contract_id;
$order = wc_get_order($contract_id);
if ($order) {
$end_date = $order->get_meta('end_date');
if ($end_date) {
$current_date = date('Y-m-d');
$end_ts = strtotime($end_date);
$now_ts = strtotime($current_date);
if ($now_ts > $end_ts) {
$data[] = [
'time' => current_time('mysql'),
'id' => 'N/A',
'title' => "Job Closure Notice",
'message' => "Your contract has ended. Please complete all job closure formalities.",
'page' => 'contracts',
'type' => 'contract_completion',
];
} elseif (($end_ts - $now_ts) <= 3 * 24 * 3600) {
$data[] = [
'time' => current_time('mysql'),
'id' => 'N/A',
'title' => "Job Closure Notice",
'message' => "Your contract is ending soon. Please prepare to complete all job closure formalities.",
'page' => 'contracts',
'type' => 'contract_completion',
];
}
}
}
}
$resulta = array("data" => $data, 'success' => 1);
$encrypted = encryptdaata($resulta);
return new WP_REST_Response($encrypted, 200);
}
function updateNotificationStatus($request)
{
$parametresen = json_decode($request->get_body(), true); // <-- safest way
$paramData = $parametresen['params'] ?? [];
if (is_array($paramData)) {
$parametres = $paramData;
} else {
$parametres = decryptdaata($paramData); // if you're using encryption
}
$user_id = $parametres['user_id'];
$notification_status = $parametres['notification_status'] ?? 0;
$type = $parametres['type'];
$columnId = $parametres['id'];
if ($type == 'agreement') {
$table_name = "wp_agreement";
$id = 'agreement_id';
} elseif ($type == 'quotation') {
$table_name = "wp_quotation";
$id = 'id';
} elseif ($type == 'contract renewal') {
$table_name = "wp_contract_renewal";
$id = 'id';
} elseif ($type == 'work order') {
$table_name = "wp_work_orders";
$id = 'id';
} else {
$resultdata = array("message" => "Invalid type provided.", 'success' => 0);
return new WP_REST_Response($resultdata, 400);
}
global $wpdb;
// Update the notification status in the wp_agreement table
$result = $wpdb->update(
$table_name,
array('notification_status' => $notification_status),
array($id => $columnId)
);
if ($result !== false) {
$resulta = array("message" => "Notification status updated successfully.", 'success' => 1);
return new WP_REST_Response($resulta, 200);
} else {
$resultdata = array("message" => "Failed to update notification status.", 'success' => 0);
return new WP_REST_Response($resultdata, 400);
}
}
function getInvoicesf($request)
{
$parametresen = $request->get_body_params() ?? array();
$parametres = decryptdaata($parametresen['params']);
$date1 = $parametres['start_date'];
$date2 = $parametres['end_date'];
$user_id = $parametres['user_id'];
$page = $parametres['page'] ?? 1;
$perpage = $parametres['perpage'] ?? 10;
$limit = " limit $perpage";
$daterange = "";
if ($page > 1) {
$perpage1 = $page * $perpage;
$perpage1 = ($perpage1 - $perpage);
$limit = " limit $perpage1,$perpage";
}
$datesBetween = "";
if (!empty($date1) && !empty($date2)) {
$limit = "";
$datesBetween = " AND date(created_date) between '$date1' and '$date2' ";
}
$whereuserid = '';
if (!empty($user_id)) {
$whereuserid = " user_id='$user_id' ";
} else {
$resultdata = array("message" => "Not a valid request.", 'success' => 0);
return new WP_REST_Response($resultdata, 400);
}
global $wpdb;
$table_name = "wp_order_invoice_details";
// $whereQuery = $whereuserid . (!empty($datesBetween) && !empty($user_id)) ? " and $datesBetween " : $whereuserid;
// $whereQuery = !empty(trim($whereQuery)) ? " where $whereQuery " : "";
$qquery = "SELECT * from $table_name WHERE $whereuserid $datesBetween order by id desc $limit";
// die($rfqquery);
// die("connttt $count");
$results = $wpdb->get_results($qquery, ARRAY_A);
if ($wpdb->last_error) {
$resultdata = array("message" => "something went wrong.", 'reson' => $wpdb->last_error);
return new WP_REST_Response($resultdata, 400);
}
if (count($results ?? []) > 0) {
$results = $results ?? [];
// for ($i = 0; $i < count($results); $i++) {
// $image = wp_get_attachment_image_src(get_post_thumbnail_id($results[$i]['product_id']), 'thumbnail'); //'single-post-thumbnail');
// $results[$i]['image'] = $image;
// unset($results[$i]['dynamic_terms_1'], $results[$i]['dynamic_terms_2'], $results[$i]['assign_terms_conditions']);
// $qtstatus = trim($results[$i]['qt_status']);
// if ($qtstatus != 'Requested For Revision') {
// // unset( $results[$i]['comments']);
// }
// $results[$i]['qt_status'] = $qtstatus === 'Quote Send to Coustmer' ? 'In Progress' : $qtstatus;
// }
$resulta = array("data" => $results ?? [], 'success' => 1);
$encrypted = encryptdaata($resulta);
return new WP_REST_Response($encrypted, 200);
} else {
if ($page > 1) {
$resulta = array("data" => [], 'success' => 1);
$encrypted = encryptdaata($resulta);
return new WP_REST_Response($encrypted, 200);
}
$resultdata = array("message" => "No Qoutes created yet. Raise a request for Quote.", 'success' => 0);
return new WP_REST_Response($resultdata, 400);
}
}
function getCartProductsf($request){
$parametersen = $request->get_body_params();
$parameters = decryptdaata($parametersen['params']);
$idss = $parameters['productsIds'] ?? '';
$user_id = intval($parameters["user_id"]);
$ids = explode(",", $idss);
global $wpdb;
$table_name_rfq = "wp_request_quote";
$getCartId = get_user_meta($user_id, 'cartlistId', true);
$getCartIdar = explode(",",$getCartId);
$cartIds = array_merge($ids,$getCartIdar);
$carIdsss= implode(',',$cartIds );
$qquery = "SELECT * FROM $table_name_rfq WHERE id in($carIdsss) and user_id='$user_id'";
// die($qquery);
$results = $wpdb->get_results($qquery, ARRAY_A);
// die(json_encode($results));
$productsAr=[];
if($results){
for ($i = 0; $i < count($results); $i++) {
$prodata = [];
try {
$proid = intval( $results[$i]['product_id']);
$products = wc_get_product($proid);
$product = (object)$products->get_data();
// $product->wp_getvis;
// $product->post_excerpt;
// $image = wp_get_attachment_image_src(get_post_thumbnail_id( $proid), 'medium'); //'single-post-thumbnail');
$thumbnail = wp_get_attachment_image_src(get_post_thumbnail_id( $proid), 'thumbnail'); //'single-post-thumbnail');
// $excerpt = get_the_excerpt($product->ID);
$product->thumbnail = $thumbnail;
// $product->image = $image;
$prodata['id'] = $proid;
$prodata['thumbnail'] = $thumbnail;
$prodata['category_ids'] = $product->category_ids;
$prodata['name'] = $product->name;
$prodata['short_description'] = $product->short_description;
$prodata['category_ids'] = $product->category_ids;
$prodata['price'] = $product->price;
$prodata['regular_price'] = $product->regular_price;
$prodata['sale_price'] = $product->sale_price;
$product->purpose;
$prodata['cartprod'] = $results[$i];
$prodata['purpose'] = get_post_meta($proid, 'purpose_of_listing', true);
$productsAr[] = $prodata;// array_merge($prodata,$results[$i]);
} catch (\Throwable $th) {
}
}
}else{
die("not data found");
}
$encrypeddata = encryptdaata(['data' => $productsAr,'cartIds'=> $carIdsss]);
return new WP_REST_Response($encrypeddata);
}
function testf($request)
{
$parameters = $request->get_body_params();
$parameters = $request;
// wp_session_start();
$inserted_id = 30;
$user_id=699;
$getWishId = get_user_meta($user_id, 'cartlistId', true);
$getwidth = "";
if ($getWishId) {
$getwidth = "getwish";
echo "getwish\n";
try{
$wishIdlist = explode(",", $getWishId);
$wishIdlistt = array_merge( $wishIdlist , ["$inserted_id"]);
$integerIDss = array_unique($wishIdlistt);
echo " integerIDss ".json_encode( $integerIDss) ."wishidlist:" .json_encode($wishIdlist)." \n";
$integerIDss = array_filter($integerIDss, 'strlen');
$sid = implode(",", $integerIDss);
}catch(Exception $e){
echo "ex: $e";
}
echo "sid: $sid\n";
} else {
$getwidth = "getwithno";
echo "getwishno\n";
$sid = "$inserted_id";
}
die("$sid");
// $parameters = decryptdaata($parametersen['params']);
if (($parameters['type'] ?? '') == 'addcart') {
$user_id = $parameters['user_id'];
// $WC_Session = new WC_Session_Handler();
// $WC_Session->set("user_id", $user_id);
// $woocommerce->session->set('user_id', $user_id);
// $woocommerce->cart->add_to_cart($productId,1,0,array(),array());
$product_id = intval($_POST['product_id']);
$start_date = sanitize_text_field($_POST['start_date']);
$end_date = sanitize_text_field($_POST['end_date']);
$shift = intval($_POST['shift']);
$location = sanitize_text_field($_POST['location']);
$application = sanitize_text_field($_POST['application']);
$product = wc_get_product($product_id);
$base_price = $product->get_price();
$start_date_obj = new DateTime($start_date);
$end_date_obj = new DateTime($end_date);
$days = $start_date_obj->diff($end_date_obj)->days + 1; // Include end date
$hours_per_day = 8;
$total_hours = $days * $shift * $hours_per_day;
$calculated_price = ($total_hours / 8) * $base_price;
$user = get_userdata($user_id); // wp_signon($logindata, true);
if (!is_wp_error($user)) {
global $current_user;
$current_user = new WP_User($user->ID, $user->first_name);
global $woocommerce;
wp_create_nonce('wc_store_api');
if (! $woocommerce->is_rest_api_request()) {
return;
}
$woocommerce->frontend_includes();
if (null === $woocommerce->cart && function_exists('wc_load_cart')) {
wc_load_cart();
}
setup_userdata($user->ID);
/**
* Fires after the current user is set.
*
* @since 2.0.1
*/
do_action('set_current_user');
// global $woocommerce;
// ------ end usersession ---
// add_action('wp_ajax_custom_add_to_cart');
$cart_item_data = [
'rfq_data' => [
'start_date' => $start_date,
'end_date' => $end_date,
'shift' => $shift,
'location' => $location,
'application' => $application,
'calculated_price' => $calculated_price
]
];
// echo "customer: " . $woocommerce->customer . "\n";
$cartdata = get_user_meta($user_id, '_woocommerce_persistent_cart_1', true);
echo json_encode($cartdata);
// c791073c732a775f4eb0a597ffc5235e
// $ajax_url = admin_url("admin-ajax.php");
// // $nonce = wp_create_nonce("send_rfq_email_nonce");
// $reqdata = [
// 'action' => 'custom_add_to_cart',
// 'product_id' => $product_id,
// 'start_date' => $start_date,
// 'end_date' => $end_date,
// 'shift' => $shift,
// 'location' => $location,
// 'application' => $application,
// 'calculated_price' => $calculated_price
// ];
// $response = wp_remote_post($ajax_url, [
// 'method' => 'POST',
// 'body' => $reqdata
// ]);
// echo "\nResponnse:::: " . json_encode($response) . "\n";
$cart_item_key = $woocommerce->cart->add_to_cart($product_id, 1, 0, [], $cart_item_data);
if ($cart_item_key) {
echo "\naddedcatttt $cart_item_key\n";
// wp_send_json_success();
} else {
echo "\nnot-addedcatttt\n";
// wp_send_json_error();
}
echo "\n finally data is: \n";
$cartdata = get_user_meta($user_id, '_woocommerce_persistent_cart_1', true);
echo json_encode($cartdata);
echo "\n finally data is: \n";
$cartItems = WC()->cart->get_cart(); // $woocommerce->cart;
echo json_encode($cartItems);
// unset($current_user);
} else {
die("not able to loginn");
}
// $WC_Session->set( $key, $value );
} else if (($parameters['type'] ?? '') == 'getcart') {
$user_id = $parameters['user_id'];
$user = get_userdata($user_id); // wp_signon($logindata, true);
if (!is_wp_error($user)) {
global $wpdb;
// die("current_userid" . get_current_user_id());
//------usersess ---
global $current_user;
$current_user = new WP_User($user->ID, $user->first_name);
global $woocommerce;
if (! WC()->is_rest_api_request()) {
return;
}
WC()->frontend_includes();
if (null === WC()->cart && function_exists('wc_load_cart')) {
wc_load_cart();
}
setup_userdata($user->ID);
/**
* Fires after the current user is set.
*
* @since 2.0.1
*/
do_action('set_current_user');
// ------ end usersession ---
// $itemdata = $woocommerce->cart->get_cart_item("c791073c732a775f4eb0a597ffc5235e");
// echo json_encode($itemdata);
// echo "customer: " . $woocommerce->customer . "\n";
$cartdata = get_user_meta($user_id, '_woocommerce_persistent_cart_1', true);
echo json_encode($cartdata);
// echo "\nn-------\n";
$cartItems = WC()->cart->get_cart(); // $woocommerce->cart;
echo json_encode($cartItems);
// WC()->cart->wc_get_post_data_by_key( "02a6088960b7f6bb6fc0102bd0470d91", default );
/// ----- start payment option ----
$order_total = WC()->cart->get_total('');
$purpose_sales = false;
$product_price = 0;
foreach (WC()->cart->get_cart() as $cart_item_key => $cart_item) {
$product_id = $cart_item['product_id'];
$purpose = get_post_meta($product_id, 'purpose_of_listing', true);
if ($purpose === 'Sales') {
$purpose_sales = true;
}
// Get product price for calculations
$product = wc_get_product($product_id);
$product_price = $product->get_regular_price();
// Check for RFQ data if needed
if (isset($cart_item['rfq_data'])) {
$start_date = $cart_item['rfq_data']['start_date'];
$end_date = $cart_item['rfq_data']['end_date'];
$shift = $cart_item['rfq_data']['shift'];
$location = $cart_item['rfq_data']['location'];
$application = $cart_item['rfq_data']['application'];
$base_price = $cart_item['rfq_data']['base_price'];
}
}
// Clean order total (remove currency symbol and format ting)
$order_total_clean = preg_replace('/[^\d.]/', '', $order_total);
// Determine payment options based on purpose and total
$payment_options = array();
$default_option = 'full'; // Always default to full payment initially
if ($purpose_sales) {
$payment_options['full'] = '100% full payment';
if ($order_total_clean > 1000000) { // 10,00,000
$payment_options['half'] = '50% payment';
$payment_options['2LC'] = '2 Lakh payment';
} else {
$payment_options['2LC'] = '2 Lakh payment';
}
} else {
$payment_options['full'] = '100% full payment';
if ($order_total_clean > (90 * $product_price)) {
$payment_options['2-Months'] = '2 Months payment';
}
}
/// ----- end payment option ----
// unset($current_user);
} else {
die("not able to loginn");
}
} else {
$prod_categories = explode(",", $parameters['parentId']);
$page = $parameters['page'] ?? 1;
$posts_per_page = $parameters['perpage'] ?? 10;
// $tax_query = array(
// 'taxonomy' => 'product_cat',
// 'field' => 'slug',
// 'terms' => $slug,
// );
$args = array(
'limit' => -1,
'orderby' => 'id',
'order' => 'ASC',
'status' => 'publish',
'tax_query' => array(
'RELATION' => "AND",
array(
'taxonomy' => 'product_cat',
'field' => 'id',
'terms' => $prod_categories,
'operator' => 'IN'
),
),
'meta_query' => array(
array(
'key' => 'purpose_of_listing',
'value' => 'Display',
'compare' => '='
)
)
);
// echo "\n" . json_encode($args) . "\n";
$productsAr = [];
$query = new WC_Product_Query($args);
$products = $query->get_products();
foreach ($products as $product) {
$productsAr[] = [
'name' => $product->name,
'id' => $product->id,
'category' => get_the_terms($product->id, 'product_cat'),
// 'image' => wp_get_attachment_image_src(get_post_thumbnail_id($product->id), 'medium'),
// 'short_description' => $product->short_description,
// 'price' => $product->price,
// 'regular_price' => $product->regular_price,
// 'sale_price' => $product->sale_price,
// 'stock_status' => $product->stock_status,
// 'image' => wp_get_attachment_thumb_url($product->get_image_id())
];
// echo " thisProducts " . $value2->name . " pro: " . $product->get_name() . ' slug:'. $product->get_slug . "\n";
// $productsAr[] = $productdata;
}
$encrypeddata = json_encode(array("length" => count($productsAr), "data" => $productsAr)); //encryptdaata(['data' => $productsAr]);
return new WP_REST_Response($encrypeddata);
}
}
function customAddToCart_mob($request)
{
$parameters = $request;
$user_id = $parameters['user_id'];
$product_id = $parameters['product_id'];
$start_date = $parameters['start_date'];
$end_date = $parameters['end_date'];
$shift = $parameters['shift'];
$location = $parameters['location'];
$application = $parameters['application'];
$calculated_price = $parameters['calculated_price'];
$user = get_userdata($user_id); // wp_signon($logindata, true);
if (!is_wp_error($user)) {
global $current_user;
$current_user = new WP_User($user->ID, $user->first_name);
global $woocommerce;
wp_create_nonce('wc_store_api');
if (! $woocommerce->is_rest_api_request()) {
return;
}
$woocommerce->frontend_includes();
if (null === $woocommerce->cart && function_exists('wc_load_cart')) {
wc_load_cart();
}
setup_userdata($user->ID);
/**
* Fires after the current user is set.
*
* @since 2.0.1
*/
do_action('set_current_user');
// ------ end usersession ---
$cart_item_data = [
'rfq_data' => [
'start_date' => $start_date,
'end_date' => $end_date,
'shift' => $shift,
'location' => $location,
'application' => $application,
'calculated_price' => $calculated_price
]
];
// $cartdata = get_user_meta($user_id, '_woocommerce_persistent_cart_1', true);
$cart_item_key = $woocommerce->cart->add_to_cart($product_id, 1, 0, [], $cart_item_data);
if ($cart_item_key) {
return 1;
} else {
return 0;
}
}
}
// function createOrderf($request){
// }