
// Wait for DOM to load using both jQuery and vanilla JS
(function($) {
    $(document).ready(function() {
        // Initialize Bootstrap components safely
        if (typeof bootstrap !== 'undefined') {
            // Company Modal Handling
            const coModal = new bootstrap.Modal('#companyModal');
            const coForm = $('#companyForm');
            
            // Edit Company - Now properly scoped
            $(document).on('click', '.edit-company', function(event) {  // Changed 'e' to 'event'
                event.preventDefault();
                const companyId = $(this).data('id');
                
                $.get(base_url + 'administrator/settings/company', {id: companyId})
                    .done(function(response) {
                        if (response.data) {

                            const company = response.data;
                            // Populate form
                            coForm.find('input[name="id"]').val(company.id);
                            coForm.find('input[name="name"]').val(company.name);
                            coForm.find('input[name="email"]').val(company.email);
                            coForm.find('input[name="tel"]').val(company.tel);
                            coForm.find('input[name="tax_id"]').val(company.tax_id);
                            coForm.find('input[name="website"]').val(company.website);
                            coForm.find('select[name="default_currency_id"]').val(company.default_currency_id);
                            coForm.find('input[name="address_1"]').val(company.address_1);
                            coForm.find('input[name="address_2"]').val(company.address_2);
                            coForm.find('textarea[name="description"]').val(company.description);
                            coForm.find('input[name="area_code"]').val(company.area_code);
                            coForm.find('textarea[name="vision"]').val(company.vision);
                            coForm.find('textarea[name="mission"]').val(company.mission);
                            coForm.find('select[name="country_id"]').val(company.country_id);

                            if(company.photo !== null){
                                $("#display-image").html("<img src="+company.photo+" class='img-fluid'>");
                            }
                            
                            $('#companyModalLabel').text('Edit Company');
                            $(".sbtn").text("Update");
                            coModal.show();
                        }
                    })
                    .fail(function() {
                        toastr.error('Failed to load company data');
                    });
            });

            // Form submission handler
            coForm.on('submit', function(event) {  // Changed 'e' to 'event'
                event.preventDefault();
                // Create FormData object for file upload
                const formData = new FormData(this);
                
                $.ajax({
                    url: base_url + 'administrator/settings/company',
                    method: 'POST',
                    data: formData,
                    processData: false, // Required for file upload
                    contentType: false, // Required for file upload
                    dataType: 'json',
                    success: function(response) {
                        if (response.success) {
                            toastr.success(response.message);
                            coModal.hide();
                            setTimeout(() => location.reload(), 1000);
                        } else {
                            if (response.errors) {
                                // Clear previous errors
                                $('.invalid-feedback').text('');
                                $('.is-invalid').removeClass('is-invalid');
                                
                                // Display new errors
                                $.each(response.errors, function(key, value) {
                                    const input = coForm.find('[name="' + key + '"]');
                                    input.addClass('is-invalid');
                                    input.next('.invalid-feedback').text(value);
                                });
                            } else {
                                toastr.error(response.message || 'An error occurred');
                            }
                        }
                    },
                    error: function(xhr) {
                        toastr.error('Server error occurred. Please try again.');
                        console.error(xhr.responseText);
                    }
                });
            });
            
        } else {
            console.error('Bootstrap not loaded!');
        }
    });
})(jQuery);



$(document).ready(function() {
    // Initialize DataTables
    $('#permissionTable, #statusTable').DataTable();

/**====================================================================
*   project PERMISSIONS
*=======================================================================*/

    const permiModal = new bootstrap.Modal('#permissionModal');
    const permiForm = $('#permissionForm');
    
    // Open modal for Permission
    $('[data-bs-target="#permissionModal"]').click(function() {
        permiForm[0].reset();
        permiForm.find('input[name="id"]').val('');
        $('#permissionModalLabel').text('Add New Permission');
    });
    
    // Edit Permission
    $(document).on('click', '.edit-permission', function() {
        const permissionId = $(this).data('id');
        
        $.get(base_url +`administrator/settings/permissions`, {id: permissionId}, function(response) {
            if (response.data) {
                const permission = response.data;
                
                permiForm.find('input[name="id"]').val(permission.id);
                permiForm.find('input[name="name"]').val(permission.name);
                permiForm.find('select[name="parent_id"]').val(permission.parent_id || '');
                permiForm.find('select[name="module_section_id"]').val(permission.module_section_id);
                permiForm.find('input[name="module"]').val(permission.module);
                permiForm.find('textarea[name="description"]').val(permission.description || '');
                 
                $('#permissionModalLabel').text('Edit Permission');
                permiModal.show();
            }
        });
    });
    
    // Submit Permission form
    permiForm.submit(function(e) {
        e.preventDefault();
        
        $.ajax({
            url: base_url + 'administrator/settings/permissions',
            method: 'POST',
            data: permiForm.serialize(),
            success: function(response) {
                if (response.success) {
                    toastr.success(response.message);
                    permiModal.hide();
                    setTimeout(() => location.reload(), 1000);
                } else {
                    toastr.error('An error occurred');
                }
            },
            error: function(xhr) {
                const errors = xhr.responseJSON?.errors;
                if (errors) {
                    $.each(errors, function(key, value) {
                        const input = permiForm.find(`[name="${key}"]`);
                        input.addClass('is-invalid');
                        input.next('.invalid-feedback').text(value);
                    });
                }
            }
        });
    });
});

(function($) {
    $(document).ready(function() {
/**====================================================================
*   Policy
*=======================================================================*/
    // Initialize modal and form
    const policyModal = new bootstrap.Modal('#policyModal');
    const policyForm = $('#policyModal form');

    // Add new policy
    $('[data-bs-target="#policyModal"]').click(function() {
        policyForm[0].reset();
        policyForm.find('input[name="id"]').val('');
        $('#staticBackdropLabel').text('Add New Policy');
        $(".sbtn").text("Save Policy");
        //clearValidationErrors();
    });

    // Edit policy
    $(document).on('click', '.edit-policy', function(e) {
        e.preventDefault();
        const policyId = $(this).data('id');
        
        $.get(base_url + 'administrator/settings/policies', {id: policyId}, function(response)
        {
                if (response.data) {

                    const policy = response.data;

                    // Populate form
                    policyForm.find('input[name="id"]').val(policy.id);
                    policyForm.find('input[name="title"]').val(policy.title);
                    policyForm.find('select[name="policy_type"]').val(policy.policy_type);
                    policyForm.find('textarea[name="description"]').val(policy.description);

                    
                    // Show current photo if exists
                    if (response.data.photo) {
                        $('#currentPhoto').html(`
                            <div class="mb-3">
                                <label class="form-label">Current Photo</label>
                                <img src="${response.data.photo}" class="img-thumbnail" style="max-height: 50px;">
                                <div class="form-text" style="font-size:10px;color:#f00;">Leave blank to keep existing</div>
                            </div>
                        `).show();
                    } else {
                        $('#currentPhoto').hide();
                    }
                    
                    // Update UI
                    $('#staticBackdropLabel').text('Edit Policy');
                    $(".sbtn").text("Update Policy");
                    
                    // Show modal
                    policyModal.show();
                } else {
                    toastr.error('Policy data not found');
                }
            })
            .fail(function() {
                toastr.error('Failed to load policy data');
            });
    });

    // Form submission
    policyForm.on('submit', function(e) {
        e.preventDefault();
        
        const formData = new FormData(this);
        
        $.ajax({
            url: policyForm.attr('action'),
            method: 'POST',
            data: formData,
            processData: false,
            contentType: false,
            dataType: 'json',
            success: function(response) {
                if (response.success) {
                    toastr.success(response.message);
                    policyModal.hide();
                    setTimeout(() => location.reload(), 1000);
                } else {
                    handleErrors(response);
                }
            },
            error: function(xhr) {
                toastr.error('Server error occurred. Please try again.');
                console.error(xhr.responseText);
            }
        });
    

    // Helper functions
    

    function handleErrors(response) {
        //clearValidationErrors();
        if (response.errors) {
            $.each(response.errors, function(key, value) {
                const input = policyForm.find('[name="' + key + '"]');
                input.addClass('is-invalid');
                input.next('.invalid-feedback').text(value);
            });
        } else {
            toastr.error(response.message || 'An error occurred');
        }
    }

});

});
})(jQuery);


//Delete Permission
function delete_permission(id, name){
    var confirmation = confirm('Are you sure want to delete this permission? ' + name);
    if(confirmation == true){
        window.location.href = base_url + ('administrator/settings/delete-permission/')+ id;
    }
}

//Delete Policy
function delete_policy(id, name){
    var confirmation = confirm('Are you sure want to delete this policy? ' + name);
    if(confirmation == true){
        window.location.href = base_url + ('administrator/settings/delete-policy/')+ id;
    }
}

//Module Sections
function add_module_section(){
   $("#modSectionModal").modal('show');
    start_load()
         
            $(".modal-title").text("Create Module Section");
            $(".sbtn").text("Save");
            setTimeout(function(){
            end_load();
    },500)
}

function edit_module_section(id)
{
    $("#modSectionModal").modal('show');
    $.ajax({
        url:  base_url + 'administrator/settings/module-sections/edit/'+ id,
        type: "GET",
        dataType: "JSON",
        success: function(data)
        {
            $('[name="id"]').val(data.id);
            $('[name="name"]').val(data.name);
            $('[name="sort_order"]').val(data.sort_order);
            $('[name = "icon"]').val(data.icon);
            $('[name = "is_active"]').val(data.is_active);
            $('[name = "description"]').val(data.description);

            
            // Change form action to update URL
            $("form").attr("action", base_url + "administrator/settings/module-sections/update");
            
            //load modal
            start_load()
            $("#modSectionModal").modal('show');
            $(".modal-title").text("Edit Module Section!");
            $(".sbtn").text("Update");
            setTimeout(function(){
            end_load();
        },500)
        }
    });
}
function delete_module_section(id, name)
{
  var confirmation = confirm('Are you sure you want to delete ' + name + ' Module?');
  if (confirmation) {
      window.location.href = base_url + '/administrator/settings/module-sections/delete/' + id;
  }
}

