$(document).ready(function(){
    var categories = [];

    getCompanies();
    getCategories();
    
    $(document).on('click', '.dragDropContainer', function (e) {
        $('#uploadDocumentFrm #updloadedFiles').click();
    });

    $(document).on('change', '#uploadDocumentFrm #updloadedFiles', function (e) {
        var html = $('#uploadedFileList').html();
        var files = e.target.files;
        var html = '';
        var categoriesHtml = '';

        categories.forEach(function(category) {
            categoriesHtml += `
                <option value="` + category.id + `">` + category.name + `</option>
            `;
        });

        for (var i = 0; i < files.length; i++) {
            var filename = files[i].name;
            var extension = files[i].type
            var icon = extension == 'application/pdf' ? "/themes/tailwind/images/pdf-icon.png" : "/themes/tailwind/images/doc-icon.png";

            html += `
                <div class="file-row" data-index="` + i + `">
                    <div class="file-details mb-3">
                        <div class="d-flex align-items-center" style="width: 25%; word-break: break-word;">
                            <img class="img-fluid mr-2" width="30" src="` + icon + `">
                            <span class="file-title">` + filename + `</span>
                        </div>
                        <div class="d-flex align-items-center">
                            <div class="file-progress-wrapper mr-2">
                                <div class="file-progress" style="width: 0%;"></div>
                            </div>
                            <span class="file-progress-percent mr-2">0%</span>
                            <img class="img-fluid file-progress-remove" width="24" src="/themes/tailwind/images/close-circle-red.png">
                        </div>
                        <div class="d-flex align-items-center">
                            <label class="col-form-label mr-2">Document category</label>
                            <select class="w-fit-content" name="bookkeeping_document_category_id">
                                ` + categoriesHtml + `
                            </select>
                        </div>
                    </div>
                    <div class="row mb-3 align-items-center">
                        <div class="col-auto" required>
                            <label class="col-form-label">Batch Name</label>
                        </div>
                        <div class="col">
                            <input type="text" class="form-control" value="" name="batch_name" required>
                        </div>
                    </div>
                    <div class="row mb-3 align-items-center">
                        <div class="col-auto" required>
                            <label class="col-form-label">Remark</label>
                        </div>
                        <div class="col">
                            <input type="text" class="form-control" value="" name="remark" required>
                        </div>
                    </div>
                    <div class="row">
                        <hr class="file-row-separator">
                    </div>
                </div>
            `;
        }

        $('#uploadedFileList').html(html);
        $('#uploadedFileCount #totalFile').html(files.length);
    });

    $(document).on('click', '#uploadDocumentFrm .file-progress-remove', function (e) {
        $(this).parents('.file-row').first().remove();
    });

    $('#uploadDocumentFrm').submit(function(e) {
        e.preventDefault();
        var action = $(this).attr('action');
        var button = $(this).find('button[type="submit"]');
        var buttonHtml = button.html();
        var totalDone = 0;
        var form = $(this);

        if (!button.is(':disabled') && action) {
            button.attr('disabled', 'disabled');
            button.html('<i class="fa fa-spinner fa-spin" style="font-size:24px"></i>');

            var files = $('#uploadDocumentFrm #updloadedFiles')[0].files;
            $('#uploadDocumentFrm .file-row').each(function() {
                var formData = new FormData();
                var fileRowElem = $(this);
                var index = fileRowElem.attr('data-index');
                var isLast = $('#uploadDocumentFrm .file-row').length - 1 == index ? true : false;

                formData.append('company_id', form.find('select[name="company_id"]').val());
                formData.append('uploaded_file', files[index]);
                formData.append('bookkeeping_document_category_id', $(this).find('select[name="bookkeeping_document_category_id"]').val());
                formData.append('batch_name', $(this).find('input[name="batch_name"]').val());
                formData.append('remark', $(this).find('input[name="remark"]').val());

                fileRowElem.find('.file-progress-wrapper .file-progress').css('width', '50%');
                fileRowElem.find('.file-progress-percent').html('50%');
                
                $.ajax({
                    url: action,
                    type: "post",
                    data: formData,
                    dataType: 'json',
                    processData: false,
                    contentType: false,
                    success:function(data) {
                        totalDone++;
                        console.log(isLast);

                        if (isLast) {
                            button.removeAttr('disabled');
                            button.html(buttonHtml);
        
                            if (data.success) {
                                popToast('success', data.message);
                                $('.reload-main-table').click();
                                $('#uploadDocumentModal').modal('hide');
                                $('#uploadedFileList').html('');
                                $('#uploadedFileCount #totalFile').html('0');
                            }
                            else {
                                popToast('danger', data.message);
                            }
                        }
                        
                        if (data.success) {
                            fileRowElem.find('.file-progress-wrapper .file-progress').css('width', '100%');
                            fileRowElem.find('.file-progress-wrapper .file-progress').addClass('green');
                            fileRowElem.find('.file-progress-percent').html('100%');
                            fileRowElem.find('#uploadedFileCount #totalDone').html(totalDone);
                        }
                    },
                    error: function(data) {
                        var errors = data.responseJSON.errors;
                        $.each(errors, function(index, error) {
                            popToast('danger', errors[0]);
                            return false;
                        });
    
                        button.removeAttr('disabled');
                    }
                });

                index++;
            });
        }
    });
    
    function getCompanies() {
        $.ajax({
            url: "/cms/bookkeepings/get-companies",
            type: "get",
            data: {},
            dataType: 'json',
            success:function(data) {
                var companies = data.companies;
                var html = '';

                companies.forEach(function(company) {
                    html += `
                        <option value="` + company.id + `" selected>` + company.name + `</option>
                    `;
                });

                $('#uploadDocumentFrm select[name="company_id"]').html(html);
            }
        });
    }

    function getCategories() {
        $.ajax({
            url: "/cms/bookkeepings/get-categories",
            type: "get",
            data: {},
            dataType: 'json',
            success:function(data) {
                categories = data.categories;
            }
        });
    }
});