document.addEventListener("DOMContentLoaded", function() {
if (typeof jQuery === 'undefined') {
console.error('jQuery is required for client-modals.js to work.');
return;
}
$(document).ready(function() {
// Generic AJAX handler for standard forms (Shortcodes & Payments)
// $(document).on('submit', '#shortcodeForm, #paymentForm, #noteForm', function(e) {
$(document).on('submit', '#shortcodeForm, #paymentForm, #noteForm, #editNoteForm, #editShortcodeForm, #editPaymentForm', function(e) {
e.preventDefault();
let $form = $(this);
let modalId = '#' + $form.closest('.modal').attr('id');
let $submitBtn = $form.find('button[type="submit"]');
let originalBtnText = $submitBtn.text();
$submitBtn.prop('disabled', true).text('Saving...');
$.ajax({
url: $form.attr('action'),
type: 'POST',
data: $form.serialize(),
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
success: function(response) {
$(modalId).modal('hide');
$form[0].reset();
// Success SweetAlert
Swal.fire({
icon: 'success',
title: 'Success!',
text: response.message || 'Record saved successfully.',
confirmButtonColor: '#0d6efd'
}).then(() => {
location.reload();
});
},
error: function(xhr) {
let errors = xhr.responseJSON?.errors;
let errorMsg = 'Something went wrong. Please check your inputs.';
if (errors) {
errorMsg = Object.values(errors).flat().join('\n');
}
// Error SweetAlert
Swal.fire({
icon: 'error',
title: 'Validation Error',
text: errorMsg,
confirmButtonColor: '#dc3545'
});
$submitBtn.prop('disabled', false).text(originalBtnText);
}
});
});
// AJAX handler for Document Upload (FormData)
$(document).on('submit', '#documentForm', function(e) {
e.preventDefault();
let formElement = this;
let $form = $(this);
let formData = new FormData(formElement);
let modalId = '#' + $form.closest('.modal').attr('id');
let $submitBtn = $form.find('button[type="submit"]');
let originalBtnText = $submitBtn.text();
$submitBtn.prop('disabled', true).text('Uploading...');
$.ajax({
url: $form.attr('action'),
type: 'POST',
data: formData,
processData: false,
contentType: false,
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
success: function(response) {
$(modalId).modal('hide');
formElement.reset();
// Success SweetAlert
Swal.fire({
icon: 'success',
title: 'Uploaded!',
text: response.message || 'Document uploaded successfully.',
confirmButtonColor: '#0d6efd'
}).then(() => {
location.reload();
});
},
error: function(xhr) {
let errors = xhr.responseJSON?.errors;
let errorMsg = 'Failed to upload document. Please check the file size and format.';
if (errors) {
errorMsg = Object.values(errors).flat().join('\n');
}
// Error SweetAlert
Swal.fire({
icon: 'error',
title: 'Upload Failed',
text: errorMsg,
confirmButtonColor: '#dc3545'
});
$submitBtn.prop('disabled', false).text(originalBtnText);
}
});
});
// Initialize Select2 for Payment Services when modal opens
$('#addPaymentModal').on('shown.bs.modal', function () {
let $select = $('#paymentServicesSelect');
// Only fetch if options haven't been loaded yet
if ($select.children('option').length === 0) {
$.ajax({
url: base_url + '/api/services',
type: 'GET',
success: function(data) {
$select.empty();
data.forEach(function(service) {
$select.append(new Option(service.name, service.name, false, false));
});
// Initialize Select2 with Bootstrap 5 theme
$select.select2({
theme: 'bootstrap-5',
dropdownParent: $('#addPaymentModal'),
placeholder: 'Search and select services...'
});
},
error: function() {
console.error('Failed to load services for Select2.');
}
});
} else {
// If already loaded, just re-initialize if needed
$select.select2({
theme: 'bootstrap-5',
dropdownParent: $('#addPaymentModal'),
placeholder: 'Search and select services...'
});
}
});
// Initialize Select2 for Note Services when modal opens
$('#addNoteModal').on('shown.bs.modal', function () {
let $select = $('#noteServicesSelect');
if ($select.children('option').length === 0) {
$.ajax({
url: base_url + '/api/services',
type: 'GET',
success: function(data) {
$select.empty();
data.forEach(function(service) {
$select.append(new Option(service.name, service.id, false, false));
});
$select.select2({
theme: 'bootstrap-5',
dropdownParent: $('#addNoteModal'),
placeholder: 'Search and select services...'
});
}
});
} else {
$select.select2({
theme: 'bootstrap-5',
dropdownParent: $('#addNoteModal'),
placeholder: 'Search and select services...'
});
}
});
// Clear Select2 values when modal is closed
$('#addNoteModal').on('hidden.bs.modal', function () {
$('#noteServicesSelect').val(null).trigger('change');
});
// Clear Select2 values when modal is closed
$('#addPaymentModal').on('hidden.bs.modal', function () {
$('#paymentServicesSelect').val(null).trigger('change');
});
// --- DYNAMIC DOCUMENT ROW HANDLERS ---
$('#addRowBtn').on('click', function() {
let rowHtml = `
`;
$('#fileRowsContainer').append(rowHtml);
updateRemoveButtons();
});
// Remove row click handler
$(document).on('click', '.remove-row-btn', function() {
$(this).closest('.file-row').remove();
updateRemoveButtons();
});
// Hide delete button if only 1 row remains
function updateRemoveButtons() {
let totalRows = $('.file-row').length;
if (totalRows === 1) {
$('.remove-row-btn').hide();
} else {
$('.remove-row-btn').show();
}
}
// Reset modal fields when closed
$('#uploadDocumentModal').on('hidden.bs.modal', function() {
$('#documentForm')[0].reset();
$('#fileRowsContainer').html(`
`);
});
// 1. Populate Edit Client Modal when opened
$(document).on('click', '[data-bs-target="#editClientModal"]', function() {
let clientId = $(this).data('client-id');
let $form = $('#editClientForm');
$form.attr('action', base_url + '/clients/' + clientId);
// Fetch Services first, then Client data
$.ajax({
url: base_url + '/api/services',
type: 'GET',
success: function(services) {
let $servicesSelect = $('#edit_services');
$servicesSelect.empty();
services.forEach(function(s) {
$servicesSelect.append(new Option(s.name, s.id));
});
// Now fetch client details
$.ajax({
url: base_url + '/clients/' + clientId + '/json',
type: 'GET',
success: function(client) {
$('#edit_name').val(client.name);
$('#edit_email').val(client.email);
$('#edit_phone').val(client.phone);
$('#edit_contact_person').val(client.contact_person);
$('#edit_company_type').val(client.company_type);
$('#edit_contract_type').val(client.contract_type);
$('#edit_industry').val(client.industry);
$('#edit_status').val(client.status);
$('#edit_currency').val(client.currency);
$('#edit_country').val(client.country);
// Helper function to set values for Select2 multi-select tags fields
function setSelect2Values(selector, values) {
let $el = $(selector);
$el.val(null).trigger('change');
if (values && Array.isArray(values)) {
values.forEach(function(val) {
if ($el.find("option[value='" + val + "']").length === 0) {
$el.append(new Option(val, val, true, true));
}
});
$el.val(values).trigger('change');
}
}
setSelect2Values('#edit_services', client.services);
setSelect2Values('#edit_message_types', client.message_types);
setSelect2Values('#edit_connections', client.connections);
setSelect2Values('#edit_support_phones', client.support_phones);
setSelect2Values('#edit_support_emails', client.support_emails);
setSelect2Values('#edit_rate_emails', client.rate_emails);
setSelect2Values('#edit_support_skype', client.support_skype);
}
});
}
});
});
// Initialize Select2 with tags option enabled for all multi-select fields inside edit modal
$('#editClientModal').on('shown.bs.modal', function () {
$('#editClientModal .select2-tags').each(function() {
if (!$(this).hasClass("select2-hidden-accessible")) {
$(this).select2({
theme: 'bootstrap-5',
dropdownParent: $('#editClientModal'),
tags: true, // Allows typing custom entries for emails, phones, etc.
tokenSeparators: [',', ' '],
placeholder: 'Select or type and hit enter...'
});
}
});
});
// Clean up Select2 when modal closes
$('#editClientModal').on('hidden.bs.modal', function () {
$('#editClientModal .select2-tags').val(null).trigger('change');
});
// Submit Edit Client Form via AJAX
$(document).on('submit', '#editClientForm', function(e) {
e.preventDefault(); // Hard stop on native form post
let $form = $(this);
let $submitBtn = $form.find('button[type="submit"]');
let originalBtnText = $submitBtn.text();
$submitBtn.prop('disabled', true).text('Updating...');
$.ajax({
url: $form.attr('action'),
type: 'POST',
data: $form.serialize(),
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
success: function(response) {
$('#editClientModal').modal('hide');
Swal.fire({
icon: 'success',
title: 'Updated!',
text: response.message || 'Client updated successfully.',
confirmButtonColor: '#0d6efd'
}).then(() => {
location.reload();
});
},
error: function(xhr) {
let errors = xhr.responseJSON?.errors;
let errorMsg = 'Something went wrong. Please check your inputs.';
if (errors) {
errorMsg = Object.values(errors).flat().join('\n');
}
Swal.fire({
icon: 'error',
title: 'Validation Error',
text: errorMsg,
confirmButtonColor: '#dc3545'
});
$submitBtn.prop('disabled', false).text(originalBtnText);
}
});
});
// Confirm and Delete Note
$(document).on('click', '.delete-note-btn', function() {
let id = $(this).data('id');
if(confirm("Are you sure you want to delete this note? This action cannot be undone.")) {
// Send AJAX DELETE request using the meta tag for CSRF
$.ajax({
url: `/notes/${id}`,
type: 'DELETE',
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
success: function(res) {
location.reload();
}
});
}
});
// Confirm and Delete Short Code
$(document).on('click', '.delete-shortcode-btn', function() {
let id = $(this).data('id');
if(confirm("Are you sure you want to delete this short code?")) {
$.ajax({
url: `/shortcodes/${id}`,
type: 'DELETE',
headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') },
success: function(res) { location.reload(); }
});
}
});
// Confirm and Delete Payment
$(document).on('click', '.delete-payment-btn', function() {
let id = $(this).data('id');
if(confirm("Are you sure you want to delete this payment record?")) {
$.ajax({
url: `/payments/${id}`,
type: 'DELETE',
headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') },
success: function(res) { location.reload(); }
});
}
});
// --- POPULATE NOTE EDIT MODAL ---
$(document).on('click', '.edit-note-btn', function() {
let id = $(this).data('id');
let body = $(this).closest('.list-group-item').find('p').text();
$('#edit_note_id').val(id);
$('#edit_note_body').val(body);
$('#editNoteForm').attr('action', `/notes/${id}`);
// Replaced vanilla JS with jQuery modal show
$('#editNoteModal').modal('show');
});
// --- POPULATE SHORT CODE EDIT MODAL ---
$(document).on('click', '.edit-shortcode-btn', function() {
let id = $(this).data('id');
$('#edit_shortcode_id').val(id);
$('#edit_sc_type').val($(this).data('type'));
$('#edit_sc_code').val($(this).data('code'));
$('#edit_sc_network').val($(this).data('network'));
$('#edit_sc_status').val($(this).data('status'));
$('#edit_sc_expiry').val($(this).data('expiry'));
$('#edit_sc_remarks').val($(this).data('remarks'));
$('#editShortcodeForm').attr('action', `/shortcodes/${id}`);
// Replaced vanilla JS with jQuery modal show
$('#editShortcodeModal').modal('show');
});
// --- POPULATE PAYMENT EDIT MODAL ---
$(document).on('click', '.edit-payment-btn', function() {
let id = $(this).data('id');
$('#edit_payment_id').val(id);
$('#edit_pay_invoice').val($(this).data('invoice'));
$('#edit_pay_amount').val($(this).data('amount'));
$('#edit_pay_date').val($(this).data('date'));
$('#edit_pay_status').val($(this).data('status'));
$('#editPaymentForm').attr('action', `/payments/${id}`);
// Replaced vanilla JS with jQuery modal show
$('#editPaymentModal').modal('show');
});
}); // <-- End of the main $(document).ready
});