/**
 * Purchase Return Types Module JavaScript
 * Auto-generated on August 5, 2025
 */

$(document).ready(function() {
    // Initialize form validation
    init_validation();
    
    // Auto-focus first field
    $('#purchase_return_type_name').focus();
});

/**
 * Initialize form validation
 */
function init_validation() {
    // Remove validation messages on input
    $('input, textarea, select').on('input change', function() {
        $('#' + $(this).attr('id') + '_msg').fadeOut(200).hide();
        $(this).removeClass('required');
    });
}

/**
 * Validate required field
 */
function check_field(id) {
    if(!$("#" + id).val().trim()) {
        $('#' + id + '_msg').fadeIn(200).show().html('Required Field').addClass('required');
        $('#' + id).addClass('required');
        return false;
    } else {
        $('#' + id + '_msg').fadeOut(200).hide();
        $('#' + id).removeClass('required');
        return true;
    }
}

/**
 * Validate all form fields
 */
function validate_form() {
    var flag = true;
    
    // Required field validations
    if(!check_field('purchase_return_type_name')) flag = false;
    if(!check_field('purchase_return_type_initial')) flag = false;
    
    return flag;
}

/**
 * Save/Update button click handler
 */
$('#save, #update').on("click", function (e) {
    e.preventDefault();
    
    var base_url = $("#base_url").val();
    var this_id = this.id;
    
    // Validate form
    if(!validate_form()) {
        toastr["warning"]("Please fill all required fields!");
        return false;
    }
    
    // Prepare form data
    var form_data = new FormData($('#purchase-return-types-form')[0]);
    
    // XSS validation
    if(!xss_validation(form_data)) { 
        return false; 
    }
    
    // Show loading
    $(".box").append('<div class="overlay"><i class="fa fa-refresh fa-spin"></i></div>');
    $("#" + this_id).attr('disabled', true);
    
    // Determine URL
    var url = (this_id == "save") ? 
        base_url + 'purchase_return_types/new_purchase_return_type' : 
        base_url + 'purchase_return_types/update_purchase_return_type';
    
    // AJAX request
    $.ajax({
        type: 'POST',
        url: url,
        data: form_data,
        cache: false,
        contentType: false,
        processData: false,
        success: function(result) {
            if(result == "success") {
                if(this_id == "save") {
                    toastr["success"]("Purchase Return Type added successfully!");
                } else {
                    toastr["success"]("Purchase Return Type updated successfully!");
                }
                setTimeout(function() {
                    window.location = base_url + "purchase_return_types";
                }, 1000);
            } else if(result == "failed") {
                toastr["error"]("Operation failed! Please try again.");
            } else {
                toastr["error"](result);
            }
        },
        error: function(xhr, status, error) {
            toastr["error"]("An error occurred: " + error);
        },
        complete: function() {
            $("#" + this_id).attr('disabled', false);
            $(".overlay").remove();
        }
    });
});

/**
 * Reset form
 */
function reset_form() {
    $('#purchase-return-types-form')[0].reset();
    $('.form-group').removeClass('has-error');
    $('.help-block').hide();
    $('#purchase_return_type_name').focus();
}

/**
 * Cancel button handler
 */
$('.btn-cancel').on('click', function() {
    if(confirm('Are you sure you want to cancel? Any unsaved changes will be lost.')) {
        window.location = $("#base_url").val() + "purchase_return_types";
    }
});

/**
 * Auto convert initials to uppercase
 */
$('#purchase_return_type_initial').on('input', function() {
    this.value = this.value.toUpperCase();
});

/**
 * Form validation on keypress
 */
$(document).on('keypress', function(e) {
    if (e.which == 13) { // Enter key
        e.preventDefault();
        var focused = $(':focus');
        if (focused.length > 0) {
            var next = focused.next(':input:visible');
            if (next.length > 0) {
                next.focus();
            } else {
                $('#save, #update').click();
            }
        }
    }
});

/**
 * Modal support for quick add (if needed)
 */
function add_purchase_return_type_modal() {
    var form_data = new FormData($('#purchase-return-types-form')[0]);
    
    if(!validate_form()) {
        toastr["warning"]("Please fill all required fields!");
        return false;
    }
    
    $.ajax({
        type: 'POST',
        url: $("#base_url").val() + 'purchase_return_types/add_purchase_return_type_modal',
        data: form_data,
        cache: false,
        contentType: false,
        processData: false,
        success: function(result) {
            try {
                var data = JSON.parse(result);
                if(data.result == "success") {
                    toastr["success"]("Purchase Return Type added successfully!");
                    // Add to dropdown if exists
                    if($('#purchase_return_type_id').length > 0) {
                        $('#purchase_return_type_id').append('<option value="' + data.id + '">' + data.purchase_return_type + '</option>');
                        $('#purchase_return_type_id').val(data.id);
                    }
                    $('#purchase_return_type_modal').modal('hide');
                    reset_form();
                } else {
                    toastr["error"](data.result);
                }
            } catch(e) {
                toastr["error"](result);
            }
        },
        error: function(xhr, status, error) {
            toastr["error"]("An error occurred: " + error);
        }
    });
}
