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) { 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); } }); }); }); });