<script src="/js/plugins/dataTables/datatables.min.js"></script>
<script src="/js/plugins/jquery-validation/jquery.validate.min.js"></script>
<link href="/css/plugins/dataTables/fixedHeader.dataTables.min.css" rel="stylesheet">
<link rel="stylesheet" href="/css/plugins/dataTables/responsive.dataTables.min.css">
<script src="/js/plugins/dataTables/dataTables.responsive.min.js"></script>
<script src="/js/sweetalert2.all.min.js"></script>
<link href="/js/plugins/autocomplete/jquery-ui.css" rel="stylesheet">
<script src="/js/plugins/autocomplete/jquery-ui.min.js"></script>
<script>
    $(document).ready(function () {


        $.fn.serializeObject = function () {
            var obj = {};

            $.each(this.serializeArray(), function (i, o) {
                var n = o.name, v = o.value;

                obj[n] = obj[n] === undefined ? v
                    : $.isArray(obj[n]) ? obj[n].concat(v)
                        : [obj[n], v];
            });

            return obj;
        };

        $('.accessories-action-modal').on('hidden.bs.modal', function () {
            $('.error-div').html(''); // Clear the HTML content of the error-div
        });



        var table = $('.footable').DataTable({
            responsive: true,
            scrollX: false,
            scrollY: '400px',
            scrollCollapse: true,
            "processing": true,
            "serverSide": true,
            "fixedHeader": true,
            "ajax": {
                "url": "{{ route('accessories-data') }}",
                "dataType": "json",
                "type": "POST",
                "data": function (result) {
                    result.form = $('#asset-filter-form').serializeObject();
                }
            },
            "createdRow": function (row, data, dataIndex) {
                if (data['action_one'] === " ") {
                    $('td:eq(1)', row).attr('colspan', 2);
                    $('td:eq(2)', row).css('display', 'none');
                    this.api().cell($('td:eq(1)', row)).data(data['action_two']);
                }
            },
            "columns": [
                { "data": "id" },
                { "data": "action_one" },
                { "data": "action_two" },
                { "data": "action_three" },
                { "data": "location" },
                { "data": "hardware_standard" },
                { "data": "available_quantity" },
                { "data": "weekly_demand" },
                { "data": "lead_time" },
                { "data": "order_quantity" },
                { "data": "purchase_indicator" }
            ],
            lengthMenu: [
                [50, 100, 200],
                ['50', '100', '200']
            ],
            columnDefs: [
                { orderable: false, targets: '_all'}
            ],
            "aaSorting": [],
            "dom": '<"top"i>rt<"bottom"flp><"clear">',
            "bAutoWidth": false,
            "bFilter": true,
            "bLengthChange": false,
            "searching": false,

            "fnDrawCallback": function( oSettings ){
                // Check if the response data exists and has a purchaseIndicator
                if (oSettings.json && oSettings.json.purchaseIndicator) {
                    var purchaseIndicator = oSettings.json.purchaseIndicator;
                    if (purchaseIndicator == 1) {
                        // Construct the URL using JavaScript string concatenation
                        var purchaseFile = oSettings.json.purchaseFile;
                        var downloadUrl = '/download/' + purchaseFile; // Use the route directly
                        var buttonHtml = '<tr><td colspan="14" align="right"><a class="btn btn-primary" href="' + downloadUrl + '" style="text-decoration: none; color: #fff">Purchase</a></td></tr>';
                        $(oSettings.nTBody).append(buttonHtml);
                    }
                }
            },
        });

        $('.select2').select2();

        $('#asset-filter-form').submit(function (e) {
            e.preventDefault();
            table.draw();
        });

        $('.accessories-filter-field').on('change', function () {
            $('#asset-filter-form').submit();
        });


        $("#create-form").validate({
            rules: {
                location_id: {
                    required: true,
                },
                make_and_model_id: {
                    required: true,
                },
                technical_spec_id: {
                    required: true,
                },
                available_quantity: {
                    required: true,
                },
            },
            errorPlacement: function (error, element) {
                error.insertAfter($(element).parent().find($('.errorText')));
            },
        });

        $('#create').on('click', function (e) {
            e.preventDefault();

            if ($('#create-form').valid()) {
                var formData = $('#create-form').serialize();
                $.ajax({
                    type: "POST",
                    url: "{{route('accessories.store')}}",
                    data: formData,
                    success: function (value) {
                        if (value.status) {
                            $('#createModal').modal('hide');
                            $('#create-form')[0].reset();
                            $('#saved-search-success').html(value.message);
                            table.draw();
                        } else {
                            $('.error-div').html('<div class="alert alert-danger"><a href="#" class="close" data-dismiss="alert" aria-label="close">&times;</a><strong>Error! </strong>' + value.message + '</div>');
                        }
                    }
                });
            }
        });

        $('#move-form').validate({
            rules: {
                location_id: {
                    required: true,
                },
                available_quantity: {
                    required: true,
                },
            },
            errorPlacement: function (error, element) {
                error.insertAfter($(element).parent().find($('.errorText')));
            },
        });

        $('#move').on('click', function (e) {
            e.preventDefault();

            if ($('#move-form').valid()) {
                var formData = $('#move-form').serialize();
                var id = $('#moveId').val();
                if (($("#available_quantity").val() == $("#available_quantity").attr("max")) && $("#move").html() != "Confirm") {
                    $("#label-msg").html("You are trying to move all accessories from this location. Are you sure you want to continue?");
                    $("#move").html("Confirm");
                    return false;
                }
                $.ajax({
                    type: "POST",
                    url: "/accessories-move/" + id,
                    data: formData,
                    success: function (value) {
                        if (value.status) {
                            $('#moveModal').modal('hide');
                            $('#move-form')[0].reset();
                            $('#saved-search-success').html(value.message);
                            table.draw();
                        } else {
                            $('.error-div').html('<div class="alert alert-danger"><a href="#" class="close" data-dismiss="alert" aria-label="close">&times;</a><strong>Error! </strong>' + value.message + '</div>');
                        }
                    }
                });
            }
        });

        $('#add-form').validate({
            rules: {
                available_quantity: {
                    required: true,
                },
            },
            errorPlacement: function (error, element) {
                error.insertAfter($(element).parent().find($('.errorText')));
            },
        });

        $('#add').on('click', function (e) {
            e.preventDefault();

            if ($('#add-form').valid()) {
                var formData = $('#add-form').serialize();
                var id = $('#addId').val();
                $.ajax({
                    type: "POST",
                    url: "accessories-add/" + id,
                    data: formData,
                    success: function (value) {
                        if (value.status) {
                            $('#addModal').modal('hide');
                            $('#add-form')[0].reset();
                            $('#saved-search-success').html(value.message);
                            table.draw();
                        } else {
                            $('.error-div').html('<div class="alert alert-danger"><a href="#" class="close" data-dismiss="alert" aria-label="close">&times;</a><strong>Error! </strong>' + value.message + '</div>');
                        }
                    }
                });
            }
        });

        $('#use-form').validate({
            rules: {
                location_id: {
                    required: true,
                },
                available_quantity: {
                    required: true,
                },
            },
            errorPlacement: function (error, element) {
                error.insertAfter($(element).parent().find($('.errorText')));
            },
        });

        $('#use').on('click', function (e) {
            e.preventDefault();

            if ($('#use-form').valid()) {
                var formData = $('#use-form').serialize();
                var id = $('#useId').val();
                $.ajax({
                    type: "POST",
                    url: "/accessories-use/" + id,
                    data: formData,
                    success: function (value) {
                        if (value.status) {
                            $('#useModal').modal('hide');
                            $('#use-form')[0].reset();
                            $('#saved-search-success').html(value.message);
                            table.draw();
                        } else {
                            $('.error-div').html('<div class="alert alert-danger"><a href="#" class="close" data-dismiss="alert" aria-label="close">&times;</a><strong>Error! </strong>' + value.message + '</div>');
                        }
                    }
                });
            }
        });

        $('#moveModal, #useModal, #addModal').on('show.bs.modal', function (e) {
            $(this).find('form #useId').val($(e.relatedTarget).data('post-id'));
            $(this).find('form #addId').val($(e.relatedTarget).data('post-id'));
            $(this).find('form #moveId').val($(e.relatedTarget).data('post-id'));
            $(this).find('form #available_quantity').prop('max', $(e.relatedTarget).data('post-quantity'));
            $(this).find('form #available_quantity').blur(function () {
                if (($("#available_quantity").val() != $("#available_quantity").attr("max"))) {
                    $("#label-msg").html("");
                    $("#btnmove").html("Save");
                }
            });
        });

        $('#save_search').on('click', function (e) {
            e.preventDefault();

            var locations = $("#location").val();
            var make_and_model = $('#make_and_model').val();
            var purchase_indicator = $('#purchase_indicator').val();
            var report_name = $("#name").val();
            var view_all = $('#view_all').val() ? ($('#view_all').prop('checked') == true ? 1 : '') : '';

            $.ajax({
                type: "POST",
                url: "/save-search",
                data: { name: report_name, locations: locations, make_and_model: make_and_model, purchase_indicator: purchase_indicator, view_all: view_all },
                success: function (result) {
                    if (result.status=='success'){
                        $('.alert').hide();
                        $('#success').show();
                        $('#success p').text(result.message);
                        if(view_all) {
                            $("#adminSavedSearch").append(result.dropdown);
                        }else{
                            $("#userSavedSearch").append(result.dropdown);
                        }
                    }else{
                        $('#error').show();
                        $('#error p').text(result.message);
                    }
                }
            }).done(function () {
                $('html, body').animate({
                    scrollTop: $("#error").offset().top
                }, 1000);
            });
        });

        $('#update_search').on('click', function (e) {
            e.preventDefault();
            $('.ajax-loader').show();

            var locations = $("#location").val();
            var make_and_model = $('#make_and_model').val();
            var purchase_indicator = $('#purchase_indicator').val();
            var report_name = $("#name").val();
            var report_id = $('#report_id').val();
            var view_all = $('#view_all').val() ? ($('#view_all').prop('checked') == true ? 1 : '') : '';

            $.ajax({
                type: "POST",
                url: "/update-search",
                data: { name: report_name, locations: locations, make_and_model: make_and_model, purchase_indicator: purchase_indicator, report_id: report_id, view_all: view_all },
                success: function (data) {
                    if(data.status=='error'){
                        $('#error').show();
                        $('#error p').text(data.message);
                    }else{
                        if(data.url) {
                            location.href = "/accessories"+data.url;
                        }else{
                            location.reload();
                        }
                    }
                }
            })
        });



        $('#delete_search').on('click', function (e) {
            e.preventDefault();
            Swal.fire({
                title: 'Are you sure?',
                text: "You won't be able to revert this!",
                icon: 'warning',
                showCancelButton: true,
                confirmButtonColor: '#3085d6',
                cancelButtonColor: '#d33',
                confirmButtonText: 'Yes, delete search!'
			}).then((result) => {
				if (result.isConfirmed) {

                    $('.ajax-loader').show();
                    var report_id = $('#report_id').val();

                    $.ajax({
                        type: "POST",
                        url: "/delete-search",
                        data: {report_id: report_id },
                        success: function (value) {
                        }
                    }).done(function () {
                        $('.ajax-loader').hide();
                        location.href = "/accessories";
                    });
                }
            });
        });
    });

    $(document.body).on("click", ".btndelete", function () {
        var hardwareStandard = $('#hardware_standard').val();
        $('#confirm-delete').modal('show');
        $('#confirm-delete').attr('data-form', $(this).parent('form').attr('id'));
        $('#confirm-message').html('Are you sure you want to delete ' + hardwareStandard + ' ? ');
    });

    $(".delete-accessory-button").on("click", function () {
        $("#" + $('#confirm-delete').attr('data-form')).submit();
    });

    function updateQuantity(field_name, accessory_id, that) {
        updatedValue = $(that).val();
        $.ajax({
            type: "POST",
            url: "/accessories-update/" + accessory_id,
            data: {
                value: updatedValue,
                field: field_name
            },
            success: function (data) {
                $('#order-qty-' + accessory_id).html(data.order_quantity);
                $('#purchase-indicator-' + accessory_id).html(data.purchase_indicator ? 'Yes' : 'No');
            }
        });
    }
</script>