Untitled

 avatar
unknown
plain_text
6 months ago
38 kB
4
Indexable
<script type="text/javascript">
    let pevalue;
    function customeropen() {
        $('select[name^="contact_id"]').focus();
    }

    window.onload = customeropen();

    function opentech() {

        $('select[name^="service_staff"]').focus();
        
      };
      
      function devicemodel() {

        $('select[name^="device_model_id"]').focus();
        
      };

      function opencustomer(){
        $('select[name^="contact_id"]').focus();
      }

      function openbrand(){
        $('select[name^="brand_id"]').focus();
      }

      function openstatus(){
        $('select[name^="status_id"]').focus();
      }
      function serialinput(){
        document.getElementByname('serial_no').focus();

      }

        Dropzone.autoDiscover = false;
        $(function () {
            var file_names = [];
            $("div#imageUpload").dropzone({
                url: base_path+'/post-document-upload',
                paramName: 'file',
                uploadMultiple: true,
                autoProcessQueue: true,
                timeout:600000, //10 min
                acceptedFiles: '{{$accepted_files}}',
                maxFiles: 4,
                headers: {
                    'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                },
                success: function(file, response) {
                    if (response.success) {
                        toastr.success(response.msg);
                        file_names.push(response.file_name);
                        $('input#images').val(JSON.stringify(file_names));
                    } else {
                        toastr.error(response.msg);
                    }
                },
            });
    
            $(document).on('click', '.delete_media', function (e) {
                e.preventDefault();
                var url = $(this).data('href');
                var this_btn = $(this);
                swal({
                    title: LANG.sure,
                    icon: "warning",
                    buttons: true,
                    dangerMode: true,
                }).then((confirmed) => {
                    if (confirmed) {
                        $.ajax({
                            method: 'GET',  
                            url: url,
                            dataType: 'json',
                            success: function(result) {
                                if(result.success == true){
                                    this_btn.closest('tr').remove();
                                    toastr.success(result.msg);
                                } else {
                                    toastr.error(result.msg);
                                }
                            }
                        });
                    }
                });
            });
        });
</script>
<script type="text/javascript">
    var Iserror=false;
        $(document).ready( function() {
            $('.submit_button').click( function(){
                $('#submit_type').val($(this).attr('value'));      
            });
            $('form#job_sheet_form').validate({
                errorPlacement: function(error, element) {
                    if (element.parent('.iradio_square-blue').length) {
                        $('.loader').removeClass('d-block')      
                        $('.loader').addClass('d-none') 
                        error.insertAfter($(".radio_btns"));      
                    } else if (element.hasClass('status')) {
                        $('.loader').removeClass('d-block')      
                        $('.loader').addClass('d-none') 
                        error.insertAfter(element.parent());
                    } else {
                        $('.loader').removeClass('d-block')      
                        $('.loader').addClass('d-none') 
                        error.insertAfter(element);

                    }
                },
                submitHandler: function(form) {
                    let adv_pay=parseInt($('#input_advance_pay').val())
                    let est_cost=parseInt($('#est_cost').val())
                    if(adv_pay>est_cost){
                        toastr.error('Advanced amount must not be greater than Estimated Amount');
                    }else{
                        form.submit();
                        $('.submit_button').prop('disabled','true');
                        setTimeout(() => {
                            $('.loader').removeClass('d-block')      
                                $('.loader').addClass('d-none') 
                        }, 5000);
                    }
                }
            });

            var data = [{
              id: "",
              text: '@lang("messages.please_select")',
              html: '@lang("messages.please_select")',
              is_complete : '0',
            }, 
            @foreach($repair_statuses as $repair_status)
                {
                id: {{$repair_status->id}},
                is_complete : '{{$repair_status->is_completed_status}}',
                @if(!empty($repair_status->color))
                    text: '<i class="fa fa-circle" aria-hidden="true" style="color: {{$repair_status->color}};"></i> {{$repair_status->name}}',
                    title: '{{$repair_status->name}}'
                @else
                    text: "{{$repair_status->name}}"
                @endif
                },
            @endforeach
            ];

            $("select#status_id").select2({
                data: data,
                escapeMarkup: function(markup) {
                    return markup;
                },
                templateSelection: function (data, container) {
                    $(data.element).attr('data-is_complete', data.is_complete);
                    return data.text;
                }
            });

            @if(!empty($default_status))
                $("select#status_id").val({{$default_status}}).change();
            @endif

//till here
var activeDeviceForm = null; // To keep track of which form triggers the modal

// Initialize the pattern lock
var lock = new PatternLock("#pattern_container", {
        onDraw: function(pattern) {
            if (activeDeviceForm) {
                activeDeviceForm.find('.security_pattern_input').val(pattern); // Store the drawn pattern
                console.log('Pattern drawn for:', activeDeviceForm.attr('id'), 'Pattern:', pattern);
            }
        },
        enableSetPattern: true
    });

    // When the "Pattern Lock" button is clicked, store the form that triggered the modal
    $(document).on('click', '.btn[data-target="#security_pattern"]', function() {
        activeDeviceForm = $(this).closest('.device-box'); // Store the device form that opened the modal

        var currentPattern = activeDeviceForm.find('.security_pattern_input').val(); // Get the existing pattern for the form

        // Reset the pattern in the modal (clear the visual pattern)
        lock.reset();

        // If the form already has a saved pattern, set it on the pattern lock
        if (currentPattern) {
            lock.setPattern(currentPattern); // This is the part where you set the previously drawn pattern
            console.log('Setting pattern for form:', activeDeviceForm.attr('id'), 'Pattern:', currentPattern);
        }
    });

    // When the "Save" button in the modal is clicked
    $(document).on('click', '.save-pattern-btn', function() {
        // Get the drawn pattern from the lock
        var pattern = lock.getPattern();

        // Ensure the drawn pattern is correctly saved in the input field of the active form
        if (activeDeviceForm) {
            activeDeviceForm.find('.security_pattern_input').val(pattern);

            // Print the saved pattern in the console
            console.log('Saved pattern for device:', activeDeviceForm.attr('id'), 'Pattern:', pattern);
        }

        // Close the modal (optional)
        $('#security_pattern').modal('hide');
    });
            
            // When brand is changed
            // Handle brand change
$(document).on('change', '.brand_id', function() {
    var currentForm = $(this).closest('.device-box'); // Get the specific form
    var selectedBrand = $(this).val();
    
    console.log('Selected brand:', selectedBrand);  // Log the selected brand
    currentForm.find('select.device_id').focus(); // Focus on the device_id in the same form
    currentForm.find(".related-items").empty(); // Clear related items for this specific form
});

// Handle device change
$(document).on('change', '.device_id', function() {
    var currentForm = $(this).closest('.device-box'); // Get the specific form for this device
    var selectedDevice = $(this).val();
    
    console.log('Selected device:', selectedDevice);  // Log the selected device
    getModelForDevice(currentForm); // Pass the context to the function
    currentForm.find(".related-items").empty(); // Clear related items for this specific form
});

// Function to fetch the models for the selected device and brand
            function getModelForDevice(currentForm) {
                var device_id = currentForm.find('.device_id').val();
                var brand_id = currentForm.find('.brand_id').val();

                console.log('Device ID:', device_id);
                console.log('Brand ID:', brand_id);

                if (!device_id || !brand_id) {
                    console.error('Device ID or Brand ID is missing!');
                    return;
                }

                var data = {
                    device_id: device_id,
                    brand_id: brand_id
                };

                $.ajax({
                    method: 'GET',
                    url: '/repair/get-device-models',
                    dataType: 'html',
                    data: data,
                    success: function(result) {
                        console.log('Result from server:', result);

                        // Populate the correct device_model_id select in this specific form
                        currentForm.find('select.device_model_id').html(result);
                        currentForm.find('select.device_model_id').focus();

                        // Reinitialize Select2 for the new dropdown (if you are using Select2)
                        currentForm.find('select.device_model_id').select2();
                    },
                    error: function(xhr, status, error) {
                        console.error('Error fetching models:', error);
                    }
                });
            }
           
            function getModelRepairChecklists(deviceFormCount) {
                var deviceFormId = 'deviceForm_' + deviceFormCount;
                var arraycount = deviceFormCount-1;
                var deviceModelId = $('#' + deviceFormId).find('select[name^="device_model_id"]').val(); // Get the correct device model ID
                if (deviceModelId) {
                    $.ajax({
                        method: 'GET',
                        url: '/repair/models-repair-checklist',
                        dataType: 'html',
                        data: { model_id: deviceModelId, arraycount: arraycount }, // Send the selected model_id to the server
                        success: function (result) {
                            // Update only the checklist for the corresponding form
                            var checklistContainer = $('#' + deviceFormId).find('.append_checklists');
                            // Append checklist to the correct form's append_checklists container
                            checklistContainer.html(result);
                        },
                        error: function (xhr, status, error) {
                            console.log("Error in fetching checklist: ", error);
                        }
                    });
                }
            }

            function getModelRepairEstCosts(deviceFormCount) {
                var deviceFormId = 'deviceForm_' + deviceFormCount;
                var data = {
                    model_id: $('#' + deviceFormId).find('select[name^="device_model_id"]').val(),
                };

                $.ajax({
                    method: 'GET',
                    url: '/repair/models-repair-est-cost',
                    dataType: 'html',
                    data: data,
                    success: function(result) {
                        $('#' + deviceFormId).find(".append_est_costs").html(result);
                    }
                });
            }
            // $(document).ready(function() {
            //     $(document).on('change', '.device_model_id', function() {
            //         var currentForm = $(this).closest('form');
            //         getModelRepairChecklists(currentForm);
            //         getModelRepairEstCosts(currentForm);
            //     });
            // });
            $(document).on('change', 'select[name^="device_model_id"]', function () {
                var deviceFormId = $(this).closest('.device-box').attr('id'); // Get the form ID
                var deviceFormCount = deviceFormId.split('_')[1]; // Extract the form count
                            if (deviceFormId) {
                                // Pass the form count to the getModelRepairChecklists function
                                getModelRepairChecklists(deviceFormCount);
                                getModelRepairEstCosts(deviceFormCount);
                            } else {
                                console.error('Device form ID is undefined');
                            }
                        });




            // $('input[type=radio][name=service_type]').on('ifChecked', function(){
            //   if ($(this).val() == 'pick_up' || $(this).val() == 'on_site') {
            //     $("div.pick_up_onsite_addr").show();
            //   } else {
            //     $("div.pick_up_onsite_addr").hide();
            //   }
            // });
            $('#service_type').on('change', function() {
                var selectedValue = $(this).val();

                if (selectedValue === 'pick_up' || selectedValue === 'on_site') {
                    $("div.pick_up_onsite_addr").show();
                } else {
                    $("div.pick_up_onsite_addr").hide();
                }
            });

            //initialize file input
            $('#upload_job_sheet_image').fileinput({
                showUpload: false,
                showPreview: false,
                browseLabel: LANG.file_browse_label,
                removeLabel: LANG.remove
            });


            var product_condition = document.querySelector('textarea#product_condition');
            tagify_p_condition = new Tagify(product_condition, {
              whitelist: {!!json_encode($product_cond)!!},
              maxTags: 100,
              dropdown: {
                maxItems: 100,           // <- mixumum allowed rendered suggestions
                classname: "tags-look", // <- custom classname for this dropdown, so it could be targeted
                enabled: 0,             // <- show suggestions on focus
                closeOnSelect: false    // <- do not hide the suggestions dropdown once an item has been selected
              }
            });

           
        });
        $('.more_btn2').click(function(){
            $($(this).data('target')).toggleClass('hide');
        });
        $('.add_parts').click(function(){
            $($(this).data('target')).toggleClass('hide');
        });
</script>
<script type="text/javascript">
    $(document).on('click', '#add_device_model', function () {
            var url = $(this).data('href');
            $.ajax({
                method: 'GET',
                url: url,
                dataType: 'html',
                success: function(result) {
                    $('#device_model_modal').html(result).modal('show');
                }
            });
        });
</script>
<script type="text/javascript">
    $(document).on('submit', 'form#device_model', function(e){
            e.preventDefault();
            var url = $('form#device_model').attr('action');
            var method = $('form#device_model').attr('method');
            var data = $('form#device_model').serialize();
            var currentForm = $('#device_model_modal').closest('.device-box');
            $.ajax({
                method: method,
                dataType: "json",
                url: url,
                data:data,
                success: function(result){
                    if (result.success) {
                        var newOption = new Option(result.data.name, result.data.id, true, true);
                        $('#device_model_id').append(newOption).trigger('change');
                        $('#device_model_modal').modal("hide");
                        toastr.success(result.msg);
                        getModelForDevice(currentForm);
                        currentForm.find('select.device_model_id').val(result.data.id).trigger('change');
                        model_datatable.ajax.reload();
                    } else {
                        toastr.error(result.msg);
                    }
                }
            });
        });
</script>

<script type="text/javascript">
    $(document).on('submit', 'form#category_add_form', function(e) {
        e.preventDefault();
        var form = $(this);
        var data = form.serialize();

        $.ajax({
            method: 'POST',
            url: $(this).attr('action'),
            dataType: 'json',
            data: data,
            beforeSend: function(xhr) {
                __disable_submit_button(form.find('button[type="submit"]'));
            },
            success: function(result) {
                if (result.success === true) {
                    var newOption = new Option(result.data.name, result.data.id, true, true);
                    $('#device_id')
                    .append(newOption)
                    .trigger('change');
                    $('div.category_modal').modal('hide');
                    toastr.success(result.msg);
                    category_table.ajax.reload();
                    
                } else {
                    toastr.error(result.msg);
                }
            },
        });
    });

</script>

<script type="text/javascript">
    $(document).on('submit', 'form#status_form', function(e){
            e.preventDefault();
            $(this).find('button[type="submit"]').attr('disabled', true);
            var data = $(this).serialize();

            $.ajax({
                method: $(this).attr('method'),
                url: $(this).attr("action"),
                dataType: "json",
                data: data,
                success: function(result){
                    if(result.success == true){
                        let newOption = new Option(result.data.name, result.data.brand_id,result.data.id, true, true);
                    $('#status_id')
                    .append(newOption)
                    .trigger('change');

                        $('div.view_modal').modal('hide');
                        toastr.success(result.msg);
                        status_table.ajax.reload();
                    } else {
                        toastr.error(result.msg);
                    }
                }
            });
        });
</script>
<!--Added to refresh brand-->
<script type="text/javascript">
    $(document).on('submit', 'form#quick_add_brand_form', function(e){
            e.preventDefault();
            $(this).find('button[type="submit"]').attr('disabled', true);
            var fd = new FormData();
            var data = $(this).serialize();
              let files=$('#brand_image')[0].files;
              let name=$('#brand_name').val();
              let description=$('#brand_description').val();
              let use_for_repair=$('#brand_use_for_repair').val();
               fd.append('file',files[0])
               fd.append('name',name)
               fd.append('description',description)
               fd.append('use_for_repair',use_for_repair)

            $.ajax({
                method: $(this).attr('method'),
                url: $(this).attr("action"),
                dataType: "json",
                data: fd,
                contentType: false,
              processData: false,
                success: function(result){
                    if(result.success == true){
                        var newOption = new Option(result.data.name, result.data.id,result.data.id, true, true);
                    $('#brand_id')
                    .append(newOption)
                    .trigger('change');

                        $('div.view_modal').modal('hide');
                        toastr.success(result.msg);
                        brand_table.ajax.reload();
                    } else {
                        toastr.error(result.msg);
                    }
                }
            });
        });
</script>

<script type="text/javascript">
    $(document).ready( function(){
		$('#search_job_sheet_parts')
            .autocomplete({
                source: function(request, response) {
                    $.getJSON(
                        '/products/list',
                        { term: request.term },
                        response
                    );
                },
                minLength: 2,
                response: function(event, ui) {
                    if (ui.content.length == 1) {
                        ui.item = ui.content[0];
                        $(this)
                                .data('ui-autocomplete')
                                ._trigger('select', 'autocompleteselect', ui);
                        $(this).autocomplete('close');
                    } else if (ui.content.length == 0) {
                        swal(LANG.no_products_found);
                    }
                },
                select: function(event, ui) {
                   job_sheet_parts_row(ui.item.variation_id);
                },
            })
            .autocomplete('instance')._renderItem = function(ul, item) {
	            var string = '<div>' + item.name;
	                if (item.type == 'variable') {
	                    string += '-' + item.variation;
	                }
	                string += ' (' + item.sub_sku + ') </div>';
                   
	                return $('<li>')
	                    .append(string)
	                    .appendTo(ul);
        	};

       	//initialize editor
        tinymce.init({
            selector: 'textarea#email_body',
        });

        $('#send_sms').change(function() {
            if ($(this). is(":checked")) {
                $('div.sms_body').fadeIn();
            } else {
                $('div.sms_body').fadeOut();
            }
        });

        $('#send_email').change(function() {
            if ($(this). is(":checked")) {
                $('div.email_template').fadeIn();
            } else {
                $('div.email_template').fadeOut();
            }
        });

        if ($('#status_id_modal').length) {
            
            $("#sms_body").val($("#status_id_modal :selected").data('sms_template'));
            $("#email_subject").val($("#status_id_modal :selected").data('email_subject'));
            tinymce.activeEditor.setContent($("#status_id_modal :selected").data('email_body'));  
        }

        $('#status_id_modal').on('change', function() {
            var sms_template = $(this).find(':selected').data('sms_template');
            var email_subject = $(this).find(':selected').data('email_subject');
            var email_body = $(this).find(':selected').data('email_body');

            $("#sms_body").val(sms_template);
            $("#email_subject").val(email_subject);
            tinymce.activeEditor.setContent(email_body);

            if ($('#status_modal .mark-as-complete-btn').length) {
                if ($(this).find(':selected').data('is_completed_status') == 1) 
                {
                    $('#status_modal').find('.mark-as-complete-btn').removeClass('hide');
                    $('#status_modal').find('.mark-as-incomplete-btn').addClass('hide');
                } else {
                    $('#status_modal').find('.mark-as-complete-btn').addClass('hide');
                    $('#status_modal').find('.mark-as-incomplete-btn').removeClass('hide');
                }
            }
        });
	});
let availabe_data=[];
	function job_sheet_parts_row(variation_id) {
		var row_index = parseInt($('#product_row_index').val());
	    var location_id = $('select#location_id').val();
        let current_vid=$('.current_variation_id').val();

        if(!availabe_data.includes(variation_id))
        {
            availabe_data.push(variation_id)

	    $.ajax({
	        method: 'POST',
	        url: "{{action('\Modules\Repair\Http\Controllers\JobSheetController@jobsheetPartRow')}}",
	        data: { variation_id: variation_id },
	        success: function(result) {
                if (result==0) {
                    toastr.error('Item out of stock');
                    return false;
                }
	            $('table#job_sheet_parts_table tbody').append(result);
	            $('input#search_job_sheet_parts').val('')
	            $('input#search_job_sheet_parts')
                        .focus()
                        .select();
	            // for price calculation
                    part_amount=parseInt($(`.part_price${variation_id}`).val());
                    part_qty=parseInt($(`.part_price${variation_id}`).data('qty'));
                    total_part_amount+=part_amount
                    total_part_qty+=part_qty
                    let charge=$('#pack_charge').html()

                    loadAllamount(total_part_qty,total_part_amount,charge)
	        },
	    });
    }else{
        toastr.error('Item already added');

    }

	}
     
	$(document).on('click', '.remove_product_row', function(){
        // checking the id qty price and then subtracting 
        let vid=$(this).data('id')
        let price=$('#qty'+vid).attr('data-totalprice')
       let charge=$('#pack_charge').html()
    //    total_part_qty=total_part_qty-qty
       total_part_amount= total_part_amount-price
        loadAllamount(total_part_qty,total_part_amount,charge)
		$(this).closest('tr').remove();
        
	})




// calling function on chaning qttotalpricefocusy 

var total_part_amount=0;
var total_part_qty=0;
$(document).on('keyup', '.input_quantity', function(){
        
        let qty=$(this).val()
        let totalprice=parseInt($(this).attr('data-totalprice'))
        let unitprice=parseInt($(this).attr('data-price'))
       let charge=$('#pack_charge').html()
       let $price=0;
       if (qty.trim() !==null && qty.trim() !=='' && qty.trim().length>0) {

        let preqty=$(this).attr('data-preqty')
                        qty=parseInt(qty)
    $price=qty*unitprice;
      total_part_qty=total_part_qty-preqty+qty
    total_part_amount= parseInt(total_part_amount-totalprice+$price)
    loadAllamount(total_part_qty-1,total_part_amount,charge)
    $(this).attr('data-preqty',qty)
    $(this).attr('data-totalprice',parseInt($price))

       }
})



	$(document).on('click', '#submit_add_part_form', function(e){
		$('form#add_part_form').submit();
	})

    var val=0

    // fetching and showing  package price 
$(document).on('click','.types_of_service_modal .btn-default',function(){
    val= $('#packing_charge').val()
    setTimeout(() => {
    loadAllamount(total_part_qty,total_part_amount,val)
}, 500); 
})




$(document).on('keyup','#packing_charge',function(){
        setInterval(() => {
            val= $(this).val()
    loadAllamount(total_part_qty,total_part_amount,val)
        }, 500);
    })

function loadAllamount(part_qty,part_price,pack_charge){
    $('#part_qty').html(parseInt(part_qty))
    $('#part_price').html(parseInt(part_price))
    $('#pack_charge').html(parseInt(pack_charge))
    $('#grand_total').html(parseInt(pack_charge)+parseInt(part_price))
    $('#est_cost_span').html(parseInt(pack_charge)+parseInt(part_price))
    $('#est_cost').val(parseInt(pack_charge)+parseInt(part_price))
}

$('#input_advance_pay').keyup(function(){
    $('#adv_pay').html($(this).val())
})

$('.submit_button').click(function(){
    $('.loader').removeClass('d-none')      
    $('.loader').addClass('d-block')
 

  
})



// disable and active adavnced payment 

$('#types_of_service_id').on('change',function(){
    let id=$(this).val();
if(id.trim()){
   let val=$('#input_advance_pay').prop('readonly','')
}else{
   $('#input_advance_pay').prop('readonly','true')

}

});




// update price onthe basis of change price in modal 

$(document).on('click','.edit_price',function(){
let vid=$(this).data('vid')
let price=$(this).data('price')
let name=$(this).data('name')
$('.product_name').html(name)
$('#product_price').val(parseInt(price))
$('#product_price').attr('data-id',vid)

// loadAllamount(part_qty,part_price,pack_charge)

})

$(document).on('keyup','#product_price',function(){
    let val=$(this).val()
    let vid=$(this).attr('data-id')
let pretotal=parseInt($('#qty'+vid).attr('data-totalprice'));

   $('#'+vid).val(val);
   $('#price'+vid).html(val);
   $('#qty'+vid).attr('data-price',val);
   let qty=$('#qty'+vid).val();
let totalp=parseInt(qty*val);
$('#qty'+vid).attr('data-totalprice',totalp);

total_part_amount=total_part_amount-pretotal+totalp;
val= $('#pack_charge').html()
loadAllamount(total_part_qty,total_part_amount,val)


})

</script>
<script>
    var tour = new Tour({
  steps: [
  {
    element: "#my-element",
    title: "Title of my step",
    content: "Content of my step"
  },
  {
    element: "#my-other-element",
    title: "Title of my step",
    content: "Content of my step"
  }
]});
</script>
<script>
    $(document).ready(function() {
    var deviceFormCount = 1; 

    function initDatepicker() {
        $('.delivery_date').daterangepicker({
            singleDatePicker: true,
            timePicker: true,
            timePickerIncrement: 15,
            format: 'YYYY-MM-DD h:mm A'
        });
    }

    function reinitializeComponents(formElement) {
        initDatepicker();
        formElement.find('.datetimepicker').datetimepicker({
            format: moment_date_format + ' ' + moment_time_format,
            ignoreReadonly: true,
        });

        // Check if formElement is the original #deviceForm_1
    if (formElement.attr('id') !== 'deviceForm_1') {
        formElement.find('.defects').each(function() {
            var defectsTextarea = this;
            
            // Destroy existing Tagify instance
            if (defectsTextarea.tagify) {
                defectsTextarea.tagify.destroy();
            }

            // Reinitialize Tagify
            new Tagify(defectsTextarea, {
                whitelist: {!! json_encode($defects) !!},
                maxTags: 100,
                dropdown: {
                    maxItems: 100,
                    classname: "tags-look",
                    enabled: 0,
                    closeOnSelect: false
                }
            }, {
                wrapper: defectsTextarea.parentElement
            });
        });
    } else {
        // Initialize Tagify for original #deviceForm_1
        $('#defects_1').each(function() {
            var defectsTextarea = this;
            console.log("Tagify",defectsTextarea);
            
            // Destroy existing Tagify instance
            if (defectsTextarea.tagify) {
                defectsTextarea.tagify.destroy();
            }

            // Reinitialize Tagify
            new Tagify(defectsTextarea, {
                whitelist: {!! json_encode($defects) !!},
                maxTags: 100,
                dropdown: {
                    maxItems: 100,
                    classname: "tags-look",
                    enabled: 0,
                    closeOnSelect: false
                }
            }, {
                wrapper: defectsTextarea.parentElement
            });
        });
    }
    // Update checkbox names and IDs
    var deviceId = parseInt(formElement.attr('id').replace('deviceForm_', '')) || 0;
    formElement.find('input[type="checkbox"]').each(function() {
        var originalName = $(this).attr('name');
        $(this).attr('name', 'repair_checklist[' + deviceId + '][' + $(this).val() + ']');
        $(this).attr('id', 'checklist_device_' + deviceId + '_' + $(this).val());
    });
    }

    $('#addNewDeviceBtn').click(function() {
        deviceFormCount++;
        var deviceFormId = 'deviceForm_' + deviceFormCount; // Construct the deviceFormId
        console.log('Current deviceFormId:', deviceFormId);
        var activeDeviceForm = null;

        $('#deviceForm_1').find('.select2').each(function() {
            if ($(this).data('select2')) {
                $(this).select2('destroy');  
            }
        });

        var newDeviceForm = $('#deviceForm_1').clone().attr('id', 'deviceForm_' + deviceFormCount);
        var activeDeviceForm = null; // Track the active device form
// Append a unique hidden input for the pattern to the cloned form
// var patternInput = $('<input type="hidden" name="security_pattern[' + (deviceFormCount - 1) + '][]" id="security_pattern_' + deviceFormCount + '" class="security_pattern_input">');
//         patternInput.appendTo(newDeviceForm);
var patternInput = $('<input type="hidden" name="security_pattern[' + (deviceFormCount - 1) + ']" id="security_pattern_' + deviceFormCount + '" class="security_pattern_input">');


// // Initialize the pattern lock
// var lock = new PatternLock("#pattern_container", {
//     onDraw: function (pattern) {
//         // Store the drawn pattern in the hidden input field inside the modal
//         $('input#security_pattern').val(pattern);
        
//         // Log the drawn pattern
//         console.log('Pattern drawn:', pattern);
//     },
//     enableSetPattern: true
// });

// var patternInput = $('<input type="hidden" name="devices[' + deviceFormCount + '][pattern]" id="' + deviceFormCount + '_pattern">');
//     patternInput.appendTo(newDeviceForm);

// // When the "Pattern Lock" button is clicked, store the form that triggered the modal
// $(document).on('click', '.btn[data-target="#security_pattern"]', function () {
//     // Store the device form (device-box) that triggered the modal
//     activeDeviceForm = $(this).closest('.device-box');
    
//     // Log the form that opened the modal
//     console.log('Modal opened by device form:', activeDeviceForm.attr('id'));
// });

// // Handle modal close event
// $('#security_pattern').on('hidden.bs.modal', function () {
//     // Reset the pattern input in the modal when it's closed without saving
//     $('#security_pattern_input_modal').val('');
//     console.log('Modal closed, pattern reset');
// });
        // Correctly replace IDs
    newDeviceForm.find('[id]').each(function() {
        var originalId = $(this).attr('id');
        if (originalId && originalId.match(/_1$/)) { // Only replace _1 at the end of the ID
            var newId = originalId.replace('_1', '_' + deviceFormCount);
            $(this).attr('id', newId);
        }
    });

    // Correctly replace name attributes
    newDeviceForm.find('input, textarea').each(function() {
        var originalName = $(this).attr('name');
        if (originalName) {
            var newName = originalName.replace(/\[\d+\]/g, '[' + (deviceFormCount - 1) + ']');
            $(this).attr('name', newName);

            // Clear the value of input and textarea fields
            $(this).val('');
        }
    });
    // Remove Tagify's HTML structure from cloned form
    newDeviceForm.find('tags').remove();  // This removes any pre-existing tags from Device 1
    newDeviceForm.find('.tagify').remove();  // Removes any leftover Tagify container

        // Remove cloned checklist content
        newDeviceForm.find('.append_checklists').empty(); // Clear out any checklist that might have been cloned

        // Ensure unique IDs for the checklist section
        newDeviceForm.find('.append_checklists').attr('id', 'checklist_' + deviceFormCount);

        var deleteButton = '<button type="button" class="btn btn-danger remove-device-btn">Delete</button>';
        newDeviceForm.find('.delete-btn').html(deleteButton); 

        $('#devicesContainer').append(newDeviceForm);

        newDeviceForm.find('.select2').select2({
            width: 'resolve' 
        });

        reinitializeComponents(newDeviceForm);

    });

    $('#devicesContainer').on('click', '.remove-device-btn', function () {
        $(this).closest('.device-box').remove();
        console.log('Device form removed. Total forms:', $('.device-box').length);
    });

    reinitializeComponents($('#deviceForm_1'));
});
</script>
Editor is loading...
Leave a Comment