<!-- Main body part -->
<div id="main-content">
<div class="container-fluid">
<!-- Page header section -->
<div class="block-header">
<div class="row clearfix">
<div class="col-xl-6 col-md-5 col-sm-12">
<h1>Subscriber</h1>
<span>Home / View Subscriber</span>
</div>
</div>
</div>
<div class="row clearfix">
<div class="col-lg-12">
<div class="card">
<div class="header">
<h2>View Subscriber</h2>
<ul class="header-dropdown dropdown">
<li><a href="<?= base_url('admin/client-master'); ?>">
<button type="button" class="btn btn-light"> <i class="fa fa-arrow-left icon"></i> Back</button> </a>
</li>
</ul>
</div>
<div class="body">
<form id="subscription_editor"
action="<?= base_url('admin/client-master/update/' . $subscriber[0]->id) ?>" method="post">
<div id="message" class="my-4"></div>
<div class="table-responsive">
<table class="table table-hover" id="subscriberTable">
<tbody>
<!-- Existing subscriber details rows -->
<tr>
<th>First Name :</th>
<td><?= $subscriber[0]->first_name ?></td>
<th>Last Name :</th>
<td><?= $subscriber[0]->last_name ?></td>
</tr>
<tr>
<th>Designation :</th>
<td><?= $subscriber[0]->designation ?></td>
<th>Organization / Company :</th>
<td><?= $subscriber[0]->organization ?></td>
</tr>
<tr>
<th>Email :</th>
<td><?= $subscriber[0]->email ?></td>
<th>Mobile No. :</th>
<td><?= $subscriber[0]->mobile ?></td>
</tr>
<tr>
<th>Country :</th>
<td><?= $subscriber[0]->country_name ?></td>
<th>Address :</th>
<td><?= $subscriber[0]->address ?></td>
</tr>
</tbody>
</table>
<div class="container-fluid mt-4">
<div class="row">
<div class="col-sm-12 tenure">
<div id="tenure_container">
<?php if (!empty($tenures)) { ?>
<?php foreach ($tenures as $index => $tenure): ?>
<div class="tenure_wrapper last_tenure_<?= $index ?> mb-3" data-tenure-id="<?= $tenure->tenure_id ?>">
<div class="tenure_checkbox">
<h5>Tenure <?= $index + 1 ?></h5>
<div class="">
<div class="extension_checkbox">
<input type="checkbox" id="last_tenure_extend_15_days_<?= $index ?>" name="last_tenure_extend_15_days_<?= $index ?>"
<?= !empty($tenure->extend_15_days) && $tenure->extend_15_days == '1' ? 'checked disabled' : '' ?> disabled>
<label for="last_tenure_extend_15_days">Extend 15 days</label>
</div>
<div class="extension_checkbox">
<input type="checkbox" id="last_tenure_extend_other_15_days_<?= $index ?>" name="last_tenure_extend_other_15_days_<?= $index ?>" <?= !empty($tenure->extend_other_15_days) && $tenure->extend_other_15_days == '1' ? 'checked disabled' : '' ?> disabled>
<label for="last_tenure_extend_other_15_days">Extend By Other 15 days</label>
</div>
<div class="extension_checkbox">
<input type="checkbox" id="last_tenure_lite_cir_monthly_report_<?= $index ?>" name="last_tenure_lite_cir_monthly_report_<?= $index ?>"
<?= !empty($tenure->is_checked) && $tenure->is_checked == '1' ? 'checked disabled' : '' ?> disabled>
<label for="last_tenure_lite_cir_monthly_report_<?= $index ?>">Lite CIR Monthly Report</label>
</div>
</div>
</div>
<div class="Add_tenure_flex input-group">
<div class="input-item" >
<label for="subscription_tenure_period_<?= $index ?>">Sub Period</label>
<select name="subscription_tenure_period[]" id="subscription_tenure_period_<?= $index ?>"
class="form-control" disabled readonly title="<?= htmlspecialchars($tenure->subscription_period) ?>">
<option value="">
<?= htmlspecialchars($tenure->subscription_period) ?>
</option>
</select>
</div>
<div class="input-item">
<label for="initial_start_<?= $index ?>">Initial Start</label>
<input type="date" id="initial_start_myInputStart_<?= $index ?>" name="initial_start_change_start[]"
value="<?= htmlspecialchars($tenure->initial_start_date) ?>" class="form-control" disabled readonly>
</div>
<div class="input-item">
<label for="initial_end_<?= $index ?>">Initial End</label>
<input type="date" id="initial_start_myInputEnd_<?= $index ?>" name="initial_start_change_end[]"
value="<?= htmlspecialchars($tenure->initial_end_date) ?>" class="form-control" disabled readonly>
</div>
<div class="input-item">
<label for="sub_tenure_type_<?= $index ?>">Subscription Type</label>
<select name="sub_tenure_type[]" id="sub_tenure_type_<?= $index ?>" class="form-control" disabled readonly title="<?php
foreach ($subscription_types as $type) {
if ($tenure->subscription_type == $type->product_id) {
echo htmlspecialchars($type->product_name);
}
}
?>">
<?php foreach ($subscription_types as $type): ?>
<option value="<?= $type->product_id ?>" <?= ($tenure->subscription_type == $type->product_id) ? 'selected' : '' ?>>
<?= htmlspecialchars($type->product_name) ?>
</option>
<?php endforeach; ?>
</select>
</div>
</div>
</div>
<?php endforeach; ?>
<?php } ?>
<?php foreach ($subscriber as $index => $tenure): ?>
<div class="tenure_wrapper existing_tenure">
<div class="tenure_checkbox">
<h5 id="tenure_id">Tenure</h5>
<div class="tenure_check_exe">
<div class="extension_checkbox">
<input type="checkbox" id="extend_15_days" name="extend_15_days" value="1"
<?= !empty($subscriber[0]->extend_15_days) && $subscriber[0]->extend_15_days == '1' ? 'checked disabled' : '' ?>>
<label for="extend_15_days">Extend 15 days</label>
</div>
<div class="extension_checkbox">
<input type="checkbox" id="extend_other_15_days" name="extend_other_15_days" value="1"
<?= !empty($subscriber[0]->extend_other_15_days) && $subscriber[0]->extend_other_15_days == '1' ? 'checked disabled' : '' ?>>
<label for="extend_other_15_days">Extend By Other 15 days</label>
</div>
<div class="extension_checkbox">
<input type="checkbox" id="lite_cir_monthly_report_<?= $index ?>" name="lite_cir_monthly_report[]"
value="1" <?= !empty($subscriber[0]->is_checked) && $subscriber[0]->is_checked == '1' ? 'checked' : '' ?>>
<label for="lite_cir_monthly_report_<?= $index ?>">Lite CIR Monthly Report</label>
</div>
<div class="extension_checkbox" id="extension_checkbox_delete">
</div>
</div>
</div>
<div class="Add_tenure_flex input-group" >
<div class="input-item">
<div class="label_heading cs_width">
<label for="subscription_period_<?= $index ?>">Subscription Period</label>
</div>
<select name="subscription_period[]" id="subscription_period_<?= $index ?>" class="form-control subscription_period" title="">
<!-- Add your options here -->
</select>
</div>
<div class="input-item">
<div class="label_heading cs_width">
<label for="initial_start_<?= $index ?>">Start Date</label>
</div>
<input type="date" id="myInputStart_<?= $index ?>" name="change_start[]" value="<?= htmlspecialchars($tenure->start_reg) ?>" class="form-control start_date" />
</div>
<div class="input-item">
<div class="label_heading cs_width">
<label for="initial_end_<?= $index ?>">End Date</label>
<span class="btn btn-success onEdit" data-target="#myInputEnd_<?= $index ?>"><i class="fa fa-pencil"></i></span>
</div>
<input type="date" id="myInputEnd_<?= $index ?>" name="change_end[]" value="<?= htmlspecialchars($tenure->end_reg) ?>" class="form-control end_date" readonly/>
</div>
<div class="input-item">
<div class="label_heading">
<label for="subscription_type_<?= $index ?>">Subscription Type</label>
<span class="commodities_selection" id="viewcommodities"> Select Custom Commodities
</span>
<span class="commodities_selection" id="viewcategories">
Select Partial Commodities
</span>
</div>
<select name="subscription_type_[]" id="subscription_type_<?= $index ?>" class="form-control" title="">
<!-- Add your options here -->
</select>
</div>
</div>
<!-- <input type="hidden" name="selected_commodities" > -->
<input type="hidden" name="selected_commodities" id="selected_commodities"
value="<?= isset($selectedcustom__items['item_ids']) ? htmlspecialchars($selectedcustom__items['item_ids'], ENT_QUOTES, 'UTF-8') : ''; ?>">
<input type="hidden" name="selected_categories" id="selected_categories" value="<?= implode(',', $subscriber[0]->choose_type ? explode(',', $subscriber[0]->choose_type) : []); ?>">
<input type="hidden" name="tenure_id[]" value="" /> <!-- Hidden field for unique ID -->
</div>
<?php endforeach; ?>
</div>
</div>
<span class="add_tenure" id="addTenureButton">+ Add more Tenure</span>
</div>
<div class="remarks" style="margin:15px;">
<tr>
<h5>Remarks :</h5>
<td>
<textarea class="remarks"
name="remarks"><?= htmlspecialchars($subscriber[0]->remarks) ?></textarea>
</td>
</tr>
</div>
</div>
<div class="client_button">
<!-- Add more tenure button -->
<button type="submit" class="btn btn-dark">Update</button>
<?php if ($subscriber[0]->user_type == 'Register') { ?>
<button type="button" uid="<?= $subscriber[0]->id ?>" class="btn btn-success user_status"
ustatus="<?= $subscriber[0]->user_type; ?>">Register</button>
<?php } else { ?>
<button type="button" uid="<?= $subscriber[0]->id ?>" class="btn btn-danger user_status"
ustatus="<?= $subscriber[0]->user_type; ?>">Unregister</button>
<?php } ?>
<input type="hidden" id="subscriptionId" value="<?= $subscriber[0]->id; ?>">
</div>
<div id="userlogTableContainer">
<div class="userlog-table-container">
<div class="export_log d-flex justify-content-between align-items-center">
<h5 class="userlog-label">User Log Table</h5>
<a href="<?= base_url('admin/client-master/export_User_log/' . $subscriber[0]->id); ?>">
<button type="button" class="btn btn-dark" id="exportBtn">
<i class="fa fa-download icon"></i>
Export Data
</button>
</a>
</div>
<table id="userlogTable" class="table table-hover dataTable js-basic-example table-custom spacing5">
<thead>
<tr>
<th>Sr No.</th>
<th>Date of Change</th>
<th class="chng_detail">Change In</th>
<th class="chng_detail">Old Entry</th>
<th>Change By</th>
<th>IP Address</th>
</tr>
</thead>
<tbody>
<?php if (!empty($user_logs)):
$i = 0;
foreach ($user_logs as $log):
$i++;
?>
<tr>
<td><?php echo $i; ?></td>
<td><?php echo date('Y-m-d', strtotime($log->change_date)); ?></td>
<td class="chng_detail" data-toggle="tooltip" title="<?php echo htmlspecialchars($log->change_details); ?>">
<?php echo $log->change_details; ?>
</td>
<td class="chng_detail" data-toggle="tooltip" title="<?php echo htmlspecialchars($log->old_entry); ?>">
<?php echo $log->old_entry; ?>
</td>
<td><?php echo $log->changed_by; ?></td>
<td><?php echo $log->ip_address; ?></td>
</tr>
<?php endforeach; ?>
<?php else: ?>
<tr>
<td colspan="6">No user logs available.</td>
</tr>
<?php endif; ?>
</tbody>
</table>
</div>
</div>
</div>
</form>
<div class="modal modal-danger fade" id="modal_popup">
<div class="modal-dialog modal-sm">
<!-- //create form to change user status -->
<form action="<?php echo base_url(); ?>admin/client-master/user_status_changed"
method="post">
<div class="modal-content">
<div class="modal-header" style="height: 150px;">
<h4 style="margin-top: 50px;text-align: center;">Are you sure to change
usertype status?</h4>
<!-- //getting value in hidden field with the hep of ID's -->
<input type="hidden" name="id" id="user_id" value="">
<input type="hidden" name="name" id="name" value="">
<input type="hidden" name="email" id="email" value="">
<input type="hidden" name="enddate" id="enddate" value="">
<input type="hidden" name="user_subscription_period" id="user_subscription_period" value="">
<input type="hidden" name="status" id="user_status" value="">
</div>
<div class="modal-footer">
<button type="button" class="btn btn-danger pull-left"
data-dismiss="modal">No</button>
<button type="submit" name="submit" class="btn btn-success">Yes</button>
</div>
</div>
</form>
</div>
</div>
<div id="specialPlanModal" class="modal">
<div class="modal-splan">
<div class="modal-content specailplan">
<div class="modal-header">
<h2 class="modal-title">Select commodities</h4>
<button type="button" class="close" id="specialPlanclose">×</button>
</div>
<!-- Modal content here -->
<div id="special-table-product">
<div class="table-responsive">
<table class="table table-bordered table-striped special">
<thead>
<tr>
<th>Select</th>
<th>Product Type</th>
</tr>
</thead>
<tbody>
<?php foreach ($partial_web as $web): ?>
<tr id="special-row">
<td>
<input type="checkbox" name="choose_type[]" id="choose_type_<?= $web['category_name'] ?>"
value="<?= $web['category_id'] ?>" data-price="<?= $web['new_cost_inr'] ?>">
</td>
<td>
<span><?= htmlspecialchars($web['category_name']) ?></span>
</td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
</div>
</div>
<div class="modal-footer">
<button type="button" id="saveSelections" class="btn btn-primary">Save</button>
</div>
</div>
</div>
</div>
<div id="CustomizedPlanModal_1" class="modal">
<div class="modal-dialog modal-lg" role="document">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title" id="Customized_product_name">
<?php foreach ($subscription_types as $type) {
if ($subscriber[0]->subscription_type== $type->product_id) {
echo htmlspecialchars($type->product_name);
}
} ?></h4>
<button type="button" class="CustomizedPlanClose_1" data-dismiss="modal">×</button>
</div>
<div class="modal-body" id="CustomizedPlanproduct_1">
<div class="row">
<div class="col-md-3" id="commodity_menu">
<ul class="nav nav-pills nav-stacked" id="commodityTabs">
<?php $firstTab = true; ?>
<?php foreach($commodity_head as $head): ?>
<li id="commodityitems" class="<?php if($head['id'] == '1') echo 'active'; ?>">
<a href="#tab_<?= $head['id'] ?>" data-toggle="tab" class="<?= $firstTab ? 'active' : ''; ?>">
<?= htmlspecialchars($head['category_name']) ?>
<span id="count_tab_<?= $head['id'] ?>" class="category-count"></span>
</a>
</li>
<?php $firstTab = false; ?>
<?php endforeach; ?>
</ul>
</div>
<div class="col-md-9">
<div class="tab-content">
<?php $indx = 0; ?>
<?php foreach($commodity_head as $ch): ?>
<div class="tab-pane <?php echo ($indx == 0) ? 'in active' : ''; ?>" id="tab_<?= $ch['id']; ?>" data-category-name="<?= htmlspecialchars($ch['category_name']) ?>">
<div class="checkbox-container">
<?php foreach($commodity as $comdity):
if($comdity['category_id'] == $ch['id']) { ?>
<label class="checkbox-item">
<input type="checkbox" name="selected_commodities_items[]"
data-category-id="<?= htmlspecialchars($comdity['category_id']) ?>"
value="<?= htmlspecialchars($comdity['id']) ?>"
>
<?= htmlspecialchars($comdity['item_name']) ?>
</label>
<?php } endforeach; ?>
</div>
</div>
<?php $indx++; ?>
<?php endforeach; ?>
</div>
</div>
</div>
</div>
<div class="modal-footer d-flex justify-content-end align-items-center">
<p class="mb-1" style="margin-right: 67%;"><strong style="color: #9f9999;">Total Commodities:</strong> <span id="selected_commodities_count"></span></p>
<button type="button"class="btn btn-primary" id="saveCustomizeddata">Save</button>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<script type="text/javascript" language="javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jszip/3.1.3/jszip.min.js"> </script>
<script src="<?= base_url(); ?>assets/plugins/general/jquery/dist/jquery.js" type="text/javascript"></script>
<script>
// on hover display tooltip
$(document).ready(function () {
$(".chng_detail").hover(
function () {
var tooltipText = $(this).find(".tooltip-text").text(); // Get text
var tooltip = $("<span class='dynamic-tooltip'></span>").text(tooltipText); // Create tooltip
$(this).append(tooltip);
tooltip.fadeIn(200);
},
function () {
$(this).find(".dynamic-tooltip").fadeOut(200, function () {
$(this).remove(); // Remove tooltip after fade out
});
}
);
});
$(document).ready(function () {
var tenureCount = $('.tenure_wrapper').length;
var isTenureModified = false;
var lastAddedTenure = null;
var allowedPartialTypes = <?= ($partial_product_id); ?>;
var allowedCustomTypes = <?= ($custom_id); ?>;
var originalData = {};
var selectProduct = $('#subscription_type_<?= $index ?>');
var selectedProduct = "<?= $subscriber[0]->subscription_type ?>";
function generateUniqueId() {
return `tenure_${Date.now()}`;
}
function detectTenureModification(tenure) {
isTenureModified = false;
tenure.find('input, select').each(function () {
var originalValue = $(this).data('original-value') || '';
var currentValue = $(this).attr('type') === 'checkbox' ? ($(this).is(':checked') ? '1' : '0') : $(this).val() || '';
if (originalValue !== currentValue) {
isTenureModified = true;
return false; // Exit loop
}
});
}
function setOriginalValues(tenure) {
tenure.find('input, select').each(function () {
var currentValue = $(this).attr('type') === 'checkbox' ? ($(this).is(':checked') ? '1' : '0') : $(this).val();
$(this).data('original-value', currentValue);
});
}
// Function to check the selected product and show the modal if necessary
function checkProductTypeAndShowModal(selectElement) {
var selectedProductType = parseInt(selectElement.val(), 10);
console.log('Selected Product Type:', selectedProductType);
$('.modal').fadeOut(); // Hide any open modal
if (!isNaN(selectedProductType) && allowedPartialTypes.includes(selectedProductType)) {
$('#specialPlanModal').fadeIn();
} else if (!isNaN(selectedProductType) && allowedCustomTypes.includes(selectedProductType)) {
$('#viewSelectedcommodities').show();
}
var enableCheckboxTypes = <?php echo json_encode(CIR_ACCESS); ?>;
var disableCheckboxTypes = <?php echo json_encode(ONLINE_FORCAST_ACCESS); ?>;
if (!isNaN(selectedProductType)) {
var currentWrapper = selectElement.closest('.tenure_wrapper');
// Target only checkboxes within the current plan
currentWrapper.find('input[name^="lite_cir_monthly_report"]').each(function() {
if (enableCheckboxTypes.includes(selectedProductType)) {
$(this).prop('checked', true);
} else if (disableCheckboxTypes.includes(selectedProductType)) {
$(this).prop('checked', false);
} else {
$(this).prop('checked', false);
}
});
}
}
function addTenureRow() {
var lastTenure = $('.tenure_wrapper:last');
var lastEndDate = new Date(lastTenure.find('input[name="change_end[]"]').val());
var today = new Date();
if (lastEndDate >= today) {
$('#message').html('<div class="alert alert-danger">You can only add a new tenure after the last tenure has expired.</div>').fadeIn(100).delay(3000).fadeOut(100);
$('html, body').animate({ scrollTop: 0 }, 1000);
// alert('You can only add a new tenure after the last tenure has expired.');
return;
}
detectTenureModification(lastTenure);
if (!isTenureModified) {
$('#message').html('<div class="alert alert-danger">You must modify the last tenure before adding a new one.</div>').fadeIn(100).delay(3000).fadeOut(100);
$('html, body').animate({ scrollTop: 0 }, 1000);
// alert('You must modify the last tenure before adding a new one.');
return;
}
var newTenure = lastTenure.clone().attr('id', generateUniqueId());
var newIndex = $('.tenure_wrapper').length;
newTenure.find('h5').text('Tenure ' + (newIndex + 1));
newTenure.find('input, select').each(function () {
var $this = $(this);
if ($this.attr('type') === 'checkbox') {
$this.prop('disabled', false).prop('checked', false);
} else if ($this.attr('type') === 'hidden' && $this.attr('name') === 'tenure_id[]') {
$this.val(newTenure.attr('id'));
} else {
$this.val('');
}
if ($this.is('select')) {
$this.prop('selectedIndex', 0);
}
$this.removeData('original-value');
});
$('#tenure_container').append(newTenure);
lastTenure.find('input, select').attr('readonly', true).attr('disabled', true);
setOriginalValues(newTenure);
lastAddedTenure = newTenure;
newTenure.find('#extension_checkbox_delete').append(`
<div class="extension_checkbox">
<i class="fa fa-trash-o" style="font-size:24px;color:red" onclick="removeTenureRow(this)"></i>
</div>
`);
// Bind change event to the select element to detect changes
$('select[name="subscription_type_[]"]').on('change', function () {
checkProductTypeAndShowModal($(this));
});
// // If there's a need to check the initial value on page load:
// $('select[name="subscription_type_[]"]').each(function () {
// checkProductTypeAndShowModal($(this));
// });
}
function removeTenureRow(element) {
if (confirm('Are you sure you want to remove this tenure?')) {
$(element).closest('.tenure_wrapper').remove();
lastAddedTenure = null;
updateTenureIds();
}
}
function updateTenureIds() {
$('.tenure_wrapper').each(function () {
$(this).attr('id', generateUniqueId());
});
}
function initializeOriginalData() {
$('#subscription_editor').find('input, select, textarea').each(function () {
var name = $(this).attr('name');
var value = $(this).attr('type') === 'checkbox' ? ($(this).is(':checked') ? '1' : '0') : $(this).val();
originalData[name] = value;
});
}
function calculateEndDate(startDate, subscriptionPeriod) {
if (!startDate || !subscriptionPeriod) return '';
var startDateObj = new Date(startDate);
var periodInMonths = {
'6_month': 6,
'1_year': 12,
'3_year': 36,
'5_year': 60
}[subscriptionPeriod] || 0;
startDateObj.setMonth(startDateObj.getMonth() + periodInMonths);
return startDateObj.toISOString().split('T')[0];
}
$(document).on('change', '.subscription_period, .start_date', function () {
var tenureWrapper = $(this).closest('.tenure_wrapper');
var startDate = tenureWrapper.find('.start_date').val();
var subscriptionPeriod = tenureWrapper.find('.subscription_period').val();
var endDate = calculateEndDate(startDate, subscriptionPeriod);
tenureWrapper.find('.end_date').val(endDate).attr('readonly', endDate ? true : false);
});
function fetchProductList() {
$.ajax({
url: '<?php echo base_url(); ?>api/product_master_list',
type: 'GET',
contentType: 'application/json',
success: function (data) {
var selectProduct = $('#subscription_type_<?= $index ?>');
selectProduct.empty().append($('<option>').val('').text('Select a product'));
// Filter the products by status and loop through each one
data.filter(product => product.product_status === "ON")
.forEach(product => {
// Create an option element with value and title attribute
var option = $('<option>')
.val(product.product_id)
.attr('title', product.product_name) // Add title attribute
.text(product.product_name);
// Append the option to the select element
selectProduct.append(option);
});
// Optionally, set the default value for the select field
selectProduct.val("<?= $subscriber[0]->subscription_type ?>");
},
error: function (error) {
console.error('Error fetching product list:', error);
}
});
}
// Get the default subscription type from PHP
var subscriptionType = <?php echo isset($tenure->subscription_type) ? (int)$tenure->subscription_type : 'null'; ?>;
// Function to update visibility based on subscription type
function updateVisibility(selectedValue) {
if (allowedCustomTypes.includes(selectedValue)) {
$('#viewcommodities').show();
} else {
$('#viewcommodities').hide();
}
if (allowedPartialTypes.includes(selectedValue)) {
$('#viewcategories').show();
} else {
$('#viewcategories').hide();
}
}
// Initialize visibility on page load
if (subscriptionType !== null) {
updateVisibility(subscriptionType);
}
// Update visibility when select changes
selectProduct.on('change', function () {
var selectedValue = parseInt($(this).val(), 10); // Convert to integer
updateVisibility(selectedValue);
// Define the sets of product types for checkbox operations
const enableCheckboxTypes = <?php echo json_encode(CIR_ACCESS); ?>.map(Number);
const disableCheckboxTypes = <?php echo json_encode(ONLINE_FORCAST_ACCESS); ?>.map(Number);
// Ensure selectedValue is a number
if (!isNaN(selectedValue)) {
$('input[id^="lite_cir_monthly_report_"]').each(function() {
var checkbox = $(this);
console.log('Processing checkbox with ID:', checkbox.attr('id')); // Debugging
// Enable or disable checkboxes based on selected product type
if (enableCheckboxTypes.includes(selectedValue)) {
checkbox.prop('checked', true);
} else {
checkbox.prop('checked', false);
}
});
}
});
function fetchSubscriptionPeriods() {
$.ajax({
url: '<?php echo base_url(); ?>api/subscription_period',
type: 'GET',
contentType: 'application/json',
success: function (data) {
var selectSubscriptionPeriod = $('#subscription_period_<?= $index ?>');
selectSubscriptionPeriod.empty().append($('<option>').val('').text('Select a subscription period'));
data.forEach(period => {
selectSubscriptionPeriod.append($('<option>').val(period).attr('title', period).text(period.replace('_', ' ')));
});
if ("<?= $subscriber[0]->subscription_period ?>") {
selectSubscriptionPeriod.val("<?= $subscriber[0]->subscription_period ?>").attr('title', selectSubscriptionPeriod.find('option:selected').attr('title'));
}
},
error: function (error) {
console.error('Error:', error);
}
});
}
$('#subscription_editor').on('submit', function (event) {
event.preventDefault();
if (!validateCommoditySelection()) {
return false; // Stop form submission if validation fails
}
var formData = $(this).serializeArray();
var formDataObject = formData.reduce(function (obj, field) {
var name = field.name;
var value = field.value;
if ($(`input[name="${name}"]`).attr('type') === 'checkbox') {
value = $(`input[name="${name}"]`).is(':checked') ? '1' : '0';
}
if (name.endsWith('[]')) {
obj[name] = obj[name] || [];
obj[name].push(value);
} else {
obj[name] = value;
}
return obj;
}, {});
console.log('Form Data Object:', formDataObject);
var isChanged = Object.keys(originalData).some(function (key) {
return originalData[key] !== formDataObject[key];
});
if (isChanged) {
// Ensure no blank data is being sent
var hasValidData = Object.values(formDataObject).some(value => String(value).trim() !== '');
if (hasValidData) {
// AJAX request to update the form
$.ajax({
url: $(this).attr('action'),
method: 'POST',
data: $(this).serialize(),
dataType: 'json',
success: function (response) {
console.log(response);
// Check if response status is valid
if (response.status) {
$('#message').html(`<div class="alert alert-success">${response.message}</div>`)
.fadeIn(100)
.delay(2000) // Keep message visible for 2 seconds
.fadeOut(100, function () {
window.location.href = 'admin/client-master';
});
} else {
$('#message').html(`<div class="alert alert-danger">${response.message}</div>`).fadeIn(100).delay(3000).fadeOut(100);
}
$('html, body').animate({ scrollTop: 0 }, 1000);
},
error: function () {
// Handle error response
$('#message').html('<div class="alert alert-danger">An error occurred. Please try again.</div>').fadeIn(100).delay(3000).fadeOut(100);
$('html, body').animate({ scrollTop: 0 }, 1000);
}
});
} else {
$('#message').html('<div class="alert alert-info">Form contains blank data. Please fill in all required fields before submission.</div>').fadeIn(100).delay(3000).fadeOut(100);
$('html, body').animate({ scrollTop: 0 }, 1000);
}
} else {
$('#message').html('<div class="alert alert-info">No changes detected. You cannot update the tenure without making changes.</div>').fadeIn(100).delay(3000).fadeOut(100);
$('html, body').animate({ scrollTop: 0 }, 1000);
}
});
$(document).on('click', '.user_status', function () {
var id = $(this).attr('uid');
var name = '<?= $subscriber[0]->first_name . ' ' . $subscriber[0]->last_name ?>';
var email = '<?= $subscriber[0]->email ?>';
var status = $(this).attr('ustatus');
var enddate = '<?= $subscriber[0]->end_reg ?>';
var subscription_period = '<?= $subscriber[0]->subscription_period ?>';
$('#user_id').val(id);
$('#name').val(name);
$('#email').val(email);
$('#enddate').val(enddate);
$('#user_subscription_period').val(subscription_period);
$('#user_status').val(status);
$('#modal_popup').modal({
backdrop: 'static',
keyboard: true,
show: true
});
});
$(document).on('click', '#specialPlanclose, #specialPlanModal', function (event) {
if ($(event.target).is('#specialPlanclose')) {
$("#specialPlanModal").fadeOut();
}
});
$(document).on('click', '.CustomizedPlanClose_1, #CustomizedPlanModal_1', function (event) {
if ($(event.target).is('.CustomizedPlanClose_1')) {
$("#CustomizedPlanModal_1").fadeOut();
}
});
$(document).on('click', '#addTenureButton', addTenureRow);
$(document).on('click', '.onEdit', function () {
var inputField = $(this).closest('.input-item').find('input');
inputField.css('background-color', '#fff').removeAttr('readonly').focus();
});
$(document).on('click', '.extension_checkbox .fa-trash-o', function () {
removeTenureRow(this);
});
fetchProductList();
var selectSubscriptionPeriod = $('#subscription_period_<?= $index ?>');
var selectedPeriod = "<?= $subscriber[0]->subscription_period ?>";
fetchSubscriptionPeriods();
initializeOriginalData();
// Function to check if end date has expired
function isEndDateExpired(endDateStr) {
// Convert endDateStr to a Date object
var endDate = new Date(endDateStr);
var today = new Date();
// Reset the time portion for accurate comparison
today.setHours(0, 0, 0, 0); // Midnight
console.log('End Date:', endDate);
console.log('Today:', today);
// Compare the end date with today
return endDate < today;
}
// Handle checkbox click event
$('#extend_15_days, #extend_other_15_days').on('change', function () {
var endDateStr = $('#subscription_editor').find('input[name="change_end[]"]').val();
var isExpired = isEndDateExpired(endDateStr);
if ($(this).attr('id') === 'extend_other_15_days') {
if (!$('#extend_15_days').is(':checked')) {
$(this).prop('checked', false); // Uncheck the checkbox
$('#message').html('<div class="alert alert-danger">You can only apply "Extend by Other 15 Days" after using "Extend by 15 Days".</div>').fadeIn(100).delay(3000).fadeOut(100);
$('html, body').animate({ scrollTop: 0 }, 1000);
return;
}
}
if (!isExpired) {
$(this).prop('checked', false); // Uncheck the checkbox
$('#message').html('<div class="alert alert-danger">You can only apply extensions after the end date has expired.</div>').fadeIn(100).delay(3000).fadeOut(100);
$('html, body').animate({ scrollTop: 0 }, 1000);
}
});
function saveSelectedCommoditiesAndCategories(modalId, checkboxContainer, commodityField, categoryField) {
let selectedCommodityIds = [];
let selectedCategoryIds = new Set(); // Store unique category IDs
// Loop through selected checkboxes
$(checkboxContainer + ' input[type="checkbox"]:checked').each(function () {
selectedCommodityIds.push($(this).val()); // Store commodity ID
selectedCategoryIds.add($(this).data('category-id')); // Store category ID
});
// Save IDs
$(commodityField).val(selectedCommodityIds.join(',')); // Save commodity IDs
$(categoryField).val([...selectedCategoryIds].join(',')); // Save unique category IDs
$(modalId).fadeOut();
}
function saveSelectedValues(modalId, checkboxContainer, inputField) {
let selectedValues = $(checkboxContainer + ' input[type="checkbox"]:checked')
.map(function () { return $(this).val().trim(); })
.get()
.join(',');
$(inputField).val(selectedValues || $(inputField).val()); // Retain previous value if none selected
$(modalId).fadeOut();
}
// ✅ Save Categories
$('#saveSelections').on('click', function () {
saveSelectedValues('#specialPlanModal', '#special-table-product', '#selected_categories');
});
// ✅ Save Commodities
let isChanged = false; // Flag to track changes
// Attach event to checkboxes to track changes
$('#CustomizedPlanModal_1 input[type="checkbox"]').on('change', function () {
isChanged = true; // Mark as changed
updateCategoryCounts();
});
$('#saveCustomizeddata').on('click', function () {
// Ensure changes have been made before allowing save
if (!isChanged) {
toastr.warning('No changes detected.', 'Info', {
timeOut: 3000,
closeButton: true,
progressBar: true
});
return false; // Stop further execution
}
// Count selected checkboxes inside #CustomizedPlanModal_1
let itemCount = $('#CustomizedPlanModal_1 input[type="checkbox"]:checked').length;
if (itemCount < 5) {
toastr.warning('At least 5 commodities must be selected.', 'Selection Error', {
timeOut: 3000,
closeButton: true,
progressBar: true
});
return false; // Stop further execution
}
// Reset change flag after saving
isChanged = false;
// If 5 or more items are selected, proceed with saving
saveSelectedCommoditiesAndCategories('#CustomizedPlanModal_1', '#CustomizedPlanproduct_1',
'#selected_commodities', '#selected_categories');
});
// Function to update the category count
function updateCategoryCounts() {
let categoryCounts = {};
let selectedItems = $('#CustomizedPlanModal_1 input[type="checkbox"]:checked'); // Define selectedItems
selectedItems.each(function () {
let category = $(this).closest(".tab-pane").attr("id");
let categoryName = $(this).closest(".tab-pane").data("category-name");
if (!categoryCounts[category]) {
categoryCounts[category] = { name: categoryName, count: 0 };
}
categoryCounts[category].count++;
});
// Reset all counts
$(".category-count").text("");
// Update UI with counts
$.each(categoryCounts, function (category, data) {
$("#count_tab_" + category.replace("tab_", "")).text(`(${data.count})`);
});
$('#selected_commodities_count').html(`${selectedItems.length}`);
console.log("Updated Counts:", categoryCounts);
}
// Function to open modal & check selected values
function openModal(modalId, dataArray, checkboxSelector) {
$(modalId).fadeIn();
console.log(`Raw Selected Data:`, dataArray);
// Ensure selectedItems is always an array and trim each value
let selectedItems = Array.isArray(dataArray)
? dataArray.map(item => item.trim())
: (dataArray ? dataArray.split(',').map(item => item.trim()) : []);
console.log(`Processed Selected Items:`, selectedItems);
$(modalId).find(checkboxSelector).each(function () {
$(this).prop('checked', selectedItems.includes($(this).val()));
});
updateCategoryCounts(); // Update counts on modal open
}
// Handle opening of "View Categories" modal
$(document).on('click', '#viewcategories', function () {
// Get values of selected commodities and categories
let selectedCommodities = $('#selected_commodities').val();
let selectedCategories = $('#selected_categories').val();
// console.log("Selected Commodities:", selectedCommodities);
// console.log("Selected Categories:", selectedCategories);
openModal("#specialPlanModal", selectedCategories, "input[type='checkbox']");
});
// Handle opening of "View Commodities" modal
$(document).on('click', '#viewcommodities', function () {
let selectedCommodities = $('#selected_commodities').val();
openModal("#CustomizedPlanModal_1", selectedCommodities, "input[type='checkbox']");
});
// Update category count when checkboxes change
$(document).on("change", '#CustomizedPlanModal_1 input[type="checkbox"]', updateCategoryCounts);
// Validate commodity selection before form submission
function validateCommoditySelection() {
var allowedPartialTypes = <?= json_encode(json_decode($partial_product_id)) ?>;
console.log("allowedPartialTypes:", allowedPartialTypes);
// var allowedPartialTypes = [4, 24, 25, 26, 32]; // must be an array, not a string!
var selectedProductType = $('select[name="subscription_type_[]"]').val();
var parsedSelectedType = parseInt(selectedProductType);
var isValidProductType = allowedPartialTypes.includes(parsedSelectedType);
var selectedCategories = []; // This would be loaded from PHP normally
selectedCategories = selectedCategories.map(String);
var isAtLeastOneSelected = $('#special-table-product input[type="checkbox"]:checked').length > 0;
var hasPreviousCommodities = selectedCategories.length > 0;
console.log("Validating Selection:");
console.log("Selected Categories:", selectedCategories);
console.log("Is at least one checkbox selected:", isAtLeastOneSelected);
console.log("Has previous commodities:", hasPreviousCommodities);
console.log("Is Valid Product Type:", isValidProductType);
if (isValidProductType && !isAtLeastOneSelected && !hasPreviousCommodities) {
$('#message').html('<div class="alert alert-danger">At least one commodity must be selected.</div>').fadeIn(100).delay(3000).fadeOut(100);
$('html, body').animate({ scrollTop: 0 }, 1000);
return false;
}
return true;
}
});
</script> |