<div id="download-dialog" class="modal fade hide" tabindex="-1">
    <div class="modal-header">
        <a class="close closeForm btnCancel report-btn-cancel" data-dismiss="modal"><i class="bi bi-x"></i></a>
        <h2>
            Export report
        </h2>

    </div>


    <div class="modal-body">
        <form class="form  form-horizontal" action="<?= htmlspecialchars($report_link) ?>" id="report-download-form">
            <fieldset>
                <div class="control-group">
                    <label class="control-label">Report type: </label>
                    <div class="controls">
                        <select id="type" name="type">
                            <option value="csv" selected>csv</option>
                            <option value="pdf">pdf</option>
                        </select>
                        <div class="export-columns-warning hide">
                            Creating PDF reports with many columns will cut off some data. <br />
                            We recommend using PDF reports with fewer columns or CSV reports to preserve all the data.
                        </div>
                    </div>
                </div>
                <?php
                if (isset($custom_title_descr) && $custom_title_descr === true)
                {
                    ?>
                    <div class="control-group">
                        <label class="control-label">Title: </label>
                        <div class="controls">
                            <input class="input" type="text" value="<?= htmlspecialchars($report_title) ?>" id="report_title" name="report_title"  size="50"/>
                        </div>
                    </div>
                    <div class="control-group">
                        <label class="control-label">Description: </label>
                        <div class="controls">
                            <textarea placeholder="optional" id="report_description" name="report_description"  rows="3" cols="10"><?= htmlspecialchars($report_description) ?></textarea>
                        </div>
                    </div>

                <?php } ?>
                <div class="control-group">
                    <label class="control-label" for="sendemail">Send report in email:</label>
                    <div class="controls">
                            <input style="vertical-align:bottom" class="checkbox" type="checkbox" id="sendemail" value="email" name="sendemail">
                    </div>
                </div>
            </fieldset>
            <fieldset id="emailfieldset" style="display: none; margin-top: 10px">
                <legend><span>Email details</span></legend>
                <div class="control-group">
                    <label class="control-label">To: </label>
                    <div class="controls">
                        <input class="input " type="text"  value="" id="to_contacts" name="to_contacts"  size="50"/>
                    </div>
                </div>

                <div class="control-group">
                    <label class="control-label">From: </label>
                    <div class="controls">
                        <input type="text" class="" value="<?= htmlspecialchars($emailFrom) ?>" id="from_contacts" name="from_contacts" size="50" />
                    </div>
                </div>
                <div class="control-group">
                    <label class="control-label">Subject: </label>
                    <div class="controls">
                        <input type="text" class="" value="<?= htmlspecialchars($report_title) ?>" id="mail_subject" name="mail_subject"  size="50" />
                    </div>
                </div>
                <div class="control-group">
                    <label class="control-label">Message: </label>
                    <div class="controls">
                        <textarea class="" id="mail_desc" name="mail_desc" rows="4" cols="43"></textarea>
                    </div>
                </div>

                <input type="hidden" id="sqlString" name="sqlString" value="<?php echo !empty($report_result['meta']['query']) ? htmlspecialchars($report_result['meta']['query']):''; ?>" />
                <input type="hidden" id="compliance_data" name="compliance_data" value="" />
                <input type="hidden" id="sqlSortColumn" name="sql_sort_column" value="">
                <input type="hidden" id="sqlSortDescending" name="sql_sort_order" value="">
                <input type="hidden" id="includes" name="includes"   value="<?php echo !empty($report_result['meta']['includes']) ? htmlspecialchars($report_result['meta']['includes']):''; ?>" />
                <input type="hidden" id="excludes" name="excludes"   value="<?php echo !empty($report_result['meta']['excludes']) ? htmlspecialchars($report_result['meta']['excludes']):''; ?>" />
                <input type="hidden" id="promiseFilter" name="promiseFilter" value="<?php echo !empty($report_result['meta']['promiseFilter']) ? htmlspecialchars($report_result['meta']['promiseFilter']):''; ?>" />
                <input type="hidden" id="category" name="category" value="">
                <input type="hidden" id="csv_data" name="csv_data" value="">
            </fieldset>
        </form>

        <div id="tempdiv" class="alert" style="display: none;" >  </div>
        <div id="tempdiv-progressbar" class="hide" style="margin-bottom: 5px;" >
            <div class="progress progress-striped active">
                <div class="bar" style="width: 0%;"></div>
            </div>
        </div>



    </div>
    <div class="modal-footer">
        <button class="btn btn-large report-btn-cancel" >Close</button>
        <button class="btn btn-primary btn-large ok-btn"  id="report-btn-ok">Export</button>
    </div>
</div>

<script type="text/javascript">
        var downloadForm = function(element)  {

            var $dialog = element;
            var $tempDiv = $('#tempdiv',$dialog);
            var reportGenerationInProgress = false;
            var clearDownloadFileInterval = false;
            var downLoadStatusData = null;


            const handlePdfColumnWarning = function (e, columnsLengthThreshold = 5) {
                const hideClass = 'hide';
                const pdfTypeValue = 'pdf';
                
                const warningBlock = document.querySelector('.export-columns-warning');
                const inventoryColumnsLength = document.querySelectorAll('#inventory-table thead th').length;
                
                if (!warningBlock) return;

                // remove hide class when 'pdf' export type is selected and columns length more than 5, otherwise add
                warningBlock.classList.toggle(hideClass, !(e.target.value === pdfTypeValue && inventoryColumnsLength > columnsLengthThreshold));
            };
            

            // initialize the dialog and bind events
            function init(title = document.querySelector('h1, #reportLabel').textContent.trim()) {
                resetDialog();
                $dialog .on("click", "#report-btn-ok.ok-btn", downloadReportStart);
                $dialog .on("click", ".report-btn-cancel", downloadCancel);
                $dialog .on("click", "#report-btn-redo", init);
                $('#report_title').val(title)
                $('#mail_subject').val(title)
                $dialog.modal(
                    {"backdrop": "static"}
                ).show();

                if (document.querySelector('#compliance_data').value) {
                    // add `Report definition - json` option to the export type selection when compliance data is presented
                    document
                        .querySelector('select#type')
                        .add(
                            Object.assign(
                                document.createElement('option'),
                                { value: 'json', text: 'Report definition - json' }
                            )
                        );
                }

                const form = document.querySelector('#report-download-form');
                form.addEventListener('keyup', function() {
                    showPrimaryButton(true);
                });

                form.addEventListener('change', function() {
                    showPrimaryButton(true);
                });

                document.querySelector('#sendemail').onclick = function (e) {
                    document.querySelector('#emailfieldset').style.display = e.target.checked ? 'block' : 'none';
                }

                const typeSelect = document.getElementById('type');

                if (typeSelect) {
                    typeSelect.removeEventListener('change', handlePdfColumnWarning);
                    typeSelect.addEventListener('change', handlePdfColumnWarning);
                    handlePdfColumnWarning({ target: typeSelect });
                }
            };

            function resetDialog() {
                downLoadStatusData = null;
                clearDownloadFileInterval = false
                $dialog.off();
                $("#report-btn-ok.ok-btn").off('click');
                $("#report-btn-ok.download-btn").off('click');
                $(".report-btn-cancel").off('click');
                reportGenerationInProgress = false;
                $tempDiv.removeClass('alert-error');
                $tempDiv.addClass('alert-info');
                $tempDiv.html('').hide();
                removeProgressBar();
                showPrimaryButton(true);
            };

            let $primaryButton = $('#report-btn-ok',$dialog);

            function showPrimaryButton(state,text) {
                var text = text || (document.getElementById('sendemail').checked ? 'Send' : 'Export');
                $primaryButton.html(text);
                $primaryButton.removeClass('download-btn');
                $primaryButton.removeAttr('disabled');
                $primaryButton.addClass('ok-btn');
                state ?  $primaryButton.show() : $primaryButton.hide();
            };

            function disablePrimaryButton() {
                $primaryButton.attr('disabled', 'disabled');
            };

            function updateProgressBar(value,text) {
                var percent = parseInt(value,10);
                var $bar =   $('.bar',$dialog);
                if (value>=0) {
                    var width = percent + '%';
                    $bar.data('currentval',percent);

                    if (text.length > 0) notifyStatus(text);
                    $bar.width(width).html(percent + '%');
                }
            };

            function initializeUpdateBar() {
                $('#tempdiv-progressbar',$dialog).show();
                updateProgressBar(0,'Initializing report generation...')
            };



            function checkDownloadFileStatus(metadata,showDownloadLink,resolution) {
                var dfd = $.Deferred();
                var refreshId = setInterval(function()
                {
                    // check the status file

                    if (clearDownloadFileInterval)  clearInterval(refreshId);

                    $.when(requestForStatus(metadata))
                    .then(function(data) {
                        if (data.state == 'fail') {
                            clearInterval(refreshId);
                            notifyError(data.message);
                            return;
                        }

                        var value = parseInt(data.status,10);
                        var status = {'value':value,'text':data.msg, 'data':data};
                        var resolvedValue = value * resolution;

                        //get current value of progress bar
                        var currentvalue = $('.bar',$dialog).data('currentval') || 0;
                        if (resolvedValue > currentvalue){
                            updateProgressBar(resolvedValue,data.message);
                        }
                        dfd.notify(status);
                        if (data.state == 'complete') {
                            dfd.resolve(status);
                            appendDownloadLink(data,showDownloadLink);
                            clearInterval(refreshId);
                        }
                    }).fail(function(jqXHR, textStatus, errorThrown) {
                        dfd.reject("error");
                        clearInterval(refreshId);
                        try {
                            var errorObj = $.parseJSON(jqXHR.responseText);
                            var errorMsg = errorObj.message;
                            notifyError(errorMsg);
                        } catch(e) {
                            var errorMsg = 'Server error. Cannot check the download status. Invalid server response.';
                            notifyError(errorMsg);
                        }
                    });

                }, 1000);
                return dfd.promise();
            };


            function appendDownloadLink(data,showDownloadLink) {
                // create download link
                if (showDownloadLink==true) {
                    var $a = 'Report downloaded successfully.';
                    notifySuccess($a);
                    reportGenerationInProgress = false;
                    disablePrimaryButton();
                    window.location.assign(data.downloadLink);
                }
            };

            function removeProgressBar() {
                $('#tempdiv-progressbar',$dialog).hide();
                 updateProgressBar(0,'');
            };

            function sendEmail(emailData) {
                $.when(initializeEmailRequest(emailData)).then(function(successData) {
                    notifySuccess(successData.message);
                    disablePrimaryButton();
                    reportGenerationInProgress = false;
                }).fail(function(jqXHR, textStatus, errorThrown) {
                    var errorObj = $.parseJSON(jqXHR.responseText);
                    var errorMsg = errorObj.message;
                    notifyError(errorMsg);
                });

            };


            function downloadCancel() {
                if ( reportGenerationInProgress) {
                    var ans = confirm('Do you want to cancel ongoing report generation?');
                    if (ans) {
                        clearDownloadFileInterval = true;

                        initializeAbortRequest();

                        $dialog.modal('hide');
                    }
                    return;
                }
                else {
                    $dialog.modal('hide');
                }


            };


            function validateFormData(formData) {

                $("#report-download-form").validate({
                    rules: {

                        to_contacts: {
                            required: "#sendemail:checked",
                            email: true
                        },
                        from_contacts: {
                            required: "#sendemail:checked",
                            email: true
                        },
                        mail_subject: {
                            required: "#sendemail:checked"
                        }
                    },
                    errorClass: "help-inline",
                    validClass: "help-inline",
                    errorElement: "span",
                    highlight: function(element, errorClass, validClass) {
                        $(element).closest(".control-group").removeClass("success").addClass("error");
                    },
                    unhighlight: function(element, errorClass, validClass) {
                        $(element).closest(".control-group").removeClass("error");
                    }
                });

                return $("#report-download-form").valid();

            };

            function downloadReportStart() {
                let emailSent = false;
                var formData = getFormData();
                var validateForm = validateFormData(formData);
                if (validateForm !== true) {
                    notifyError('Some errors were encountered');
                    return;
                }
                notifyStatus('Starting download..',true);
                reportGenerationInProgress = true;
                $.when(initializeDownloadRequest(formData))
                .then(
                function(data) {
                    downLoadStatusData = data;

                    if (typeof(downLoadStatusData) !== 'undefined' && downLoadStatusData != null) {

                        var $sendMail = $('#sendemail',$dialog).is(':checked') ? $('#sendemail',$dialog).val() : null;
                        // check for data error
                        var showDownloadLink = ($sendMail) ? false : true;

                        if (data.status != null && data.status.error != null) {
                            notifyError(downLoadStatusData.status.error);
                            return;
                        }
                        initializeUpdateBar();
                        if (data.reportformat == 'pdf') {
                            downLoadStatusData.checkFile = 'csv';

                            $.when( checkDownloadFileStatus(downLoadStatusData,false,.05) ).then(
                            function(status){
                                notifyStatus('Starting PDF generation...',true);
                                initializePdfGeneration(downLoadStatusData).then(
                                function(data) {
                                    downLoadStatusData.checkFile = 'pdf';
                                    checkDownloadFileStatus(downLoadStatusData,showDownloadLink,1).then(
                                    function(status) {
                                        //send email;
                                        if ($sendMail && !emailSent) {
                                            emailSent = true;
                                            notifyStatus('sending email...',true);
                                            removeProgressBar();
                                            var emailData = $.extend(downLoadStatusData, status.data,formData);
                                            sendEmail(emailData);
                                        }
                                    }
                                );
                                }
                            )
                            });

                        } else {
                            data.checkFile = data.reportformat;
                            checkDownloadFileStatus(downLoadStatusData,showDownloadLink,1).then(function(status) {
                                if ($sendMail && !emailSent) {
                                    emailSent = true;
                                    notifyStatus('sending email...',true);
                                    removeProgressBar();
                                    var emailData = $.extend(downLoadStatusData, status.data,formData);
                                    sendEmail(emailData);
                                }

                            });
                        }
                    } else {
                        // we are not getting anything from server, must probably an error case
                        var  error = "Something went wrong while generating this report. Please check the logs for more details.";
                        notifyError(error);

                    }
                }
            )
                .fail(
                function(jqXHR, textStatus, errorThrown) {
                    if (jqXHR.status == 401) {
                        unAuthorizedHandler();
                    }
                    var  error = "Something went wrong while generating this report. Please check the logs for more details.";
                    if (!errorThrown || 0 === errorThrown.length) {
                        errorThrown = error;
                    }
                    notifyError(error);
                }
            );

            };


            function requestForStatus(statusData) {

                //hack for advanced reports
                if (statusData.reportId == 'advancedreports') {
                    statusData.jobId = statusData.status.id;
                }


                    var req =  $.ajax({
                        type: "POST",
                        url: '<?php echo site_url('pdfreports/checkDownloadStatus/') ?>',
                        data: statusData,
                        async: false,
                        dataType: 'json'
                    });


                return req;
            };

            function initializeDownloadRequest(postData) {
                var req =  $.ajax({
                    type: "POST",
                    url: $('form#report-download-form', $dialog).attr('action'),
                    data: postData,
                    dataType:'json',
                    async: true
                });
                return req;
            };

            function initializeAbortRequest() {
                if (downLoadStatusData != null) {
                    var url = '<?php echo site_url('pdfreports/cancelReportGeneration') ?>';
                    var req =  $.ajax({
                        type: "POST",
                        url: url,
                        data: downLoadStatusData,
                        dataType:'json',
                        async: true
                    });
                    return req;
                }
            };


            function initializePdfGeneration(postData) {
                var url = '<?php echo site_url('pdfreports/fireOffPdfGeneration') ?>';
                var req =  $.ajax({
                    type: "POST",
                    url: url,
                    data: postData,
                    async: true
                });
                return req;
            };


            function initializeEmailRequest(postData) {
                var req =  $.ajax({
                    type: "POST",
                    url: '<?php echo site_url('pdfreports/sendEmail/') ?>',
                    data: postData,
                    dataType:'json',
                    async: true
                });
                return req;

            }


            function notifyError(txt) {
                removeProgressBar();
                $tempDiv.removeClass('alert-info');
                $tempDiv.addClass('alert-error');
                $tempDiv.show().html(txt);
                $dialog.scrollTop($('.modal-footer').offset.top);
                showPrimaryButton(true,'Retry');
                scrollToBottom();
                reportGenerationInProgress = false;

            };

            function notifySuccess(txt) {
                removeProgressBar();
                $tempDiv.removeClass('alert-error').removeClass('alert-info');
                $tempDiv.addClass('alert-success');
                $tempDiv.show().html(txt);
                scrollToBottom();
                reportGenerationInProgress = false;
                setTimeout(() => $tempDiv.hide(), 2500);
            };

            function notifyStatus(txt,showLoadingIcon) {
                $tempDiv.removeClass('alert-error');
                $tempDiv.addClass('alert-info');
                $tempDiv.show().html(txt);
                scrollToBottom();
            };


            function scrollToBottom() {
                //Append the new content goes here
                //Getting the element's new height now
                var sHeight = $('.modal-body',$dialog)[0].scrollHeight;
                //Scrolling the element to the sHeight
                $('.modal-body',$dialog).scrollTop(sHeight);

            };




            function getFormData() {

                var data=
                    {
                    'rf':$('#type',$dialog).val(),
                    'to':$('#to_contacts',$dialog).val(),
                    'subject':$('#mail_subject',$dialog).val(),
                    'message':$('#mail_desc',$dialog).val(),
                    'from':$('#from_contacts',$dialog).val(),
                    'pdfaction': $('#sendemail',$dialog).is(':checked') ? $('#sendemail',$dialog).val() : null,
                    'page':'<?php echo $current; ?>',
                    'rows':'<?php echo $number_of_rows; ?>',
                    'timezone':$('#timezone',$dialog).val(),

                    'compliance_data' : $('#compliance_data', $dialog).val(),
                    'sqlString'    : $('#sqlString',     $dialog).val(),
                    'sqlSortColumn'    : $('#sqlSortColumn', $dialog).val(),
                    'sqlSortDescending'    : $('#sqlSortDescending', $dialog).val(),
                    'includes'     : ($('#includes', $dialog).val() !== '' ?  JSON.parse($('#includes', $dialog).val()) : '') ,
                    'excludes'     : ($('#excludes', $dialog).val() !== '' ?  JSON.parse($('#excludes', $dialog).val()) : '') ,
                    'promiseFilter': $('#promiseFilter', $dialog).val(),

                    'report_title' : $('#report_title', $dialog).val(),
                    'report_description' : $('#report_description', $dialog).val(),
                    'report_category' : $('#category', $dialog).val(),
                    'report_csvArray' : $('#csv_data', $dialog).val()
                }

                return data;
            };

            return {
                init: init
            };

        };
</script>
