nhance/app/Views/leads_form.php

2661 lines
119 KiB
PHP

<style>
.readonly-color {
background-color: #e0e0e0;
/* Darker background */
color: #666;
/* Darker text color */
}
.readonly-select {
pointer-events: none;
background-color: #f0f0f0;
color: #666;
}
.input-icon {
position: relative;
}
.input-icon .additional-icon {
position: absolute;
top: 50%;
right: 12px;
transform: translateY(-50%);
pointer-events: none;
color: #495057;
}
hr.solid {
border-top: 3px solid #bbb;
}
.select2-hidden-accessible+.select2-container .select2-dropdown {
display: none !important;
}
.select2-container .select2-selection--multiple .select2-selection__choice {
color: #000000;
}
.select2-selection__choice {
background-color: #0a8794 !important;
color: white !important;
font-weight: bold;
}
.select2-selection__choice__remove {
color: white !important;
margin-right: 5px;
}
</style>
<style>
.info-icon-wrapper {
position: relative;
display: inline-block;
cursor: pointer;
top: 30px;
left: 35px;
font-size: 22px;
}
.info-tooltip {
visibility: hidden;
opacity: 0;
width: max-content;
max-width: 300px;
background-color: #333;
color: #fff;
text-align: left;
padding: 10px;
border-radius: 6px;
position: absolute;
z-index: 999;
bottom: 125%;
/* Show above icon */
left: 50%;
transform: translateX(-50%);
font-size: 12px;
white-space: normal;
transition: opacity 0.3s;
}
.info-tooltip::after {
content: "";
position: absolute;
top: 100%;
/* Arrow below tooltip */
left: 50%;
margin-left: -5px;
border-width: 5px;
border-style: solid;
border-color: #333 transparent transparent transparent;
}
.info-icon-wrapper:hover .info-tooltip {
visibility: visible;
opacity: 1;
}
/* dont forgot it keep it safe card and card body space remover */
/* bcoz in design */
.card-body {
margin-top: 0px !important;
}
/* this css as per design so not declare in golbal */
/* bcoz in design */
#collapseOne {
border: 1px solid #BFF3F5 !important;
border-radius: 10px !important;
border-width: 1px !important;
}
/* Live field highlight driven by Parsley state */
input.parsley-error,
textarea.parsley-error,
select.parsley-error {
border-color: #dc3545 !important;
box-shadow: 0 0 0 0.2rem rgba(220, 53, 69, 0.12) !important;
}
input.parsley-success,
textarea.parsley-success,
select.parsley-success {
border-color: #28a745 !important;
box-shadow: 0 0 0 0.2rem rgba(40, 167, 69, 0.08) !important;
}
</style>
<?php
$isLeadEditEb = isset($lead_edit_data) && ! empty($lead_edit_data);
$ebPageTitle = $isLeadEditEb ? 'Edit Opportunities - (EB)' : 'Add Opportunities - (EB)';
?>
<script>
var pageHideMainNavTitle = true;
var pageTitle = '<?= $ebPageTitle ?>';
var pageBackButton = '<a href="<?= base_url('leads/list') ?>" class="topbar-icon-btn" data-toggle="tooltip" data-placement="top" title="Back" aria-label="Back"><i class="ri-arrow-left-s-line"></i></a>';
</script>
<script src="<?= base_url('public/assets/js/pages/leads_form_validation.js') ?>"></script>
<div class="container-fluid-min">
<div class="row" id="leads_form">
<div class="col-12">
<div class="card">
<div class="card-body">
<div class="row" style="margin-bottom:1rem;">
<!-- <div class="col-6" style="align-self: center;">
<h4 id="page_title" style="position: relative;">Add Lead</h4>
</div>
<div class="col-3" style="text-align: right; position: relative; left: 211px;">
<!-- <button class="btn btn-primary waves-effect waves-light" onclick="fileupload(this)">file upload</button> ->
</div>
<div class="col-1" style="text-align: right; position: relative; left: 193px;">
<a href="<?= base_url('leads/list') ?>" type="button" id="btnAdd"
class="btn btn-primary waves-effect waves-light">Back</a>
</div> -->
<!-- <h4 class="d-flex align-items-center" style="gap: 8px;">
<a href="<?= base_url('leads/list') ?>" style="cursor: pointer;">
<i class="mdi mdi-chevron-left" style="font-size: 43px;"></i>
</a>
<span class="title-text" id="page_title" style="position: relative;">Add Opportunity</span>
</h4> -->
</div>
<form role="form" class="parsley-examples" method="post" id="leads_form_id"
enctype="multipart/form-data">
<input type="hidden" name="id" id="leads_primarykey">
<input type="hidden" name="actual_lead_id" id="actual_lead_id" value="<?= isset($actual_lead_id) ? $actual_lead_id : 0 ?>">
<div class="card" id="collapseOne">
<div class="card-body">
<h4 class="card-title mb-3">Opportunity Details</h4>
<hr>
<div class="form-row">
<div class="form-group col-md-4">
<label for="lead_type">Opportunity Type<span class="text-danger">*</span></label>
<select class="form-control" id="lead_type" name="lead_type" required>
<option value="">Select Opportunity Type</option>
<?php
if (isset($lead_type) && count($lead_type)) {
foreach ($lead_type as $key => $value) {
if ($key == 1) {
echo "<option value=" . $key . " selected>" . $value . "</option>";
} else {
echo "<option value=" . $key . ">" . $value . "</option>";
}
}
}
?>
</select>
</div>
<div class="form-group col-md-4">
<label for="issuer">Issuer<span class="text-danger">*</span></label>
<select class="form-control" id="issuer" name="issuer" required>
<option value='2' selected>Nhance</option>;
<!-- <?php
if (isset($issuer) && count($issuer)) {
foreach ($issuer as $key => $value) {
echo "<option value=" . $key . ">" . $value . "</option>";
}
}
?> -->
</select>
</div>
</div>
</div>
</div>
<!-- <hr> --> <!-- bcoz removed in design -->
<!-- client row -->
<div class="card" id="collapseOne">
<div class="card-body">
<div class="d-flex justify-content-between align-items-center mb-3">
<h4 class="card-title mb-0">Client Information</h4>
<div class="form-group freshFields mb-0 d-flex align-items-center">
<label for="exixting_client" class="mb-0 mr-2">Existing Client</label>
<label class="switch mb-0">
<input id="exixting_client" type="checkbox" name="exixting_client">
<span class="slider round" style="height: 27px;"></span>
</label>
</div>
</div>
<hr>
<div class="form-row">
<div class="form-group col-md-4 renewalFields rolloverhide" style="display: none;">
<label for="client_id">Client<span class="text-danger">*</span></label>
<select class="form-control" id="client_id" name="client_id">
<option value="">Select Client</option>
</select>
</div>
<div class="form-group col-md-4 renewalFields rolloverhide" style="display: none;">
<label for="client_branch_id">Branch<span class="text-danger">*</span></label>
<select class="form-control" id="client_branch_id" name="client_branch_id"
onchange="getBranchData(this,1)">
<option value="">Select Branch</option>
</select>
</div>
<!-- <div class="form-group col-md-3 freshFields">
<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 freshFields">
<label for="entity_type_id">Entity Type<span class="text-danger">*</span></label>
<select class="form-control" id="entity_type_id" name="entity_type_id" required>
<option value="" selected>Select Entity</option>
<?php
if (isset($entity) && count($entity)) {
foreach ($entity as $key => $value) {
echo "<option value=" . $value['id'] . ">" . $value['name'] . "</option>";
}
}
?>
</select>
</div>
<div class="form-group col-md-4 freshFields">
<label for="client_name">Client Name<span class="text-danger">*</span></label>
<input type="text" class="form-control" id="client_name" name="client_name"
placeholder="Enter Client Name" required>
</div>
<div class="form-group col-md-4 freshFields">
<label for="client_short_name">Client Short Name<span class="text-danger">*</span></label>
<input type="text" class="form-control" id="client_short_name" name="client_short_name"
placeholder="Enter Client Short Name" onkeyup="validateInput(this, 'clients', 'short_name')" required>
</div>
<!-- <div class="form-group col-md-3 renewalFields" style="display: none;">
<label for="source_policy_id"> Source Policy <span id="base_danger"
class="text-danger">*</span></label>
<select class="form-control" id="source_policy_id" name="source_policy_id">
<option value="" selected>Select Source Policy</option>
</select>
</div>
<div class="form-group col-md-3 renewalFields" style="display: none;">
<label for="source_policy_start_date">Source Policy Start Date<span class="text-danger"></span></label>
<input type="text" class="form-control readonly-select" id="source_policy_start_date" name="source_policy_start_date" readonly>
</div>
<div class="form-group col-md-3 renewalFields" style="display: none;">
<label for="source_policy_end_date">Source Policy End Date<span class="text-danger"></span></label>
<input type="text" class="form-control" id="source_policy_end_date" name="source_policy_end_date" readonly>
</div> -->
<!-- <div class="form-group col-md-3">
<label for="pan">PAN<span class="text-danger"></span></label>
<input type="text" class="form-control" id="pan" placeholder="Enter PAN Number"
data-parsley-error-message="Invalid PAN Number. Example: ABCDE1234F" name="pan"
data-parsley-trigger="change" data-parsley-pattern="^[A-Z]{5}[0-9]{4}[A-Z]$">
</div> -->
</div>
</div>
</div>
<!-- end client row -->
<!-- <hr> --> <!-- bcoz removed in design -->
<!-- branch row-->
<div class="card" id="collapseOne">
<div class="card-body">
<h4 class="card-title mb-3">Branch Information</h4>
<hr>
<div class="form-row">
<div class="form-group col-md-4">
<label for="gst">GST<span class="text-danger">*</span></label>
<input type="text" class="form-control" id="gst" placeholder="Enter GST Number"
data-parsley-error-message="Invalid GST Number. Example: 12ABCDE1234F5Z6" name="gst"
data-parsley-trigger="change"
data-parsley-pattern="^\d{2}[A-Z]{5}\d{4}[A-Z]{1}[A-Z\d]{1}[Z]{1}[A-Z\d]{1}$" required>
</div>
<div class="form-group col-md-4">
<label for="branch_name">Branch Name<span class="text-danger">*</span></label>
<input type="text" class="form-control" id="branch_name" name="branch_name"
placeholder="Enter Branch Name" required>
</div>
<div class="form-group col-md-4">
<label for="branch_code">Branch Code<span class="text-danger">*</span></label>
<input type="text" class="form-control" id="branch_code" name="branch_code"
placeholder="Enter Branch Code" required>
</div>
<div class="form-group col-md-4 renewalFields rolloverhide">
<label for="contact_person_summary">Contact Person<span class="text-danger">*</span></label>
<select class="form-control" name="contact_person_summary" id="contact_person_summary">
<option value="">Select a Contact</option>
</select>
</div>
<div class="form-group col-md-4 freshFields">
<label for="contact_person_name">Contact Person Name<span class="text-danger">*</span></label>
<input type="text" class="form-control" id="contact_person_name" name="contact_person_name"
placeholder="Enter Contact Name" required>
</div>
<div class="form-group col-md-4">
<label for="contact_person_mobile">Contact Person Mobile<span
class="text-danger">*</span></label>
<input type="text" class="form-control" id="contact_person_mobile"
name="contact_person_mobile" placeholder="Enter Contact Mobile" required>
</div>
<div class="form-group col-md-4">
<label for="contact_person_email">Contact Person Email<span
class="text-danger">*</span></label>
<input type="text" class="form-control" id="contact_person_email"
name="contact_person_email" placeholder="Enter Contact Email" required>
</div>
</div>
</div>
</div>
<!-- policy row -->
<div class="card" id="collapseOne">
<div class="card-body">
<h4 class="card-title mb-3">Policy Details</h4>
<hr>
<div id="dynamic-form-container"></div>
</div>
</div>
<!-- <hr> --> <!-- bcoz removed in design -->
<!-- other row -->
<div class="card" id="collapseOne">
<div class="card-body">
<div class="d-flex justify-content-between align-items-center mb-3">
<h4 class="card-title mb-0">Sales & Assignment</h4>
<div class="form-group mb-0 d-flex align-items-center">
<label for="is_insurer_auto_mail" class="mb-0 mr-2">Insurer Auto Mail</label>
<label class="switch mb-0">
<input id="is_insurer_auto_mail" type="checkbox" name="is_insurer_auto_mail">
<span class="slider round" style="height: 27px;"></span>
</label>
</div>
</div>
<hr>
<div class="form-row">
<div class="form-group col-md-4">
<label for="salse_person_id">Sales Person<span class="text-danger">*</span></label>
<select class="form-control" id="salse_person_id" name="salse_person_id" multiple required>
<option value="">Select Sales Person</option>
<?php if (isset($salse_team)) { ?>
<?php foreach ($salse_team as $value) { ?>
<option value="<?= $value['id']; ?>">
<?= $value['first_name']; ?>
</option>
<?php } ?>
<?php } ?>
</select>
</div>
<div class="form-group col-md-4">
<label for="status"> Status <span id="base_danger" class="text-danger">*</span></label>
<select class="form-control" id="lead_status" name="status" required>
<option value="" selected>Select Status</option>
<?php
if (isset($lead_status) && count($lead_status)) {
foreach ($lead_status as $key => $value) {
if ($key == 'queued') {
echo "<option value=" . $key . " selected>" . $value . "</option>";
} else {
echo "<option value=" . $key . ">" . $value . "</option>";
}
}
}
?>
</select>
</div>
<div class="form-group col-md-4">
<label for="next_reminder_date">Next Reminder Date<span class="text-danger"></span></label>
<div class="input-icon">
<input type="text" class="form-control" id="next_reminder_date" name="next_reminder_date" placeholder="DD/MM/YYYY">
<i class="mdi mdi-calendar-blank-outline additional-icon"></i>
</div>
</div>
</div>
<div class="form-row" id="lost_reason_div" style="display: none;">
<div class="form-group col-md-12">
<label for="lost_reason">Lost Reason <span class="text-danger">*</span></label>
<textarea class="form-control" id="lost_reason" name="lost_reason" rows="4" placeholder="Please specify why this opportunity was lost"></textarea>
</div>
</div>
<div class="form-row">
<div class="form-group col-md-12">
<label for="notes">Remarks</label>
<textarea class="form-control" id="notes" name="notes" rows="4"></textarea>
</div>
</div>
</div>
</div>
<div class="form-group text-right m-b-0" id="submitButton">
<button type="submit" class="btn btn-primary waves-effect waves-light mr-1"
id="lead_form_submit_btn">Submit</button>
</div>
</form>
</div>
</div>
</div>
</div><!-- end form row -->
<?php include("newClientModal.php") ?>
</div>
<script>
var actualLeadClientName = '';
var actualLeadShortName = '';
let claimIndex = 1;
setTimeout(() => {
var policyStart = $(".policy_start_date");
var policyEnd = $(".policy_end_date");
if (policyStart.length === 0 || policyEnd.length === 0) {
console.log("Elements still not found after delay.");
return;
}
console.log("Elements found, setting IDs...");
var lead_type = $('#lead_type').val();
var increment = 1;
var start_date_id = lead_type == "1" ? `policy_start_date_${increment}` : "policy_start_date";
var end_date_id = lead_type == "1" ? `policy_end_date_${increment}` : "policy_end_date";
policyStart.attr("id", start_date_id);
$("label[for='policy_start_date'], label[for^='policy_start_date_']").attr("for", start_date_id);
policyEnd.attr("id", end_date_id);
$("label[for='policy_end_date'], label[for^='policy_end_date_']").attr("for", end_date_id);
}, 3000);
$(document).ready(function() {
$('#salse_person_id').parsley({
errorsContainer: function(ParsleyField) {
if (ParsleyField.$element.hasClass('select2-hidden-accessible')) {
return ParsleyField.$element.siblings('.select2-container');
}
return ParsleyField.$element;
}
});
$('#client_id').parsley({
errorsContainer: function(ParsleyField) {
if (ParsleyField.$element.hasClass('select2-hidden-accessible')) {
return ParsleyField.$element.siblings('.select2-container');
}
return ParsleyField.$element;
}
});
$('#client_branch_id').parsley({
errorsContainer: function(ParsleyField) {
if (ParsleyField.$element.hasClass('select2-hidden-accessible')) {
return ParsleyField.$element.siblings('.select2-container');
}
return ParsleyField.$element;
}
});
});
</script>
<script>
//SELECT2 document ready function
$(document).ready(function() {
$("#lead_type").change(function() {
$("input, select").removeClass("readonly-select");
$("input, select").removeAttr("readonly");
// 5.3'+increment);
var lead_type = $(this).val();
var increment = 1; // Example increment value (modify as needed)
var start_date_id = (lead_type == "1") ? `policy_start_date_${increment}` : "policy_start_date";
var end_date_id = (lead_type == "1") ? `policy_end_date_${increment}` : "policy_end_date";
$(".policy_start_date").attr("id", start_date_id);
// $("label[for]").attr("for", start_date_id);
$(".policy_end_date").attr("id", end_date_id);
// $("label[for]").attr("for", end_date_id);
// $('#leads_form_id')[0].reset();
// console.log("Updated ID:", newId);
if (lead_type == 1) {
var policy_start_datePicker = flatpickr("#policy_start_date_" + increment, {
dateFormat: "d/m/Y",
allowInput: false,
onChange: function(selectedDates) {
var policy_end_date = new Date(selectedDates[0]);
policy_end_date.setFullYear(policy_end_date.getFullYear() + 1);
policy_end_date.setDate(policy_end_date.getDate() - 1); // Set end date to last day of selected year
policy_end_datePicker.setDate(policy_end_date);
// console.log('this object', this);
// console.log('id of this element:', this.element);
// console.log('id of this element:', this.element.id);
// let increment = this.element.id.split('_').pop();
// console.log(increment); // Outputs: 1
// console.log('increment', increment);
// console.log('policy_start_datePicker selectedDates', selectedDates);
// console.log('policy_start_datePicker incurred_claim_date_', $(
// "#incurred_claim_date_" + increment).val());
// Recalculate policy_run_days if incurred claim date is already selected
// if ($("#incurred_claim_date_" + increment).val()) {
// console.log('policy_start_datePicker selectedDates', selectedDates);
// calculatePolicyRunDays(increment);
// }
}
});
} else if (lead_type == 2) {
$("#source_policy_id").prop("required", true);
$("#source_policy_start_date").prop("required", true);
$("#source_policy_end_date").prop("required", true);
$("#source_policy_id").show();
$("#source_policy_start_date").show();
$("#source_policy_start_date").show();
$('#source_policy_id').closest('.form-group').find('label').show();
$('#source_policy_start_date').closest('.form-group').find('label').show();
$('#source_policy_end_date').closest('.form-group').find('label').show();
// Check if the asterisk doesn't already exist, then add it
let $label = $("#source_policy_id").closest("div").find("label");
if ($label.find(".text-danger").length === 0) {
$label.append(' <span class="text-danger">*</span>');
}
let $label2 = $("#source_policy_start_date").closest("div").find("label");
if ($label2.find(".text-danger").length === 0) {
$label2.append(' <span class="text-danger">*</span>');
}
let $label3 = $("#source_policy_end_date").closest("div").find("label");
if ($label3.find(".text-danger").length === 0) {
$label3.append(' <span class="text-danger">*</span>');
}
var addOption = $('#client_id option[value="add_client"]');
if (addOption.length > 0) {
addOption.remove();
}
}
if (lead_type != 1) {
dataIncrement = 1;
// updateRenewalFields(dataIncrement);
let incurred_claim_date_id = 'incurred_claim_date';
var incurred_claim_datepicker = flatpickr("#" + incurred_claim_date_id, {
dateFormat: "d/m/Y",
allowInput: false,
});
}
var policy_end_datePicker = flatpickr("#policy_end_date_" + increment, {
dateFormat: "d/m/Y",
allowInput: false
});
document.getElementById('source_policy_start_date').readOnly = true;
document.getElementById('source_policy_end_date').readOnly = true;
$('#source_policy_start_date, #source_policy_end_date').addClass('readonly-select');
$('#client_id').select2();
$('#client_branch_id').select2();
$('#source_policy_id').val("");
console.log('---- completed ----')
});
console.log('increment count for insurer and tpa ', increment);
$('#insurer_' + increment).select2();
$('#tpa_' + increment).select2();
addHTMLInput();
setTimeout(function() {
$("textarea.select2-search__field").attr('rows', '1');
$("textarea.select2-search__field").css('resize', 'none');
}, 1000)
$('.first_year_').select2();
$("[id*='first_year']").select2();
$("[id*='claim_type']").select2();
$("[id*='first_casue_of_death_']").select2();
$('#insurer_' + increment).select2();
$('#tpa_' + increment).select2();
$('#proposed_insurer').select2();
$('#proposed_tpa').select2();
$('#client_id').select2();
$('#client_branch_id').select2();
$('#source_policy_id').val("");
console.log('---- completed ----')
var next_reminder_date = flatpickr("#next_reminder_date", {
dateFormat: "d/m/Y",
allowInput: false,
minDate: "today"
});
})
//------------------------------ GET DATA ( EDIT, BRANCH, POLICY ) ---------------------------------------------------------------------------
//view and edit Lead data function ( NOT IN USE DON'T DELETE )
function togglePolicyTypeDivider(dataIncrement) {
var $policyType = $('#policy_type_id_' + dataIncrement);
var selectedPolicyText = ($policyType.find('option:selected').text() || '').toLowerCase();
var isGmcPolicy = selectedPolicyText.indexOf('gmc') !== -1;
var $policyDivider = $('#appendArea_' + dataIncrement).find('hr').first();
if ($policyDivider.length) {
$policyDivider.toggle(!isGmcPolicy);
}
}
function getLeadsDataForEdit(input) {
$('.loader').fadeIn();
$('.loader-mask').fadeIn();
$('#leads_form_id')[0].reset();
var id = input;
console.log('Selected Leads:', id);
let dataIncrement = 1;
$.ajax({
url: '<?= base_url("leads/list/") ?>' + id,
type: "GET",
dataType: 'json',
success: function(res) {
$('.btnDiv').hide();
$('#appendArea_' + dataIncrement).empty();
console.log('getLeadsDataForEdit', res);
if (res.status == true) {
$('#appendArea_' + dataIncrement).append(res.data.html);
if (typeof window.refreshLeadsFormValidation === 'function') {
window.refreshLeadsFormValidation();
}
togglePolicyTypeDivider(dataIncrement);
let policy_type_id = res.data.policy_type_id;
let lead_type = res.data.lead_type;
if (policy_type_id == 1 || policy_type_id == 6 || policy_type_id == 7) {
let newId = 'appendAreaForClaim_' + dataIncrement;
$('#appendAreaForClaim').attr('id', newId);
}
leadTypeBsedHideAndShow(lead_type)
if (lead_type == 1) {
$('.claim-row').hide();
} else {
$('.claim-row').show();
if (policy_type_id == 1) {
$('.gpaClaimFileds').show();
$('.lifeClaimFields').hide();
} else if (policy_type_id == 6 || policy_type_id == 7) {
$('.gpaClaimFileds').hide();
$('.lifeClaimFields').show();
}
}
if (lead_type != 1 && policy_type_id != 1 && policy_type_id != 6 && policy_type_id != 7) {
// updateRenewalFields(dataIncrement);
// let incurred_claim_date_id = 'incurred_claim_date_' + dataIncrement;
let incurred_claim_date_id = 'incurred_claim_date';
var incurred_claim_datepicker = flatpickr("#" + incurred_claim_date_id, {
dateFormat: "d/m/Y",
allowInput: false,
onChange: function(selectedDates) {
console.log('Flatpickr instance:', this);
console.log('ID of this element:', this.input.id);
// Extract the increment value from the element's ID
let increment = this.input.id.split('_').pop();
console.log('Extracted increment:', increment);
let lead_type = $('#lead_type').val();
var policyStartDate = $("#source_policy_start_date");
if (lead_type == 3) {
policyStartDate = $("#policy_start_date");
}
console.log('Selected Dates:', selectedDates);
console.log('policy start date instance', policyStartDate)
console.log('Policy Start Date:', policyStartDate.val());
// Recalculate policy_run_days if policy start date is already selected
// if (policyStartDate.val()) {
// calculatePolicyRunDays(increment);
// }
}
});
// var premium_date_datepicker = flatpickr("#" + premium_date_id, {
// dateFormat: "d/m/Y",
// allowInput: false
// });
$('#proposed_insurer_' + dataIncrement).select2();
$('#proposed_tpa_' + dataIncrement).select2();
}
hide_list_show_add();
pageTitle = 'Edit Opportunities - (EB)';
pageBackButton = '<a href="<?= base_url('leads/list') ?>" class="topbar-icon-btn" data-toggle="tooltip" data-placement="top" title="Back" aria-label="Back"><i class="ri-arrow-left-s-line"></i></a>';
if (typeof window.applyTopNavbarTitle === 'function') {
window.applyTopNavbarTitle();
}
$('#leads_primarykey').val(res.data.id);
$('#actual_lead_id').val(res.data.actual_lead_id || 0);
$('#policy_start_date').val(res.data.policy_end_date);
$('#lead_type').val(res.data.lead_type);
$('#issuer').val(res.data.issuer);
$('#client_type').val(res.data.client_type);
$('#client_name').val(res.data.client_name);
$('#client_short_name').val(res.data.client_short_name);
$('#entity_type_id').val(res.data.entity_type_id);
$('#lead_status').val(res.data.status).trigger('change');
$('#lost_reason').val(res.data.lost_reason || '');
$('#notes').val(res.data.notes);
let existingClientId = res.data.client_id || res.data.is_client_created || 0;
console.log('existingClientId', existingClientId);
if (lead_type == 3) {
if (existingClientId && existingClientId != 0) {
$('#exixting_client').prop('checked', true).trigger('change');
} else {
$('#exixting_client').prop('checked', false).trigger('change');
}
}
setTimeout(function() {
$('#client_id').val(existingClientId).change();
setTimeout(function() {
$('#client_branch_id').val(res.data.client_branch_id).change();
setTimeout(function() {
$('#source_policy_id').val(res.data.source_policy_id);
$('#pan').val(res.data.pan);
$('#gst').val(res.data.gst);
$('#branch_name').val(res.data.branch_name);
$('#branch_code').val(res.data.branch_code);
$('#contact_person_name').val(res.data
.contact_person_name);
$('#contact_person_mobile').val(res.data
.contact_person_mobile);
$('#contact_person_email').val(res.data
.contact_person_email);
$('#policy_type_id_1').val(res.data.policy_type_id)
.select2();
$('.loader').fadeOut();
$('.loader-mask').delay(350).fadeOut('slow');
}, 1000)
}, 1000);
}, 1000);
var insurer = res.data.insurer_branch_id + '-' + res.data.insurer_id;
var tpa = res.data.tpa_branch_id + '-' + res.data.tpa_id;
var proposed_insurer = res.data.proposed_insurer_branch_id + '-' + res.data
.proposed_insurer_id;
var proposed_tpa = res.data.proposed_tpa_branch_id + '-' + res.data.proposed_tpa_id;
$('#insurer_1').val(insurer).select2();
$('#tpa_1').val(tpa).select2();
$('#policy_start_date_1').val(res.data.policy_start_date);
$('#policy_end_date_1').val(res.data.policy_end_date);
$('#file_name_display').text('Upload File Name : ' + res.data.file_name);
if (res.data.salse_person_id) {
selecSalsePerson(res.data.salse_person_id);
}
} else {
console.log('No data found');
}
},
error: function(xhr, status, error) {
$('.loader').fadeOut();
$('.loader-mask').delay(350).fadeOut('slow');
console.error(xhr.responseText);
console.error(status, error);
}
});
}
var allContacts = "";
//client branch data
function getBranchData(input, inputType) {
if (inputType == 1) {
var client_branch_id = $(input).val();
} else {
client_branch_id = input;
}
if (client_branch_id) {
$('.loader').fadeIn();
$('.loader-mask').fadeIn();
$.ajax({
url: '<?php echo base_url('util/get_client_branch_data/'); ?>' + client_branch_id,
type: "GET",
dataType: 'json',
success: function(res) {
console.log('getBranchData response', res);
if (res.status == true) {
$('#gst').val(res.data.gst);
$('#pan').val(res.data.pan);
$('#branch_name').val(res.data.branch_name);
$('#branch_code').val(res.data.branch_code);
allContacts = res.contact;
$('#contact_person_summary').empty();
$('#contact_person_summary').append($('<option>', {
value: "",
text: "Select a Contact"
}));
res.contact.forEach((value, key) => {
if (value.name && value.email) {
// let display_value = `${value.name} - ${value.email} - ${value.mobile}`;
let display_value = value.name;
$('#contact_person_summary').append($('<option>', {
value: key, // index or key in array/object
text: display_value
}));
}
});
// $('#contact_person_name').val(res?.contact?.name || '');
// $('#contact_person_mobile').val(res?.contact?.mobile || '');
// $('#contact_person_email').val(res?.contact?.email || '');
$('#pan').prop('readOnly', true);
$('#gst').prop('readOnly', true);
$('#branch_name').prop('readOnly', true);
$('#branch_code').prop('readOnly', true);
$('#contact_person_name').prop('readOnly', true);
$('#contact_person_mobile').prop('readOnly', true);
$('#contact_person_email').prop('readOnly', true);
// $('#policy_type_id_1').prop('readOnly', true);
$('.loader').fadeOut();
$('.loader-mask').delay(350).fadeOut('slow');
} else {
$('#gst').val('');
$('#pan').val('');
$('#branch_name').val('');
$('#branch_code').val('');
$('#contact_person_name').val('');
$('#contact_person_mobile').val('');
$('#contact_person_email').val('');
console.log(res.message, 'warning');
}
$('.loader').fadeOut();
$('.loader-mask').delay(350).fadeOut('slow');
},
error: function(xhr, status, error) {
console.error(xhr.responseText);
console.error(status, error);
}
});
}
}
// Client Policy Data
function getPolicyData(client_policy_id, increment_count) {
console.log('client_policy_id', client_policy_id);
console.log('increment_count', increment);
if (client_policy_id) {
// Show loader
$('.loader').fadeIn();
$('.loader-mask').fadeIn();
$.ajax({
url: '<?php echo base_url('client/policy/list/'); ?>' + client_policy_id,
type: "GET",
dataType: 'json',
success: function(res) {
console.log('getPolicyData response:', res);
if (res.status === true && res.data) {
console.log("res.data.source_policy_start_date", res.data.source_policy_start_date)
console.log("res.data.source_policy_end_date", res.data.source_policy_end_date)
$('#source_policy_start_date').val(res.data.source_policy_start_date);
$('#source_policy_end_date').val(res.data.source_policy_end_date);
for (let i = 1; i <= increment_count; i++) {
$(`#policy_type_id`).removeClass('readonly-select ').select2();
$(`#insurer_${i}`).removeClass('readonly-select ').select2();
$(`#tpa_${i}`).removeClass('readonly-select ').select2();
console.log('Updating fields for row:', i);
const insurer = `${res.data.insurer_branch_id}-${res.data.insurer_id}`;
const tpa = `${res.data.tpa_branch_id}-${res.data.tpa_id}`;
console.log('policy data', res);
// Update fields with response data
$(`#policy_type_id_${i}`).val(res.data.policy_type_id).trigger('change');
$(`#insurer_${i}`).val(insurer).trigger('change');
$(`#tpa_${i}`).val(tpa).trigger('change');
$(`#proposed_insurer_${i}`).val(insurer).trigger('change');
$(`#proposed_tpa_${i}`).val(tpa).trigger('change');
$('#policy_start_date').val(res.new_start_date);
$('#policy_end_date').val(res.end_date);
$("#policy_end_date").prop('readOnly', true);
$("#policy_start_date").prop("readOnly", true);
$(`#policy_type_id_${i}`).addClass('readonly-select ').select2('destroy');
$(`#insurer_${i}`).addClass('readonly-select ').select2('destroy');
$(`#tpa_${i}`).addClass('readonly-select ').select2('destroy');
$(`#proposed_insurer_${i}`).addClass('readonly-select ').select2('destroy');
$(`#proposed_tpa_${i}`).addClass('readonly-select ').select2('destroy');
}
} else {
console.warn('Invalid response:', res.message || 'Unknown error');
// Reset fields if response is invalid
for (let i = 1; i <= increment_count; i++) {
$(`#policy_type_id_${i}`).val('').trigger('change');
$(`#insurer_${i}`).val('').trigger('change');
$(`#tpa_${i}`).val('').trigger('change');
$(`#proposed_insurer_${i}`).val('').trigger('change');
$(`#proposed_tpa_${i}`).val('').trigger('change');
}
}
// Hide loader
$('.loader').fadeOut();
$('.loader-mask').delay(350).fadeOut('slow');
},
error: function(xhr, status, error) {
console.error('AJAX Error:', xhr.responseText || error);
// Reset fields on error
for (let i = 1; i <= increment_count; i++) {
$(`#policy_type_id_${i}`).val('').trigger('change');
$(`#insurer_${i}`).val('').trigger('change');
$(`#tpa_${i}`).val('').trigger('change');
$(`#proposed_insurer_${i}`).val('').trigger('change');
$(`#proposed_tpa_${i}`).val('').trigger('change');
}
$('.loader').fadeOut();
$('.loader-mask').delay(350).fadeOut('slow');
}
});
} else {
console.warn('Client policy ID is required.');
// Reset fields if no client policy ID is provided
for (let i = 1; i <= increment_count; i++) {
$(`#policy_type_id_${i}`).val('').trigger('change');
$(`#insurer_${i}`).val('').trigger('change');
$(`#tpa_${i}`).val('').trigger('change');
$(`#proposed_insurer_${i}`).val('').trigger('change');
$(`#proposed_tpa_${i}`).val('').trigger('change');
}
}
}
function getCustomFields(input, dataIncrement) {
console.log('getCustomFields', input);
let policy_type_id = $(input).val();
console.log("policy_type_id", policy_type_id);
var lead_type = $('#lead_type').val();
console.log("lead_type", lead_type);
let url = '<?= base_url('util/getPolicyTypeFields/') ?>';
let requestData = {
policy_type_id: policy_type_id,
};
// Show loader
$('.loader').fadeIn();
$('.loader-mask').fadeIn();
// Send AJAX request
sendAjaxRequestForGlobal(url, 'GET', requestData, function(response) {
console.log('Data fetched successfully:', response);
$('#appendArea_' + dataIncrement).empty();
if (response.status == true) {
console.log(response.message, 'SUCCESS');
$('#appendArea_' + dataIncrement).append(response.data);
if (typeof window.refreshLeadsFormValidation === 'function') {
window.refreshLeadsFormValidation();
}
togglePolicyTypeDivider(dataIncrement);
console.log("Policy Type ID : ", policy_type_id);
if (policy_type_id == 1 || policy_type_id == 6 || policy_type_id == 7) {
let newId = 'appendAreaForClaim_' + dataIncrement;
$('#appendAreaForClaim').attr('id', newId);
appendThreeYearsClaims(dataIncrement)
}
leadTypeBsedHideAndShow(lead_type)
if (lead_type == 1) {
$('.claim-row').hide();
} else {
$('.claim-row').show();
if (policy_type_id == 1) {
$('.gpaClaimFileds').show();
$('.lifeClaimFields').hide();
} else if (policy_type_id == 6 || policy_type_id == 7) {
$('.gpaClaimFileds').hide();
$('.lifeClaimFields').show();
}
}
if (lead_type != 1 && policy_type_id != 1 && policy_type_id != 6 && policy_type_id != 7) {
if (lead_type == 1) {
updateRenewalFields(dataIncrement);
}
// let incurred_claim_date_id = 'incurred_claim_date_' + dataIncrement;
let incurred_claim_date_id = 'incurred_claim_date';
var incurred_claim_datepicker = flatpickr("#" + incurred_claim_date_id, {
dateFormat: "d/m/Y",
allowInput: false,
onChange: function(selectedDates) {
console.log('Flatpickr instance:', this);
console.log('ID of this element:', this.input.id);
// Extract the increment value from the element's ID
let increment = this.input.id.split('_').pop();
console.log('Extracted increment:', increment);
var policyStartDate = $("#source_policy_start_date");
if (lead_type == 3) {
policyStartDate = $("#policy_start_date");
}
console.log('Selected Dates:', selectedDates);
console.log('policy start date instance', policyStartDate)
console.log('Policy Start Date:', policyStartDate.val());
// Recalculate policy_run_days if policy start date is already selected
// if (policyStartDate.val()) {
// calculatePolicyRunDays(increment);
// }
}
});
$('#proposed_insurer_' + dataIncrement).select2();
$('#proposed_tpa_' + dataIncrement).select2();
}
} else {
console.log(response.message, 'WARNING');
}
// Hide loader
$('.loader').fadeOut();
$('.loader-mask').delay(350).fadeOut('slow');
}, function(xhr, status, error) {
console.error('Error fetching data:', error);
console.error(xhr.responseText);
toastr.error('An error occurred while fetch data.', 'Error');
// Hide loader
$('.loader').fadeOut();
$('.loader-mask').delay(350).fadeOut('slow');
});
}
//---------------------- MULTI POLICY APPEND -----------------------------------------------------------------------------------
var increment = 1;
function addHTMLInput(check = null) {
const container = document.getElementById('dynamic-form-container');
const newRow = document.createElement('div');
newRow.className = 'form-row dynamic-form-row';
if (increment > 1) {
const hrElement = document.createElement('hr');
container.appendChild(hrElement);
}
// Main div
newRow.innerHTML += `
<div class="form-group col-md-4 renewalFields" style="display: none;">
<label for="source_policy_id"> Source Policy <span id="base_danger"
class="text-danger">* </span></label>
<select class="form-control" id="source_policy_id" name="source_policy_id">
<option value="" selected>Select Source Policy</option>
</select>
</div>
<div class="form-group col-md-4 renewalFields" style="display: none;">
<label for="source_policy_start_date">Source Policy Start Date<span class="text-danger"></span></label>
<input type="text" class="form-control readonly-select" id="source_policy_start_date" name="source_policy_start_date" readonly>
</div>
<div class="form-group col-md-4 renewalFields" style="display: none;">
<label for="source_policy_end_date">Source Policy End Date<span class="text-danger"></span></label>
<input type="text" class="form-control" id="source_policy_end_date" name="source_policy_end_date" readonly>
</div>
<div class="form-group col-md-4">
<label for="policy_type_id">Policy Type <span class="text-danger">*</span></label>
<select class="form-control" id="policy_type_id_${increment}" name="policy_type_id[]" onchange="getCustomFields(this, ${increment})" required>
<option value="">Select Policy Type</option>
<?php
if (isset($policy_type) && count($policy_type)) {
foreach ($policy_type as $value) {
if ($value['allocg'] != "Non-EB" && $value['allocg'] != "Marine") {
echo "<option value='" . $value['id'] . "'>" . $value['policy_type'] . "</option>";
}
}
}
?>
</select>
</div>
<div class="form-group col-md-4 proposed_div">
<label for="insurer">Insurer <span class="text-danger"></span></label>
<select class="form-control" id="insurer_${increment}" name="insurer[]" onchange="insurerChange(this, ${increment})">
<option value="">Select Insurer</option>
<?php if (isset($insurer)) { ?>
<?php foreach ($insurer as $value) { ?>
<option value="<?= $value['id'] . '-' . $value['insurer_id'] ?>">
<?= $value['insurer_name'] . '-' . $value['branch_code'] ?>
</option>
<?php } ?>
<?php } ?>
</select>
</div>
<div class="form-group col-md-4 proposed_div">
<label for="tpa">TPA <span class="text-danger"></span></label>
<select class="form-control" id="tpa_${increment}" name="tpa[]" onchange="tpaChange(this, ${increment})">
<option value="">Select TPA</option>
<?php if (isset($tpa)) { ?>
<?php foreach ($tpa as $value) { ?>
<option value="<?= $value['id'] . '-' . $value['tpa_id'] ?>">
<?= $value['tpa_short_name'] . '-' . $value['branch_code'] ?>
</option>
<?php } ?>
<?php } ?>
</select>
</div>
<div class="form-group col-md-4">
<label for="policy_start_date">Date of Commencement <span class="text-danger">*</span></label>
<div class="input-icon">
<input type="text" class="form-control policy_start_date" id="policy_start_date_${increment}" name="policy_start_date[]" placeholder="Enter DOC" onchange="calculatePolicyMetrics(this)" autocomplete="off" >
<i class="mdi mdi-calendar-blank-outline additional-icon"></i>
</div>
</div>
<div class="form-group col-md-4">
<label for="policy_end_date">Date of Expiry <span class="text-danger">*</span></label>
<div class="input-icon">
<input type="text" class="form-control policy_end_date" id="policy_end_date_${increment}" name="policy_end_date[]" placeholder="Enter DOE" autocomplete="off">
<i class="mdi mdi-calendar-blank-outline additional-icon"></i>
</div>
</div>
<div id="appendArea_${increment}" class = "form-group col-md-12 appendArea"></div>
<div class="card" style="width:100%; background-color: transparent;">
<div class="card-body" style="background-color: #fff !important; border: 0px !important;">
<div id="multiFileAppendArea_${increment}"></div>
</div>
</div>
<div class="form-group col-md-12 btnDiv" style="position: relative;top: 28px;float: right;text-align: end;">
<a class="btn btn-danger waves-effect waves-light" onclick="removeHTMLInput(this)">x</a>
<a class="btn btn-primary waves-effect waves-light mr-1" onclick="addHTMLInput(1)">+</a>
</div>
`;
container.appendChild(newRow);
if (typeof window.refreshLeadsFormValidation === 'function') {
window.refreshLeadsFormValidation();
}
//append mutli file html
addFileField(increment);
var lead_type = $('#lead_type').val();
leadTypeBsedHideAndShow(lead_type)
$('#policy_type_id_' + increment).parsley({
errorsContainer: function(ParsleyField) {
if (ParsleyField.$element.hasClass('select2-hidden-accessible')) {
return ParsleyField.$element.siblings('.select2-container');
}
return ParsleyField.$element;
}
});
$('#insurer_' + increment).select2();
$('#tpa_' + increment).select2();
$('#proposed_insurer_' + increment).select2();
$('#proposed_tpa_' + increment).select2();
$('#policy_type_id_' + increment).select2();
lead_type = $('#lead_type').val();
// var start_date_id = lead_type == "1" ? `policy_start_date_${increment}` : "policy_start_date";
// var end_date_id = lead_type == "1" ? `policy_end_date_${increment}` : "policy_end_date";
// $(".policy_start_date").attr("id", start_date_id);
// $(".policy_end_date").attr("id", end_date_id);
// Initialize date pickers
if (lead_type == 1) {
var policy_start_datePicker = flatpickr("#policy_start_date_" + increment, {
dateFormat: "d/m/Y",
allowInput: false,
onChange: function(selectedDates) {
var policy_end_date = new Date(selectedDates[0]);
policy_end_date.setFullYear(policy_end_date.getFullYear() + 1);
policy_end_date.setDate(policy_end_date.getDate() -
1); // Set end date to last day of selected year
policy_end_datePicker.setDate(policy_end_date);
console.log('this object', this);
console.log('id of this element:', this.element);
console.log('id of this element:', this.element.id);
let increment = this.element.id.split('_').pop();
console.log(increment); // Outputs: 1
// console.log('increment', increment);
// console.log('policy_start_datePicker selectedDates', selectedDates);
// console.log('policy_start_datePicker incurred_claim_date_', $("#incurred_claim_date_" +
// increment).val());
// Recalculate policy_run_days if incurred claim date is already selected
// if ($("#incurred_claim_date_" + increment).val()) {
// console.log('policy_start_datePicker selectedDates', selectedDates);
// calculatePolicyRunDays(increment);
// }
}
});
}
var policy_end_datePicker = flatpickr("#policy_end_date_" + increment, {
dateFormat: "d/m/Y",
allowInput: false
});
$('#source_policy_id').on('change', function() {
let client_policy_id = $(this).val();
console.log('increment given', increment);
getPolicyData(client_policy_id, increment);
})
if (check == 1) {
let client_policy_id = $('#source_policy_id').val();
if (client_policy_id) {
getPolicyData(client_policy_id, increment);
}
}
increment++; // Increment after adding the input
}
function removeHTMLInput(element) {
const container = document.getElementById('dynamic-form-container');
const rows = container.querySelectorAll('.dynamic-form-row');
if (rows.length > 1) {
const row = element.closest('.dynamic-form-row');
const hrElement = row.previousElementSibling; // Get the <hr> before the row
console.log(hrElement);
console.log(hrElement.tagName);
if (hrElement && hrElement.tagName === 'HR') { // Check if it's an <hr> element
hrElement.remove(); // Remove the <hr>
}
row.remove();
}
}
function removeExtraForms() {
const container = document.getElementById('dynamic-form-container');
if (!container) {
console.error("Container element not found");
return;
}
// Remove all .dynamic-form-row except the first one
const rows = container.querySelectorAll('.dynamic-form-row');
rows.forEach((row, index) => {
if (index > 0) row.remove();
});
// Remove all <hr> elements except the first one
const hrElements = container.querySelectorAll('hr');
hrElements.forEach((hr, index) => {
if (index > 0) hr.remove();
});
}
//------------------------ CALCULATION ---------------------------------------------------------------------------------
// function calculatePolicyRunDays(increment) {
// // console.log('calculatePolicyRunDays function called');
// // console.log('increment', increment);
// // let lead_type = $('#lead_type').val();
// // var policyStartDate = $("#source_policy_start_date");
// // if(lead_type == 3){
// // policyStartDate = $("#policy_start_date");
// // }
// // var policyStartDate = flatpickr.parseDate(policyStartDate.val(), "d/m/Y");
// // var incurredClaimDate = flatpickr.parseDate($("#incurred_claim_date_" + increment).val(), "d/m/Y");
// // console.log('policyStartDate', policyStartDate)
// // console.log('incurredClaimDate', incurredClaimDate)
// // if (policyStartDate && incurredClaimDate) {
// // var timeDiff = Math.abs(policyStartDate - incurredClaimDate); // Time difference in milliseconds
// // console.log('timeDiff', timeDiff);
// // var daysDiff = Math.ceil(timeDiff / (1000 * 60 * 60 * 24) + 1); // Convert to days and add 1
// // console.log('daysDiff', daysDiff);
// // $("#policy_run_days_" + increment).val(daysDiff); // Set value in the policy_run_days_ input
// // }
// }
// function incurredClaimSum(input) {
// // let increment = input.id.split('_').pop(); // Extract the increment part
// // console.log('increment', increment);
// // // Retrieve and convert the values to numbers, fallback to 0 if empty or invalid
// // let paid_claims = Number($('#paid_claims_' + increment).val()) || 0;
// // console.log('paid_claims', paid_claims);
// // let outstanding_claims = Number($('#outstanding_claims_' + increment).val()) || 0;
// // console.log('outstanding_claims', outstanding_claims);
// // // Calculate the incurred claim
// // let incurred_claims = paid_claims + outstanding_claims;
// // console.log('incurred_claims', incurred_claims);
// // // Set the calculated value
// // $('#incurred_claims_' + increment).val(incurred_claims);
// // // ------------------------------------------------------------------------------------------
// // let policy_run_days = Number($('#policy_run_days_' + increment).val()) || 0;
// // console.log('policy_run_days', policy_run_days);
// // console.log('incurred claims ' + incurred_claims);
// // // Prevent division by zero in annualised claims calculation
// // let annualised_claims = policy_run_days > 0 ? incurred_claims / policy_run_days * 365 : 0;
// // let annualised_claims_roundoff = Math.round(annualised_claims);
// // console.log('annualised_claims', annualised_claims_roundoff);
// // $('#annualised_claims_' + increment).val(annualised_claims_roundoff);
// // // ------------------------------------------------------------------------------------------
// // // Prevent division by zero in incurred claim ratio calculation
// // let premium_as_on_date = Number($('#premium_date_' + increment).val()) || 0;
// // let incurred_claim_ratio = (annualised_claims > 0 && premium_as_on_date > 0)
// // ? (annualised_claims / premium_as_on_date)
// // : 0;
// // let incurred_claim_ratio_roundoff = isFinite(incurred_claim_ratio)
// // ? Math.round(incurred_claim_ratio)
// // : 0;
// // console.log('incurred_claim_ratio', incurred_claim_ratio_roundoff);
// // $('#incurred_claims_ratio_' + increment).val(incurred_claim_ratio_roundoff);
// // // ------------------------------------------------------------------------------------------
// // let earnedPremium = parseFloat($('#earned_premium_' + increment).val()) || 0;
// // console.log('earnedPremium:', earnedPremium);
// // // Prevent division by zero
// // let earnedClaimsRatio = earnedPremium > 0 ? annualised_claims / earnedPremium : 0;
// // // Round to nearest integer
// // let earnedClaimsRatioRounded = Math.round(earnedClaimsRatio);
// // console.log('earnedClaimsRatio:', earnedClaimsRatio);
// // // Set the value to the corresponding input
// // $('#earned_claims_ratio_' + increment).val(earnedClaimsRatioRounded);
// }
// function earnedPremiumCalc(input) {
// // let increment = input.id.split('_').pop(); // Extract the increment part
// // console.log('increment', increment);
// // let premium_as_on_date = Number($('#premium_date_' + increment).val()) || 0;
// // // Retrieve and convert the values to numbers, fallback to 0 if empty or invalid
// // let premium_at_inception = Number($('#premium_at_inception_' + increment).val()) || 0;
// // console.log('premium_at_inception', premium_at_inception);
// // let policy_run_days = Number($('#policy_run_days_' + increment).val()) || 0;
// // console.log('policy_run_days', policy_run_days);
// // // Prevent division by zero and calculate earned premium
// // let earned_premium = premium_as_on_date > 0 ? (premium_as_on_date / 365) * 364 : 0;
// // console.log('earned_premium', earned_premium);
// // let earned_premium_roundoff = Math.round(earned_premium);
// // // Set the calculated value with two decimal places
// // $('#earned_premium_' + increment).val(earned_premium_roundoff);
// }
function calculatePolicyMetrics(input) {
let lead_type = $('#lead_type').val();
console.log('Lead Type:', lead_type);
let increment = input.id.split('_').pop(); // Extract increment
if (lead_type == 1) {
return;
}
let input_id = input.id;
console.log('--- calculatePolicyMetrics called ---');
console.log('Input ID:', input_id);
console.log('Increment:', increment);
let sourcePolicyDateVal = $('#source_policy_start_date').val()?.trim();
let policyStartDateVal = $('#policy_start_date').val()?.trim() || $('#policy_start_date_1').val()?.trim();
let policyStartDateInput = null;
if (sourcePolicyDateVal && lead_type == 2) {
policyStartDateInput = $('#source_policy_start_date');
console.log('Using Source Policy Start Date:', sourcePolicyDateVal);
} else if (policyStartDateVal) {
if (input_id == "policy_start_date_1") {
policyStartDateInput = $('#policy_start_date_1');
} else {
policyStartDateInput = $('#policy_start_date');
}
console.log('Using Policy Start Date:', policyStartDateVal);
} else {
toastr.warning('Policy start date or Date of Commencement is empty. Please fill in the date field.', "WARNING.. !");
console.warn('Both policy start dates are missing or invalid');
$(input).val('');
return; // stop further execution
}
// let policyStartDateInput = (lead_type == 3) ? $('#policy_start_date') : $('#source_policy_start_date');
console.log('Policy Start Date Input:', policyStartDateInput.val());
let policyStartDate = flatpickr.parseDate(policyStartDateInput.val(), "d/m/Y");
let incurredClaimDate = flatpickr.parseDate($("#incurred_claim_date").val(), "d/m/Y");
console.log('Parsed Policy Start Date:', policyStartDate);
console.log('Parsed Incurred Claim Date:', incurredClaimDate);
if (policyStartDate && incurredClaimDate) {
let timeDiff = Math.abs(incurredClaimDate - policyStartDate);
console.log('Time Difference (ms):', timeDiff);
let daysDiff = Math.ceil(timeDiff / (1000 * 60 * 60 * 24) + 1);
console.log('Policy Run Days:', daysDiff);
$('#policy_run_days').val(daysDiff);
}
let paid_claims = Number($('#paid_claims').val()) || 0;
let outstanding_claims = Number($('#outstanding_claims').val()) || 0;
console.log('Paid Claims:', paid_claims);
console.log('Outstanding Claims:', outstanding_claims);
let incurred_claims = paid_claims + outstanding_claims;
console.log('Incurred Claims:', incurred_claims);
$('#incurred_claims').val(incurred_claims);
let policy_run_days = Number($('#policy_run_days').val()) || 0;
console.log('Policy Run Days (Final):', policy_run_days);
let annualised_claims = policy_run_days > 0 ? (incurred_claims / policy_run_days) * 365 : 0;
// let annualised_claims_roundoff = annualised_claims.toFixed(2);
let annualised_claims_roundoff = Math.trunc(annualised_claims);
console.log('Annualised Claims:', annualised_claims);
console.log('Annualised Claims (Rounded):', annualised_claims_roundoff);
$('#annualised_claims').val(annualised_claims_roundoff);
let premium_as_on_date = Number($('#premium_date').val()) || 0;
console.log('Premium as on Date:', premium_as_on_date);
let incurred_claim_ratio = (incurred_claims > 0 && premium_as_on_date > 0) ?
(incurred_claims / premium_as_on_date) * 100 :
0;
let incurred_claim_ratio_roundoff = isFinite(incurred_claim_ratio) ? incurred_claim_ratio.toFixed(2) : 0;
console.log('Incurred Claim Ratio:', incurred_claim_ratio);
console.log('Incurred Claim Ratio (Rounded):', incurred_claim_ratio_roundoff);
$('#incurred_claims_ratio').val(incurred_claim_ratio_roundoff);
let earned_premium = premium_as_on_date > 0 ? (premium_as_on_date / 365) * policy_run_days : 0;
// let earned_premium_roundoff = earned_premium.toFixed(2);
let earned_premium_roundoff = Math.trunc(earned_premium);
console.log('Earned Premium:', earned_premium);
console.log('Earned Premium (Rounded):', earned_premium_roundoff);
$('#earned_premium').val(earned_premium_roundoff);
let earnedClaimsRatio = premium_as_on_date > 0 ? (annualised_claims / premium_as_on_date) * 100 : 0;
let earnedClaimsRatioRounded = earnedClaimsRatio.toFixed(2);
console.log('Earned Claims Ratio:', earnedClaimsRatio);
console.log('Earned Claims Ratio (Rounded):', earnedClaimsRatioRounded);
$('#earned_claims_ratio').val(earnedClaimsRatioRounded);
console.log('--- End of calculatePolicyMetrics ---\n');
}
$(document).on("input", "#incept_no_of_lives", function () {
if (this.value.length > 10) {
this.value = this.value.slice(0, 10); // max 10 digits
}
this.value = this.value.replace(/\D/g, '');
});
$(document).on("input", "#incept_emp_count, #incept_dept_count, #renewal_emp_count, #renewal_dept_count, #exp_emp_count, #exp_dept_count", function() {
if (this.value.length > 10) {
this.value = this.value.slice(0, 10); // max 10 digits
}
this.value = this.value.replace(/\D/g, '');
calculateTotalLives(this);
});
function calculateTotalLives(input) {
var lead_type = $('#lead_type').val();
if (lead_type == 1) {
let formRow = input.closest('.form-row');
if (formRow) {
// Get the employee count and dependent count within the same row
let empCountInput = formRow.querySelector('[name="incept_emp_count[]"]');
let depCountInput = formRow.querySelector('[name="incept_dept_count[]"]');
let totalLivesInput = formRow.querySelector('[name="incept_no_of_lives[]"]');
// Parse the input values as integers, defaulting to 0 if empty
let empCount = empCountInput ? parseInt(empCountInput.value) || 0 : 0;
let depCount = depCountInput ? parseInt(depCountInput.value) || 0 : 0;
// Calculate total lives
let totalLives = empCount + depCount;
// Set the total lives input value
if (totalLivesInput) {
totalLivesInput.value = totalLives;
}
}
} else {
console.log("Function Called");
if (input.id === "incept_emp_count" || input.id === "incept_dept_count") {
var incept_emp_count = parseInt($("#incept_emp_count").val()) || 0;
var incept_dept_count = parseInt($("#incept_dept_count").val()) || 0;
var totalCount = incept_emp_count + incept_dept_count;
$("#incept_no_of_lives").val(totalCount);
} else if (input.id === "renewal_emp_count" || input.id === "renewal_dept_count") {
var renewal_emp_count = parseInt($("#renewal_emp_count").val()) || 0;
var renewal_dept_count = parseInt($("#renewal_dept_count").val()) || 0;
var totalCount = renewal_emp_count + renewal_dept_count;
$("#renewal_no_of_lives").val(totalCount);
} else {
var exp_emp_count = parseInt($("#exp_emp_count").val()) || 0;
var exp_dept_count = parseInt($("#exp_dept_count").val()) || 0;
var totalCount = exp_emp_count + exp_dept_count;
$("#exp_no_of_lives").val(totalCount);
}
}
}
//------------------------ FORM SUBMIT ---------------------------------------------------------------------------------
$("#leads_form_id").submit(function(event) {
event.preventDefault();
var isValid = $('#leads_form_id').parsley().validate();
if (!isValid) {
$('#leads_form_id').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 salse_person_id = $("#salse_person_id").val();
console.log('salse_person_id : ', salse_person_id);
form_action = '<?= base_url('leads/create') ?>';
$('.loader').fadeIn();
$('.loader-mask').fadeIn();
var formData = new FormData($('#leads_form_id')[0]);
var policy_type_ids = formData.getAll('policy_type_id[]');
console.table(policy_type_ids);
console.log('form policy ', policy_type_ids);
const jsonString = JSON.stringify(salse_person_id);
console.log('jsonString', jsonString);
// Append the JSON string to the FormData object
formData.append('salse_person_id', jsonString);
// Convert the claim experience array to JSON
const finyearJsonString = gatherClaimExperienceData(policy_type_ids);
console.log('finyearJsonString', finyearJsonString);
formData.append('finyear', finyearJsonString);
$.ajax({
data: formData,
url: form_action,
type: "POST",
dataType: 'json',
processData: false,
contentType: false,
success: function(res) {
$('.loader').fadeOut();
$('.loader-mask').delay(350).fadeOut('slow');
console.log('inception_form_response', res)
if (res.status == true) {
toastr.success(res.message, 'Success');
window.location.href = '<?= base_url('leads/list') ?>';
} else {
toastr.error(res.message, 'Error');
}
},
error: function(xhr, status, error) {
const hostname = window.location.hostname;
if (hostname === 'localhost' || hostname === '127.0.0.1') {
// DEVELOPER MODE: Show everything in a nice group
console.group("%c Debug: Server Error ", "background: #222; color: #bada55; padding: 2px;");
console.error("Status:", xhr.status);
console.error("Type:", error);
console.error("Full Response:", xhr.responseText);
console.groupEnd();
} else {
// LIVE MODE: Only log a simple, non-revealing error
console.error("Server Error: Action could not be completed. Reference Code: " + xhr.responseText);
}
$('.loader').fadeOut();
$('.loader-mask').delay(350).fadeOut('slow');
if (xhr.status === 400) {
let response = JSON.parse(xhr.responseText);
let errorMessages = "";
let seenMessages = []; // Array to store unique messages
if (response.errors) {
$.each(response.errors, function (field, message) {
if (!seenMessages.includes(message)) {
errorMessages += `• ${message}<br>`;
seenMessages.push(message); // Mark this message as "seen"
}
});
toastr.error(errorMessages, 'Validation Error', { "allowHtml": true });
} else {
toastr.warning(response.message || 'Validation failed', 'Warning');
}
} else if (xhr.status === 403) {
let response = JSON.parse(xhr.responseText);
toastr.error(response.message, 'Security Policy');
} else if (xhr.status === 500) {
toastr.error('Something went wrong . Please try again later.', 'Server Error');
} else {
toastr.error('An unexpected error occurred. Please try again later.', 'Error');
}
}
});
});
//-----------------------------------------------------------------------------------------------------------
$('#lead_type').change(function() {
let value = $(this).val()
leadTypeBsedHideAndShow(value, true)
if (value != 1 && value != 3) {
removeExtraForms();
}
$('#contact_person_summary').empty();
$('#contact_person_summary').append($('<option>', {
value: "",
text: "Select a Contact"
}));
$("#gst").val("");
$("#branch_name").val("");
$("#branch_code").val("");
$("#contact_person_name").val("");
$("#contact_person_mobile").val("");
$("#contact_person_email").val("");
// Fresh fields
$('#exixting_client').prop('checked', false);
$("#client_type").prop("selectedIndex", 0);
$("#entity_type_id").prop("selectedIndex", 0);
$("#client_name").val("");
$("#client_short_name").val("");
$('#client_type').removeClass('readonly-select');
$('#entity_type_id').removeClass('readonly-select');
$("#client_name").prop('readonly', false);
$("#client_short_name").prop('readonly', false);
// Renewal fields
$("#client_id").prop("selectedIndex", 0);
$("#client_branch_id").prop("selectedIndex", 0);
$("#source_policy_id").empty();
$('#source_policy_id').append($('<option>', {
value: "",
text: "Select a Policy"
}));
$("#pan").val("");
$('#policy_type_id_1').prop("selectedIndex", 0)
$('#insurer_1').prop("selectedIndex", 0)
$('#tpa_1').prop("selectedIndex", 0);
$('#policy_start_date').val("");
$('#policy_end_date').val("");
$("#appendArea_1").empty();
// $('#source_policy_start_date').val("");
// $('#source_policy_end_date').val("");
// $('#incurred_claims_date').val("");
// $('#paid_claims').val("");
// $('#outstanding_claims').val("");
// $('#incurred_claims').val("");
// $('#policy_run_days').val("");
// $('#premium_at_inception').val("");
// $('#premium_date').val("");
// $('#earned_premium').val("");
// $('#annualised_claims').val("");
// $('#incurred_claims_ratio').val("");
// $('#earned_claims_ratio').val("");
let incurred_claim_date_id = 'incurred_claim_date';
if ($('#' + incurred_claim_date_id).length) {
flatpickr("#" + incurred_claim_date_id, {
dateFormat: "d/m/Y",
allowInput: false,
onChange: function(selectedDates) {
try {
let increment = this.input.id.split('_').pop();
console.log('Incurred claim date changed:', selectedDates);
let policyStartDate = $("#source_policy_start_date");
if (policyStartDate.val()) {
calculatePolicyRunDays(increment);
}
} catch (error) {
console.error('Error in incurred_claim_datepicker:', error);
}
}
});
} else {
console.warn(`Incurred claim date field #${incurred_claim_date_id} not found.`);
}
// --- Re-populate Actual Lead data if it was cleared ---
if ($('#actual_lead_id').val() && $('#actual_lead_id').val() != 0) {
$('#client_name').val(actualLeadClientName);
// Re-generate short name from the stored client name to ensure consistency
if (actualLeadClientName.trim() !== '') {
let baseName = actualLeadClientName
.trim()
.substring(0, 10)
.replace(/\s+/g, '')
.toUpperCase();
makeUniqueShortName(baseName);
} else {
$('#client_short_name').val('').parsley().reset();
}
}
})
function insurerChange(input, unique_id) {
var lead_type = $('#lead_type').val()
if (lead_type == 2) {
var val = $(input).val();
$('#proposed_insurer_' + unique_id).val(val).select2();
}
}
function tpaChange(input, unique_id) {
var lead_type = $('#lead_type').val()
if (lead_type == 2) {
var val = $(input).val();
$('#proposed_tpa_' + unique_id).val(val).select2();
}
}
//-----------------------------------------------------------------------------------------------------------
// function gatherClaimExperienceData(policy_id) {
// // console.log('policy id', policy_id);
// // Initialize an empty array for the claim experience data
// let claimExperience = [];
// for (let i = 0; i < policy_id.length; i++) {
// // Loop through the rows and extract data for each year
// $(`[name="first_year[]"][id*='_${policy_id[i]}_']`).each(function(index) {
// // Extract values for the first, second, and third year claims
// console.log('index ', index);
// const firstYear = $(`[name="first_year[]"][id*='_${policy_id[i]}_']`).eq(index).val();
// const firstClaimAmount = $(`input[name="first_claim_amount[]"][id*='_${policy_id[i]}_']`).eq(index)
// .val();
// const firstClaimStatus = $(`input[name="first_claim_status[]"][id*='_${policy_id[i]}_']`).eq(index)
// .val();
// const firstCauseOfDeath = $(`[name="first_casue_of_death[]"][id*='_${policy_id[i]}_']`).eq(index)
// .val() || null;
// const firstDeathDate = $(`input[name="first_death_date[]"][id*='_${policy_id[i]}_']`).eq(index)
// .val() || null;
// const claimType = $(`[name="claim_type[]"][id*='_${policy_id[i]}_']`).eq(index).val() || null;
// // Push each year's data into the array
// claimExperience.push({
// "finyear": [{
// "year": firstYear,
// "claim_amount": firstClaimAmount,
// "status": firstClaimStatus,
// "cause_of_death": firstCauseOfDeath,
// "death_date": firstDeathDate,
// 'claim_type': claimType,
// 'policy_type': policy_id[i]
// }]
// });
// });
// }
// console.log('claim experience', claimExperience);
// return JSON.stringify(claimExperience);
// }
function gatherClaimExperienceData() {
let claimData = [];
$(".claim-row").each(function() {
let year = $(this).find("[name='first_year[]']").val();
let claimAmount = $(this).find("[name='first_claim_amount[]']").val();
let claimStatus = $(this).find("[name='first_claim_status[]']").val();
let claimType = $(this).find("[name='claim_type[]']").val();
let causeOfDeath = $(this).find("[name='first_cause_of_death[]']").val();
let deathDate = $(this).find("[name='first_death_date[]']").val();
let emp_id = $(this).find("[name='emp_id[]']").val();
let emp_name = $(this).find("[name='emp_name[]']").val();
let gender = $(this).find("[name='gender[]']").val();
let designation = $(this).find("[name='designation[]']").val();
let sum_insured = $(this).find("[name='sum_insured[]']").val();
claimData.push({
"year": year,
"emp_id": emp_id,
"emp_name": emp_name,
"gender": gender,
"designation": designation,
"sum_insured": sum_insured,
"death_date": deathDate,
"cause_of_death": causeOfDeath,
"settled": claimAmount,
});
});
let finalJson = {
"finyear": claimData
};
console.log(finalJson);
let jsonString = JSON.stringify(finalJson);
console.log(jsonString);
return jsonString;
}
//-----------------------------------------------------------------------------------------------------------
// do not remove this
// function appendThreeYearsClaims(count) {
// // let count = $('#appendAreaForClaim').data('count');
// console.log("count", count);
// let policy_type_id = $('#policy_type_id_' + count).val()
// console.log('policy_type_id', policy_type_id);
// console.log('claimIndex from parent', claimIndex);
// let increment = claimIndex;
// let claimsFields = `
// <div class="row claim-row">
// <div class="form-group col-md-2">
// <label for="first_year_${increment}">Year<span class="text-danger">*</span></label>
// <select class="form-control first_year_" id="first_year_${increment}" name="first_year[]">
// <option value="">Select Year</option>
// <?php foreach ($lastFiveYears as $year) {echo "<option value='$year'>$year</option>";} ?>
// </select>
// </div>
// <div class="form-group col-md-2">
// <label for="first_claim_amount_${increment}">Claim/Settled Amount<span class="text-danger">*</span></label>
// <input type="text" class="form-control" id="first_claim_amount_${increment}" name="first_claim_amount[]">
// </div>
// <div class="form-group col-md-2">
// <label for="first_claim_status_${increment}">Claim Status<span class="text-danger">*</span></label>
// <input type="text" class="form-control" id="first_claim_status_${increment}" name="first_claim_status[]">
// </div>
// <div class="form-group col-md-2 lifeClaimFields" style="display:none;">
// <label for="first_cause_of_death_${increment}">Nature/Cause Of Death <span class="text-danger">*</span></label>
// <select class="form-control" id="first_cause_of_death_${increment}" name="first_cause_of_death[]">
// <option value="">Select Cause of Death</option>
// <?php foreach ($causeOfDeath as $cause => $death_value) {echo "<option value='$cause'>$death_value</option>";} ?>
// </select>
// </div>
// <div class="form-group col-md-2 lifeClaimFields" style="display:none;">
// <label for="first_death_date_${increment}">Date of Death<span class="text-danger">*</span></label>
// <input type="text" class="form-control" id="first_death_date_${increment}" name="first_death_date[]">
// </div>
// <div class="form-group col-md-2 gpaClaimFileds" style="display:none;">
// <label for="claim_type_${increment}">Claim Type<span class="text-danger">*</span></label>
// <select class="form-control" id="claim_type_${increment}" name="claim_type[]">
// <option value="">Select Claim Type</option>
// <?php foreach ($gpaClaimType as $claimType => $claim_value) {echo "<option value='$claimType'>$claim_value</option>";} ?>
// </select>
// </div>
// <div class="form-group col-md-2">
// <div class="" style="position: relative; top: 28px; float: right; text-align: end;">
// <a class="btn btn-danger waves-effect waves-light" onclick="removeClaim(this, ${count})">x</a>
// <a class="btn btn-primary waves-effect waves-light mr-1" onclick="appendThreeYearsClaims(${count})">+</a>
// </div>
// </div>
// </div>
// `;
// // Append new claim fields
// let referenceDiv = document.getElementById('appendAreaForClaim_' + count);
// if (referenceDiv) {
// referenceDiv.insertAdjacentHTML('beforeend', claimsFields);
// } else {
// console.error('Element not found: appendAreaForClaim_' + count);
// }
// // Increment claim index
// console.log("claim index " + claimIndex);
// claimIndex++;
// console.log("after claim index " + claimIndex);
// if (policy_type_id == 1) {
// $('.gpaClaimFileds').show();
// $('.lifeClaimFields').hide();
// } else if (policy_type_id == 6 || policy_type_id == 7) {
// $('.gpaClaimFileds').hide();
// $('.lifeClaimFields').show();
// }
// // Initialize Select2 for the newly added fields
// $("#first_year_" + increment).select2();
// $("#claim_type_" + increment).select2();
// $("#first_cause_of_death_" + increment).select2();
// toggleRequiredFields();
// }
function appendThreeYearsClaims(count) {
// let count = $('#appendAreaForClaim').data('count');
console.log("count", count);
let policy_type_id = $('#policy_type_id_' + count).val()
console.log('policy_type_id', policy_type_id);
console.log('claimIndex from parent', claimIndex);
let increment = claimIndex;
let claimsFields = `
<div class="row claim-row">
<div class="form-group col-md-2">
<label for="first_year_${increment}">Year<span class="text-danger">*</span></label>
<select class="form-control first_year_" id="first_year_${increment}" name="first_year[]">
<option value="">Select Year</option>
<?php foreach ($lastFiveYears as $year) {
echo "<option value='$year'>$year</option>";
} ?>
</select>
</div>
<div class="form-group col-md-2">
<label for="emp_id_${increment}">Emp ID<span class="text-danger">*</span></label>
<input type="text" class="form-control" id="emp_id_${increment}" name="emp_id[]">
</div>
<div class="form-group col-md-2">
<label for="emp_name_${increment}">Employee Name<span class="text-danger">*</span></label>
<input type="text" class="form-control" id="emp_name_${increment}" name="emp_name[]">
</div>
<div class="form-group col-md-2">
<label for="gender_${increment}">Gender<span class="text-danger">*</span></label>
<select class="form-control" id="gender_${increment}" name="gender[]">
<option value="">Select Gender</option>
<option value="Female">Female</option>
<option value="Male">Male</option>
</select>
</div>
<div class="form-group col-md-2">
<label for="designation_${increment}">Designation <span class="text-danger">*</span></label>
<input type="text" class="form-control" id="designation_${increment}" name="designation[]">
</div>
<div class="form-group col-md-2">
<label for="sum_insured_${increment}">Sum Insured <span class="text-danger">*</span></label>
<input type="text" class="form-control" id="sum_insured_${increment}" name="sum_insured[]">
</div>
<div class="form-group col-md-2">
<label for="first_death_date_${increment}">Date of Death<span class="text-danger">*</span></label>
<div class="input-icon">
<input type="text" class="form-control death_date flatpickr-date" id="first_death_date_${increment}" name="first_death_date[]" autocomplete="off">
<i class="mdi mdi-calendar-blank-outline additional-icon"></i>
</div>
</div>
<div class="form-group col-md-2">
<label for="first_cause_of_death_${increment}">Nature/Cause Of Death <span class="text-danger">*</span></label>
<select class="form-control" id="first_cause_of_death_${increment}" name="first_cause_of_death[]">
<option value="">Select Cause of Death</option>
<?php foreach ($causeOfDeath as $cause => $death_value) {
echo "<option value='$cause'>$death_value</option>";
} ?>
</select>
</div>
<div class="form-group col-md-2">
<label for="first_claim_amount_${increment}">Claim/Settled Amount<span class="text-danger">*</span></label>
<input type="text" class="form-control" id="first_claim_amount_${increment}" name="first_claim_amount[]">
</div>
<!-- <div class="form-group col-md-2">
<label for="first_claim_status_${increment}">Claim Status<span class="text-danger">*</span></label>
<input type="text" class="form-control" id="first_claim_status_${increment}" name="first_claim_status[]">
</div> -->
<!-- <div class="form-group col-md-2 gpaClaimFileds" style="display:none;">
<label for="claim_type_${increment}">Claim Type<span class="text-danger">*</span></label>
<select class="form-control" id="claim_type_${increment}" name="claim_type[]">
<option value="">Select Claim Type</option>
<?php foreach ($gpaClaimType as $claimType => $claim_value) {
echo "<option value='$claimType'>$claim_value</option>";
} ?>
</select>
</div> -->
<div class="form-group col-md-2">
<div class="" style="position: relative; top: 28px; float: right; text-align: end;">
<a class="btn btn-danger waves-effect waves-light" onclick="removeClaim(this, ${count})">x</a>
<a class="btn btn-primary waves-effect waves-light mr-1" onclick="appendThreeYearsClaims(${count})">+</a>
</div>
</div>
</div>
`;
// Append new claim fields
let referenceDiv = document.getElementById('appendAreaForClaim_' + count);
if (referenceDiv) {
referenceDiv.insertAdjacentHTML('beforeend', claimsFields);
} else {
console.error('Element not found: appendAreaForClaim_' + count);
}
// Increment claim index
console.log("claim index " + claimIndex);
claimIndex++;
console.log("after claim index " + claimIndex);
if (policy_type_id == 1) {
$('.gpaClaimFileds').show();
$('.lifeClaimFields').hide();
} else if (policy_type_id == 6 || policy_type_id == 7) {
$('.gpaClaimFileds').hide();
$('.lifeClaimFields').show();
}
// Initialize Select2 for the newly added fields
$("#first_year_" + increment).select2();
$("#claim_type_" + increment).select2();
$("#first_cause_of_death_" + increment).select2();
$("#gender_" + increment).select2();
flatpickr('.flatpickr-date', {
dateFormat: 'd-m-Y', // Example format: 11-10-2025
allowInput: true, // Allow manual typing
maxDate: 'today', // Optional: disable future dates
});
toggleRequiredFields();
}
function removeClaim(btn, count) {
const container = document.getElementById('appendAreaForClaim_' + count);
const rows = container.querySelectorAll('.claim-row');
if (rows.length > 1) {
const row = btn.closest('.claim-row');
row.remove();
}
}
function leadTypeBsedHideAndShow(value, resetValues = false) {
if (value == 1) {
$('.btnDiv').show();
$('.claim-row').hide();
$('.emp_title_text').text('No of Employees')
$('.depnd_title_text').text('No of Dependents')
$('.total_title_text').text('Total Lives')
$('.renewalFields').find('select, input').removeAttr('required');
$('.renewalFields').hide();
$('.freshFields').find('select, input').attr('required', 'required');
$('.freshFields').show();
// $('.proposed_div').hide().find('select, input').removeAttr('required');
if (resetValues) {
$('#gst').val('');
$('#pan').val('');
$('#branch_name').val('');
$('#branch_code').val('');
$('#contact_person_name').val('');
$('#contact_person_mobile').val('');
$('#contact_person_email').val('');
$('#client_type').val('');
$('#client_name').val('');
$('#client_short_name').val('');
$('#entity_type_id').val('');
}
$('#exixting_client').removeAttr('required');
} else if (value == 3) {
$('.btnDiv').hide();
$('.claim-row').show();
$('.emp_title_text').text('No of Employees at Inception')
$('.depnd_title_text').text(' No of Dependents at Inception')
$('.total_title_text').text('Total Lives at Inception')
$('.freshFields').find('select, input').attr('required', 'required');
$('.freshFields').show();
$('.rolloOverFields').find('select, input').attr('required', 'required');
$('.renewalFields').show();
$('#source_policy_id').hide();
$('#source_policy_start_date').hide();
$('#source_policy_end_date').hide();
$('#source_policy_id').closest('.form-group').hide();
$('#source_policy_start_date').closest('.form-group').hide();
$('#source_policy_end_date').closest('.form-group').hide();
$('.source_policy_id').find('select, input').attr('required', 'required');
$('.source_policy_start_date').find('select, input').attr('required', 'required');
$('.source_policy_end_date').find('select, input').attr('required', 'required');
$('.rolloverhide').hide();
if (resetValues) {
$('#gst').val('');
$('#pan').val('');
$('#branch_name').val('');
$('#branch_code').val('');
$('#contact_person_name').val('');
$('#contact_person_mobile').val('');
$('#contact_person_email').val('');
$('#client_type').val('');
$('#client_name').val('');
$('#client_short_name').val('');
$('#entity_type_id').val('');
}
$('#exixting_client').removeAttr('required');
} else {
$('.btnDiv').hide();
$('.claim-row').show();
$('.emp_title_text').text('No of Employees at Inception')
$('.depnd_title_text').text(' No of Dependents at Inception')
$('.total_title_text').text('Total Lives at Inception')
$('.freshFields').find('select, input').removeAttr('required');
$('.freshFields').hide();
$('.renewalFields').show();
if (value != 3) {
$('.renewalFields').find('select, input').attr('required', 'required');
$("#source_policy_id").removeAttr("required");
$("#source_policy_start_date").removeAttr("required");
$("#source_policy_end_date").removeAttr("required");
$('#source_policy_id').show();
$('#source_policy_start_date').show();
$('#source_policy_end_date').show();
$('#source_policy_id').closest('.form-group').show();
$('#source_policy_start_date').closest('.form-group').show();
$('#source_policy_end_date').closest('.form-group').show();
} else {
$('#source_policy_id').hide();
$('#source_policy_start_date').hide();
$('#source_policy_end_date').hide();
$('#source_policy_id').closest('.form-group').hide();
$('#source_policy_start_date').closest('.form-group').hide();
$('#source_policy_end_date').closest('.form-group').hide();
}
// $('.proposed_div').show().find('select, input').attr('required', 'required');
$('#policy_end_date').removeAttr('required');
$('#policy_start_date').removeAttr('required');
$('#claims').removeAttr('required');
$('#source_policy_start_date').attr('readonly', 'readonly');
$('#source_policy_end_date').attr('readonly', 'readonly');
console.log('readonly set', $('#source_policy_start_date').prop('readonly')); // should print true
if (resetValues) {
$('#gst').val('');
$('#pan').val('');
$('#branch_name').val('');
$('#branch_code').val('');
$('#contact_person_name').val('');
$('#contact_person_mobile').val('');
$('#contact_person_email').val('');
}
}
toggleRequiredFields();
}
function toggleRequiredFields() {
try {
$('.claim-row').each(function() {
var isRowHidden = $(this).css('display') === 'none';
$(this).find('.form-group').each(function() {
var input = $(this).find('input, select');
if (input.attr('name') === "gender[]") {
return;
}
if (input.length === 0) {
console.warn('No input/select fields found in:', this);
return;
}
// Remove required if row is hidden, otherwise check field visibility
input.prop('required', !isRowHidden && $(this).css('display') !== 'none');
});
});
} catch (error) {
console.error('Error in toggleRequiredFields:', error);
}
}
function updateRenewalFields(increment) {
console.log('updateRenewalFields function called');
$(".renewalCalculation input, .renewalCalculation select").each(function() {
let oldId = $(this).attr("id");
if (oldId) {
let newId = oldId + "_" + increment;
$(this).attr("id", newId);
}
});
}
$('#exixting_client').change(function() {
$('#contact_person_summary').empty();
$('#contact_person_summary').append($('<option>', {
value: "",
text: "Select a Contact"
}));
$("#gst").val("");
$("#pan").val("");
$("#branch_name").val("");
$("#branch_code").val("");
$("#contact_person_name").val("");
$("#contact_person_mobile").val("");
$("#contact_person_email").val("");
// Fresh fields
$("#client_type").prop("selectedIndex", 0);
$("#entity_type_id").prop("selectedIndex", 0);
$("#client_name").val("");
$("#client_short_name").val("");
// Renewal fields
$("#client_id").select2();
$("#client_branch_id").select2();
if ($(this).is(':checked')) {
$('#client_id').closest('.form-group').show();
$('#client_branch_id').closest('.form-group').show();
$('#contact_person_summary').closest('.form-group').show();
$('#client_type').addClass('readonly-select');
$('#entity_type_id').addClass('readonly-select');
$("#client_name").prop('readonly', true);
$("#client_short_name").prop('readonly', true);
$("#client_id").prop("required", true);
$("#client_branch_id").prop("required", true);
$("#contact_person_summary").prop("required", true);
$("#contact_person_name").prop("required", false);
$('#contact_person_name').closest('.form-group').hide();
$("#client_name").prop("required", false);
$('#client_name').closest('.form-group').hide();
} else {
$('#client_id').closest('.form-group').hide();
$('#client_branch_id').closest('.form-group').hide();
$('#contact_person_summary').closest('.form-group').hide();
$('#client_type').removeClass('readonly-select');
$('#entity_type_id').removeClass('readonly-select');
$("#client_name").prop('readonly', false);
$("#client_short_name").prop('readonly', false);
$("#client_id").prop("required", false);
$("#client_branch_id").prop("required", false);
$("#contact_person_summary").prop("required", false);
$("#contact_person_name").prop("required", true);
$('#contact_person_name').closest('.form-group').show();
$("#client_name").prop("required", true);
$('#client_name').closest('.form-group').show();
}
});
$(document).ready(function() {
var actual_lead_client_details = <?= json_encode($actual_lead_client_details ?? null) ?>;
var actual_lead_contact_person_details = <?= json_encode($actual_lead_contact_person_details ?? null) ?>;
// -------------------------------
// CLIENT DETAILS AUTO FILL
// -------------------------------
if (actual_lead_client_details) {
actualLeadClientName = actual_lead_client_details.company_name || '';
$('#client_name').val(actualLeadClientName);
$('#gst').val(actual_lead_client_details.gst_number || '');
if (actual_lead_client_details.client_type !== undefined && actual_lead_client_details.client_type !== null && actual_lead_client_details.client_type !== '') {
$('#client_type').val(String(actual_lead_client_details.client_type));
}
// existingShortName = actual_lead_client_details.short_name || '';
// if (existingShortName) {
// // ── Short name EXISTS — just populate and validate ────────
// $('#client_short_name').val(existingShortName);
// // validateInput($('#client_short_name')[0], 'clients', 'short_name');
// } else { }
// Auto-generate short name from company name
// Use a small delay to ensure DOM is ready
setTimeout(function () {
let baseName = actual_lead_client_details.company_name
.trim()
.substring(0, 10)
.replace(/\s+/g, '')
.toUpperCase();
makeUniqueShortName(baseName);
}, 300);
}
// Auto-generate short name from client name on user input.
$('#client_name').on('input', function() {
let clientName = $(this).val();
if (clientName.trim() !== '') {
let baseName = clientName
.trim()
.substring(0, 10)
.replace(/\s+/g, '')
.toUpperCase();
makeUniqueShortName(baseName);
} else {
$('#client_short_name').val('').parsley().reset();
}
});
// Keep short name variable in sync if it's generated or changed
$('#client_short_name').on('input change', function() {
if ($('#actual_lead_id').val() && $('#actual_lead_id').val() != 0) {
actualLeadShortName = $(this).val();
}
});
// -------------------------------
// CONTACT PERSON AUTO FILL
// -------------------------------
if (actual_lead_contact_person_details) {
$('#contact_person_name').val(actual_lead_contact_person_details.name || '');
$('#contact_person_mobile').val(actual_lead_contact_person_details.mobile || '');
$('#contact_person_email').val(actual_lead_contact_person_details.email || '');
}
$('#lead_status').change(function() {
if ($(this).val() === 'lost') {
$('#lost_reason_div').show();
$('#lost_reason').attr('required', 'required');
} else {
$('#lost_reason_div').hide();
$('#lost_reason').val("");
$('#lost_reason').removeAttr('required');
}
});
// Check on page load
if ($('#lead_status').val() === 'lost') {
$('#lost_reason_div').show();
$('#lost_reason').attr('required', 'required');
} else {
// Ensure it's hidden and not required if the initial value is not 'lost'
$('#lost_reason_div').hide();
$('#lost_reason').val("");
$('#lost_reason').removeAttr('required');
}
});
//-----------------------------------------------------------------------------------------------------------
</script>