var dzNew = {
    init: function() {
        this.on('addedfile', function(file, response) {
            $('#addImages').hide();
        });
        this.on("sendingmultiple", function(file, xhr, formData) {
            formData.append('title', $('#publicProjectTitle').val());
            formData.append('description', $('#publicProjectDescription').val());
            formData.append('projectId', $('#publicProjectProjectId').val());
            formData.append('status', $('#publicProjectStatus').val());
            formData.append('city', $('#publicProjectCity').val());
            formData.append('value', $('#publicProjectValue').val());
            formData.append('type', $('#publicProjectType').val());
            formData.append('fromdz', 1);
        });
        this.on('successmultiple', function(file, response) {
            // console.log(response);
            this.removeAllFiles();
            $('#addImages').show();
            // toastr["success"]("Your post was created successfully. Please allow up to 60 seconds for the post to be visible in the portal.", "Post created successfully")
        });
        this.on('errormultiple', function(file, message) {
            // console.log(message);
            // toastr["error"](message, "Error");
        });
        this.on('reset', function() {
            $('#addImages').show();
        });
        this.on('complete', function() {
            location.reload(true);
        });
    },
    paramName: 'file',
    url: "/clients/admin/src/new-public-project.php",
    autoProcessQueue: false,
    uploadMultiple: true,
    acceptedFiles: 'image/jpeg,image/png',
    parallelUploads: 100,
    maxFilesize: 30,
    maxFiles: 100,
    previewTemplate: '<div class="dz-preview dz-file-preview text-center me-2"><div class="dz-details"><img data-dz-thumbnail /></div><div class="dz-progress"><span class="dz-upload" data-dz-uploadprogress></span></div><div class="dz-error-message"><span data-dz-errormessage></span></div><a class="text-danger" href="javascript:undefined;" data-dz-remove>Remove</a></div>',
};

var dzEdit = {
    init: function() {
        this.on('addedfile', function(file, response) {
            $('#addEditImages').hide();
        });
        this.on("sendingmultiple", function(file, xhr, formData) {
            formData.append('publicProjectId', $('#editPublicProjectId').val());
            formData.append('title', $('#editPublicProjectTitle').val());
            formData.append('description', $('#editPublicProjectDescription').val());
            formData.append('projectId', $('#editPublicProjectProjectId').val());
            formData.append('status', $('#editPublicProjectStatus').val());
            formData.append('city', $('#editPublicProjectCity').val());
            formData.append('value', $('#editPublicProjectValue').val());
            formData.append('type', $('#editPublicProjectType').val());
            formData.append('fromdz', 1);
        });
        this.on('successmultiple', function(file, response) {
            // console.log(response);
            this.removeAllFiles();
            $('#addEditImages').show();
            // toastr["success"]("Your post was created successfully. Please allow up to 60 seconds for the post to be visible in the portal.", "Post created successfully")
        });
        this.on('errormultiple', function(file, message) {
            // console.log(message);
            // toastr["error"](message, "Error");
        });
        this.on('reset', function() {
            $('#addEditImages').show();
        });
        this.on('complete', function() {
            location.reload(true);
        });
    },
    paramName: 'file',
    url: "/clients/admin/src/edit-public-project.php",
    autoProcessQueue: false,
    uploadMultiple: true,
    acceptedFiles: 'image/jpeg,image/png',
    parallelUploads: 100,
    maxFilesize: 30,
    maxFiles: 100,
    previewTemplate: '<div class="dz-preview dz-file-preview text-center me-2"><div class="dz-details"><img data-dz-thumbnail /></div><div class="dz-progress"><span class="dz-upload" data-dz-uploadprogress></span></div><div class="dz-error-message"><span data-dz-errormessage></span></div><a class="text-danger" href="javascript:undefined;" data-dz-remove>Remove</a></div>',
}

function initNewDropzone() {
    return new Dropzone("div#publicProjectDropzone", dzNew);
}

function initEditDropzone() {
    return new Dropzone("div#editPublicProjectDropzone", dzEdit);
}

$(document).ready(function() {
    $(document).on('click', '.editPublicProjectShareButton', function(e) {
        $('#editPublicProjectShareModalBody').html(loader);

        var id = $(this).data('id');

        $.ajax({
            url: '/clients/admin/ajax/edit-public-project-share-form.php',
            method: 'POST',
            dataType: 'html',
            data: {
                id: id
            },
            success: function (data) {
                // console.log(data);
                $('#editPublicProjectShareModalBody').html(data);
                $('.selectpicker').selectpicker();
            },
            error: function (e) {
                // var error = e.responseJSON.error;
                // console.log(error);
            }
        });
    });

    $(document).on('change', '#publicProjectsCheckAll', function(e) {
        if ( $(this).is(':checked') ) {
            $('.publicProjectsCheck').prop('checked', true);
        } else {
            $('.publicProjectsCheck').prop('checked', false);
        }
    });

    $(document).on('change', '.publicProjectsCheck', function(e) {
        if ( $(this).is(':checked') ) {
            //show buttons
        } else {
            //hide buttons
        }
    });

    $(document).on('submit', '#newPublicProjectForm', function(e) {
        $('#newPublicProjectSubmit').prop('disabled', true);
        $('#newPublicProjectModalFooter').html(loader);
        if ( dz.files.length > 0 ) {
            e.preventDefault();
            e.stopPropagation();
            dz.processQueue();
        } else {
            $('#newPublicProjectForm').submit();
        }
    });

    $(document).on('click', '.editPublicProjectButton', function(e) {
        $('#editPublicProjectModalBody').html(loader);

        var id = $(this).data('id');

        $.ajax({
            url: '/clients/admin/ajax/edit-public-project-form.php',
            method: 'POST',
            dataType: 'html',
            data: {
                id: id
            },
            success: function(data) {
                // console.log(data);
                $('#editPublicProjectModalBody').html(data);
                initObserver();
                initEditDropzone();
                Sortable.create(document.getElementById('editPublicProjectDragContainer'), {
                    delay: 100,
                    delayOnTouchOnly: true,
                    onEnd: function(evt) {
                        let order = [];
                        $('.editPublicProjectDragItem').each(function(i, e) {
                            order.push({"id": $(e).data('id'), "order": i});
                        });
                        console.log(order);

                        $.ajax({
                            url: '/clients/admin/ajax/order-public-project-attachments.php',
                            method: 'POST',
                            data: {
                                id: $('#editPublicProjectId').val(),
                                order: order
                            },
                            success: function(data) {
                                // console.log(data);
                            },
                            error: function (e) {
                            }
                        });
                    },
                });
            },
            error: function (e) {
                // var error = e.responseJSON.error;
                // console.log(error);
            }
        });
    });

    $(document).on('submit', '#editPublicProjectForm', function(e) {
        let dze = Dropzone.forElement("#editPublicProjectDropzone");

        $('#editPublicProjectSubmit').prop('disabled', true);
        $('#editPublicProjectModalFooter').html(loader);
        if ( dze.files.length > 0 ) {
            e.preventDefault();
            e.stopPropagation();
            dze.processQueue();
        } else {
            $('#editPublicProjectForm').submit();
        }
    });

    $(document).on('click', '.deletePublicProjectAttachment', function(e) {
        let col = $(this).closest('.publicProjectAttachmentCol');
        if ( window.confirm("Are you sure you want to remove this image from the public project?") == true ) {
            $.ajax({
                url: '/clients/admin/ajax/delete-public-project-attachment.php',
                method: 'POST',
                data: {
                    id: $(this).data('id')
                },
                success: function(data) {
                    // console.log(data);
                    // $(this).closest('.publicProjectAttachmentCol').remove();
                    col.remove();
                },
                error: function (e) {
                    // var error = e.responseJSON.error;
                    // console.log(error);
                }
            });
        }
    });

    $(document).on('click', '.sharePublicProjectButton', function(e) {
        let id = $(this).data('id');
        $('#newPublicProjectShareSelect').selectpicker('val', id.toString());
    });

    $(document).on('click', '.viewShareLogsButton', function(e) {
        $('#shareLogsModalBody').html(loader);

        var id = $(this).data('id');

        $.ajax({
            url: '/clients/admin/ajax/view-share-logs.php',
            method: 'POST',
            dataType: 'html',
            data: {
                id: id
            },
            success: function (data) {
                // console.log(data);
                $('#shareLogsModalBody').html(data);
            },
            error: function (e) {
                // var error = e.responseJSON.error;
                // console.log(error);
            }
        });
    });

    var ppTable = new DataTable('#publicProjectsDT', {
        // dom: '<"d-flex justify-content-between my-2"<"d-flex me-auto"l><"d-flex ms-auto"f>>',
        layout: {
            topStart: {
                pageLength: {
                    menu: [10, 25, 50, 100],
                    text: '_MENU_'
                }
            },
            topEnd: {
                search: {
                    text: '',
                    placeholder: 'Search'
                }
            },
            bottomStart: null
        },
        columns: [
            // {
            //     name: 'zeroth',
            //     className: 'dt-control',
            //     orderable: false,
            //     data: null,
            //     defaultContent: '',
            //     target: 0
            // },
            // {name: 'first', orderable: false},
            {name: 'second', orderable: true},
            {name: 'third', orderable: true},
            {name: 'fourth', orderable: true},
            {name: 'fifth', orderable: true},
            {name: 'sixth', orderable: true},
            {name: 'seventh', orderable: true},
            {name: 'eighth', orderable: true},
            {name: 'ninth', orderable: true},
            {name: 'tenth', orderable: false},
            // {name: 'eleventh', orderable: false, visible: false, targets: 10},
        ],
        pageLength: 100,
        // scrollX: true,
        // fixedColumns: true,
        order: [[0, 'asc']]
    });
    new DataTable('#publicProjectsShareDT', {
        // dom: '<"d-flex justify-content-between my-2"<"d-flex me-auto"l><"d-flex ms-auto"f>>',
        layout: {
            topStart: {
                pageLength: {
                    menu: [10, 25, 50, 100],
                    text: '_MENU_'
                }
            },
            topEnd: {
                search: {
                    text: '',
                    placeholder: 'Search'
                }
            },
            bottomStart: null
        },
        pageLength: 50
    });

    var clipboard = new ClipboardJS('.copyPublicProjectShareLink');
    clipboard.on('success', function(e) {
        $(e.trigger).html('<i class="bi bi-check"></i>');
        setTimeout(function() {
            $(e.trigger).html('<i class="bi bi-copy"></i>');
        }, 2000);
    });

    const dz = initNewDropzone();

    Fancybox.bind("[data-fancybox]", {
        Toolbar: {
            display: {
                left: ["infobar"],
                middle: [],
                right: ["iterateZoom", "slideshow", "thumbs", "close"],
            },
        },
    });
});