| 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/woocommerce-rfq/ |
Upload File : |
<?php
/*
Plugin Name: WooCommerce RFQ
Description: Adds a Request for Quote (RFQ) button with custom fields to WooCommerce products.
Version: 1.2
Author: Itrosys
*/
if (!defined("ABSPATH")) {
exit(); // Exit if accessed directly
}
// Include the admin RFQ functionality
include plugin_dir_path(__FILE__) . "admin-rfq.php";
// Include the admin RFQ functionality
include plugin_dir_path(__FILE__) . "admin-downloadstdratecard.php";
// Include the admin Quatation functionality
include plugin_dir_path(__FILE__) . "admin-quotation.php";
// Include the admin Quatation functionality
include plugin_dir_path(__FILE__) . "quotation_edit.php";
// Include the rfq in my-account functionality
include plugin_dir_path(__FILE__) . "rfq-for-myaccount.php";
// Include the Discount approval page
include plugin_dir_path(__FILE__) . "approval_discount.php";
// Include the Terms page
// include plugin_dir_path(__FILE__) . "terms.php";
// Include the Revision details page
include plugin_dir_path(__FILE__) . "quotes-revision-details.php";
// Add custom fields and RFQ button to the product page
function add_custom_fields_and_rfq_button()
{
global $wpdb;
// if (!is_user_logged_in() || !is_product() || has_term('buy-used-equipment-to-buy', 'product_cat')) {
// return;
// }
$product_id = get_the_ID();
global $product;
// Get the custom attribute "Purpose of Listing"
$purpose = $product->get_attribute('Purpose of Listing');
// Check if the product is in "rent" category or any of its children
$has_rent_category = has_term('rent', 'product_cat', $product_id);
// 🔸 If stock is 0, and it's NOT a rental product, block the form
if (!$product->is_in_stock() && !(strcasecmp($purpose, 'Renting') === 0 || $has_rent_category)) {
echo '<div class="alert alert-danger mt-4">This product is already given for rent</div>';
return;
}
if (is_user_logged_in() && is_product() && !has_term('buy-used-equipment-to-buy', 'product_cat')) {
// 🔹 Query existing bookings from wp_request_quote
$bookings = $wpdb->get_results("
SELECT start_date, end_date
FROM wp_request_quote
WHERE product_id = $product_id
AND rfq_status != 'Cancelled'
AND status = 'Active'
AND order_id != 0
");
$disabled_dates = [];
foreach ($bookings as $booking) {
$start = new DateTime($booking->start_date);
$end = new DateTime($booking->end_date);
while ($start <= $end) {
$disabled_dates[] = $start->format('Y-m-d');
$start->modify('+1 day');
}
}
?>
<script>
const disabledDates = <?php echo json_encode(array_unique($disabled_dates)); ?>;
</script>
<style>
.flatpickr-input {
background: url("/wp-content/uploads/2025/09/calender-icon.png") no-repeat right 10px center;
background-size: 18px;
padding-right: 35px; /* space for icon */
}
.woocommerce-product-attributes-item--smu_hours .woocommerce-product-attributes-item__value{padding:10px !important;}
</style>
<!-- Include Flatpickr -->
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/flatpickr/dist/flatpickr.min.css">
<script src="https://cdn.jsdelivr.net/npm/flatpickr"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<div class="row mt-3 custom-fields form-group">
<div class="col-md-12 mt-2">
<div class="row">
<div class="date-field col-md-6 mb-0">
<label class="form-label" for="start_date">Start Date:</label>
<input class="form-control rfq-date-field" type="date" id="start_date" name="start_date" placeholder="dd-mm-yyyy"
min="<?php echo date('Y-m-d', strtotime('+5 days')); ?>" onkeydown="return false" onpaste="return false" disabled>
<? /***php echo date('Y-m-d', strtotime('+14 days')); */?>
</div>
<div class="date-field col-md-6 mb-0">
<label class="form-label" for="end_date">End Date:</label>
<input class="form-control rfq-date-field" type="date" id="end_date" name="end_date" placeholder="dd-mm-yyyy" disabled
onkeydown="return false" onpaste="return false">
</div>
</div>
</div>
<div class="row">
<!-- <p style="margin:-10px 0 0 30px;color:red;font-size: 12px;">* Any dates on which the product is already rented are disabled and cannot be selected.</p> -->
</div>
<?php
$id = $product->get_id();
$taxonomy = 'pa_yard-location';
$term_names = array();
$term_ids = get_posts(array(
'post_type' => 'product',
'post__in' => array($product_id),
'fields' => 'ids',
'posts_per_page' => 1,
));
$terms = wp_get_post_terms($id, $taxonomy);
if (!is_wp_error($terms) && !empty($terms)) {
foreach ($terms as $term) {
$term_names[] = $term->name;
}
}
$yard_location_output = implode(', ', $term_names);
$selected_location = '';
if(!empty($term_names))
{
$selected_location = $term_names[0];
}
$states = get_terms([
'taxonomy' => 'pa_yard-location',
'hide_empty' => false,
'parent' => 0 // Only top-level (states)
]);
?>
<div class="col-md-12 mt-2">
<label class="form-label font-weight-bold" for="location" style="color:#616161;">Location: <span class="rent_state"> </span> - <span class="rent_district"> </span></label>
<input type="hidden" name="location" id="location" value="<?php echo $selected_location; ?>">
</div>
<?php
if (is_product()) {
global $post;
$product_id = $post->ID;
$product_cats = wp_get_post_terms($product_id, 'product_cat');
if (!has_term('rent-power-rental', 'product_cat', $product_id)) { ?>
<!-- <div class="col-md-12 mt-2">
<label style="color:#616161;" class="form-label font-weight-bold" for="shift">No Of Shifts Required:</label>
<select class="form-control rfq-date-field" id="shift" name="shift">
<option value="">Select Shift</option>
<option value="1">1 Shift (8 hours)</option>
<option value="2">2 Shifts (16 hours)</option>
<option value="3">3 Shifts (24 hours)</option>
</select>
<div id="pricingtxt-message" class="mt-3" style="display:none;"></div>
</div> --->
<div class="col-md-12 mt-2 d-none">
<label style="color:#616161;" class="form-label font-weight-bold" for="application">Select Application:</label>
<select class="form-control rfq-date-field" id="application" name="application">
<option value="">Select Application</option>
<option value="Mining">Mining</option>
<option value="Road/Rail/Metro Construction">Road/Rail/Metro Construction</option>
<option value="Irrigation">Irrigation</option>
<option value="Building Construction">Building Construction</option>
<option value="Material Handling">Material Handling</option>
<option value="Earth Work">Earth Work</option>
<option value="Others">Others</option>
</select>
<div id="pricingtxt-message" class="mt-3" style="display:none;"></div>
</div><?php }
}
?>
</div>
<div class="d-flex mt-2 mb-3">
<div class="mr-3">
<button id="rfq_button" type="button">Proceed to Rent</button>
</div>
<!-- <div class="mr-3">
<button id="custom-rfq-btn">Request for Quote</button>
</div> -->
<div class="mr-3">
<button id="back-btn" onclick="window.history.back();">Back</button>
</div>
<div class="mt-3 d-none">
<button id="stdprice_button"><i class="icon icon-download"></i> Download Quote </button>
</div>
</div>
<div class="row d-none">
<p style="margin-left:14px;color:red;font-size: 12px;">* Rental rates can differ based on application</p>
</div>
<div id="spinner" style="display:none;">
<img style="width:22px;" src="<?php echo plugin_dir_url(
__FILE__
); ?>spinner.gif" alt="Loading...">
</div>
<div id="rfq-message" style="display:none;"></div>
<div id="thank-you-popup"
style="display: none; position: fixed; top: 0; left: 0; right: 0; bottom: 0; background: rgba(0,0,0,0.7); z-index: 9999; justify-content: center; align-items: center;">
<div
style="background: #fff; padding: 30px; border-radius: 8px; text-align: center; max-width: 400px; margin: auto;">
<h2>Thank You!</h2>
<p>Your request has been submitted successfully. Our team will contact you soon.</p>
<button id="close-popup" style="margin-top: 20px; padding: 15px 30px;border: none;">Close</button>
</div>
</div>
<iframe id="response-output" style="display:none;"></iframe>
<?php
$quote_url = "quotes.php";
?>
<script>
document.addEventListener("DOMContentLoaded", function() {
flatpickr("#start_date", {
dateFormat: "Y-m-d",
// minDate: "today",
minDate: new Date().fp_incr(5),
disable: disabledDates,
onChange: function(selectedDates, dateStr, instance) {
let endPicker = document.querySelector("#end_date")._flatpickr;
if (endPicker) {
endPicker.set('minDate', dateStr);
}
}
});
flatpickr("#end_date", {
dateFormat: "Y-m-d",
// minDate: "today",
minDate: new Date().fp_incr(35),
disable: disabledDates
});
});
</script>
<script type="text/javascript">
jQuery(document).ready(function($) {
jQuery('#start_date').on('change', function() {
var startDate = new Date($(this).val());
var endDateInput = $('#end_date');
var endDate = new Date(endDateInput.val());
// If end date is before start date, reset it
if (endDate < startDate) {
endDateInput.val('');
}
// Set min attribute of end date input to start date
endDateInput.attr('min', $(this).val());
});
$('#shift').on('change', function() {
var start_date = $('#start_date').val();
var end_date = $('#end_date').val();
var shift = $('#shift').val();
var product_id = <?php echo get_the_ID(); ?>;
// Validate if date fields are selected
// Validate if date fields are selected
if (start_date === '') {
alert('Please select start date.');
return;
}
if (end_date === '') {
alert('Please select end date.');
return;
}
if (shift === '') {
alert('Please select shift.');
return;
}
if (location === '') {
alert('Please select location.');
return;
}
// Show the spinner
$('#spinner').show();
$.ajax({
url: '<?php echo admin_url("admin-ajax.php"); ?>',
type: 'POST',
data: {
action: 'get_pricing_data',
start_date: start_date,
end_date: end_date,
shift: shift,
product_id: product_id,
user_id: '<?php echo get_current_user_id(); ?>'
},
success: function(response) {
// Hide the spinner
$('#spinner').hide();
// Show success rfq-message
// $('#pricingtxt-message').html('Total Rental Price: ₹ '+response).css({
// 'color': '#008000', // Green color
// 'font-weight': 'bold' // Bold font weight
// }).hide();
if (response.trim() === 'empty') {
// Show "Hello World" if price is empty
$('#pricingtxt-message').html('Hello World').css({
'color': '#ff0000', // Red color for default message
'font-weight': 'bold' // Bold font weight
}).hide();
} else {
// Show the pricing information if price is available
$('#pricingtxt-message').html('Total Rental Price: ₹ ' + response).css({
'color': '#008000', // Green color
'font-weight': 'bold' // Bold font weight
}).hide();
}
},
error: function(error) {
// Hide the spinner
$('#spinner').hide();
// Show error rfq-message
$('#rfq-message').html(
'There was an error submitting your request. Please try again.')
.hide();
}
});
});
$('#rfq_button').on('click', function(e) {
e.preventDefault();
var start_date = $('#start_date').val();
var end_date = $('#end_date').val();
// var shift = $('#shift').val();
// var shift = $('#shift').length ? ($('#shift').val() === "0" ? "1" : $('#shift').val()) : '1';
var shift = $('#shift').length ? $('#shift').val() : '1';
// var application = $('#application').length ? $('#application').val() : 'default';
var product_id = <?php echo get_the_ID(); ?>;
var location = $('#location').val();
// Validate if date fields are selected
// Validate if date fields are selected
if (start_date === '') {
alert('Please select start date.');
return;
}
if (end_date === '') {
alert('Please select end date.');
return;
}
if (shift === '') {
alert('Please select shift.');
return;
}
if (location === '') {
alert('Please select location.');
return;
}
/*if (application === '') {
alert('Please select application.');
return;
} */
// Show the spinner
$('#spinner').show();
$.ajax({
url: '<?php echo admin_url("admin-ajax.php"); ?>',
type: 'POST',
data: {
action: 'save_rfq_data',
start_date: start_date,
end_date: end_date,
shift: shift,
location: location,
product_id: product_id,
// application: application,
user_id: '<?php echo get_current_user_id(); ?>'
},
success: function(response) {
console.log('Save RFQ Response:', response);
if (response.success) {
// Second AJAX request
$.ajax({
url: '<?php echo admin_url("admin-ajax.php"); ?>',
type: 'POST',
data: {
action: 'send_rfq_email',
user_id: '<?php echo get_current_user_id(); ?>',
nonce: '<?php echo wp_create_nonce("send_rfq_email_nonce"); ?>'
},
success: function(emailResponse) {
console.log('Send Email Response:', emailResponse);
if (emailResponse.success) {
$('#spinner').hide();
// $('#rfq-message').html('Redirecting to Cart')
// .css({
// 'color': '#008000',
// 'font-weight': 'bold'
// })
// .show();
} else {
// alert(
// 'Error occurred while sending email. Please try again.'
// );
}
},
error: function() {
// alert(
// 'Error occurred while sending email. Please try again.'
// );
$('#spinner').hide();
}
});
} else {
// alert('Error occurred while saving data. Please try again.');
$('#spinner').hide();
}
},
error: function(error) {
// Hide the spinner
$('#spinner').hide();
// Show error rfq-message
$('#rfq-message').html(
'Thank you for raising Request for Quote, our executives will contact you soon.'
).css({
'color': '#008000', // Green color
'font-weight': 'bold' // Bold font weight
}).show();
}
});
});
$('#rfq_button').on('click', function(e) {
e.preventDefault();
var start_date = $('#start_date').val();
var end_date = $('#end_date').val();
var shift = $('#shift').length ? $('#shift').val() : '1';
var location = $('#location').val();
var product_id = <?php echo get_the_ID(); ?>;
if (!start_date || !end_date || !location ||
($('#shift').length > 0 && !$('#shift').val())
) {
alert('Please fill all fields.');
return;
}
// 🔹 First check if cart already has items
$.ajax({
url: '<?php echo admin_url("admin-ajax.php"); ?>',
type: 'POST',
data: { action: 'check_cart_items' },
success: function(res) {
if (res.has_items) {
// Show popup if cart already has items
$('#cart-check-confirm').fadeIn();
// ✅ Handle popup buttons
$(document).off('click', '#clear-cart').on('click', '#clear-cart', function() {
$.ajax({
url: '<?php echo admin_url("admin-ajax.php"); ?>',
type: 'POST',
data: { action: 'clear_cart' },
success: function() {
$('#cart-check-confirm').fadeOut();
proceedToAddCart(); // Continue adding product
}
});
});
$(document).off('click', '#cancel-cart').on('click', '#cancel-cart', function() {
$('#cart-check-confirm').fadeOut();
});
} else {
proceedToAddCart();
}
}
});
// 🔹 Function to continue cart process
function proceedToAddCart() {
$('#spinner').show();
$.ajax({
url: '<?php echo admin_url("admin-ajax.php"); ?>',
type: 'POST',
data: {
action: 'get_pricing_data',
start_date: start_date,
end_date: end_date,
shift: shift,
product_id: product_id,
user_id: '<?php echo get_current_user_id(); ?>'
},
success: function(response) {
if (response.trim() === 'empty') {
$('#spinner').hide();
alert('Price not available.');
return;
}
var calculated_price = parseFloat(response);
$.ajax({
url: '<?php echo admin_url("admin-ajax.php"); ?>',
type: 'POST',
data: {
action: 'custom_add_to_cart',
product_id: product_id,
start_date: start_date,
end_date: end_date,
location: location,
...( $('#shift').length ? { shift: shift } : {} ),
calculated_price: calculated_price
},
success: function(cart_response) {
$('#spinner').hide();
if (cart_response.success) {
window.location = '<?php echo wc_get_cart_url(); ?>';
} else {
alert('Failed to add to cart.');
}
},
error: function() {
$('#spinner').hide();
alert('Error adding to cart.');
}
});
},
error: function() {
$('#spinner').hide();
alert('Error calculating price.');
}
});
}
});
$('#stdprice_button').on('click', function(e) {
e.preventDefault();
var start_date = $('#start_date').val();
var end_date = $('#end_date').val();
var shift = $('#shift').val();
var product_id = <?php echo get_the_ID(); ?>;
var location = $('#location').val();
// Validate if date fields are selected
// Validate if date fields are selected
if (start_date === '') {
alert('Please select start date.');
return;
}
if (end_date === '') {
alert('Please select end date.');
return;
}
if (shift === '') {
alert('Please select shift.');
return;
}
if (location === '') {
alert('Please select location.');
return;
}
// Show the spinner
$('#spinner').show();
var dataToPass = {
product_id: product_id,
quantity: 1,
shift: shift,
location: location,
start_date: start_date,
end_date: end_date,
user_id: '<?php echo get_current_user_id(); ?>'
};
// Build query string from dataToPass object
var queryString = Object.keys(dataToPass).map(function(key) {
return encodeURIComponent(key) + '=' + encodeURIComponent(dataToPass[key]);
}).join('&');
$('#spinner').hide();
$('#rfq-message').html(
'Thank you for downloading Offering Quote, our executives will contact you soon.').css({
'color': '#008000', // Green color
'font-weight': 'bold' // Bold font weight
}).show();
// Redirect to quotes.php with query string
//window.location.href = '<?php echo esc_url(plugin_dir_url(__FILE__) . 'quotes.php'); ?>' + '?' + queryString;
window.open('<?php echo esc_url(plugin_dir_url(__FILE__) . 'quotes.php'); ?>' + '?' +
queryString, '_blank');
});
var productId = <?php echo get_the_ID(); ?>;
// Make an AJAX request to check if the price is empty
$.ajax({
url: '<?php echo admin_url("admin-ajax.php"); ?>',
type: 'POST',
data: {
action: 'check_price',
product_id: productId
},
success: function(response) {
if (response.success) {
if (response.data === 'empty') {
$('#stdprice_button').hide(); // Hide the Offering Quote button
}
} else {
console.log('Error:', response.data);
}
},
error: function(xhr, status, error) {
console.log('AJAX Error:', error);
}
});
///// TP Code
$('#custom-rfq-btn').on('click', function(e) {
e.preventDefault();
var start_date = $('#start_date').val();
var end_date = $('#end_date').val();
// var shift = $('#shift').length ? ($('#shift').val() === "0" ? "1" : $('#shift').val()) : '1';
var shift = $('#shift').length ? $('#shift').val() : '1';
// var application = $('#application').length ? $('#application').val() : 'default';
var location = $('#location').val();
// Validation
if (start_date === '') {
alert('Please select start date.');
return;
}
if (end_date === '') {
alert('Please select end date.');
return;
}
if (location === '') {
alert('Please select location.');
return;
}
if (shift === '') {
alert('Please select shift.');
return;
}
// if (application === '') {
// alert('Please select Application.');
// return;
// }
$('#spinner').show();
$.ajax({
url: "<?php echo admin_url('admin-ajax.php'); ?>", // Corrected: wrapped in quotes
type: 'POST',
dataType: 'json',
data: {
action: 'save_rfq_data',
product_id: <?php echo get_the_ID(); ?>,
user_id: "<?php echo get_current_user_id(); ?>",
user_name: "<?php echo esc_js(wp_get_current_user()->display_name); ?>",
user_email: "<?php echo esc_js(wp_get_current_user()->user_email); ?>",
location: location,
start_date: start_date,
end_date: end_date,
shift: shift,
rfqdiscount: 0,
region: '',
// application: application,
enquiry_id: 0,
created_by: "<?php echo esc_js(wp_get_current_user()->display_name); ?>",
order_id: 0
},
success: function(response) {
$('#spinner').hide();
if (response.success) {
$('#thank-you-popup').fadeIn(); // Show thank-you popup
} else {
alert(response.data.message || 'Submission failed.');
}
},
error: function() {
$('#spinner').hide();
alert('An error occurred. Please try again later.');
}
});
});
// Close popup
$('#close-popup').on('click', function() {
$('#thank-you-popup').fadeOut();
});
});
jQuery(document).ready(function($){
let rent_start_date = localStorage.getItem('rent_start_date');
let rent_end_date = localStorage.getItem('rent_end_date');
let rent_state = localStorage.getItem('rent_state');
let rent_district = localStorage.getItem('rent_district');
$('.rent_state').text(rent_state);
$('.rent_district').text(rent_district);
$('#location').val(rent_district);
function calculateAndUpdatePrice() {
var startDate = $('#start_date').val();
var endDate = $('#end_date').val();
var basePriceText = $('.price .woocommerce-Price-amount bdi').text(); // e.g. "₹3,125"
if (!startDate || !endDate || !basePriceText) {
return; // wait for valid inputs
}
var start = new Date(startDate);
var end = new Date(endDate);
var timeDiff = end - start;
var days = Math.ceil(timeDiff / (1000 * 3600 * 24)) + 1;
if (days <= 0) {
days = 1;
}
var monthlyPrice = <?php echo floatval($product->get_price()); ?>;
// var monthlyPrice = parseFloat(basePriceText.replace(/[₹,]/g, ''));
var basePrice = (monthlyPrice / 30);
var newPrice = (basePrice * days);
//console.log(newPrice, basePrice, days);
var formattedPrice = '<bdi>₹' + newPrice.toLocaleString('en-IN', {maximumFractionDigits: 0}) + '</bdi>';
$('.price .woocommerce-Price-amount').html(formattedPrice);
}
var fpEnd = flatpickr("#end_date", {
dateFormat: "Y-m-d",
minDate: "today" // default minDate
});
function change_end_date() {
let current_start_date = $('#start_date').val();
if (!current_start_date) return;
let minEndDate = new Date(current_start_date);
minEndDate.setMonth(minEndDate.getMonth() + 1);
function formatDate(date) {
let day = ("0" + date.getDate()).slice(-2);
let month = ("0" + (date.getMonth() + 1)).slice(-2);
let year = date.getFullYear();
return year + "-" + month + "-" + day;
}
console.log(formatDate(minEndDate));
fpEnd.set('minDate', formatDate(minEndDate));
$('#end_date').val(formatDate(minEndDate));
$('#end_date').attr('min', formatDate(minEndDate));
}
$('#end_date').on('change', calculateAndUpdatePrice);
$('#start_date').on('change', change_end_date);
});
</script>
<?php }
}
add_action(
"woocommerce_single_product_summary",
"add_custom_fields_and_rfq_button",
35
);
// Create the request_quote table on plugin activation
function create_request_quote_table()
{
global $wpdb;
$table_name = $wpdb->prefix . "request_quote";
$charset_collate = $wpdb->get_charset_collate();
$sql = "CREATE TABLE $table_name (
id mediumint(9) NOT NULL AUTO_INCREMENT,
rmsID varchar(20) NOT NULL,
user_id mediumint(9) NOT NULL,
user_name varchar(100) NOT NULL,
user_email varchar(100) NOT NULL,
product_id mediumint(9) NOT NULL,
product_name varchar(255) NOT NULL,
start_date date NOT NULL,
end_date date NOT NULL,
shift int(2) NOT NULL,
location varchar(100) NOT NULL,
region varchar(50) NOT NULL,
calculated_price decimal(10,2) NOT NULL,
status varchar(20) NOT NULL DEFAULT 'Active',
rfq_status varchar(20) NOT NULL DEFAULT 'Pending',
application varchar(20) NOT NULL,
requested_on datetime NOT NULL,
order_id int(50) DEFAULT NULL,
PRIMARY KEY (id)
) $charset_collate;";
$table_name2 = $wpdb->prefix . "download_std_ratecard";
$charset_collate2 = $wpdb->get_charset_collate();
$sql2 = "CREATE TABLE $table_name2 (
id mediumint(9) NOT NULL AUTO_INCREMENT,
user_id mediumint(9) NOT NULL,
user_name varchar(100) NOT NULL,
user_email varchar(100) NOT NULL,
product_id mediumint(9) NOT NULL,
product_name varchar(255) NOT NULL,
start_date date NOT NULL,
end_date date NOT NULL,
shift int(2) NOT NULL,
location varchar(100) NOT NULL,
region varchar(50) NOT NULL,
calculated_price decimal(10,2) NOT NULL,
status varchar(20) NOT NULL DEFAULT 'Active',
downloaded_on datetime NOT NULL,
PRIMARY KEY (id)
) $charset_collate2;";
require_once ABSPATH . "wp-admin/includes/upgrade.php";
dbDelta($sql);
dbDelta($sql2);
}
register_activation_hook(__FILE__, "create_request_quote_table");
// Handle RFQ submission
function save_rfq_data() {
global $wpdb;
$table_name = $wpdb->prefix . "request_quote";
// Validate inputs
$user_id = intval($_POST["user_id"] ?? 0);
$start_date = sanitize_text_field($_POST["start_date"] ?? '');
$end_date = sanitize_text_field($_POST["end_date"] ?? '');
$shift = intval($_POST["shift"] ?? 0);
$product_id = intval($_POST["product_id"] ?? 0);
$location = sanitize_text_field($_POST["location"] ?? '');
// $application = sanitize_text_field($_POST["application"] ?? '');
// Check for required fields
if (!$user_id || !$start_date || !$end_date || !$product_id || !$location) {
wp_send_json_error(['message' => 'Missing required fields.']);
return;
}
// Get user info
$user_info = get_userdata($user_id);
if (!$user_info) {
error_log('Invalid user_id: ' . $user_id);
wp_send_json_error(['message' => 'Invalid user.']);
return;
}
$user_name = $user_info->user_login;
$user_email = $user_info->user_email;
// Get product info
$product = wc_get_product($product_id);
if (!$product) {
error_log('Invalid product_id: ' . $product_id);
wp_send_json_error(['message' => 'Invalid product.']);
return;
}
$product_name = $product->get_name();
$base_price = floatval($product->get_price());
// Calculate price
try {
$start_date_obj = new DateTime($start_date);
$end_date_obj = new DateTime($end_date);
if ($start_date_obj > $end_date_obj) {
wp_send_json_error(['message' => 'End date must be after start date.']);
return;
}
// $interval = $start_date_obj->diff($end_date_obj);
// $days = $interval->days + 1; // Include end date
// $hours_per_day = 8;
// $total_hours = ($days * $shift * $hours_per_day);
// $total_hours = ($shift == 0) ? ($days * $hours_per_day) : ($days * $shift * $hours_per_day);
// $calculated_price = ($total_hours / 8) * $base_price;
// Calculate difference in days
$days_diff = $end_date_obj->diff($start_date_obj)->days + 1;
// Ensure at least 1 day
if ($days_diff <= 0) {
$days_diff = 1;
}
// Get product price
$monthly_price = floatval($product->get_price());
// Per-day price
$per_day_price = $monthly_price / 30;
// Calculate total price for the period
$calculated_price = $per_day_price * $days_diff;
// Round price (like JS maximumFractionDigits: 0)
$calculated_price = round($calculated_price, 0);
} catch (Exception $e) {
error_log('Date calculation error: ' . $e->getMessage());
wp_send_json_error(['message' => 'Invalid date format.']);
return;
}
// Get region
$region = function_exists('getRegion') ? getRegion($location) : '';
// Check for overlapping bookings
$overlap = $wpdb->get_var($wpdb->prepare("
SELECT COUNT(*)
FROM $table_name
WHERE product_id = %d
AND rfq_status != 'Cancelled'
AND status = 'Active'
AND order_id !=0
AND start_date <= %s
AND end_date >= %s
", $product_id, $end_date, $start_date));
if ($overlap > 0) {
wp_send_json_error(['message' => 'Selected dates overlap with an existing booking.']);
return;
}
// Generate rmsID
$max_value = $wpdb->get_var("SELECT MAX(id) FROM $table_name");
$rmsID = 'RMS00' . (is_null($max_value) ? 1 : $max_value + 1);
// Insert data
$result = $wpdb->insert($table_name, [
'user_id' => $user_id,
'rmsID' => $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,
'rfqdiscount' => 0, // Add if required by table
'final_price' => null, // Add if required by table
'enquiry_id' => 0, // Add if required by table
'created_by' => $user_name, // Add if required by table
'order_id' => 0, // Add if required by table
'requested_on' => current_time('mysql'),
'status' => 'Active',
'rfq_status' => 'Pending'
]);
if ($result === false) {
error_log('Database insert failed: ' . $wpdb->last_error);
wp_send_json_error(['message' => 'Failed to save booking.']);
return;
}
// Get inserted ID
$request_quote_id = $wpdb->insert_id;
// Send notification
if (function_exists('create_notification')) {
$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.',
[
'meta_input' => [
'user_id' => $user_id,
'action' => 'request_for_quote',
'request_quote_id' => $request_quote_id,
]
]
);
}
wp_send_json_success(['message' => 'Booking saved successfully!']);
}
add_action("wp_ajax_save_rfq_data", "save_rfq_data");
add_action("wp_ajax_nopriv_save_rfq_data", "save_rfq_data");
// Get Pricing Data
function get_pricing_data()
{
global $product;
$user_id = intval($_POST["user_id"]);
$user_info = get_userdata($user_id);
$user_name = $user_info->user_login;
$user_email = $user_info->user_email;
$start_date = sanitize_text_field($_POST["start_date"]);
$end_date = sanitize_text_field($_POST["end_date"]);
$shift = intval($_POST["shift"]);
$product_id = intval($_POST["product_id"]);
$product = wc_get_product($product_id);
$product_name = $product->get_title();
$base_price = $product->get_price();
// 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
// if($shift == 0){
// $total_hours = $days * $hours_per_day;
// }
// else{
// $total_hours = $days * $shift * $hours_per_day;
// }
// $total_hours = ($shift == 0) ? ($days * 1 * $hours_per_day) : ($days * $shift * $hours_per_day);
$total_hours = $days * $shift * $hours_per_day;
$calculated_price = ($total_hours / 8) * $base_price;
echo number_format($calculated_price, 1);
// wp_send_json_success();
}
add_action("wp_ajax_get_pricing_data", "get_pricing_data");
add_action("wp_ajax_nopriv_get_pricing_data", "get_pricing_data");
// Update RFQ Data
function update_rfq_data()
{
global $wpdb;
global $product;
$table_name = $wpdb->prefix . "request_quote";
$user_id = intval($_POST["user_id"]);
$user_name = $_POST["user_name"];
$user_email = $_POST["user_email"];
$product_id = intval($_POST["product_id"]);
$product = wc_get_product($product_id);
$product_name = $product->get_title();
$start_date = sanitize_text_field($_POST["start_date"]);
$end_date = sanitize_text_field($_POST["end_date"]);
$shift = intval($_POST["shift"]);
$calculated_price = $_POST["calculated_price"];
$rfq_status = $_POST["rfq_status"];
// Remove everything except numbers, decimal point, and minus sign
$price = str_replace(',', '', $calculated_price);
$rfq_id = intval($_POST["rfq_id"]);
$wpdb->update($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,
"calculated_price" => $price,
"rfq_status" => $rfq_status
], ['id' => $rfq_id]);
wp_send_json_success();
}
add_action("wp_ajax_update_rfq_data", "update_rfq_data");
add_action("wp_ajax_nopriv_update_rfq_data", "update_rfq_data");
// Enqueue CSS file
function woocommerce_rfq_enqueue_styles()
{
if (is_user_logged_in()) {
wp_enqueue_style(
"woocommerce-rfq-styles",
plugin_dir_url(__FILE__) . "css/custom-style.css"
);
wp_enqueue_style(
"woocommerce-rfq-styles",
plugin_dir_url(__FILE__) . "css/quotes.css"
);
}
}
add_action("wp_enqueue_scripts", "woocommerce_rfq_enqueue_styles");
// Enqueue Bootstrap via CDN
function woocommerce_rfq_enqueue_scripts()
{
wp_enqueue_style(
"bootstrap-css",
"https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css"
);
wp_enqueue_script(
"bootstrap-js",
"https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js",
["jquery"],
"4.5.2",
true
);
wp_enqueue_script('html2pdf-js', 'https://cdnjs.cloudflare.com/ajax/libs/html2pdf.js/0.9.2/html2pdf.bundle.min.js', array(), null, true);
}
add_action("wp_enqueue_scripts", "woocommerce_rfq_enqueue_scripts");
function getRegion($location)
{
$south = ['Karnataka', 'Kerala', 'Tamil Nadu'];
$east = ['Andhra Pradesh', 'Telangana'];
$west = ['Maharashtra', 'Goa', 'Gujarat'];
$north = ['Madhya Pradesh', 'Chhattisgarh'];
if (in_array($location, $south)) {
return 'South';
} elseif (in_array($location, $north)) {
return 'North';
} elseif (in_array($location, $east)) {
return 'East';
} elseif (in_array($location, $west)) {
return 'West';
} else {
return 'Others';
}
}
// added by aseema
add_action('wp_ajax_gett_pricing_data', 'gett_pricing_data');
add_action('wp_ajax_nopriv_gett_pricing_data', 'gett_pricing_data');
function gett_pricing_data()
{
global $wpdb;
$product_id = intval($_POST['product_id']);
// Query to get the price meta value
$price = $wpdb->get_var($wpdb->prepare(
"SELECT meta_value FROM $wpdb->postmeta WHERE post_id = %d AND meta_key = '_price'",
$product_id
));
// Check if the price is empty
if (empty($price)) {
echo 'empty';
} else {
echo $price;
}
wp_die();
}
add_action('wp_ajax_check_price', 'check_price_ajax');
add_action('wp_ajax_nopriv_check_price', 'check_price_ajax');
function check_price_ajax()
{
if (!isset($_POST['product_id'])) {
wp_send_json_error('Product ID not provided.');
}
$product_id = intval($_POST['product_id']);
$price = get_post_meta($product_id, '_price', true);
// Return whether the price is empty or not
$response = empty($price) ? 'empty' : 'available';
wp_send_json_success($response);
}
?>