jQuery(document).ready(function($) {
// Cache DOM elements
const form = $('#enquiryForm');
const countrySelect = $('#country');
const pincodeContainer = $('#pincodeGroup');
const pincodeSelect = $('#pincode');
const productSelect = $('#product');
const divisionSelect = $('#division_name');
const submitBtn = form.find('button[type="submit"]');
const isCoreInput = $('#is_core');
const divisionNameTextInput = $('#division_name_text');
// Debug mode - set to true to enable console logging
const DEBUG = true;
// Helper Functions
const debugLog = (message, data = null) => {
if (!DEBUG) return;
console.log(`BMS Form Debug: ${message}`);
if (data) console.log(JSON.stringify(data, null, 2));
};
const errorLog = (message, error = null) => {
console.error(`BMS Form Error: ${message}`);
if (error) console.error(error);
};
const resetDependentFields = () => {
pincodeSelect.val('').html('');
productSelect.val('').html('').prop('disabled', true);
divisionSelect.val('').html('');
isCoreInput.val('');
divisionNameTextInput.val('');
};
// Check URL parameters for pre-populated values
function getUrlParameter(name) {
name = name.replace(/[\[]/, '\\[').replace(/[\]]/, '\\]');
const regex = new RegExp('[\\?&]' + name + '=([^]*)');
const results = regex.exec(location.search);
return results === null ? '' : decodeURIComponent(results[1].replace(/\+/g, ' '));
}
// Get pre-populated values from URL with more parameters
const prePopulatedProductId = getUrlParameter('product_id');
const prePopulatedProductName = getUrlParameter('product_name');
const prePopulatedCategoryId = getUrlParameter('category_id');
const prePopulatedCategoryName = getUrlParameter('category_name');
const prePopulatedDivisionName = getUrlParameter('division_name');
const prePopulatedDivisionType = getUrlParameter('division_type');
// Initialize form with these parameters
if (prePopulatedProductId) {
// First, select the country - default to India if not specified
$(document).ready(function() {
// Wait for countrySelect to be populated
const checkCountrySelect = setInterval(function() {
if (countrySelect.find('option[value="in"]').length > 0) {
clearInterval(checkCountrySelect);
// Select India by default for most products
countrySelect.val('in').trigger('change');
// Wait for pincode options to load after country selection
setTimeout(function() {
// Find appropriate pincode based on division type
if (prePopulatedDivisionType) {
// Look for pincodes that match the division type
let pincodeFound = false;
pincodeSelect.find('option').each(function() {
const $option = $(this);
const pincodeType = $option.data('type');
if (pincodeType === prePopulatedDivisionType) {
pincodeSelect.val($option.val()).trigger('change');
pincodeFound = true;
return false; // break loop
}
});
// If no matching pincode, select the first one
if (!pincodeFound) {
const firstPincode = pincodeSelect.find('option[value!=""]').first().val();
if (firstPincode) {
pincodeSelect.val(firstPincode).trigger('change');
}
}
} else {
// Default to first pincode if no division type info
const firstPincode = pincodeSelect.find('option[value!=""]').first().val();
if (firstPincode) {
pincodeSelect.val(firstPincode).trigger('change');
}
}
// Wait for divisions to load after pincode selection
setTimeout(function() {
// Try to find matching division/category
if (prePopulatedCategoryId) {
if (divisionSelect.find(`option[value="${prePopulatedCategoryId}"]`).length) {
divisionSelect.val(prePopulatedCategoryId).trigger('change');
} else {
// Try to match by division name
if (prePopulatedDivisionName) {
let divisionFound = false;
divisionSelect.find('option').each(function() {
const $option = $(this);
const optionDivName = $option.data('division-name');
if (optionDivName &&
optionDivName.toLowerCase() === prePopulatedDivisionName.toLowerCase()) {
divisionSelect.val($option.val()).trigger('change');
divisionFound = true;
return false; // break loop
}
});
// If no matching division, select first one
if (!divisionFound) {
const firstDivision = divisionSelect.find('option[value!=""]').first().val();
if (firstDivision) {
divisionSelect.val(firstDivision).trigger('change');
}
}
}
}
}
// Wait for products to load after division selection
setTimeout(function() {
// Select the product
if (prePopulatedProductId) {
if (productSelect.find(`option[value="${prePopulatedProductId}"]`).length) {
productSelect.val(prePopulatedProductId).prop('disabled', false);
} else if (prePopulatedProductName) {
// If product not in dropdown, add it
productSelect.append(``);
productSelect.val(prePopulatedProductId).prop('disabled', false);
}
}
}, 800);
}, 800);
}, 800);
}
}, 200);
});
}
debugLog('Pre-populated values', {
productId: prePopulatedProductId,
productName: prePopulatedProductName,
categoryId: prePopulatedCategoryId
});
// Load countries function
function loadCountries() {
debugLog('Loading countries');
countrySelect.html('');
$.ajax({
url: bmsForm.ajax_url,
type: 'POST',
dataType: 'json',
data: {
action: 'bms_get_countries',
nonce: bmsForm.nonce
},
success: function(response) {
debugLog('Countries response', response);
if (response.success && response.data) {
let options = '';
response.data.forEach(country => {
options += ``;
});
countrySelect.html(options);
// If we have a pre-populated product, select default country (India or first in list)
if (prePopulatedProductId) {
// Try to select India first as default
if (countrySelect.find('option[value="in"]').length) {
countrySelect.val('in').trigger('change');
} else {
// Otherwise select the first non-empty country
const firstCountry = countrySelect.find('option[value!=""]').first().val();
if (firstCountry) {
countrySelect.val(firstCountry).trigger('change');
}
}
}
} else {
countrySelect.html(`
`);
// If we have a pre-populated product, select India as default
if (prePopulatedProductId) {
countrySelect.val('in').trigger('change');
}
}
},
error: function(xhr, status, error) {
errorLog('Countries fetch error', { status, error, response: xhr.responseText });
countrySelect.html(`
`);
// If we have a pre-populated product, select India as default
if (prePopulatedProductId) {
countrySelect.val('in').trigger('change');
}
}
});
}
// Toggle Pincode field visibility based on country and load proper data
function handleCountryChange() {
const selectedCountry = countrySelect.val();
const selectedOption = countrySelect.find('option:selected');
const requiresPincode = selectedOption.data('requires-pincode') === 1 || selectedOption.data('requires-pincode') === "1";
const selectedCountryName = selectedOption.text().trim();
debugLog('Country changed', {
country: selectedCountry,
countryName: selectedCountryName,
requiresPincode: requiresPincode
});
// Reset dependent fields
resetDependentFields();
if (!selectedCountry) {
pincodeContainer.hide();
pincodeSelect.prop('required', false);
return;
}
// Check if country requires pincode
if (requiresPincode) {
// India or other country that requires pincode
pincodeContainer.show();
pincodeSelect.prop('required', true);
loadPincodes(selectedCountry);
} else {
// Other countries without pincode requirement
pincodeContainer.hide();
pincodeSelect.prop('required', false);
// For non-India countries, load divisions directly
loadDivisionsByCountry(selectedCountry);
}
}
// Load pincodes for a country
function loadPincodes(country) {
pincodeSelect.html('');
$.ajax({
url: bmsForm.ajax_url,
type: 'POST',
dataType: 'json',
data: {
action: 'bms_get_pincodes',
nonce: bmsForm.nonce,
country: country
},
success: function(response) {
debugLog('Pincodes response', response);
if (response.success && response.data) {
let options = '';
response.data.forEach(pincode => {
options += ``;
});
pincodeSelect.html(options);
// If we came from a product page and have a default pincode, select it
if (prePopulatedProductId && response.data.length > 0) {
// For simplicity, select the first process pincode or just the first one
const processPincode = response.data.find(p => p.types.includes('process'));
if (processPincode) {
pincodeSelect.val(processPincode.value).trigger('change');
} else if (response.data[0]) {
pincodeSelect.val(response.data[0].value).trigger('change');
}
}
} else {
pincodeSelect.html('');
}
},
error: function(xhr, status, error) {
errorLog('Pincodes fetch error', { status, error });
pincodeSelect.html('');
}
});
}
// Load divisions directly by country (for non-India countries)
function loadDivisionsByCountry(country) {
debugLog('Loading divisions for country', { country: country });
divisionSelect.html('');
$.ajax({
url: bmsForm.ajax_url,
type: 'POST',
dataType: 'json',
data: {
action: 'bms_get_divisions',
nonce: bmsForm.nonce,
country: country,
parent_only: true // Only get top-level categories
},
success: function(response) {
debugLog('Divisions by country response', response);
if (response.success && response.data && response.data.length > 0) {
// Set the core/process flag based on first division or default to process
const firstDivision = response.data[0];
isCoreInput.val(firstDivision.division_type === 'core' ? 'true' : 'false');
// Populate division dropdown
let options = '';
response.data.forEach(division => {
options += ``;
});
divisionSelect.html(options);
// If we have a pre-populated category, select it
if (prePopulatedCategoryId) {
handlePrePopulatedCategory();
}
} else {
// Fallback: Load all product categories
loadAllProductCategories(country);
}
},
error: function(xhr, status, error) {
errorLog('Divisions fetch error', { status, error });
// On error, fall back to loading all product categories
loadAllProductCategories(country);
}
});
}
// Fallback function to load all product categories when divisions aren't found
function loadAllProductCategories(country) {
debugLog('Falling back to loading all product categories');
$.ajax({
url: bmsForm.ajax_url,
type: 'POST',
dataType: 'json',
data: {
action: 'bms_get_product_categories',
nonce: bmsForm.nonce,
parent_only: true // Only get top-level categories
},
success: function(response) {
debugLog('Product categories response', response);
if (response.success && response.data && response.data.length > 0) {
let options = '';
response.data.forEach(category => {
options += ``;
});
divisionSelect.html(options);
// Default to process for other countries
isCoreInput.val('false');
// If we have a pre-populated category, select it
if (prePopulatedCategoryId) {
handlePrePopulatedCategory();
}
} else {
divisionSelect.html('');
}
},
error: function(xhr, status, error) {
errorLog('Product categories fetch error', { status, error });
divisionSelect.html('');
}
});
}
// Load divisions based on pincode
function loadDivisionsByPincode(pincode) {
debugLog('Loading divisions for pincode', { pincode: pincode });
divisionSelect.html('');
$.ajax({
url: bmsForm.ajax_url,
type: 'POST',
dataType: 'json',
data: {
action: 'bms_get_divisions',
nonce: bmsForm.nonce,
pincode: pincode,
parent_only: true // Only get top-level categories
},
success: function(response) {
debugLog('Divisions response', response);
if (response.success && response.data && response.data.length > 0) {
let options = '';
response.data.forEach(item => {
options += ``;
});
divisionSelect.html(options);
// If we have a pre-populated category, select it
if (prePopulatedCategoryId) {
handlePrePopulatedCategory();
}
} else {
divisionSelect.html('');
}
},
error: function(xhr, status, error) {
errorLog('Divisions fetch error', { status, error });
divisionSelect.html('');
}
});
}
// Enhanced helper function to handle pre-populated category with better fallbacks
function handlePrePopulatedCategory() {
debugLog('Handling pre-populated category', { categoryId: prePopulatedCategoryId });
// Make sure pincode is selected first if required
if (pincodeContainer.is(':visible') && !pincodeSelect.val()) {
debugLog('Waiting for pincode selection before handling category');
setTimeout(handlePrePopulatedCategory, 500);
return;
}
// Log all available options for debugging
const availableOptions = [];
divisionSelect.find('option').each(function() {
if ($(this).val()) {
availableOptions.push({
value: $(this).val(),
text: $(this).text(),
divisionName: $(this).data('division-name')
});
}
});
debugLog('Available division options', availableOptions);
// Try multiple approaches to find the right category
// 1. Direct match by category ID
if (divisionSelect.find(`option[value="${prePopulatedCategoryId}"]`).length) {
debugLog('Found exact category match', { categoryId: prePopulatedCategoryId });
divisionSelect.val(prePopulatedCategoryId).trigger('change');
return;
}
// 2. Try to match by category name from URL (if available)
const categoryName = getUrlParameter('category_name');
if (categoryName) {
let found = false;
divisionSelect.find('option').each(function() {
if ($(this).text().toLowerCase().includes(categoryName.toLowerCase())) {
debugLog('Found category by name match', { value: $(this).val(), name: $(this).text() });
divisionSelect.val($(this).val()).trigger('change');
found = true;
return false; // Break the loop
}
});
if (found) return;
}
// 3. Look for a parent category
getTopLevelCategory(prePopulatedCategoryId, function(topCategoryId) {
if (topCategoryId && divisionSelect.find(`option[value="${topCategoryId}"]`).length) {
debugLog('Found parent category match', { categoryId: topCategoryId });
divisionSelect.val(topCategoryId).trigger('change');
} else {
// 4. If all else fails, try to fetch category details directly
fetchCategoryDetails(prePopulatedCategoryId);
}
});
}
// New function to fetch specific category details
function fetchCategoryDetails(categoryId) {
debugLog('Fetching detailed category information', { categoryId: categoryId });
$.ajax({
url: bmsForm.ajax_url,
type: 'POST',
dataType: 'json',
data: {
action: 'bms_get_category_details',
nonce: bmsForm.nonce,
category_id: categoryId
},
success: function(response) {
if (response.success && response.data) {
const categoryDetails = response.data;
debugLog('Category details received', categoryDetails);
// If this isn't a top-level category, get the top-level parent
if (categoryDetails.parent_id) {
getTopLevelCategory(categoryDetails.id, function(topCategoryId) {
if (topCategoryId && divisionSelect.find(`option[value="${topCategoryId}"]`).length) {
divisionSelect.val(topCategoryId).trigger('change');
return;
} else {
// Continue with existing logic
matchByDivisionName(categoryDetails);
}
});
} else {
matchByDivisionName(categoryDetails);
}
}
},
error: function(xhr, status, error) {
errorLog('Category details fetch error', { status, error });
}
});
}
// Helper to match by division name
function matchByDivisionName(categoryDetails) {
// Try to match by division name if available
if (categoryDetails.division_name) {
let found = false;
divisionSelect.find('option').each(function() {
const optionDivisionName = $(this).data('division-name');
if (optionDivisionName &&
optionDivisionName.toLowerCase() === categoryDetails.division_name.toLowerCase()) {
debugLog('Found matching division by name', {
value: $(this).val(),
divisionName: optionDivisionName
});
divisionSelect.val($(this).val()).trigger('change');
found = true;
return false; // Break the loop
}
});
if (found) return;
}
// If parent has a division, try to match by that
if (categoryDetails.parent_division_name) {
let found = false;
divisionSelect.find('option').each(function() {
const optionDivisionName = $(this).data('division-name');
if (optionDivisionName &&
optionDivisionName.toLowerCase() === categoryDetails.parent_division_name.toLowerCase()) {
debugLog('Found matching division by parent division name', {
value: $(this).val(),
divisionName: optionDivisionName
});
divisionSelect.val($(this).val()).trigger('change');
found = true;
return false; // Break the loop
}
});
if (found) return;
}
// If we get here, no match was found - select first available option
const firstOption = divisionSelect.find('option[value!=""]').first();
if (firstOption.length) {
debugLog('No specific match found, selecting first available option', {
value: firstOption.val(),
text: firstOption.text()
});
divisionSelect.val(firstOption.val()).trigger('change');
}
}
// Enhanced function to get top-level parent category
function getTopLevelCategory(categoryId, callback) {
debugLog('Getting top-level category for', { categoryId: categoryId });
$.ajax({
url: bmsForm.ajax_url,
type: 'POST',
dataType: 'json',
data: {
action: 'bms_get_top_level_category',
nonce: bmsForm.nonce,
category_id: categoryId
},
success: function(response) {
debugLog('Top-level category response', response);
if (response.success && response.data) {
const topCategoryId = response.data.id;
if (typeof callback === 'function') {
callback(topCategoryId);
} else {
// Try to select the top-level category
if (divisionSelect.find(`option[value="${topCategoryId}"]`).length) {
divisionSelect.val(topCategoryId).trigger('change');
}
}
} else if (typeof callback === 'function') {
callback(null);
}
},
error: function(xhr, status, error) {
errorLog('Top-level category fetch error', { status, error });
if (typeof callback === 'function') {
callback(null);
}
}
});
}
// Enhanced directProductFetch function
function directProductFetch(productId) {
if (!productId) return;
debugLog('Directly fetching product data', { productId });
$.ajax({
url: bmsForm.ajax_url,
type: 'POST',
dataType: 'json',
data: {
action: 'bms_get_single_product_data',
nonce: bmsForm.nonce,
product_id: productId
},
success: function(response) {
if (response.success && response.data) {
const productData = response.data;
debugLog('Product data fetched successfully', productData);
// Store product data globally
window.fetchedProductData = productData;
// STEP 1: Select country
countrySelect.val(productData.country || 'in').trigger('change');
// STEP 2: Wait for country change to process before handling pincode
setTimeout(function() {
// Check if we have a recommended pincode from the product data
if (productData.pincode && pincodeContainer.is(':visible')) {
// Wait for pincodes to load if necessary
if (pincodeSelect.find('option').length <= 1) {
waitForPincodeOptions(function() {
selectPincodeForProduct(productData);
});
} else {
selectPincodeForProduct(productData);
}
} else {
// If pincode not required or not provided, proceed to division selection
waitForDivisionOptions(function() {
selectDivisionForProduct(productData);
});
}
}, 500);
}
},
error: function(xhr, status, error) {
errorLog('Error fetching product data', { status, error });
}
});
}
// Helper function to wait for pincode options to load
function waitForPincodeOptions(callback) {
const maxAttempts = 10;
let attempts = 0;
function checkOptions() {
if (pincodeSelect.find('option[value!=""]').length > 0 || attempts >= maxAttempts) {
callback();
} else {
attempts++;
setTimeout(checkOptions, 300);
}
}
checkOptions();
}
// Helper function to find and select the most appropriate pincode
function selectPincodeForProduct(productData) {
debugLog('Finding appropriate pincode for product', productData);
// Try exact match first
if (productData.pincode && pincodeSelect.find(`option[value="${productData.pincode}"]`).length) {
pincodeSelect.val(productData.pincode).trigger('change');
return;
}
// Try to find a pincode that matches the division type
if (productData.division_name) {
// Look for a pincode with matching core/process type based on division
const divisionType = productData.division_type ||
(productData.division_name.toLowerCase().indexOf('core') >= 0 ? 'core' : 'process');
// Find pincode options with data-type attribute matching the division type
const matchingPincodes = pincodeSelect.find(`option[data-type="${divisionType}"]`);
if (matchingPincodes.length) {
// Select the first matching pincode
pincodeSelect.val(matchingPincodes.first().val()).trigger('change');
return;
}
}
// If no match, select the first available pincode as fallback
const firstPincode = pincodeSelect.find('option[value!=""]').first().val();
if (firstPincode) {
pincodeSelect.val(firstPincode).trigger('change');
}
}
// Helper function to wait for division options to load
function waitForDivisionOptions(callback) {
const maxAttempts = 10;
let attempts = 0;
function checkOptions() {
if (divisionSelect.find('option[value!=""]').length > 0 || attempts >= maxAttempts) {
callback();
} else {
attempts++;
setTimeout(checkOptions, 300);
}
}
checkOptions();
}
// Function to wait for pincodes to load
function waitForPincodesToLoad(productData) {
// Check if pincodes have loaded
if (pincodeSelect.find('option[value!=""]').length > 1) {
// Select first available pincode
selectFirstAvailablePincode();
} else {
// Wait a bit longer and try again
setTimeout(function() {
if (pincodeSelect.find('option[value!=""]').length > 1) {
selectFirstAvailablePincode();
} else {
debugLog('Pincodes failed to load after waiting');
}
}, 1000);
}
}
// Function to select the first available pincode
function selectFirstAvailablePincode() {
debugLog('Selecting first available pincode');
const firstPincode = pincodeSelect.find('option[value!=""]').first().val();
if (firstPincode) {
pincodeSelect.val(firstPincode).trigger('change');
}
}
// Helper function to select the correct division for a product
function selectDivisionForProduct(productData) {
debugLog('Attempting to select division for product', {
categoryId: productData.category_id,
productId: productData.product_id,
productName: productData.product_name
});
// Log all available divisions
const availableDivisions = [];
divisionSelect.find('option').each(function() {
if ($(this).val()) {
availableDivisions.push({
value: $(this).val(),
text: $(this).text(),
divisionName: $(this).data('division-name')
});
}
});
debugLog('Available divisions:', availableDivisions);
// Try matching by exact category ID first
if (productData.category_id && divisionSelect.find(`option[value="${productData.category_id}"]`).length) {
debugLog('Found exact category match, selecting', productData.category_id);
divisionSelect.val(productData.category_id).trigger('change');
// Wait for products to load
waitForProductsToLoad(productData);
return;
}
// Try matching by parent category ID if available
if (productData.parent_category_id &&
divisionSelect.find(`option[value="${productData.parent_category_id}"]`).length) {
debugLog('Found parent category match, selecting', productData.parent_category_id);
divisionSelect.val(productData.parent_category_id).trigger('change');
// Wait for products to load
waitForProductsToLoad(productData);
return;
}
// Try matching by division name attribute
if (productData.division_name) {
let divisionFound = false;
divisionSelect.find('option').each(function() {
const optionDivisionName = $(this).data('division-name');
if (optionDivisionName &&
optionDivisionName.toLowerCase() === productData.division_name.toLowerCase()) {
debugLog('Found division name match, selecting', $(this).val());
divisionSelect.val($(this).val()).trigger('change');
divisionFound = true;
return false; // Break the loop
}
});
if (divisionFound) {
// Wait for products to load
waitForProductsToLoad(productData);
return;
}
}
// If we get here, try using the first available division as fallback
const firstDivision = divisionSelect.find('option[value!=""]').first();
if (firstDivision.length) {
debugLog('No specific match found, selecting first available division', firstDivision.val());
divisionSelect.val(firstDivision.val()).trigger('change');
// Wait for products to load
waitForProductsToLoad(productData);
} else {
debugLog('No divisions available to select');
}
}
// Helper function to wait for products to load and select the correct one
function waitForProductsToLoad(productData) {
debugLog('Waiting for products to load for selected division');
// Wait for products to load after division selection
setTimeout(function() {
// Check if product dropdown has options
if (productSelect.find('option').length > 1) {
selectProductForDivision(productData);
} else {
// Wait longer for products to load
debugLog('Products not loaded yet, waiting longer...');
setTimeout(function() {
selectProductForDivision(productData);
}, 1500);
}
}, 1000);
}
// Helper function to select the correct product
function selectProductForDivision(productData) {
debugLog('Attempting to select product', {
productId: productData.product_id,
productName: productData.product_name
});
// Log all available products
const availableProducts = [];
productSelect.find('option').each(function() {
if ($(this).val()) {
availableProducts.push({
value: $(this).val(),
text: $(this).text()
});
}
});
debugLog('Available products:', availableProducts);
// Check if the specific product exists in the dropdown
if (productData.product_id &&
productSelect.find(`option[value="${productData.product_id}"]`).length) {
debugLog('Found exact product match, selecting', productData.product_id);
productSelect.val(productData.product_id).prop('disabled', false);
return;
}
// Try matching by product name if ID not found
if (productData.product_name) {
let productFound = false;
productSelect.find('option').each(function() {
if ($(this).text().toLowerCase() === productData.product_name.toLowerCase()) {
debugLog('Found product name match, selecting', $(this).val());
productSelect.val($(this).val()).prop('disabled', false);
productFound = true;
return false; // Break the loop
}
});
if (productFound) return;
}
// If product not found in the dropdown but we have the product data, add it
if (productData.product_id && productData.product_name) {
debugLog('Product not found in dropdown, adding it manually');
productSelect.append(``);
productSelect.val(productData.product_id).prop('disabled', false);
} else {
debugLog('Cannot find or add the product');
}
}
// Helper function to select country
function selectCountry(countryCode, callback) {
debugLog('Selecting country', { country: countryCode });
if (countrySelect.find(`option[value="${countryCode}"]`).length) {
countrySelect.val(countryCode).trigger('change');
} else if (countrySelect.find('option[value="in"]').length) {
countrySelect.val('in').trigger('change');
}
setTimeout(function() {
if (typeof callback === 'function') {
callback();
}
}, 500);
}
// Helper function to select category from product data
function selectCategoryFromProductData(productData) {
debugLog('Trying to select category from product data', {
categoryId: productData.category_id,
parentCategoryId: productData.parent_category_id,
divisionName: productData.division_name
});
// Log all available options for debugging
const availableOptions = [];
divisionSelect.find('option').each(function() {
if ($(this).val()) {
availableOptions.push({
value: $(this).val(),
text: $(this).text(),
divisionName: $(this).data('division-name')
});
}
});
debugLog('Available division options', availableOptions);
let categorySelected = false;
// First try: Exact match by category ID
if (productData.category_id && divisionSelect.find(`option[value="${productData.category_id}"]`).length) {
debugLog('Found exact category match', { categoryId: productData.category_id });
divisionSelect.val(productData.category_id).trigger('change');
categorySelected = true;
}
// Second try: Parent category
else if (productData.parent_category_id &&
divisionSelect.find(`option[value="${productData.parent_category_id}"]`).length) {
debugLog('Found parent category match', { categoryId: productData.parent_category_id });
divisionSelect.val(productData.parent_category_id).trigger('change');
categorySelected = true;
}
// Third try: Match by division name
else if (productData.division_name) {
divisionSelect.find('option').each(function() {
const optionDivisionName = $(this).data('division-name');
if (optionDivisionName &&
optionDivisionName.toLowerCase() === productData.division_name.toLowerCase()) {
debugLog('Found matching division by name', {
value: $(this).val(),
divisionName: optionDivisionName
});
divisionSelect.val($(this).val()).trigger('change');
categorySelected = true;
return false; // Break the loop
}
});
}
// If no category selected but we have options, select the first non-empty one
if (!categorySelected && divisionSelect.find('option[value!=""]').length > 1) {
const firstOption = divisionSelect.find('option[value!=""]').first();
debugLog('No specific match found, selecting first available option', {
value: firstOption.val(),
text: firstOption.text()
});
divisionSelect.val(firstOption.val()).trigger('change');
categorySelected = true;
}
// Wait for division to be selected and load products
setTimeout(function() {
// Now select/handle the product
if (productData.product_id) {
if (productSelect.find(`option[value="${productData.product_id}"]`).length) {
// If product exists in dropdown, select it
productSelect.val(productData.product_id).prop('disabled', false);
debugLog('Selected existing product', {
productId: productData.product_id,
productName: productData.product_name
});
} else {
// If product not in dropdown, add it and select
productSelect.append(``);
productSelect.val(productData.product_id).prop('disabled', false);
debugLog('Added and selected product', {
productId: productData.product_id,
productName: productData.product_name
});
}
}
}, 1000);
}
// Load products based on division/category (for both India and non-India flow)
// Modify the loadProductsByDivision function to better handle pre-populated products
function loadProductsByDivision(divisionId) {
debugLog('Loading products for division', { divisionId: divisionId });
productSelect.html('').prop('disabled', true);
$.ajax({
url: bmsForm.ajax_url,
type: 'POST',
dataType: 'json',
data: {
action: 'bms_get_products_by_category',
nonce: bmsForm.nonce,
category_id: divisionId
},
success: function(response) {
debugLog('Products response', response);
if (response.success && response.data && response.data.length > 0) {
let options = '';
// Flag to check if our pre-populated product is in the results
let prePopulatedProductFound = false;
// Add all products to dropdown
response.data.forEach(product => {
const isSelected = (prePopulatedProductId && product.value == prePopulatedProductId) ? 'selected' : '';
if (isSelected) prePopulatedProductFound = true;
options += ``;
});
// Add the dropdown options
productSelect.html(options).prop('disabled', false);
// If we have a pre-populated product but it wasn't in the results, add it manually
if (prePopulatedProductId && prePopulatedProductName && !prePopulatedProductFound) {
debugLog('Adding pre-populated product manually', {
id: prePopulatedProductId,
name: prePopulatedProductName
});
// Append the product at the end
productSelect.append(``);
}
// Force the selection (needed in some browsers)
if (prePopulatedProductId) {
productSelect.val(prePopulatedProductId);
}
} else {
productSelect.html('');
// If no products found but we have pre-populated product info, add just that product
if (prePopulatedProductId && prePopulatedProductName) {
debugLog('No products found, adding pre-populated product only', {
id: prePopulatedProductId,
name: prePopulatedProductName
});
productSelect.html(``);
productSelect.val(prePopulatedProductId).prop('disabled', false);
}
}
},
error: function(xhr, status, error) {
errorLog('Products fetch error', { status, error });
// Even on error, if we have pre-populated product info, add that product
if (prePopulatedProductId && prePopulatedProductName) {
debugLog('Error loading products, adding pre-populated product only', {
id: prePopulatedProductId,
name: prePopulatedProductName
});
productSelect.html(``);
productSelect.val(prePopulatedProductId).prop('disabled', false);
} else {
productSelect.html('').prop('disabled', true);
}
}
});
}
// Add this function to ensure the product is selected
function forceProductSelection() {
if (prePopulatedProductId && prePopulatedProductName) {
debugLog('Force selecting product', { id: prePopulatedProductId, name: prePopulatedProductName });
// Check if product exists in dropdown
if (productSelect.find(`option[value="${prePopulatedProductId}"]`).length) {
productSelect.val(prePopulatedProductId).prop('disabled', false);
} else {
// Add it if it doesn't exist
productSelect.append(``);
productSelect.val(prePopulatedProductId).prop('disabled', false);
}
}
}
// Event Listeners
countrySelect.on('change', handleCountryChange);
pincodeSelect.on('change', function() {
const selectedPincode = $(this).val();
const selectedOption = $(this).find('option:selected');
const selectedTypes = selectedOption.data('types') || [];
const selectedBranches = selectedOption.data('branches') || [];
// Set is_core based on the first type (for backward compatibility)
isCoreInput.val(selectedTypes.includes('core') ? 'true' : 'false');
debugLog('Pincode selected', {
pincode: selectedPincode,
types: selectedTypes,
branches: selectedBranches
});
if (selectedPincode) {
loadDivisionsByPincode(selectedPincode);
} else {
divisionSelect.html('');
productSelect.html('').prop('disabled', true);
}
});
divisionSelect.on('change', function() {
const selectedOption = $(this).find('option:selected');
const divisionId = $(this).val();
const divisionName = selectedOption.data('division-name') || selectedOption.text().trim();
const divisionType = selectedOption.data('division-type') || 'process';
divisionNameTextInput.val(divisionName);
isCoreInput.val(divisionType === 'core' ? 'true' : 'false');
debugLog('Division selected', {
divisionId: divisionId,
divisionName: divisionName,
divisionType: divisionType
});
// Load products for both India and non-India flow
if (divisionId) {
loadProductsByDivision(divisionId);
} else {
productSelect.html('').prop('disabled', true);
}
});
// Form submission handler
function handleFormSubmit(e) {
e.preventDefault();
if (!form[0].checkValidity()) {
form.addClass('was-validated');
return;
}
const selectedDivision = divisionSelect.find('option:selected');
const divisionName = selectedDivision.data('division-name') || selectedDivision.text().trim();
const divisionType = selectedDivision.data('division-type') || 'process';
const formData = {
fullName: $('#fullName').val(),
designation: $('#designation').val(),
email: $('#email').val(),
phone: $('#phone').val(),
company: $('#company').val(),
country: countrySelect.val(),
pincode: pincodeSelect.val(),
product: productSelect.val(),
category_id: divisionSelect.val(),
division_name: divisionSelect.val(),
note: $('#note').val(),
is_core: divisionType === 'core' ? 'true' : 'false',
division_name_text: divisionName
};
debugLog('Submitting form', formData);
submitBtn.prop('disabled', true).text('Submitting...');
$.ajax({
url: bmsForm.ajax_url,
type: 'POST',
dataType: 'json',
data: {
action: 'bms_process_form_submission',
nonce: bmsForm.nonce,
form_data: formData
},
success: function(response) {
debugLog('Form submission response', response);
if (response.success) {
alert(response.data.message);
form[0].reset();
resetDependentFields();
} else {
alert(response.data.message || 'An error occurred. Please try again.');
}
},
error: function(xhr, status, error) {
errorLog('Form submission error', { status, error });
alert('An unexpected error occurred. Please try again.');
},
complete: function() {
submitBtn.prop('disabled', false).text('Send Enquiry');
}
});
}
form.on('submit', handleFormSubmit);
// Initialize form
loadCountries();
pincodeContainer.hide(); // Hide pincode field initially
debugLog('Form initialized');
});
jQuery(document).ready(function($) {
$('#pincode').select2({
placeholder: "Search or select a Pincode",
allowClear: true,
width: '100%'
});
});
Warning: session_start(): Session cannot be started after headers have already been sent in /var/www/html/wp-content/themes/forbes-marshall-child/functions.php on line 353
Warning: Cannot modify header information - headers already sent by (output started at /var/www/html/wp-content/plugins/branch-management-system/branch-management-system.php:1) in /var/www/html/wp-content/plugins/gtranslate/gtranslate.php on line 84
Warning: Cannot modify header information - headers already sent by (output started at /var/www/html/wp-content/plugins/branch-management-system/branch-management-system.php:1) in /var/www/html/wp-includes/pluggable.php on line 1450
Warning: Cannot modify header information - headers already sent by (output started at /var/www/html/wp-content/plugins/branch-management-system/branch-management-system.php:1) in /var/www/html/wp-includes/pluggable.php on line 1453