nhance/app/Views/policyRegisterModel.php
2025-05-13 12:40:55 +05:30

1662 lines
74 KiB
PHP

<div class="modal fade" id="policyRegisterModel" tabindex="-1" aria-labelledby="fullWidthModalLabel" aria-hidden="true" data-backdrop="static" data-keyboard="false">
<div class="modal-dialog modal-xl modal-dialog-centered">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title" id="fullWidthModalLabel">REGISTER POLICY INFORMATION</h4>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">&times;</span>
</button>
</div>
<input type="hidden" name="policyName" id="policyName">
<input type="hidden" name="leadID" id="leadID">
<input type="hidden" name="policySI" id="policySI">
<div class="modal-body">
<!-- Tabs Navigation -->
<ul class="nav nav-pills navtab-bg nav-justified" id="policyTabs">
<li class="nav-item">
<a id="product-selection-tab" data-toggle="tab" aria-expanded="false" class="nav-link active" href="#product-selection" aria-current="page">Product Selection</a>
</li>
<li class="nav-item">
<a id="policy-details-tab" data-toggle="tab" aria-expanded="false" class="nav-link" href="#policy-details">Policy Details</a>
</li>
<li class="nav-item">
<a id="risk-info-tab" data-toggle="tab" aria-expanded="false" class="nav-link" href="#risk-information">Risk Information</a>
</li>
<li id="risksplitupTab" class="nav-item">
<a id="risk-splitup-tab" data-toggle="tab" aria-expanded="false" class="nav-link" href="#risk-splitup">Risk Split UP Information</a>
</li>
</ul>
<!-- Tab Content -->
<div class="tab-content mt-3">
<!-- Product selection Tab -->
<div class="tab-pane fade show active" id="product-selection">
<form id="productSelectionForm" class="parsley-examples" enctype="multipart/form-data">
<div class="row">
<div class="form-group col-md-3">
<button type="button" class="btn btn-primary" id="getDataFromLead" onclick="assignLeadData()">Get Data From Lead</button>
</div>
<div class="form-group burglary col-md-3">
<button type="button" class="btn btn-primary burglary" id="sameAsFire" onclick="copyFirePolicy()">Same as Fire Policy</button>
</div>
</div>
<div class="row">
<div class="form-group col-md-4">
<label>Select Business Type<span class="text-danger">*</span></label>
</div>
<div class="form-group col-md-4">
<label for="singleProduct">Single Location</label>
<input type="checkbox" id="singleProduct" name="singleProduct" class="business-type-checkbox" checked />
</div>
<div class="form-group col-md-4">
<label for="multipleProduct">Multiple Location</label>
<input type="checkbox" id="multipleProduct" name="multipleProduct" class="business-type-checkbox" />
</div>
</div>
<div class="form-group col-md-4" id="multilocation_type_div">
<label for="multilocation_type" class="form-label">Multilocation Type <span class="text-danger">*</span></label>
<select id="multilocation_type" name="multilocation_type" class="form-control">
<option value="">Select</option>
<option value="multiLocation">Multilocation Without Floater</option>
<option value="multiFloater">Multilocation With Floater</option>
</select>
</div>
<div class="row">
<div class="form-group col-md-4">
<label for="client_type">Client Type<span class="text-danger">*</span></label>
<select class="form-control" id="client_type" name="client_type" required>
<option value="">Select Client type</option>
<?php
if (isset($client_type) && count($client_type)) {
foreach ($client_type as $key => $value) {
echo "<option value='" . $key . "' >" . $value . "</option>";
}
}
?>
</select>
</div>
<div class="form-group col-md-4">
<label for="type_of_buisness">Type of Buisness <span class="text-danger">*</span></label>
<select class="form-control" id="type_of_buisness" name="type_of_buisness" required>
<option value="">Select a Buisness</option>
<?php
if (isset($buisness_type) && count($buisness_type)) {
foreach ($buisness_type as $key => $value) {
echo "<option value='" . $key . "' >" . $value . "</option>";
}
}
?>
</select>
</div>
<div class="form-group col-md-4">
<label for="buisnessNature">Nature of Business<span class="text-danger">*</span></label>
<input type="text" class="form-control" id="buisnessNature" name="buisness_nature" required />
</div>
</div>
<hr>
<div class="text-right">
<button type="submit" class="btn btn-primary" id="submitProductSelection">Proceed</button>
</div>
</form>
</div>
<!-- Policy Details Tab -->
<div class="tab-pane fade" id="policy-details">
<h5>Product Information</h5>
<form id="policyDetailsForm" class="parsley-examples" enctype="multipart/form-data">
<div class="row">
<div class="form-group col-md-4">
<label for="valueOfRisk">Value of the Risk<span class="text-danger">*</span></label>
<input type="number" id="valueOfRisk" name="value_of_risk" class="form-control" required />
</div>
</div>
<div class="row">
<div class="form-group col-md-4">
<label for="insured_name">Insured Name<span class="text-danger">*</span></label>
<input type="text" id="insured_name" name="insured_name" class="form-control" required />
</div>
<div class="form-group col-md-4">
<label for="email">Email Id<span class="text-danger">*</span></label>
<input type="text" id="email" name="email" class="form-control" required />
</div>
<div class="form-group col-md-4">
<label for="mobile">Mobile Number<span class="text-danger">*</span></label>
<input type="text" id="mobile" name="mobile" class="form-control" required />
</div>
</div>
<hr>
<h5>Communication Address</h5>
<div class="row">
<div class="form-group col-md-4">
<label for="pin_code">Pin Code<span class="text-danger">*</span></label>
<input type="text" id="pin_code" name="pin_code" class="form-control" required />
</div>
<div class="form-group col-md-4">
<label for="address1">Address 1<span class="text-danger">*</span></label>
<input type="text" id="address1" name="address1" class="form-control" required />
</div>
<div class="form-group col-md-4">
<label for="address2">Address 2</label>
<input type="text" id="address2" name="address2" class="form-control" />
</div>
</div>
<div class="row">
<div class="col-md-4 dt-switch-wrapper">
<div class="custom-control custom-switch">
<input type="checkbox" class="custom-control-input" id="terrorismSwitch">
<label class="custom-control-label" for="terrorismSwitch">Is Terrorism Required?</label>
</div>
</div>
<div class="form-group col-md-4">
<label for="policy_term">Policy Term<span class="text-danger">*</span></label>
<select id="policy_term" name="policy_term" class="form-control" required>
<option value="">Select</option>
<option value="1_month">1 Month</option>
<option value="2_month">2 Months</option>
<option value="3_month">3 Months</option>
<option value="4_month">4 Months</option>
<option value="5_month">5 Months</option>
<option value="6_month">6 Months</option>
<option value="7_month">7 Months</option>
<option value="8_month">8 Months</option>
<option value="9_month">9 Months</option>
<option value="10_month">10 Months</option>
<option value="11_month">11 Months</option>
<option value="12_month">12 Months</option>
<option value="2_year">2 Year</option>
<option value="3_year">3 Year</option>
<option value="4_year">4 Year</option>
<option value="5_year">5 Year</option>
<option value="6_year">6 Year</option>
<option value="7_year">7 Year</option>
<option value="8_year">8 Year</option>
<option value="9_year">9 Year</option>
<option value="10_year">10 Year</option>
</select>
</div>
<div id="locationNoDIV" class="form-group col-md-4">
<label for="location_no">No of location<span class="text-danger">*</span></label>
<select id="location_no" name="location_no" class="form-control">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
</select>
</div>
</div>
<hr>
<div class="row">
<div class="form-group col-md-12">
<label for="hypothecations">Hypothecations</label>
<textarea id="hypothecations" name="hypothecations" class="form-control" rows="3"></textarea>
</div>
</div>
<div class="text-right">
<button type="submit" id="addRiskBtn" class="btn btn-primary">Add Risk Locations</button>
</div>
</form>
</div>
<!-- Risk Information Tab -->
<div class="tab-pane fade" id="risk-information">
<form id="policyRiskAddressForm" class="parsley-examples" enctype="multipart/form-data">
<div id="addRiskInfo"></div>
<div class="text-right">
<button type="submit" id="riskSplitup" class="btn btn-primary">Validate and Add Risk Split up</button>
</div>
<!-- <div class="row">
<div class="col-md-12 text-right">
<button type="submit" id="submitPolicyRisk" class="btn btn-primary">Submit For Validation</button>
</div>
</div> -->
</form>
</div>
<!-- Risk Splitup Tab -->
<div class="tab-pane fade" id="risk-splitup">
<form id="policyRiskSplitUpForm" class="parsley-examples" enctype="multipart/form-data">
<div id="addRiskSplitUp"></div>
<div class="text-right">
<button type="submit" id="riskSplitUPButton" class="btn btn-primary">Register</button>
</div>
</form>
</div>
</div>
<!-- Contact Information Tab -->
</div>
</div>
<!-- <div class="modal-footer">
<button type="button" class="btn btn-primary">Submit</button>
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
</div> -->
</div>
</div>
</div>
<script>
var totalSI;
var finalData = {};
// console.log("policyName : ", $('#policyName').val());
var policyName = $('#policyName').val();
const occupancyMaster = <?= json_encode($occupancy) ?>;
// console.log("Occupancy : ", occupancyMaster);
var storedPolicyData = {};
storedPolicyData = JSON.parse(localStorage.getItem('policyData'));
var isFormDirty = false;
$(document).ready(function() {
// Listen for changes in all inputs, selects, and textareas within your modal
$('#policyRegisterModel').on('change input', 'input, select, textarea', function() {
// alert("function called");
isFormDirty = true;
// console.log("Form is dirty",isFormDirty);
});
});
$(document).ready(function() {
// resetAllform();
// console.log("Stored date Found : ", typeof(storedPolicyData));
if (!$.isEmptyObject(storedPolicyData)) {
// prepareDataForEdit(storedPolicyData);
} else {
// console.log("inside else trying to open product sleection tab");
// const productSelectionTab = new bootstrap.Tab(document.getElementById);
const productSelectionTab = new bootstrap.Tab(document.getElementById('product-selection-tab'));
productSelectionTab.show();
hideAndShowBurglary();
}
})
var increment = 1;
var increment2 = 1;
var productSelectionData = {};
var policyDetailsData = {};
var policyRiskAddress = {};
var policyRiskSplitUpData = {};
$(document).ready(function() {
hideAndShowBurglary();
// resetAllform();
if ($.isEmptyObject(storedPolicyData)) {
$('#multilocation_type_div').hide();
}
// When a business-type checkbox changes, handle exclusive selection
$('.business-type-checkbox').on('change', function() {
const $current = $(this);
const id = $current.attr('id');
// If the current checkbox is checked:
if ($current.is(':checked')) {
// Uncheck the other business-type checkboxes without triggering their change event
$('.business-type-checkbox').not($current).prop('checked', false);
if (id === 'multipleProduct') {
// For multiple product, show the multilocation container and mark it
$('#multilocation_type_div').show();
$('#multilocation_type').show();
$('#multilocation_type').prop('required', true);
} else if (id === 'singleProduct') {
// For single product, hide the multilocation container and remove attribute
$('#multilocation_type').closest('.form-group').hide();
$('#multilocation_type').prop('required', false);
}
} else {
// If uncheckked and it's the multiple product, hide the container
if (id === 'multipleProduct') {
$('#multilocation_type').closest('.form-group').hide();
$('#multilocation_type').prop('required', false);
}
}
});
});
$('#productSelectionForm').submit(function(event) {
// console.log("Submit function called");
event.preventDefault();
var isValid = $('#productSelectionForm').parsley().validate();
// console.log('isValid', isValid)
if (!isValid) {
$('#productSelectionForm').find('input, select, textarea').each(function() {
if ($(this).parsley().isValid() === false && !$(this).val()) {
// console.log('Empty field ID:', this.id);
}
});
// console.log('Form is Empty', 'Warning');
return;
}
productSelectionData = {};
// // console.log("submit function is clicked");
// event.preventDefault();
var formDataProductSelection = $("#productSelectionForm").serializeArray();
$.each(formDataProductSelection, function(i, field) {
productSelectionData[field.name] = field.value;
});
productSelectionData['singleProduct'] = $('#singleProduct').is(':checked') ? 'on' : 'off';
productSelectionData['multipleProduct'] = $('#multipleProduct').is(':checked') ? 'on' : 'off';
productSelectionData['multilocation_type'] = $('#singleProduct').is(':checked') ? "" : productSelectionData['multilocation_type'];
if (!$('#singleProduct').is(':checked') && !$('#multipleProduct').is(':checked')) {
// productSelectionData = {};
toastr.warning("Please choose a Product", "Warning");
} else {
policydetailsOpen();
}
// console.log("form data product selection : ", productSelectionData);
})
function policydetailsOpen() {
// PolicyTabOpened();
// console.log("function is called");
// Use the ID for the Policy Details tab button.
// const policyDetailsTab = new bootstrap.Tab(document.getElementById('policy-details-tab'));
const policyDetailsTab = new bootstrap.Tab(document.getElementById('policy-details-tab'));
policyDetailsTab.show();
}
$("#policyRiskSplitUpForm").submit(function(event) {
event.preventDefault();
isFormDirty = false;
var isValid = $('#policyRiskSplitUpForm').parsley().validate();
// console.log('isValid', isValid);
if (!isValid) {
$('#policyRiskSplitUpForm').find('input, select, textarea').each(function() {
if ($(this).parsley().isValid() === false && !$(this).val()) {
// console.log('Empty field ID:', this.id);
}
});
// console.log('Form is Empty', 'Warning');
return;
}
// Serialize the form into an array of objects {name, value}
const formDataSplitUp = $("#policyRiskSplitUpForm").serializeArray();
// Manually add checkbox values for each row (even if unchecked)
for (let i = 0; i < increment2; i++) {
formDataSplitUp.push({
name: `burglary_theft_switch[]`,
value: $(`#burglaryTheftSwitch_${i}`).is(':checked') ? 'on' : 'off'
});
formDataSplitUp.push({
name: `first_loss[]`,
value: $(`#firstLoss_${i}`).is(':checked') ? 'on' : 'off'
});
formDataSplitUp.push({
name: `loss_in_3_years[]`,
value: $(`#lossIN3Years_${i}`).is(':checked') ? 'on' : 'off'
});
}
// console.log("form from : ", formDataSplitUp);
// if (productSelectionData.multipleProduct == 'on') {
// let selectionType = productSelectionData.multilocation_type;
// if (selectionType == 'multiFloater') {
let InProcess = [...document.querySelectorAll('[id^="stockInProcess_"]')].map(el => Number(el.value) || 0);
let rawMaterial = [...document.querySelectorAll('[id^="rawMaterial_"]')].map(el => Number(el.value) || 0);
let findMaterial = [...document.querySelectorAll('[id^="finishedStock_"]')].map(el => Number(el.value) || 0);
let building = [...document.querySelectorAll('[id^="building_"]')].map(el => Number(el.value) || 0);
let content = [...document.querySelectorAll('[id^="content_"]')].map(el => Number(el.value) || 0);
let furniture = [...document.querySelectorAll('[id^="furniture_"]')].map(el => Number(el.value) || 0);
let plantAndMachinery = [...document.querySelectorAll('[id^="plantAndMachinery_"]')].map(el => Number(el.value) || 0);
let electricalFittings = [...document.querySelectorAll('[id^="electricalFittings_"]')].map(el => Number(el.value) || 0);
totalSI = InProcess.reduce((acc, val) => acc + val, 0) +
rawMaterial.reduce((acc, val) => acc + val, 0) +
findMaterial.reduce((acc, val) => acc + val, 0) +
building.reduce((acc, val) => acc + val, 0) +
content.reduce((acc, val) => acc + val, 0) +
furniture.reduce((acc, val) => acc + val, 0) +
plantAndMachinery.reduce((acc, val) => acc + val, 0) +
electricalFittings.reduce((acc, val) => acc + val, 0);
let allowedSI = Number($("#policySI").val()) || 0;
// alert(allowedSI);
if (totalSI != allowedSI) {
console.log("allowedSI : ", allowedSI, " totalSI : ", totalSI);
toastr.error("Sum Insured Does not Match Allowed Limit", "ERROR");
return false;
}
// console.log("Total SI: ", totalSI);
// } else {
// let InProcess = [...document.querySelectorAll('[id^="stockInProcess_"]')].map(el => Number(el.value) || 0);
// let rawMaterial = [...document.querySelectorAll('[id^="rawMaterial_"]')].map(el => Number(el.value) || 0);
// let findMaterial = [...document.querySelectorAll('[id^="finishedStock_"]')].map(el => Number(el.value) || 0);
// totalSI = InProcess.reduce((acc, val) => acc + val, 0) +
// rawMaterial.reduce((acc, val) => acc + val, 0) +
// findMaterial.reduce((acc, val) => acc + val, 0);
// }
// }
// console.log("Form is trying to submit : ", formDataSplitUp);
const groupData = [];
// Determine the number of dynamic rows based on a field that appears per row
const totalRows = formDataSplitUp.filter(field => field.name === "building[]").length;
if (totalRows != policyDetailsData.location_no) {
toastr.error("Please Enter All Risk Address", "ERROR");
return;
}
// Initialize empty objects for each row
for (let i = 0; i < totalRows; i++) {
groupData.push({});
}
// Track the position of each field type in the grouped data
const fieldCounts = {};
formDataSplitUp.forEach(field => {
const fieldName = field.name.replace('[]', '');
// Initialize count if not exists
if (typeof fieldCounts[fieldName] === 'undefined') {
fieldCounts[fieldName] = 0;
}
let index = fieldCounts[fieldName];
// If groupData at this index doesn't exist, push a new object
if (!groupData[index]) {
groupData[index] = {};
}
groupData[index][fieldName] = field.value;
fieldCounts[fieldName]++;
});
policyRiskSplitUpData = groupData;
// console.log("Grouped Data as Objects: ", policyRiskSplitUpData);
savePolicyDataLocal();
});
$("#policyRiskAddressForm").submit(function(event) {
event.preventDefault();
var isValid = $('#policyRiskAddressForm').parsley().validate();
// console.log('isValid', isValid)
if (!isValid) {
$('#policyRiskAddressForm').find('input, select, textarea').each(function() {
if ($(this).parsley().isValid() === false && !$(this).val()) {
// console.log('Empty field ID:', this.id);
}
});
// console.log('Form is Empty', 'Warning');
return;
}
const formData = $("#policyRiskAddressForm").serializeArray();
console.log("formdata 1 : ", formData);
$("[id^='isBasement_']").each(function() {
let checkbox = $(this);
let isChecked = checkbox.is(":checked");
let increment = checkbox.attr("id").split("_")[1];
formData.push({
name: `is_basement[]`,
value: isChecked ? "yes" : "no"
});
});
console.log("formdata 2 : ", formData);
const groupedData = [];
// Determine the number of dynamic rows
const totalRows = formData.filter(field => field.name === "pin_code[]").length;
if (totalRows != policyDetailsData.location_no) {
toastr.error("Please Enter All Risk Address", "ERROR");
return;
}
// Initialize empty objects for each row
for (let i = 0; i < totalRows; i++) {
groupedData.push({});
}
// Track the position of each field type in the grouped data
const fieldCounts = {};
formData.forEach(field => {
const fieldName = field.name.replace('[]', '');
// Initialize count for this field type if not exists
if (!fieldCounts[fieldName]) {
fieldCounts[fieldName] = 0;
}
const index = fieldCounts[fieldName]; // Correctly track field index
groupedData[index][fieldName] = field.value;
// Increment the count for the next occurrence of this field type
fieldCounts[fieldName]++;
});
policyRiskAddress = groupedData;
console.log("Grouped Data as Objects: ", policyRiskAddress);
// if (productSelectionData.singleProduct == 'on') {
// savePolicyDataLocal();
// } else {
riskSplitup();
// }
});
$("#policyDetailsForm").submit(function(event) {
event.preventDefault();
var isValid = $('#policyDetailsForm').parsley().validate();
// console.log('isValid', isValid)
if (!isValid) {
$('#policyDetailsForm').find('input, select, textarea').each(function() {
if ($(this).parsley().isValid() === false && !$(this).val()) {
// console.log('Empty field ID:', this.id);
}
});
// console.log('Form is Empty', 'Warning');
return;
}
var formData = $("#policyDetailsForm").serializeArray();
formData.push({
name: "terrorism",
value: $('#terrorismSwitch').is(':checked') ? 'yes' : 'no'
})
$.each(formData, function(i, field) {
policyDetailsData[field.name] = field.value;
});
console.log("form data", formData);
if (formData !== null && formData !== '') {
const riskTab = new bootstrap.Tab(document.getElementById('risk-info-tab'));
riskTab.show();
}
});
function riskSplitup() {
// riskSplitupTabOpened()
const riskSplitTab = new bootstrap.Tab(document.getElementById('risk-splitup-tab'));
riskSplitTab.show();
}
$(document).ready(function() {
// resetAllform();
$('a[data-toggle="tab"]').on('shown.bs.tab', function(e) {
if (e.target.id === 'policy-details-tab') {
if (Object.keys(productSelectionData).length > 0) {
$("#policy-details").show();
validatePolicyBasedOnProductSelection();
} else {
$("#policy-details").hide();
toastr.warning("Please Choose a Product First", "Warning");
}
} else if (e.target.id === 'risk-splitup-tab') {
contianertoCheck = document.getElementById("addRiskSplitUp");
// console.log("policy det", policyRiskAddress.length)
if (!$.isEmptyObject(policyRiskAddress)) {
if (increment2 == 1) {
policyRiskAddress.forEach(function() {
// console.log("increment count is ", increment2)
addHTMLInputForRiskSplitUP();
validatePolicyBasedOnProductSelection();
hideAndShowBurglary();
})
}else{
// alert("you got ir");
console.log("increment2",increment2);
console.log("policyRiskAddress.length",policyRiskAddress.length);
policyRiskAddress.forEach(function() {
if (increment2 <= policyRiskAddress.length) {
// console.log("increment count is ", increment2)
addHTMLInputForRiskSplitUP();
validatePolicyBasedOnProductSelection();
hideAndShowBurglary();
}
})
// else {
// const container = document.getElementById("addRiskSplitUp");
// container.innerHTML = "";
// increment2 = 1;
// if (increment2 <= policyRiskAddress.length) {
// policyRiskAddress.forEach(function() {
// // console.log("increment count is ", increment2)
// addHTMLInputForRiskSplitUP();
// validatePolicyBasedOnProductSelection();
// hideAndShowBurglary();
// // increment2++;
// })
// // alert("fdg");
// }
// }
}
} else {
if (contianertoCheck.innerHTML == "") {
addHTMLInputForRiskSplitUpWarninig();
}
}
} else if (e.target.id === 'risk-info-tab') {
// console.log("function called ");
contianertoCheck = document.getElementById("addRiskInfo");
// // console.log("policy details data ", policyDetailsData);
if (!$.isEmptyObject(policyDetailsData)) {
if (increment == 1) {
// console.log("inside if ");
addHTMLInputForRiskAddress();
$('select[id^="occupancy_"]').select2();
validatePolicyBasedOnProductSelection();
}
} else {
// console.log("inside else ");
if (contianertoCheck.innerHTML == "") {
addHTMLInputForRiskAddressWarninig();
}
}
const riskTab = new bootstrap.Tab(document.getElementById('risk-info-tab'));
riskTab.show();
}
});
});
function addHTMLInputForRiskSplitUpWarninig() {
const containerWarninig = document.getElementById('addRiskSplitUp');
const newRow = document.createElement('div');
newRow.innerHTML += `
<h3>Please Enter Risk Address Before Adding the splitup</h3>
`;
containerWarninig.appendChild(newRow);
}
function addHTMLInputForRiskSplitUP() {
// // console.log("Function called ", increment2, " times");
const container = document.getElementById("addRiskSplitUp");
// container.innerHTML = '';
const newRowRisk = document.createElement("div");
// // console.log("Risk Split Up for address : ", policyRiskAddress.length)
// policyRiskAddress
console.log(increment2);
console.log(policyRiskAddress[increment2-1])
newRowRisk.innerHTML += `
<h5 class = "fire">Fire <?= isset($product) ? $product : "" ?> Details</h5>
<h5>Risk Split Up for Address : ${policyRiskAddress[increment2-1].address1} ${policyRiskAddress[increment2-1].address2}</h5>
<input type = "hidden" name = "location_selected[]" value = "${policyRiskAddress[increment2-1].select_location}" id = "location_selected_${increment2}" />
<div class = "row">
<div class="form-group col-md-4 multi_location_company">
<label for="building_${increment2}">Building</label>
<input type="number" id="building_${increment2}" name="building[]" class="form-control multi_location_company " />
</div>
<div class="form-group col-md-4 multi_location_company ">
<label for="content_${increment2}">Content</label>
<input type="number" id="content_${increment2}" name="content[]" class="form-control multi_location_company " />
</div>
<div class="form-group col-md-4 multi_location_company ">
<label for="furniture_${increment2}">Furniture/Office Equipment</label>
<input type="number" id="furniture_${increment2}" name="furniture[]" class="form-control multi_location_company " />
</div>
<div class="form-group col-md-4 multi_location_company ">
<label for="plantAndMachinery_${increment2}">Plant and Machinery</label>
<input type="number" id="plantAndMachinery_${increment2}" name="plant_and_machinery[]" class="form-control multi_location_company " />
</div>
<div class="form-group col-md-4 multi_location_company">
<label for="electricalFittings_${increment2}">Electrical Fittings</label>
<input type="number" id="electricalFittings_${increment2}" name="electrical_fittings[]" class="form-control multi_location_company "/>
</div>
</div>
<br>
<div class = "stockSI">
<h5>Stock Sum Insured</h5>
<div class = "row">
<div class="form-group col-md-4 multi_location_company">
<label for="stockInProcess_${increment2}">Stock In Process</label>
<input type="number" id="stockInProcess_${increment2}" name="stock_in_process[]" class="form-control multi_location_company" />
</div>
<div class="form-group col-md-4 multi_location_company">
<label for="rawMaterial_${increment2}">Raw Material</label>
<input type="number" id="rawMaterial_${increment2}" name="raw_material[]" class="form-control multi_location_company" />
</div>
<div class="form-group col-md-4 multi_location_company">
<label for="finishedStock_${increment2}">Stock</label>
<input type="number" id="finishedStock_${increment2}" name="finished_stock[]" class="form-control multi_location_company"/>
</div>
</div>
<hr>
</div>
<div class = "row">
<div class = "form-group col-md-3">
<div class="form-check burglary">
<input name = "burglary_theft_switch[]" type="checkbox" class="form-check-input burglary" id="burglaryTheftSwitch_${increment2}">
<label class="form-check-label burglary" for="burglaryTheftSwitch_${increment2}">Burglary Theft Opted</label>
</div>
</div>
<div class = "form-group col-md-3">
<div class="form-check burglary">
<input type="checkbox" name ="first_loss[]" class="form-check-input burglary" id="firstLoss_${increment2}">
<label class="form-check-label burglary" for="firstLoss_${increment2}">First Loss</label>
</div>
</div>
<div class = "form-group col-md-3 burglary">
<input name = "loss_in_3_years[]" type="checkbox" class="form-check-input burglary" id="lossIN3Years_${increment2}">
<label class="form-check-label burglary" for="lossIN3Years_${increment2}">Any Loss in last 3 Years</label>
</div>
<div class = "form-group col-md-3 burglary">
<input name = "buisnness_interuption[]" type="checkbox" class="form-check-input burglary" id="buisnnessInteruption_${increment2}">
<label class="form-check-label burglary" for="buisnnessInteruption_${increment2}">Buisness Interuption</label>
</div>
<div class = "form-group col-md-3 burglary">
<label for="firstLossPercent_${increment2}">First Loss %<span class="text-danger">*</span></label>
<select required id="firstLossPercent_${increment2}" name="first_loss_percent[]" class="form-control burglary">
<option value="10" selected>10 %</option>
<option value="20">20 %</option>
<option value="30">30 %</option>
<option value="40">40 %</option>
<option value="50">50 %</option>
</select>
</div>
<div class="form-group col-md-3 burglary">
<label for="annualGrossProfit_${increment2}">Annual Gross Profit<span class="text-danger">*</span></label>
<input type="text" id="annualGrossProfit_${increment2}" name="annual_gross_profit[]" class="form-control burglary" required/>
</div>
<div class="form-group col-md-3 burglary">
<label for="indemnityPeriod_${increment2}">Indemnity Period<span class="text-danger">*</span></label>
<input type="text" id="indemnityPeriod_${increment2}" name="indemnity_period[]" class="form-control burglary" required/>
</div>
</div>
`;
container.appendChild(newRowRisk);
increment2++;
}
function addHTMLInputForRiskAddressWarninig() {
const containerWarninig = document.getElementById('addRiskInfo');
const newRow = document.createElement('div');
newRow.innerHTML += `
<h3>Please Enter Policy Details before adding the Risk Address</h3>
`;
containerWarninig.appendChild(newRow);
}
function addHTMLInputForRiskAddress() {
const container = document.getElementById('addRiskInfo');
// container.innerHTML = "";
const newRow = document.createElement('div');
// // console.log("policy details ", policyDetailsData);
newRow.className = 'form-row dynamic-form-row mb-3';
newRow2 = document.createElement("div");
// newRow2.className = 'form-row btn mb-3';
newRow.innerHTML = `
<div class="row">
<div id="sameAsCommunicationAddress_div" class="form-group col-md-12">
<input type="checkbox" id="sameAsCommunicationAddress" onchange="addOrRemoveAdd()">
<label for="sameAsCommunicationAddress">Same as Communication Address</label>
</div>
</div>
<div class="row">
<div class="form-group col-md-4">
<label for="pin_code_${increment}">Pin Code<span class="text-danger">*</span></label>
<input type="text" id="pin_code_${increment}" name="pin_code[]" class="form-control" required/>
</div>
<div class="form-group col-md-4">
<label for="address1_${increment}">Address 1<span class="text-danger">*</span></label>
<input type="text" id="address1_${increment}" name="address1[]" class="form-control" required />
</div>
<div class="form-group col-md-4">
<label for="address2_${increment}">Address 2</label>
<input type="text" id="address2_${increment}" name="address2[]" class="form-control" />
</div>
<div class="form-group col-md-4">
<label for="address3_${increment}">Address 3</label>
<input type="text" id="address3_${increment}" name="address3[]" class="form-control" />
</div>
<div class="form-group col-md-4" style = "width: 10px !important;">
<label for="occupancy_${increment}">Occupancy Risk<span class="text-danger">*</span></label>
<select id="occupancy_${increment}" name="occupancy[]" class="form-control" onchange="showRequiredFieldsBasedOnLocation(this)" required>
<option value="">Select</option>
${occupancyMaster.map(occupancy =>
`<option value="${occupancy.id}">${occupancy.description}</option>`
).join('')}
</select>
</div>
<div class="form-group col-md-4 common_location_occupancy">
<label for="iibCode_${increment}">IIB Code<span class="text-danger">*</span></label>
<input type="text" onchange = "updateOccupancyRisk(this)" id="iibCode_${increment}" name="iib_code[]" class="form-control common_location_occupancy" required>
</div>
<div class="form-group col-md-4">
<label for="constructionType_${increment}">Construction Type<span class="text-danger">*</span></label>
<select id="constructionType_${increment}" name="construction_type[]" class="form-control">
<option value="kutcha" selected>Kutcha</option>
<option value="pucca">Pucca</option>
</select>
</div>
<div class="dt-switch-wrapper col-md-4 common_location_occupancy d-flex align-items-center">
<div class="custom-control custom-switch d-flex justify-content-center">
<input type="checkbox" class="custom-control-input" id="isBasement_${increment}" onchange="hideShowBasement(this)">
<label class="custom-control-label" for="isBasement_${increment}">Basement</label>
</div>
</div>
<div class="form-group col-md-4" style="display:none" >
<label for="basementSI_${increment}">Basement Utilisation</label>
<input type="text" id="basementSI_${increment}" name="basement_si[]" class="form-control"/>
</div>
<div class="form-group col-md-4 multiLocationOccupancy">
<label for="select_location_${increment}">Location <span class="text-danger">*</span></label>
<select required id="select_location_${increment}" name="select_location[]" class="form-control multiLocationOccupancy">
<option value = "1" selected>Location 1</option>
</select>
</div>
<div class="form-group col-md-12 multiLocationOccupancy">
<label for="buisness_desc_${increment}">Business Description <span class="text-danger">*</span></label>
<textarea required id="buisness_desc_${increment}" name="buisness_desc[]" class="form-control multiLocationOccupancy" rows="3"></textarea>
</div>
<div class="form-group col-md-4 multiLocationOccupancyWithoutFloater">
<label for="age_of_building_${increment}">Age of Building <span class="text-danger">*</span></label>
<select required id="age_of_building_${increment}" name="age_of_building[]" class="form-control multiLocationOccupancyWithoutFloater">
<option value="upto20" selected>Upto 20</option>
<option value="20to30">20 to 30</option>
<option value="above30">Above 30</option>
</select>
</div>
<div class="form-group col-md-5 multiLocationOccupancyWithoutFloater">
<label for="isHigherGrouds_${increment}">Is Risk Located on Higher Grounds <span class="text-danger">*</span></label>
<select required id="isHigherGrouds_${increment}" name="is_higher_grounds[]" class="form-control multiLocationOccupancyWithoutFloater">
<option value="no" selected>No</option>
<option value="yes">Yes</option>
</select>
</div>
</div>
<div class="row">
<div class="form-group col-md-4">
<button type="button" class="btn btn-secondary duplicate-btn">Add/Duplicate Locations</button>
</div>
</div>
<hr>
`;
container.appendChild(newRow);
// container.appendChild(newRow2);
const selectElement = document.getElementById(`select_location_${increment}`);
selectElement.innerHTML = "";
for (let i = 1; i <= policyDetailsData.location_no; i++) {
console.log("location no : ", policyDetailsData.location_no);
const option = document.createElement('option');
option.value = `Location ${i}`;
option.textContent = `Location ${i}`;
selectElement.appendChild(option);
}
increment++;
}
$(document).on('change', '[id^="occupancy_"]', function() {
// var selectedProduct = productSelectionData;
// if (selectedProduct.singleProduct == 'on') {
// }
});
$(document).on('click', '.duplicate-btn', function () {
if (policyDetailsData.location_no >= increment) {
const $rowToClone = $(this).closest('.form-row');
// Destroy Select2 for the current and previous occupancy fields
$(`#occupancy_${increment}`).select2('destroy');
$(`#occupancy_${increment - 1}`).select2('destroy');
// Clone the row
const $clone = $rowToClone.clone();
// Clean up select2 artifacts from the clone
$clone.find('.select2-hidden-accessible').each(function () {
$(this).select2('destroy');
});
$clone.find('.select2-container').remove();
// Update all IDs in the clone
$clone.find('[id]').each(function () {
const oldId = $(this).attr('id');
const newId = oldId.replace(/_(\d+)$/, `_${increment}`);
$(this).attr('id', newId);
});
// Update all labels
$clone.find('label').each(function () {
const oldFor = $(this).attr('for');
if (oldFor) {
const newFor = oldFor.replace(/_(\d+)$/, `_${increment}`);
$(this).attr('for', newFor);
}
});
// Insert the cloned row after the original
$clone.insertAfter($rowToClone);
// Refill and update the select_location dropdown
const selectElement = document.getElementById(`select_location_${increment}`);
selectElement.innerHTML = "";
for (let i = 1; i <= policyDetailsData.location_no; i++) {
const option = document.createElement('option');
option.value = `Location ${i}`;
option.textContent = `Location ${i}`;
selectElement.appendChild(option);
}
for (let i = 1;i<increment;i++){
let selectedLocation = $(`#select_location_${i}`).val();
$(`#select_location_${increment} option[value="${selectedLocation}"]`).remove();
}
// Re-initialize Select2 for both fields
$(`#occupancy_${increment - 1}`).select2(); // previous
$(`#occupancy_${increment}`).select2(); // current
$(`#iibCode_${increment}`).val(""); // current
increment++;
} else {
toastr.error("Maximum number of allowed locations reached", "Error");
}
});
function addOrRemoveAdd() {
// console.log("chceck box clicked");
if ($("#sameAsCommunicationAddress").is(":checked")) {
$("#pin_code_1").val(policyDetailsData.pin_code);
$("#address1_1").val(policyDetailsData.address1);
$("#address2_1").val(policyDetailsData.address2);
$("#address3_1").val(policyDetailsData.address3);
} else {
$("#pin_code_1").val("");
$("#address1_1").val("");
$("#address2_1").val("");
$("#address3_1").val("");
}
}
function validatePolicyBasedOnProductSelection() {
var selectedProduct = productSelectionData;
if (selectedProduct.singleProduct == 'on') {
// console.log("inside if ");
$('[class*="single_location"]').show();
$("#locationNoDIV").hide();
$("#location_no").removeAttr("required", false);
// $('[class*="duplicate-btn"]').hide();
$("[id^='select_location']").hide();
$('[id^="select_location"]').hide().prev('label').hide();
$("[id^='select_location']").removeAttr('required', false);
// $('[class*="single_location_occupancy"]').hide().removeAttr("required", false);
// $('[class*="multi_location_company"]').hide().removeAttr('required');
// $("#riskSplitup").hide();
$("#submitPolicyRisk").show();
// $("#risksplitupTab").hide();
// $('[class*="multiLocationOccupancy"]').hide().removeAttr('required', false);
// $('[class*="multiLocationOccupancyWithoutFloater"]').hide().removeAttr('required', false);
} else if (selectedProduct.multipleProduct == 'on') {
// console.log("inside elseif");
$('[class*="single_location"]').hide().removeAttr('required');
// $('[class*="single_location_occupancy"]').hide().removeAttr('required');
$('[class*="multi_location_company"]').show();
$("#sameAsCommunicationAddress_div").hide();
$("#locationNoDIV").show();
$("#location_no").prop("required", "required");
$("#riskSplitup").show();
$("#submitPolicyRisk").hide();
$("[id^='select_location']").show();
$('[id^="select_location"]').show().prev('label').hide();
$("[id^='select_location']").prop('required', 'required');
// $('[class*="multiLocationOccupancyWithoutFloater"]').hide().removeAttr('required', false);
$("#risksplitupTab").show();
if (selectedProduct.multilocation_type == "stockFloater") {
$('[class*="stockSI"]').hide().removeAttr('required', false);
}
}
// $('[class*="common_location_occupancy"]').hide().removeAttr('required');
// $('[class*="multiLocationOccupancyWithoutFloater"]').hide().removeAttr('required', false);
// $('[class*="multiLocationOccupancy"]').hide().removeAttr('required', false);
}
function showRequiredFieldsBasedOnLocation(element) {
if (element) {
var selectedOccupancy = $(element).val(); // FIXED
var selectedOccupancyMasterRow = occupancyMaster.find(iib => iib.id == selectedOccupancy);
if (!selectedOccupancyMasterRow) return;
var iibCODE = selectedOccupancyMasterRow.iib_code;
var elementID = element.id; // FIXED
let increment = elementID.split("_").pop();
setTimeout(function() {
$(`#iibCode_${increment}`).val(iibCODE);
}, 500);
}
$('[class*="common_location_occupancy"]').show().prop("required", true);
var selectedProduct = productSelectionData;
if (selectedProduct.singleProduct === 'on') {
$('[class*="single_location_occupancy"]').show().prop("required", true);
} else if (selectedProduct.multipleProduct === 'on') {
$('[class*="multiLocationOccupancy"]').show().prop('required', true);
if (selectedProduct.multilocation_type === "multiLocation") {
$('[class*="multiLocationOccupancyWithoutFloater"]').show().prop('required', true);
} else if (selectedProduct.multilocation_type === "multiFloater") {
$('[class*="multiLocationOccupancyWithoutFloater"]').hide().removeAttr('required');
} else if (selectedProduct.multilocation_type === "stockFloater") {
$('[class*="multiLocationOccupancyWithoutFloater"]').show().prop('required', true);
$('[class*="stockSI"]').hide().removeAttr('required');
}
}
}
function registerPolicyData() {
var policyType;
var policyAcronym;
if (totalSI <= 50000000) {
policyType = "Bharat Sookshma Udyam Suraksha (BSUS)"
policyAcronym = "bsu"
} else if (totalSI > 50000000 && totalSI <= 500000000) {
policyType = "Bharat Laghu Udyam Suraksha (BLUS)"
policyAcronym = "blu"
} else if (totalSI > 500000000) {
policyType = "Standard Fire and Special Perils (SFSP)";
policyAcronym = "sfsp"
}
modifyExcessTable(policyAcronym);
// Build the initial JSON object with productSelection and policyDetails
var outputData = {
policyType: policyType,
productSelection: productSelectionData,
policyDetails: policyDetailsData,
locations: []
};
// Loop over each policy risk address
$.each(policyRiskAddress, function(index, riskAddress) {
// Find the corresponding policyRiskSplitUp entry by matching the location identifier
var matchingRiskSplitUp = $.grep(policyRiskSplitUpData, function(item) {
return item.location_selected === riskAddress.select_location;
});
// If a match is found, use the first match; otherwise, use an empty object.
var riskSplitUpData = matchingRiskSplitUp.length > 0 ? matchingRiskSplitUp[0] : {};
// Create a location object that groups the risk and split-up data together
var locationObj = {
select_location: riskAddress.select_location,
policyRisk: riskAddress,
policyRiskSplitUp: riskSplitUpData
};
// Add this location to the locations array
outputData.locations.push(locationObj);
});
return outputData;
}
function savePolicyDataLocal() {
isSaved = false;
// Generate the JSON structure using the registerPolicyData function
var policyData = registerPolicyData();
// Retrieve existing data from localStorage
var existingData = JSON.parse(localStorage.getItem('policyData')) || {};
// Ensure policyName is correctly retrieved
var policyName = $('#policyName').val();
if (!policyName) {
// console.error("Policy name is undefined. Cannot save data.");
return;
}
policyName = policyName.toLowerCase();
// Merge the new policy data into existing data
existingData[policyName] = policyData;
// Save the updated data back to localStorage
localStorage.setItem('policyData', JSON.stringify(existingData));
if (!$.isEmptyObject(existingData)) {
// console.log("DATA FROM DB : ", (existingData));
let data = (existingData);
Object.keys(data).forEach(key => {
policySummary[key] = addPolicySummaryTable(data[key], key);
prependTable(policySummary[key], key);
});
}
$('.loader').fadeIn();
$('.loader-mask').fadeIn();
toastr.success("Policy Information Collected ", "SUCCESS");
closeModal();
changeTerrorism(Number($("#policySI").val()));
$('.loader').fadeOut();
$('.loader-mask').delay(350).fadeOut('slow');
// console.log("Updated policy data in localStorage:", existingData);
}
function saveTODB(data, leadID) {
var url = '<?= base_url('rfq/savePolicyInfo') ?>';
$('.loader').fadeIn();
$('.loader-mask').fadeIn();
// console.log("trying to submit data : ", data, " with this lead id : ", leadID);
$.ajax({
url: url,
data: {
registration_json: data,
lead_id: leadID
},
method: "POST",
success: function(response) {
if (response.status == true) {
toastr.success(response.message, "Success");
// window.location.reload();
} else {
toastr.error(response.message, "Error");
}
$('.loader').fadeOut();
$('.loader-mask').delay(350).fadeOut('slow');
// window.location.reload();
},
error: function(xhr, status, error) {
$('.loader').fadeOut();
$('.loader-mask').delay(350).fadeOut('slow');
// console.error(xhr.responseText);
// console.error(status, error);
}
})
}
function loadPolicyDataBack(storedPolicyData) {
if (storedPolicyData) {
var parsedData = storedPolicyData;
// Assign back to original variables
productSelectionData = parsedData.productSelection;
policyDetailsData = parsedData.policyDetails;
// Since your JSON groups locations together,
// extract policyRiskAddress and policyRiskSplitUpData from each location
policyRiskAddress = [];
policyRiskSplitUpData = [];
$.each(parsedData.locations, function(index, loc) {
policyRiskAddress.push(loc.policyRisk);
policyRiskSplitUpData.push(loc.policyRiskSplitUp);
});
// alert("Data restored to original variables.");
} else {
// console.log("No policy data found in local storage.");
}
}
function prepareDataForEdit(data) {
// alert(policyName);
// console.log("Prepare data : ",data);
if (policyName == "Fire") {
data = data.fire;
if (!data) {
return
};
loadPolicyDataBack(data);
assignDataToFields(data);
// alert("something wrong");
} else if (policyName == "Burglary") {
data = data.burglary;
if (!data) {
return
};
loadPolicyDataBack(data);
assignDataToFields(data);
// alert("inside else");
} else {
// alert("nothing");
}
// console.log("policy data : ", data);
// Populate Product Selection
// Show first tab
$('#product-selection-tab a').tab('show');
// Update all increment counters
increment = data.locations.length + 1;
increment2 = data.locations.length + 1;
showRequiredFieldsBasedOnLocation();
hideAndShowBurglary();
}
function assignDataToFields(data) {
$('#singleProduct').prop('checked', data.productSelection.singleProduct === 'on');
$('#multipleProduct').prop('checked', data.productSelection.multipleProduct === 'on');
// console.log($('#multipleProduct').is(":checked") ? "yes" : "no");
$('#multipleProduct').is(":checked") ? $('#multilocation_type').show() : $('#multilocation_type').hide();
$('#multilocation_type').val(data.productSelection.multilocation_type);
$("#client_type").val(data.productSelection.client_type);
$("#type_of_buisness").val(data.productSelection.type_of_buisness);
$("#buisnessNature").val(data.productSelection.buisness_nature);
$("#valueOfRisk").val(data.policyDetails.value_of_risk);
// Trigger product selection change
$('.business-type-checkbox').trigger('change');
// Populate Policy Details
const policyDetails = data.policyDetails;
Object.keys(policyDetails).forEach(key => {
$(`#${key}`).val(policyDetails[key]);
// console.log("Key ", key, " set value : ", policyDetails[key]);
});
$('#terrorismSwitch').prop('checked', policyDetails.terrorism === "yes")
// Populate Risk Addresses
data.locations.forEach((location, index) => {
addHTMLInputForRiskAddress();
showRequiredFieldsBasedOnLocation();
// if (index > 0) $('.duplicate-btn').first().trigger('click');
const prefix = `_${index + 1}`;
const risk = location.policyRisk;
// Populate address fields
$(`#pin_code${prefix}`).val(risk.pin_code);
$(`#address1${prefix}`).val(risk.address1);
$(`#address2${prefix}`).val(risk.address2);
$(`#address3${prefix}`).val(risk.address3);
// Populate risk details
$(`#constructionType${prefix}`).val(risk.construction_type);
$(`#occupancy${prefix}`).select2();
$(`#occupancy${prefix}`).val(risk.occupancy).trigger("change");
// $(`#isBasement${prefix}`).val(risk.is_basement);
$(`#iibCode${prefix}`).val(risk.iib_code);
$(`#buisness_desc${prefix}`).val(risk.buisness_desc);
$(`#select_location${prefix}`).val(risk.select_location);
$(`#basementSI${prefix}`).val(risk.basement_si);
$(`#isBasement${prefix}`).prop('checked', risk.is_basement === "yes").trigger("change");
});
// Populate Risk Split-Up Data
data.locations.forEach((location, index) => {
addHTMLInputForRiskSplitUP();
showRequiredFieldsBasedOnLocation();
const prefix = `_${index + 1}`;
const splitUp = location.policyRiskSplitUp;
$(`#building${prefix}`).val(splitUp.building);
$(`#content${prefix}`).val(splitUp.content);
$(`#furniture${prefix}`).val(splitUp.furniture);
$(`#plantAndMachinery${prefix}`).val(splitUp.plant_and_machinery);
$(`#electricalFittings${prefix}`).val(splitUp.electrical_fittings);
$(`#stockInProcess${prefix}`).val(splitUp.stock_in_process);
$(`#rawMaterial${prefix}`).val(splitUp.raw_material);
$(`#finishedStock${prefix}`).val(splitUp.finished_stock);
if (policyName == "Burglary") {
$(`#annualGrossProfit${prefix}`).val(splitUp.annual_gross_profit);
$(`#indemnityPeriod${prefix}`).val(splitUp.indemnity_period);
$(`#firstLossPercent${prefix}`).val(splitUp.first_loss_percent);
$(`#burglaryTheftSwitch${prefix}`).prop('checked', splitUp.burglary_theft_switch === 'on');
$(`#firstLoss${prefix}`).prop('checked', splitUp.first_loss === 'on');
$(`#lossIN3Years${prefix}`).prop('checked', splitUp.loss_in_3_years === 'on');
$(`#buisnnessInteruption${prefix}`).prop('checked', splitUp.loss_in_3_years === 'on');
}
});
isFormDirty = false; // Reset the form dirty flag
}
function checkandassignLeadData() {
var checkedStatus = $("#dataFromLead").is(":checked") ? true : false;
if (checkedStatus) {
assignLeadData();
}
}
function assignLeadData() {
const lead_data = <?= json_encode(json_decode($lead_data['custom_fields'])) ?>;
var clientName = <?= isset($lead_data['client_name']) ? json_encode($lead_data['client_name']) : "" ?>;
var client_type = <?= isset($lead_data['client_type']) ? $lead_data['client_type'] : "" ?>;
var mobile = <?= isset($lead_data['contact_person_mobile']) ? $lead_data['contact_person_mobile'] : "" ?>;
var contact_email = "<?= isset($lead_data['contact_person_email']) ? $lead_data['contact_person_email'] : "" ?>";
var panNo = <?= isset($lead_data['client_type']) ? $lead_data['client_type'] : "" ?>;
var buisnessType = <?= isset($lead_data['entity_type_id']) ? $lead_data['entity_type_id'] : "" ?>;
// console.log("client_type : ".client_type);
if (lead_data) {
// lead_data = JSON.parse(lead_data);
// console.log("Lead Data : ", typeof(lead_data));
if (lead_data.risk_location == "Single") {
// console.log("single ");
$("#singleProduct").prop("checked", true).trigger("change");
} else if (lead_data.risk_location.startsWith("multi")) {
$("#multipleProduct").prop("checked", true).trigger("change");
if (lead_data.risk_location == "multi_with_floter") {
$("#multilocation_type").val("multiFloater").trigger("change");
} else {
$("#multilocation_type").val("multiLocation").trigger("change");
}
}
$("#client_type").val(client_type).trigger("change");
$("#insured_name").val(clientName);
$("#address1").val(lead_data.address);
$("#pin_code").val(lead_data.pincode);
$("#mobile").val(mobile);
$("#email").val(contact_email);
console.log("buisness type : ", buisnessType);
$("#type_of_buisness").val(buisnessType);
// var policy_type = lead_data.policy_type_id;
}
}
function hideAndShowBurglary() {
// console.log("hide and show function called ");
policyName = $("#policyName").val();
// console.log("hiding the other policy not ths : ", policyName);
if (policyName == "Burglary") {
$('[class*="burglary"]').show();
$('[class*="fire"]').hide().removeAttr('required', false);
} else {
$('[class*="fire"]').show().prop("required", "required");
$('[class*="burglary"]').hide().removeAttr('required', false);
}
}
function resetAllform() {
// isFormDirty = false;
// console.log("FORM RESETED SUCCESSFULLY");
$("#productSelectionForm")[0].reset();
$("#policyDetailsForm")[0].reset();
$("#policyRiskAddressForm")[0].reset();
$("#policyRiskSplitUpForm")[0].reset();
$('#policyTabs .nav-link').removeClass('active show');
$('#product-selection-tab').addClass('active');
// $("#addRiskInfo, #addRiskSplitUp").empty();
increment = 1
increment2 = 1
// Reset tab content
$('.tab-pane').removeClass('active show');
// $('#product-selection').addClass('active show');
// $("#policy_register_forms .tab-pane.show.active").removeClass("active show");
// Reset form fields
$('form').trigger('reset');
hideAndShowBurglary()
}
$('.close').on('click', function(e) {
console.log("is form dirty : ", isFormDirty);
if (isFormDirty) {
e.preventDefault();
e.stopPropagation();
Swal.fire({
title: 'You have unsaved changes!',
text: 'Do you want to close without saving your data?',
icon: 'warning',
showCancelButton: true,
confirmButtonText: 'Yes, close it',
cancelButtonText: 'No, stay here',
}).then((result) => {
if (result.isConfirmed) {
isFormDirty = false; // Reset flag
closeModal();
resetAllform();
// $('#policyRegisterModel').modal('hide');
$('.tab-pane').removeClass('active show');
$("#addRiskInfo, #addRiskSplitUp").empty();
}
});
return false;
} else {
resetAllform();
$('.tab-pane').removeClass('active show');
$("#addRiskInfo, #addRiskSplitUp").empty();
}
});
function copyFirePolicy() {
// console.log("Copying Fire Policy Data...");
storedPolicyData = JSON.parse(localStorage.getItem('policyData'));
if (storedPolicyData.fire) {
var data = storedPolicyData.fire;
if (!data) {
return
};
loadPolicyDataBack(data);
assignDataToFields(data);
}
increment = data.locations.length + 1;
increment2 = data.locations.length + 1;
showRequiredFieldsBasedOnLocation();
hideAndShowBurglary();
}
$(document).on('input', 'input[id^="pin_code"]', function() {
// alert("inside");
let value = $(this).val().replace(/\D/g, '').slice(0, 6);
$(this).val(value);
});
function closeModal() {
document.querySelector('#policyRegisterModel [data-dismiss="modal"]').click();
}
function updateOccupancyRisk(element) {
let iibCode = $(element).val();
// Find matching occupancy row
let matchedOccupancy = occupancyMaster.find(iib => iib.iib_code == iibCode);
let matchedId = matchedOccupancy ? matchedOccupancy.id : null;
// Get increment from the element ID, like "iibCode_3"
let elementID = element.id;
let increment = elementID.split("_").pop(); // Extract "3" from "iibCode_3"
if (matchedId) {
$(`#occupancy_${increment}`).val(matchedId).trigger("change");
$(`#occupancy_${increment}`).select2();
} else {
toastr.error("Invalid IIB Code", "Error");
}
}
function hideShowBasement(element) {
let elementID = element.id;
let increment = elementID.split("_").pop();
let isBasement = $(`#isBasement_${increment}`).is(":checked");
// Get the label associated with the input
let label = $(`label[for='basementSI_${increment}']`);
if (isBasement) {
$(`#basementSI_${increment}`).parent().show();
$(`#basementSI_${increment}`).prop("required", "required");
// Add * if not already there
if (label.find(".text-danger").length === 0) {
label.append('<span class="text-danger">*</span>');
}
} else {
$(`#basementSI_${increment}`).parent().hide();
$(`#basementSI_${increment}`).removeAttr("required");
// Remove * if exists
label.find(".text-danger").remove();
}
}
// function saveDataAsDraft() {
// return new Promise((resolve) => {
// const forms = [
// document.getElementById('productSelectionForm'),
// document.getElementById('policyDetailsForm'),
// document.getElementById('policyRiskAddressForm'),
// document.getElementById('policyRiskSplitUpForm')
// ];
// let isDirty = false;
// forms.forEach(form => {
// if (form) {
// const formInputs = form.querySelectorAll('input, select, textarea');
// formInputs.forEach(input => {
// if (input.defaultValue !== input.value && input.value !== '') {
// isDirty = true;
// }
// if (input.type === 'checkbox' || input.type === 'radio') {
// if (input.checked !== input.defaultChecked) {
// isDirty = true;
// }
// }
// });
// }
// });
// if (isDirty) {
// Swal.fire({
// title: 'You have unsaved changes!',
// text: 'Do you want to close without saving your data?',
// icon: 'warning',
// showCancelButton: true,
// confirmButtonText: 'Yes, close it',
// cancelButtonText: 'No, stay here',
// }).then((result) => {
// resolve(result.isConfirmed);
// });
// } else {
// resolve(true); // No unsaved changes, allow closing
// }
// });
// }
</script>