nhance/app/Views/client_branch.php

1429 lines
53 KiB
PHP
Executable File
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

<style>
/* Hide the dropdown list */
/* .select2-container--default .select2-dropdown {
display: none;
} */
.select2-hidden-accessible + .select2-container .select2-dropdown {
display: none !important;
}
.select2-container .select2-selection--multiple .select2-selection__choice {
color: #000000;
}
/* .select2-search__field{
height: 2px !important;
} */
.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>
.cards {
display: inline-block;
margin: 5px;
padding: 10px;
background-color: #f8f9fa;
border: 1px solid #ced4da;
border-radius: 4px;
}
.cards button {
background: none;
border: none;
color: red;
font-size: 16px;
cursor: pointer;
}
</style>
<style>
.switch-branch-contact {
position: relative;
display: inline-block;
width: 54px;
height: 34px;
}
.switch-branch-contact input {
opacity: 0;
width: 0;
height: 0;
}
.slider-branch-contact {
position: absolute;
cursor: pointer;
top: 0;
left: 0;
right: 0;
bottom: 0;
background-color: #ccc;
-webkit-transition: .4s;
transition: .4s;
}
.slider-branch-contact:before {
position: absolute;
content: "";
height: 19px;
width: 19px;
left: 4px;
bottom: 4px;
background-color: white;
-webkit-transition: .4s;
transition: .4s;
}
input:checked + .slider-branch-contact {
background-color: #00999E;
}
input:focus + .slider-branch-contact {
box-shadow: 0 0 1px #00999E;
}
input:checked + .slider-branch-contact:before {
-webkit-transform: translateX(26px);
-ms-transform: translateX(26px);
transform: translateX(26px);
}
/* Rounded sliders */
.slider-branch-contact.round-branch-contact {
border-radius: 34px;
}
.slider-branch-contact.round-branch-contact:before {
border-radius: 50%;
}
</style>
<div class="tab-pane fade" id="branch-tab">
<input type="hidden" id="client_id_for_client_branch" value="<?= isset($client['id']) ? $client['id'] : '' ?>" />
<div class="row float-right" style="padding-bottom: 10px;position: relative;right: 13px;">
<button type="button" id="btnBranchAdd" class="btn btn-primary waves-effect waves-light btn-sm"><span
class="mdi mdi-plus-box-outline" aria-hidden="true" style="padding: 5px 10px;"></span>Add Branch</button>
</div>
<div class="table-responsive" id="branch_table">
<table data-custom-table-css="table" class="table table-borderless table-nowrap mb-0">
<thead class="">
<tr>
<th>Branch Name</th>
<th>Branch Code</th>
<th>Action</th>
</tr>
</thead>
<tbody id="branch_list">
<tr id="branch_no_data_row">
<td colspan="3" class="text-center">No data available</td>
</tr>
</tbody>
</table>
</div>
<div class="row" id="add_branch">
<div class="col-12">
<div class="card-body">
<div class="row float-left" style="position: relative; bottom: 20px; left: 13px;">
<button type="button" id="btnAutoBranchFetch"
class="btn btn-primary waves-effect waves-light btn-sm ">Fetch Client Branch (Pre-Enrolment)</button>
</div>
<div class="row float-right" style="position: relative; bottom: 20px; right: 13px;">
<button type="button" id="btnBranchBack"
class="btn btn-primary waves-effect waves-light btn-sm btnBack"><span class="mdi mdi-format-list-bulleted"
aria-hidden="true" style="padding: 5px 10px;"></span>Back To List</button>
</div>
<hr>
<form role="form" class="parsley-examples" method="post" id="branch_form" enctype="multipart/form-data">
<input type="hidden" class="form-control" value="<?= csrf_hash() ?>" name="<?= csrf_token() ?>" />
<!-- post_client_id as client_id -->
<input type="hidden" name="client_id" id="client_id_branch"
value="<?= isset($client['id']) ? $client['id'] : '' ?>" />
<!-- pre_branch_id -->
<input type="hidden" name="pre_branch_id" id="pre_branch_id"
value="<?= isset($pre_branch_id) ? $pre_branch_id : '' ?>" />
<!-- post_branch_id as branch_id_primarykey -->
<input type="hidden" name="branch_id_primarykey" id="branch_id_primarykey" />
<div class="form-group">
<div class="form-row">
<div class="form-group col-md-6">
<label for="branch_name">Branch Name<span class="text-danger">*</span></label>
<input type="text" class="form-control" id="branch_name" placeholder="Enter Branch Name"
name="branch_name" required data-parsley-minlength="3"
data-parsley-pattern="^[a-zA-Z0-9\\s_-]+$"
data-parsley-pattern-message="Branch Name can contain letters, numbers, spaces, underscore (_) and hyphen (-).">
</div>
<div class="form-group col-md-6">
<label for="branch_code">Branch Code<span class="text-danger">*</span></label>
<input type="text" class="form-control" id="branch_code" placeholder="Enter Branch Code"
name="branch_code" onchange="setDefaultUnitValue(this)" required
data-parsley-pattern="^[a-zA-Z0-9_-]+$"
data-parsley-pattern-message="Branch Code can contain letters, numbers, underscore (_) and hyphen (-).">
</div>
</div>
<div class="form-row">
<div class="form-group col-md-6">
<label for="address1">Address Line 1<span class="text-danger">*</span></label>
<input type="text" class="form-control" id="address1" name="address1" placeholder="Enter Address 1" required>
</div>
<div class="form-group col-md-6">
<label for="address2">Address Line 2<span class="text-danger"></span></label>
<input type="text" class="form-control" id="address2" placeholder="Enter Address 2" name="address2">
</div>
</div>
<div class="form-row">
<div class="form-group col-md-3">
<label for="state">State<span class="text-danger">*</span></label>
<select class="form-control" id="state" name="state" required>
<option value="">Select State</option>
<?php foreach($state as $value) { ?>
<option value="<?= $value['id'] ?>"><?= $value['state'] ?></option>
<?php } ?>
</select>
</div>
<div class="form-group col-md-3">
<label for="district">District<span class="text-danger">*</span></label>
<input type="text" class="form-control" id="district" placeholder="Enter District"
name="district" required
data-parsley-pattern="^[a-zA-Z0-9\\s-]+$"
data-parsley-pattern-message="District can contain letters, numbers, spaces, and hyphens.">
</div>
<div class="form-group col-md-3">
<label for="city">City<span class="text-danger">*</span></label>
<input type="text" class="form-control" id="branch_city" placeholder="Enter City"
name="city" required
data-parsley-pattern="^[a-zA-Z0-9\\s-]+$"
data-parsley-pattern-message="City can contain letters, numbers, spaces, and hyphens.">
</div>
<div class="form-group col-md-3">
<label for="gst">Pincode<span class="text-danger">*</span></label>
<input type="text" class="form-control" id="pincode" placeholder="Enter Pincode" name="pincode"
maxlength="6" required data-parsley-pattern="^[0-9]{6}$"
data-parsley-pattern-message="Pincode must be exactly 6 digits.">
</div>
</div>
<div class="form-row">
<div class="form-group col-md-4">
<label for="gst">GST<span class="text-danger">*</span></label>
<input type="text" name="gst" class="form-control" id="gst" placeholder="Enter GST Number" data-parsley-error-message="Invalid GST Number format." data-parsley-trigger="change" data-parsley-pattern="^\d{2}[A-Z]{5}\d{4}[A-Z]{1}[A-Z\d]{1}Z[A-Z\d]{1}$" required>
</div>
<div class="form-group col-md-4">
<label for="state">Units<span class="text-danger"></span></label>
<select id="selected" class="form-control" multiple="multiple" name="units[]" >
</select>
</div>
<div class="form-group col-md-4">
<label class="switch-branch-contact" style="position: relative;top: 43px;left: 20px;">
<input id="sez" type="checkbox" name="sez">
<span class="slider-branch-contact round-branch-contact" style="height: 27px;"></span>
</label>
<label for="sez" style="position: relative;bottom: 5px;left: 85px;">Enable SEZ</label>
</div>
</div>
<hr>
<div class="form-row">
<div class="form-group col-md-6">
<label>Contact 1</label>
</div>
</div>
<div class="form-row">
<input type="hidden" name="branch_table_pk[]" id="branch_table_pk" >
<div class="form-group col-md-6">
<label for="first_name">Name<span class="text-danger">*</span></label>
<input value="" type="text" class="form-control" placeholder="Enter Contact Name"
name="name[]" id="name" required
data-parsley-pattern="^[A-Za-z\s]+$"
data-parsley-pattern-message="Contact name may contain only letters and spaces.">
</div>
<div class="form-group col-md-6">
<label for="designation">Designation<span class="text-danger">*</span></label>
<input value="" type="text" class="form-control" placeholder="Enter Designation Name"
name="designation[]" id="designation" required
pattern="[A-Za-z0-9\-_/ ]+"
data-parsley-pattern="^[A-Za-z0-9\\-_\\/ ]+$"
data-parsley-pattern-message="Designation may only contain letters, numbers, /, -, _ and spaces."
oninput="this.value = this.value.replace(/[^A-Za-z0-9\-_\/ ]/g, '')"
title="Designation may only contain letters, numbers, /, -, _ and spaces only allowed">
</div>
</div>
<div class="form-row">
<div class="form-group col-md-6">
<label for="last_name">Email<span class="text-danger">*</span></label>
<input value="" type="text" class="form-control" placeholder="Enter Contact Email"
name="email[]" id="email" data-parsley-trigger="change"
data-parsley-pattern="^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$"
data-parsley-pattern-message="Please enter a valid email format (e.g., name@domain.com)."
onchange="validateDuplicateByClientBranch(this, 'email','branchBtnSubmit')" required>
</div>
<div class="form-group col-md-6">
<label for="mobile">Mobile<span class="text-danger">*</span></label>
<input value="" type="text" class="form-control" placeholder="Enter Contact Mobile"
name="mobile[]" id="mobile"
onchange="validateDuplicateByClientBranch(this, 'mobile','branchBtnSubmit')"
onkeypress="return onlyNumbers(event)" maxlength="10" minlength="10"
data-parsley-pattern="^[0-9]{10}$"
data-parsley-pattern-message="Mobile number must be exactly 10 digits."
data-parsley-required-message="Mobile number must be exactly 10 digits."
required>
</div>
</div>
<div class="form-group" style="display: flex;">
<button style="margin-right: 10px;" type="button" class="btn btn-primary btn-sm ac"
onclick="appendContactHtml()" id="add">Add Contact</button>
<button type="button" class="btn btn-danger btn-sm" onclick="removeContact(this)"
id="remove_btn">Remove</button>
</div>
<div id="container"></div>
</div>
<div class="form-group text-right m-b-0">
<button type="submit" class="btn btn-primary waves-effect waves-light mr-1"
id="branchBtnSubmit">Submit</button>
<button type="button" class="btn btn-secondary waves-effect btnBack"
id="btnBack">Cancel</button>
</div>
</form>
</div>
</div>
</div> <!-- end col-->
</div>
<!-- end -->
<script>
var branch_form_action = '';
var contactCount = 1;
var branch_PrimaryKey = $('#client_id_for_client_branch').val();
function ensureBranchNoDataRow() {
const branchList = $('#branch_list');
const hasDataRows = branchList.find('tr').not('#branch_no_data_row').length > 0;
if (hasDataRows) {
$('#branch_no_data_row').remove();
} else if ($('#branch_no_data_row').length === 0) {
branchList.append('<tr id="branch_no_data_row"><td colspan="3" class="text-center">No data available</td></tr>');
}
}
$(document).ready(function() {
branch_PrimaryKey = $('#client_id_branch').val();
$('#add_branch').hide();
$('.btnBack').hide();
if (branch_PrimaryKey !== '') {
var branchTable = '';
var data = <?= isset($client_branch) ? json_encode($client_branch) : '[]' ?>;
console.log('branch data', data)
var role = data.role
delete data.role;
console.log(role)
$.each(data, function(index, item) {
if(role != 3 && role != 4){
branchTable += `
<tr>
<td>${item.branch_name}</td>
<td>${item.branch_code}</td>
<td>
<a class="mdi mdi-lead-pencil btnBranchEdit" href="#" data-id="${item.id}" style="font-size:18px;"></a>
<a style="color:#02a8b5" data-id="${item.id}" onclick="removeClientBranch(this)"><i data-id="${item.id}" class="mdi mdi-delete" style="font-size:18px;"></i></a>
</td>
</tr>
`;
}else{
branchTable += `
<tr>
<td>${item.branch_name}</td>
<td>${item.branch_code}</td>
<td>
<a class="mdi mdi-lead-pencil btnBranchEdit" href="#" data-id="${item.id}" style="font-size:18px;"></a>
</td>
</tr>
`;
}
});
$('#branch_list').append(branchTable);
ensureBranchNoDataRow();
}
ensureBranchNoDataRow();
});
$('#btnBranchAdd').click(function() {
branch_form_action = '<?= base_url("client/branch/create"); ?>';
$('#add_branch').show();
$('#branch_table').hide();
$('.btnBack').show();
$('#btnBranchAdd').hide();
$('#branch_name').val('');
$('#branch_code').val('');
$('#state').val('');
$('#district').val('');
$('#branch_city').val('');
$('#branch_form')[0].reset();
$('#branch_form').parsley().reset();
$('#pre_branch_id').val('');
$('#branch_id_primarykey').val('');
$('.ac').css('display', 'block');
contactCount = 1
var addButton = document.getElementById('add');
if (addButton.style.display === 'none') {
addButton.style.display = 'block';
}
var buttonIds = JSON.parse(localStorage.getItem('buttonIds')) || [];
for (var i = 0; i < buttonIds.length; i++) {
var firstElement = buttonIds[i].split('_')[0];
console.log(firstElement);
// Find the element by its ID
var elementToRemove = document.getElementById(firstElement);
console.log(elementToRemove);
if (elementToRemove) {
console.log(elementToRemove);
elementToRemove.parentNode.removeChild(elementToRemove);
}
localStorage.removeItem('buttonIds')
}
})
$('.btnBack').click(function() {
$('#add_branch').hide();
$('#branch_table').show();
$('.btnBack').hide();
$('#btnBranchAdd').show();
$('#branch_name').val('');
$('#branch_code').val('');
$('#state').val('');
$('#district').val('');
$('#branch_city').val('');
$('#branch_form')[0].reset();
$('.ac').css('display', 'block');
$('.parsley-errors-list').remove();
$('#branch_form').parsley().reset();
contactCount = 1
var buttonIds = JSON.parse(localStorage.getItem('buttonIds')) || [];
for (var i = 0; i < buttonIds.length; i++) {
var firstElement = buttonIds[i].split('_')[0];
console.log(firstElement);
// Find the element by its ID
var elementToRemove = document.getElementById(firstElement);
console.log(elementToRemove);
if (elementToRemove) {
console.log(elementToRemove);
elementToRemove.parentNode.removeChild(elementToRemove);
}
}
window.scrollTo({ top: 0, behavior: 'smooth' });
})
$("#branch_form").submit(function(event) {
var selectedValues = $("#selected").val();
console.log(selectedValues, selectedValues);
console.log("branch_id_primarykey", $('#branch_id_primarykey').val());
let level_contect_data = getContactsData();
console.log('level_contect_data', level_contect_data);
event.preventDefault();
branch_PrimaryKey = $('#client_id_branch').val();
console.log('branch_PrimaryKey', branch_PrimaryKey)
if (branch_PrimaryKey === '') {
toastr.error('Client is required', 'Error');
$('#insurer').val('');
$('#tpa').val('');
$('#policy').html('<option value="" selected>Select Policy</option>');
return;
}
var isValid = $('#branch_form').parsley().validate();
if (isValid) {
$('.loader').fadeIn();
$('.loader-mask').fadeIn();
var formData = new FormData($('#branch_form')[0]);
const jsonString = JSON.stringify(selectedValues);
const level_contect_data_json_string = JSON.stringify(level_contect_data);
console.log('jsonString', jsonString);
console.log('level_contect_data_json_string', level_contect_data_json_string);
// Append the JSON string to the FormData object
formData.append('units', jsonString);
formData.append('level_contect_data', level_contect_data_json_string);
$.ajax({
data: formData,
url: branch_form_action,
type: "POST",
dataType: 'json',
processData: false,
contentType: false,
success: function(res) {
console.log('client branch submit response', res)
if (res) {
setTimeout(function() {
$('.loader').fadeOut();
$('.loader-mask').delay(350).fadeOut('slow');
$('#add_branch').hide();
$('#branch_table').show();
$('.btnBack').hide();
$('#btnBranchAdd').show();
if(res.status == false){
toastr.error(res.message, 'Error');
}else{
toastr.success(res.message, 'Success');
newBranchSavedPeaseCallTheHrAccessFormApi = true;
}
// var message = (branch_PrimaryKey === '') ?
// 'Client Branch Created successfully' :
// 'Client Branch Updated successfully';
// toastr.success(message, 'Success');
}, 800);
}
$('#branch_list tr').remove();
var branchTableInsert = ''
var role = res.data.role
delete res.data.role;
console.log(role)
$.each(res.data, function(index, item) {
// console.log('client_branch_data', item)
if(role != 3 && role != 4){
branchTableInsert += `
<tr>
<td>${item.branch_name}</td>
<td>${item.branch_code}</td>
<td>
<a class="mdi mdi-lead-pencil btnBranchEdit" href="#" data-id="${item.id}" style="font-size:18px;"></a>
<a style="color:#02a8b5" data-id="${item.id}" onclick="removeClientBranch(this)"><i data-id="${item.id}" class="mdi mdi-delete" style="font-size:18px;"></i></a>
</td>
</tr>
`;
}else{
branchTableInsert += `
<tr>
<td>${item.branch_name}</td>
<td>${item.branch_code}</td>
<td>
<a class="mdi mdi-lead-pencil btnBranchEdit" href="#" data-id="${item.id}" style="font-size:18px;"></a>
</td>
</tr>
`;
}
});
$('#branch_list').append(branchTableInsert);
ensureBranchNoDataRow();
},
error: function(xhr, status, error) {
console.error(xhr.responseText);
console.error(status, error);
setTimeout(function() {
$('.loader').fadeOut();
$('.loader-mask').delay(350).fadeOut('slow');
console.log('Something Wrong!', 'warning');
if(xhr.status === 409){
alert('The Current Branch is Already Existing..!!');
}
else 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) {
// Only add the message if it hasn't been seen before
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');
}
}, 300);
},
complete: function() {
console.log('Ajax request completed');
window.scrollTo({ top: 0, behavior: 'smooth' });
}
});
}
contactCount = 1
});
$('body').on('click', '.btnBranchEdit', function() {
var buttonIds = JSON.parse(localStorage.getItem('buttonIds')) || [];
for (var i = 0; i < buttonIds.length; i++) {
var firstElement = buttonIds[i].split('_')[0];
console.log(firstElement);
// Find the element by its ID
var elementToRemove = document.getElementById(firstElement);
console.log(elementToRemove);
if (elementToRemove) {
console.log(elementToRemove);
elementToRemove.parentNode.removeChild(elementToRemove);
}
localStorage.removeItem('buttonIds')
}
contactCount = 1
$('.loader').fadeIn();
$('.loader-mask').fadeIn();
var branch_id = $(this).attr('data-id');
$('#branch_id_primarykey').val(branch_id);
branch_form_action = '<?= base_url("client/branch/edit"); ?>';
$.ajax({
url: '<?php echo base_url('client/branch/list/');?>' + branch_id,
type: "GET",
dataType: 'json',
success: function(res) {
console.log('branch response', res);
setTimeout(function() {
$('.loader').fadeOut();
$('.loader-mask').delay(350).fadeOut('slow');
}, 500);
$('#add_branch').show();
$('#branch_table').hide();
$('.btnBack').show();
$('#btnBranchAdd').hide();
$('#branch_name').val(res.data.branch_name);
$('#branch_code').val(res.data.branch_code);
$('#pincode').val(res.data.pincode);
$('#address1').val(res.data.address1);
$('#address2').val(res.data.address2);
$('#gst').val(res.data.gst);
$('#state option[value="' + res.data.state + '"]').prop('selected', true);
$('#district').val(res.data.district);
$('#branch_city').val(res.data.city);
$('#branch_PrimaryKey').val(res.data.id);
$('#pre_branch_id').val(res.data.pre_branch_id??'')
if(res.data.sez == 1){
$('#sez').prop('checked', true);
}else{
$('#sez').prop('checked', false);
}
appendOption(res.data.units)
// $('#branch_table_pk').val(res.contact[0].id);
// $('#name').val(res.contact[0].name);
// $('#email').val(res.contact[0].email);
// $('#mobile').val(res.contact[0].mobile);
// $('#designation').val(res.contact[0].designation);
if (res.contact && res.contact.length > 0 && res.contact[0]) {
$('#branch_table_pk').val(res.contact[0].id || '');
$('#name').val(res.contact[0].name || '');
$('#email').val(res.contact[0].email || '');
$('#mobile').val(res.contact[0].mobile || '');
$('#designation').val(res.contact[0].designation || '');
} else {
$('#branch_table_pk').val('');
$('#name').val('');
$('#email').val('');
$('#mobile').val('');
$('#designation').val('');
}
res.contact.shift();
// console.log(res.contact.length)
for (let index = 0; index < res.contact.length; index++) {
const contact = res.contact[index];
if (contact !== undefined) {
appendContactHtml(contact);
}
}
},
error: function(xhr, status, error) {
console.error(xhr.responseText);
console.error(status, error);
setTimeout(function() {
$('.loader').fadeOut();
$('.loader-mask').delay(350).fadeOut('slow');
toastr.warning('Something Wrong!', 'Warning');
}, 1000);
}
});
console.log(branch_form_action);
});
// $("#remove_btn").click(function() {
// $("#name").val('');
// $("#email").val('');
// $("#mobile").val('');
// $("#designation").val('');
// })
// Initialize the contact count
function appendContactHtml(contact = false, reset = false) {
console.log('appendContactHtml function called ')
contactCount++;
var container = document.getElementById('container');
var uniqueId = Date.now().toString();
var html = `
<div id="${uniqueId}">
<hr>
<div class="form-row">
<div class="form-group col-md-6">
<label>Contact ${contactCount}</label>
</div>
</div>
<div class="form-row">
<input type="hidden" name="branch_table_pk[]" id="${uniqueId}_branch_table_pk" value="${contact !== undefined && contact !== false ? contact.id : ''}">
<div class="form-group col-md-6">
<label for="${uniqueId}_first_name">Name<span class="text-danger">*</span></label>
<input value="${contact !== undefined && contact !== false ? contact.name : ''}" type="text" class="form-control" placeholder="Enter Contact Name" name="name[]" id="${uniqueId}_name" required
data-parsley-pattern="^[A-Za-z\\s]+$"
data-parsley-pattern-message="Contact name may contain only letters and spaces.">
</div>
<div class="form-group col-md-6">
<label for="${uniqueId}_designation">Designation<span class="text-danger">*</span></label>
<input value="${contact !== undefined && contact !== false ? contact.designation : ''}" type="text" class="form-control" placeholder="Enter Designation Name" name="designation[]" id="${uniqueId}_designation" required
pattern="[A-Za-z0-9\-_/ ]+"
data-parsley-pattern="^[A-Za-z0-9\\-_\\/ ]+$"
data-parsley-pattern-message="Designation may only contain letters, numbers, /, -, _ and spaces."
oninput="this.value = this.value.replace(/[^A-Za-z0-9\-_\/ ]/g, '')"
title="Designation may only contain letters, numbers, /, -, _ and spaces only allowed">
</div>
</div>
<div class="form-row">
<div class="form-group col-md-6">
<label for="${uniqueId}_last_name">Email<span class="text-danger">*</span></label>
<input value="${contact !== undefined && contact !== false ? contact.email : ''}" type="text" class="form-control" placeholder="Enter Contact Email" name="email[]" id="${uniqueId}_email" data-parsley-trigger="change" data-parsley-pattern="^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}$" data-parsley-pattern-message="Please enter a valid email format (e.g., name@domain.com)." onchange="validateDuplicateByClientBranch(this, 'email', 'branchBtnSubmit')" required>
</div>
<div class="form-group col-md-6">
<label for="${uniqueId}_mobile">Mobile<span class="text-danger">*</span></label>
<input value="${contact !== undefined && contact !== false ? contact.mobile : ''}" type="text" class="form-control" placeholder="Enter Contact Mobile" name="mobile[]" id="${uniqueId}_mobile" onchange="validateDuplicateByClientBranch(this, 'mobile', 'branchBtnSubmit')" onkeypress = "return onlyNumbers(event)" maxlength="10" minlength="10" data-parsley-pattern="^[0-9]{10}$" data-parsley-pattern-message="Mobile number must be exactly 10 digits." data-parsley-required-message="Mobile number must be exactly 10 digits." required>
</div>
</div>
<div class="form-group" style="display: flex;">
<button style="margin-right: 10px;" type="button" class="btn btn-primary btn-sm ac" onclick="appendContactHtml()" id="${uniqueId}_add">Add Contact</button>
<button type="button" class="btn btn-danger btn-sm" onclick="removeContact(this)" id="${uniqueId}_remove">Remove</button>
</div>
</div>
`;
if (reset == false) {
console.log(reset)
container.insertAdjacentHTML('beforeend', html);
storeButtonId(uniqueId + '_add');
if (contactCount >= 3) {
hideStoredAddButtons();
}
}
}
// function removeContact(button) {
// var uniqueId = button.id.split("_")[0];
// var contactSection = document.getElementById(uniqueId);
// if (contactSection) {
// contactSection.parentNode.removeChild(contactSection);
// contactCount--;
// if (contactCount < 3) {
// var addButton = document.querySelector('.ac');
// if (addButton) {
// addButton.style.display = 'block';
// }
// }
// }
// }
function removeContact(button) {
var uniqueId = button.id.split("_")[0];
console.log('uniqueId', uniqueId);
var contactSection = document.getElementById(uniqueId);
console.log('contactSection', contactSection);
confirmActionSweertAlert("Do you want to remove this contact?", "Yes, Proceed!", "No, Cancel").then((confirmed) => {
if(confirmed){
if (contactSection) {
let unique_param = uniqueId + '_branch_table_pk';
console.log('unique_param', unique_param);
let other_id = $('#' + unique_param).val();
console.log('other_id', other_id);
contactSection.parentNode.removeChild(contactSection);
contactCount--;
if (contactCount < 3) {
var addButton = document.querySelector('.ac');
if (addButton) {
addButton.style.display = 'block';
}
}
if(other_id){
removeLevelContacts(other_id);
}
}else{
$("#name").val('');
$("#email").val('');
$("#mobile").val('');
$("#designation").val('');
let first_id = $('#branch_table_pk').val();
console.log('first_id', first_id);
if(first_id){
removeLevelContacts(first_id);
}
}
}
});
}
function storeButtonId(id) {
var buttonIds = JSON.parse(localStorage.getItem('buttonIds')) || [];
buttonIds.push(id);
localStorage.setItem('buttonIds', JSON.stringify(buttonIds));
}
function hideStoredAddButtons() {
var storedIds = JSON.parse(localStorage.getItem('buttonIds')) || [];
storedIds.forEach(function(id) {
var addButton = document.getElementById(id);
var first_addButton = document.querySelector('.ac')
if (addButton) {
addButton.style.display = 'none';
first_addButton.style.display = 'none';
}
});
}
function showNextAddButton() {
var storedIds = JSON.parse(localStorage.getItem('buttonIds')) || [];
var addButtonShown = false;
// Iterate through the stored IDs to find the next "Add" button to show
storedIds.forEach(function(id) {
if (!addButtonShown) {
var addButton = document.getElementById(id);
if (addButton && addButton.style.display === 'none') {
addButton.style.display = 'block';
addButtonShown = true; // Set to true once an "Add" button is shown
}
}
});
}
function validateForm() {
var isValid = true;
$('#branch_form input, #branch_form select').each(function() {
if ($(this).is('input[type="text"]') || $(this).is('select')) {
if ($.trim($(this).val()) == '') {
isValid = false;
return false;
}
}
});
return isValid;
}
function onlyNumbers(event) {
var charcode;
charcode = event.which || event.keyCode;
if (charcode >= 48 && charcode <= 57) return true;
return false;
}
function removeClientBranch(element) {
Swal.fire({
title: "Are you sure?",
text: "You need to remove this client branch.",
icon: "info",
showCancelButton: true,
confirmButtonColor: "#3085d6",
confirmButtonText: "Yes",
}).then((result) => {
if (result.isConfirmed) {
var id = element.getAttribute('data-id');
var form_action = '<?= base_url("client/branch/remove/") ?>' + id;
$.ajax({
url: form_action,
type: "GET",
dataType: 'json',
processData: false,
contentType: false,
success: function(res) {
// console.log(res.status == true);
if (res) {
if (res.status == true) {
toastr.success(res.message, 'Success');
location.reload();
} else {
toastr.warning(res.message, 'Warning');
}
}
},
error: function(xhr, status, error) {
console.error(xhr.responseText);
console.error(status, error);
setTimeout(function() {
$('.loader').fadeOut();
$('.loader-mask').delay(350).fadeOut('slow');
console.log('Something Wrong!', 'warning');
}, 1000);
}
});
}
});
}
function checkMobileNumber(input) {
console.log('function called')
console.log(input);
console.log('Input Value', input.value);
var mobileNumber = input.value;
var url = '<?php echo base_url('util/checkHRNumber/') ?>' + mobileNumber;
$.get(url, function(response) {
console.log(response)
console.log(response.data)
if (response.data > 0) {
toastr.warning('The Mobile Number Already Exist.', 'Warning');
input.value = "";
return;
}
}).fail(function(xhr, status, error) {
console.error(xhr.responseText);
console.error(status, error);
});
}
// function generateShortName() {
// let clientName = $("#client_name").val().trim();
// if (clientName.length > 0) {
// let shortName = clientName.substring(0, 10).replace(/\s+/g, '').toUpperCase(); // Take first 10 chars , space removed, converted caps
// $("#short_name").val(shortName);
// makeUniqueShortName(shortName);
// }else{
// $("#short_name").val('');
// }
// }
let shortNameTimer;
$("#client_name").on("input change keyup", function() {
clearTimeout(shortNameTimer); // cancel previous call
shortNameTimer = setTimeout(() => {
generateShortName(); // only runs after 200ms pause
}, 200); // adjust debounce delay as needed
});
function generateShortName() {
let clientInput = $("#client_name");
let shortInput = $("#short_name");
let oldClientName = clientInput.data("old-name"); // from DB
let oldShortName = shortInput.data("old-short"); // from DB
let newClientName = clientInput.val().trim();
console.log(`LN 882 : NEW - ${newClientName} | OLD - ${oldClientName} | OLD SN - ${oldShortName}`);
if (newClientName.toUpperCase() === (oldClientName || '').toUpperCase()) {
shortInput.val(oldShortName);
return;
}
if (newClientName.length == 0) {
shortInput.val('');
return;
}
if (newClientName.length > 0) {
let shortName = newClientName.substring(0, 10).replace(/\s+/g, '').toUpperCase();
shortInput.val(shortName);
makeUniqueShortName(shortName);
}
}
function makeUniqueShortName(baseName) {
let input = $("#short_name")[0]; // input element
checkDuplicateTableFieldValue("clients", "short_name", baseName, function(isDuplicate) {
if (isDuplicate) {
// Append sequence until unique
let counter = 1;
function tryNext() {
let padded = String(counter).padStart(3, '0'); // 001, 002, 003
let newName = baseName + padded;
checkDuplicateTableFieldValue("clients", "short_name", newName, function(exists) {
if (exists) {
counter++;
tryNext(); // keep checking
} else {
$("#short_name").val(newName);
validateInput(input, "clients", "short_name", "clientBtnSubmit");
}
});
}
tryNext();
} else {
$("#short_name").val(baseName);
validateInput(input, "clients", "short_name", "clientBtnSubmit");
}
});
}
function validateInput(input, table, field, submitButId){
let value = $(input).val();
let label = $(input).closest('.form-group').find('label').text().replace('*', '').trim();
let message = "Value is duplicate!";
if(label){
message = label + " already exists!";
}
checkDuplicateTableFieldValue(table, field, value, function(isDuplicate) {
if (isDuplicate) {
toastr.warning(message, 'Warning');
// $(input).val('')
$('#' + submitButId).prop('disabled', true);
} else{
$('#' + submitButId).prop('disabled', false);
}
});
}
function validateDuplicateByClientBranch(input, field, submitButId) {
let value = $(input).val().trim();
let clientId = $('#client_id_branch').val();
let branchId = $('#branch_id_primarykey').val();
let label = $(input).closest('.form-group').find('label').text().replace('*', '').trim();
let message = label ? label + " is duplicate!" : "Value is duplicate!";
console.log(`cId: ${clientId} | bId: ${branchId}`);
// Don't forgot be careful
// 1 Local duplication check (User entered)
let isLocalDuplicate = false;
$('input[name="' + field + '[]"]').each(function(index) {
let compareVal = $(this).val().trim();
console.log(`Entered value: ${value} | Contact ${index+1} value: ${$(this).val()}`);
if (this !== input && compareVal !== '' && compareVal === value) {
isLocalDuplicate = true;
return false;
}
});
if (isLocalDuplicate) {
console.log(`r u n Local`);
console.log(`duplicate found for ${field}`);
toastr.warning(message, 'Warning');
$('#' + submitButId).prop('disabled', true);
return;
}
// important Skip empty values
if (value === '') {
checkAllFieldsValid(submitButId);
return;
}
// Don't forgot be careful
// 2 Server-side duplicate check (DB)
$.ajax({
url: '<?= base_url("client/others/check-duplicate") ?>',
type: 'POST',
data: {
client_id: clientId,
branch_id: branchId,
value: value,
field: field
},
dataType: 'json',
success: function(response) {
if (response.isDuplicate) {
console.log(`r u n Server`);
console.log(`duplicate found for ${field}`);
toastr.warning(message, 'Warning');
$('#' + submitButId).prop('disabled', true);
} else {
console.log(`No duplicate for ${field}`);
checkAllFieldsValid(submitButId);
}
},
error: function(xhr, status, error) {
console.error('AJAX Error:', error);
}
});
}
// recheck all contacts before enabling submit
function checkAllFieldsValid(submitButId) {
let emailDuplicates = false;
let mobileDuplicates = false;
// cross check all EMAIL duplicates
let emailSeen = [];
$('input[name="email[]"]').each(function() {
let val = $(this).val().trim();
if (val && emailSeen.includes(val)) {
emailDuplicates = true;
} else if (val) {
emailSeen.push(val);
}
});
// cross check all MOBILE duplicates
let mobileSeen = [];
$('input[name="mobile[]"]').each(function() {
let val = $(this).val().trim();
if (val && mobileSeen.includes(val)) {
mobileDuplicates = true;
} else if (val) {
mobileSeen.push(val);
}
});
if (emailDuplicates || mobileDuplicates) {
$('#' + submitButId).prop('disabled', true);
// show correct message based on whats duplicated
if (emailDuplicates && mobileDuplicates) {
toastr.warning("Email and Mobile values are duplicate!", "Warning");
console.log('Both Email and Mobile duplicates');
} else if (emailDuplicates) {
toastr.warning("Email duplicate!", "Warning");
console.log('Cross Check Email duplicates');
} else if (mobileDuplicates) {
toastr.warning("Mobile duplicate!", "Warning");
console.log('Cross Check Mobile duplicates');
}
console.log(`btn Dis - true`);
} else {
console.log('unique — enable');
console.log(`btn Dis - false`);
$('#' + submitButId).prop('disabled', false);
}
}
function getContactsData() {
const contacts = [];
const ids = $('input[name="branch_table_pk[]"]');
const names = $('input[name="name[]"]');
const mobiles = $('input[name="mobile[]"]');
const emails = $('input[name="email[]"]');
const designations = $('input[name="designation[]"]');
for (let i = 0; i < ids.length; i++) {
contacts.push({
id: $(ids[i]).val() || null,
name: $(names[i]).val(),
mobile: $(mobiles[i]).val(),
email: $(emails[i]).val(),
designation: $(designations[i]).val()
});
}
return contacts;
}
function removeLevelContacts(id){
let url = '<?= base_url('util/removeLevelContacts') ?>';
let requestData = {
id: id,
};
// Send AJAX request
sendAjaxRequestForGlobal(url, 'GET', requestData, function(response) {
console.log('Data fetched successfully:', response);
if (response.status == true) {
toastr.success(response.message, 'Success');
} else {
toastr.warning(response.message, 'Warning');
}
}, function(xhr, status, error) {
console.error('Error fetching data:', error);
console.error(xhr.responseText);
});
}
</script>
<script>
$(document).ready(function() {
$("#selected").select2({
tags: true,
placeholder: "Enter Units",
tokenSeparators: [], // Disable default token separators
createTag: function (params) {
var term = $.trim(params.term);
if (term === '') {
return null;
}
return {
id: term,
text: term,
newTag: true
};
}
})
$("textarea.select2-search__field").attr('rows', '1');
$("textarea.select2-search__field").css('resize', 'none');
// Intercept keydown event
$("#selected").on('select2:select', function (e) {
var newTag = e.params.data.newTag;
// Remove the tag if it was not created by pressing Enter
if (!newTag) {
$(this).find('option[value="' + e.params.data.id + '"]').remove();
$(this).trigger('change');
}
});
// Listen for the Enter key
$("#selected").on('keydown', function (e) {
if (e.key === 'Enter') {
var $input = $(this).data('select2').dropdown.$search || $(this).data('select2').selection.$search;
var term = $.trim($input.val());
if (term !== '') {
var option = new Option(term, term, true, true); // Set selected to true
$(this).append(option).trigger('change');
$input.val('');
}
e.preventDefault(); // Prevent the default action of the Enter key
}
});
// Get the Select2 container element
var select2Container = $('#selected').next('.select2-container');
// Find the dropdown within the Select2 container
var select2Dropdown = select2Container.find('.select2-dropdown');
// Set the display style to none
select2Dropdown.css('display', 'none');
});
$(document).ready(function() {
// Wait for Select2 to be fully initialized and rendered
$('#selected').on('select2:open', function (e) {
// Get the Select2 dropdown element
var select2Dropdown = $('.select2-container--open').find('.select2-dropdown');
// Set the display style to none
select2Dropdown.css('display', 'none');
});
});
function appendOption(data){
data = JSON.parse(data);
$('#selected').empty();
$.each(data, function(index, item) {
const option = $('<option>', {
value: item,
text:item,
selected: true
});
$('#selected').append(option);
});
}
function setDefaultUnitValue()
{
var client_id = $('#client_id_branch').val();
var branch_code = $('#branch_code').val();
var units = $('#selected').val();
console.log('client_id', client_id)
console.log('branch_code', branch_code)
console.log('units', units)
var url_for_get_client_details = '<?php echo base_url('util/get_client_details/') ?>' + client_id;
if(units.length == 0 || units.length == 1){
$.get(url_for_get_client_details, function(response){
console.log(response)
console.log(response.data)
if (!response || !response.data || !response.data.short_name) {
if (!response) {
console.log('Response is null');
} else if (!response.data) {
console.log('Response data is null');
} else if (!response.data.short_name) {
toastr.warning('The client has no Short name');
}
} else {
$('#selected').empty();
var default_unit = response.data.short_name + '-' + branch_code;
if(units.length == 1){
if(units[0] != default_unit){
const option = $('<option>', {
value: default_unit,
text: default_unit,
selected: true
});
$('#selected').append(option);
}
}else{
const option = $('<option>', {
value: default_unit,
text: default_unit,
selected: true
});
$('#selected').append(option);
}
}
}).fail(function(xhr, status, error) {
console.error(xhr.responseText);
console.error(status, error);
});
}
}
</script>