<?php $nonce = wp_create_nonce( 'quttera' ); ?>

<script type="text/javascript">

    var last_log_line           = 0;
    var initial_load            = true;
    var log_lines               = Array();
    var max_log_lines           = 20;
    var logs_refresh_timer_set  = false;
    var progress_bar_timer      = 0;
    var execution_status_reload = 1024*1024;
    var status_reload_timer     = 0;
    var scanner_running         = false;

    jQuery(document).ready(function($) {
        $.ajaxSetup({
            type: 'POST',
            async: true,
            url: ajaxurl, /* predefined WP value */
            complete: function(xhr,status) {
                if ( status != 'success' ) {
                    console.log("Failed to communicate with WP for " + ajaxurl + " status " + status);
                }
            }
        });


        $('#run-internal-scanner').click( function() {
            console.log("run-internal-scan clicked");
            /*
             * Check if internal scan is not running
             */

            document.getElementById("total_scanned_files").innerHTML            = 0;
            document.getElementById("scanned_clean_files").innerHTML            = 0;
            document.getElementById("scanned_pos_suspicious_files").innerHTML   = 0;
            document.getElementById("scanned_suspicious_files").innerHTML       = 0;
            document.getElementById("scanned_malicious_files").innerHTML        = 0;

            document.getElementById("total_scanned_rows").innerHTML             = 0;
            document.getElementById("scanned_clean_rows").innerHTML             = 0;
            document.getElementById("scanned_pos_suspicious_rows").innerHTML    = 0;
            document.getElementById("scanned_suspicious_rows").innerHTML        = 0;
            document.getElementById("scanned_malicious_rows").innerHTML         = 0;

            QtrIsInternalScanRunning();
            console.log("Is scanner running " + scanner_running );

            if( scanner_running == true ){
	            QtrShowProgressBar();
                console.log("Internal scan already runing");
                return false;
            }

            scanner_running = true;
            QtrCleanExecutionLog();
            QtrRunInternalScan( 0 );
            QtrShowEmptyThreatsReport ( );
	        QtrShowProgressBar();
            QtrStartProgressBarTimer();
            QtrStartExecutionStatusReload( 1024*1024*100 );
            return false;
        });


        $('#clean-log').click( function() {
            QtrCleanExecutionLog();
        });


        $('#stop-internal-scanner').click( function() {
            console.log("stop_internal_scan"); 
            /*
             * Hide progress bar
             */ 
            QtrHideProgressBar();
            /*
             * Stop progress bar update timer
             */
            QtrStopProgressBarTimer();
            /*
             * Stop logs reading from remote
             */
            QtrStopExecutionStatusReload();

            jQuery.ajax({
                data: {
                    action: 'scanner-stop_internal_scan',
                    _wpnonce: '<?php echo $nonce; ?>',
                }, 
                success: function(r) {
                    QtrLogMessage("INFO", "Termination sent successfully. Waiting for scan job");
                    QtrLogMessage("INFO", r );
                    console.log(r);
                }//end of success function
            });
        });

        $('#get-scanner-report').click( function() {
            console.log("get_scanner_report"); 
            jQuery.ajax({
                data: {
                    action: 'scanner-get_file_report',
                    _wpnonce: '<?php echo $nonce; ?>',
                }, 

                success: function(r) {
                    var data = r;
                    data = data.replace(/</g, "&#60;");
                    data = data.replace(/>/g, "&#62;");
                    var win = window.open();
                    win.document.write(decodeURIComponent(data).replace(/(?:\r\n|\r|\n)/g, '<br/>'));
                    win.focus();
                    return ;
                }
            });
        });

        /*
         * Hook to catch bootstrap tabs switching
         */ 
        $('a[data-toggle="tab"]').on('shown.bs.tab', function(e){
             var currentTab = $(e.target).text();       // get current tab
             var LastTab = $(e.relatedTarget).text();   // get last tab
             //alert(currentTab);
             if( currentTab.indexOf("Detected") >= 0 ){
                 console.log("Detected Threats");
                 QtrReloadDetectedThreatsReport();
             }else if( currentTab.indexOf("Summary") >= 0 ){
                 //alert("Summary");
                 QtrReloadExecutionStatus();
             }else if( currentTab.indexOf("Ignored") >= 0 ){
                 //alert("Ignored Threats");
                 QtrReloadIgnoredThreatsReport();
             }
        });


        $('#clean-ignore-list').click( function() {
            console.log("clean-ignore-list"); 
            jQuery.ajax({
                data: {
                    action: 'scanner-clean_ignore_list',
                    _wpnonce: '<?php echo $nonce; ?>',
                }, 
                success: function(r) {
                    QtrLogMessage("INFO", "Ignore list cleaned successfully");
                    QtrLogMessage("INFO", r );
                    console.log(r);
                    /*
                     * refresh list of detect threat and restore all threats removed from ignore list
                     */
                    QtrReloadDetectedThreatsReport();
                    QtrReloadIgnoredThreatsReport();
                }//end of success function
            });
        });


        $('#clean-files-white-list').click( function() {
            console.log("clean-files-white-list"); 
            jQuery.ajax({
                data: {
                    action: 'scanner-clean_files_whitelist',
                    _wpnonce: '<?php echo $nonce; ?>',
                }, 
                success: function(r) {
                    QtrLogMessage ("INFO", "Files whitellist cleaned successfully");
                    QtrLogMessage ("INFO", r );
                    console.log(r);
                    /*
                     * refresh list of detect threat and restore all threats removed from ignore list
                     */
                    QtrReloadDetectedThreatsReport();
                }//end of success function
            });
        });


        $('#threat-filter').change( function() {
            var filter = $(this).val();
            $('#detected_threats_report [data-severity]').each(function() {
                if ( filter === 'all' || $(this).data('severity') === filter ) {
                    $(this).show();
                } else {
                    $(this).hide();
                }
            });
        });

        $('#clean-threats-white-list').click( function() {
            console.log("clean-threats-white-list"); 
            jQuery.ajax({
                data: {
                    action: 'scanner-clean_threats_whitelist',
                    _wpnonce: '<?php echo $nonce; ?>',
                }, 
                success: function(r) {
                    QtrLogMessage ("INFO", "Threats whitellist cleaned successfully");
                    QtrLogMessage ("INFO", r );
                    console.log(r);
                    /*
                     * refresh list of detect threat and restore all threats removed from ignore list
                     */
                    QtrReloadDetectedThreatsReport();
                }//end of success function
            });
        });

        /*
         * Event handler for copy threat name button
         */
        $(document).on('click', '.copyThreatBtn', function() {
            var threatName = $(this).data('threat');
            QtrCopyToClipboard(threatName, this);
        });

        /*
         * Custom tooltip handler for copy buttons
         */
        $(document).on('mouseenter', '.copyThreatBtn', function() {
            var tooltipText = 'Paste the copied threat name into the search box.';
            var $tooltip = $('<div class="qtr-tooltip" style="position: absolute; background-color: #00BFFF; color: #fff; padding: 8px 12px; border-radius: 4px; font-size: 12px; white-space: nowrap; z-index: 9999; bottom: 100%; left: 50%; transform: translateX(-50%); margin-bottom: 8px; display: flex; align-items: center; justify-content: center; line-height: 1; font-weight: bold;">').text(tooltipText);
            
            $(this).data('tooltip-element', $tooltip);
            $('body').append($tooltip);
            
            var offset = $(this).offset();
            $tooltip.css({
                top: (offset.top - $tooltip.outerHeight() - 8) + 'px',
                left: (offset.left + $(this).outerWidth() / 2) + 'px'
            });
        });

        $(document).on('mouseleave', '.copyThreatBtn', function() {
            var $tooltip = $(this).data('tooltip-element');
            if ($tooltip) {
                $tooltip.remove();
                $(this).data('tooltip-element', null);
            }
        });

        /*
         * Clean last log line to retrieve an entire log
         */
        last_log_line = 0;

        /*
         * Show the hidden pane
         */
        $('#progress-pane').show();

        QtrIsInternalScanRunning();

        if( scanner_running == true ){
            console.log("Quttera internal scan already running");
            /*
             * retrieve log and execution statistics
             * and show progress bar
             */
            QtrStartExecutionStatusReload( 1024*1024*100 );
            QtrReloadExecutionStatus();
            QtrShowProgressBar();
            QtrStartProgressBarTimer();
        }
        else
        {
            console.log("Quttera internal scan is not running");
            /*
             * Reload status from remote
             */ 
            QtrReloadExecutionStatus();
            /*
             * just to start reload timer
             */ 
            QtrStartExecutionStatusReload(0);
        }

    }); 


    function QtrStartExecutionStatusReload( count ){
        execution_status_reload = count;
        if( status_reload_timer == 0 ){
            status_reload_timer = setInterval(  QtrReloadExecutionStatusTimer,
                                                5000);
        }
    }


    function QtrStopExecutionStatusReload(){
        execution_status_reload = 5;
    }


    function QtrStartProgressBarTimer(){
        console.log("QtrStartProgressBarTimer called");
        if( progress_bar_timer == 0 ){
            progress_bar_timer = setInterval(   QtrUpdateProgressBar,
                                                5000);
        }
    }


    function QtrStopProgressBarTimer(){
        if( progress_bar_timer ){
            clearInterval(progress_bar_timer);
            progress_bar_timer = 0;
        }
    }

    function QtrShowProgressBar(){
        console.log("QtrShowProgressBar called");
        document.getElementById("no_progress_bar").style.display = 'none';
	    document.getElementById("progress_bar").style.display = 'block';
        document.getElementById("run-internal-scanner").style.display = 'none';
	    document.getElementById("stop-internal-scanner").style.display = 'block';

    }

    function QtrHideProgressBar(){
        console.log("QtrHideProgressBar called");
        document.getElementById("progress_bar").style.display = 'none';
	    document.getElementById("no_progress_bar").style.display = 'block';
        document.getElementById("run-internal-scanner").style.display = 'block';
	    document.getElementById("stop-internal-scanner").style.display = 'none';
    }

    function QtrUpdateProgressBar(){
        console.log("QtrUpdateProgressBar called");
        if( execution_status_reload > 0 )
        {
            QtrIsInternalScanRunning();
            console.log("Is scanner running " + scanner_running );
            if( scanner_running == true ){
                QtrShowProgressBar();
            }else{
                QtrHideProgressBar();
            }
        }
        else
        {
            console.log("QtrUpdateProgressBar: scanner is not running");
        }
    }

    function QtrIsInternalScanRunning(){
        jQuery.ajax({
            data: {
                action: 'scanner-is_internal_scan_running',
                _wpnonce: '<?php echo $nonce; ?>',
            },
            async: false,  //should be synchronous to return correct value
            success: function(r) {
                console.log(r);
                if( r == "yes" ){
                    //console.log("Scanner is running");
                    scanner_running = true;
                    return true;
                }else{
                    //console.log("Scanner is not running");
                    scanner_running = false;
                    return false;
                }					
            }//end of success function
        });

        return scanner_running;
    };


    function QtrReloadExecutionStatusTimer(){
        if( !scanner_running ){
            /*
             * Check if internal scan done
             */ 
            if( execution_status_reload > 3 ){
                /*
                 * Yes, it seems that internal scan terminated,
                 * Stop status reload after a minute
                 */ 
                execution_status_reload = 3
            }
        }

        if( execution_status_reload > 0 ){
            execution_status_reload -= 1;
            QtrReloadExecutionStatus();
        }
    }


    function QtrReloadExecutionStatus(){
        QtrReloadDetectedThreatsReport();
        QtrReloadExecutionStats();        
    }


    function QtrCleanExecutionLog( ){
        console.log("QtrCleanExecutionLog called");
        last_log_line = 0;

        jQuery.ajax({
            data: {
                action: 'scanner-clean_log',
                _wpnonce: '<?php echo $nonce; ?>',
            }, 
            success: function(r) {
                //console.log(r);
            }
        });
    }

    function QtrReloadExecutionStats ( )
    {
        jQuery.ajax({
            data: {
                action: 'scanner-get_stats',
                _wpnonce: '<?php echo $nonce; ?>',
            }, 
            success: function(r) {
                var counters = jQuery.parseJSON(r);
                QtrUpdateExecutionStats( counters );
            }//end of success function
        });

    }


    function QtrReloadDetectedThreatsReport ( )
    {
        jQuery.ajax({
            data: {
                action: 'scanner-get_detected_threats',
                _wpnonce: '<?php echo $nonce; ?>',
            }, 
            success: function(r) 
            {
                //console.log(r);

                var threats = jQuery.parseJSON(r);

                if( Array.isArray(threats) )
                {
                    QtrCleanDetectedThreatsReport();

                    if( threats.length != 0 )
                    {
                        for(var i = 0; i < threats.length; i++ )
                        {
                            QtrAddToDetectedThreatsReport( threats[i] );
                        }
                    }
                    else
                    {
                        console.log("Threats arry is clean");
                        QtrShowEmptyThreatsReport();
                    }
                    //
                }
                else
                {
                    console.log("Retrieved invalid output: " + r);
                }
            }//end of success function
        });
    }



    function QtrShowEmptyThreatsReport ( )
    {
        document.getElementById('detected_threats_report').style.display    = 'none';
        document.getElementById('detected_threats_report').style.display    = 'block';
        document.getElementById("detected_threats_report").innerHTML        = "<center><p>No entries have been found</p></center>";
    }


    function QtrCleanDetectedThreatsReport ( )
    {
        document.getElementById("detected_threats_report").innerHTML = "";
    }


    function QtrSeverityLabel( raw ) {
        var s = raw.toLowerCase();
        if ( s === 'enmaliciousthreattype'            || s.indexOf('mal')  >= 0 ) return 'Malicious activity detected, immediate action recommended';
        if ( s === 'enpotentiallysuspiciousthreattype' || s.indexOf('pot')  >= 0 ) return 'Unusual behavior detected';
        if ( s === 'ensuspiciousthreattype'            || s.indexOf('susp') >= 0 ) return 'Suspicious patterns identified, investigation recommended';
        return raw;
    }

    function QtrAddToDetectedThreatsReport( report )
    {
        var alert_type = "alert alert-info";
        var severity   = report["SEVERITY"].toLowerCase();

        if( severity.indexOf("malicious") >= 0 ){
            alert_type = "alert alert-danger";
        }else if( severity.indexOf("susp") >= 0 ){
            alert_type = "alert alert-warning";
        }

        var threat = report["THREAT"].substr(0,20);
        var threat_sig = report["THREAT_SIG"];
        var entry_specific_rows = "";
        var action_buttons = "";

        // Check if this is a file entry or database entry
        if( report["FILE"] !== undefined ) {
            // FILE ENTRY
            var filename = QtrStripFilePath(report["FILE"], 60);
            var file_md5 = report["FILE_MD5"];
            var copyBtnId = "copyBtn-" + file_md5 + "-" + threat_sig;
            
            entry_specific_rows += "<tr><td>File: </td><td> " + filename + "</td></tr>\n";
            entry_specific_rows += "<tr><td>File signature: </td><td> " + report["FILE_MD5"] + "</td></tr>\n";
            entry_specific_rows += "<tr><td style=\"vertical-align: middle;\">Threat name: </td><td>" + report["THREAT_NAME"] + " <button class='copyThreatBtn btn btn-sm bg-transparent text-info fw-bold ms-2 me-3 rounded-3' style='border: 1px solid #00BFFF; background-color: transparent;' data-threat=\"" + report["THREAT_NAME"] + "\" id='" + copyBtnId + "'>&#x1F4CB;</button> <a href=\"https://threats.quttera.com\" target=\"_blank\" rel=\"noopener noreferrer\"><b>Threat Encyclopedia</b></a> </td></tr>\n";
            entry_specific_rows += "<tr><td>Threat: </td><td> " + threat + "</td></tr>\n";
            entry_specific_rows += "<tr><td>Details: </td><td> " + report["DETAILS"] + "</td></tr>\n";
            
            var fix_rows = "";
            if( report["FIX_ENABLED"] !== undefined ){
                fix_rows += "<tr><td>Auto-fix enabled: </td><td> " + report["FIX_ENABLED"] + " <a href=\"admin.php?page=quttera_wm_scanner_settings#pane-scanner\">Edit in settings</a></td></tr>\n";
            }
            if( report["FIX_SUCCEEDED"] !== undefined ){
                fix_rows += "<tr><td>Auto-fix succeeded: </td><td> " + report["FIX_SUCCEEDED"] + "</td></tr>\n";
            }
            entry_specific_rows += fix_rows;
            
            action_buttons = "<div class='btn-group btn-group-xs'>\n" + 
                "<button type='button' class='btn btn-sm bg-white border text-info fw-bold m-1 rounded-3' style='border-color: #00BFFF;' id=\"" + file_md5 + "\" onclick='QtrWhitelistFile(\"" + file_md5 + "\")'>WhiteList</button>\n" +
                "<button type='button' class='btn btn-sm bg-white border text-info fw-bold m-1 rounded-3' style='border-color: #00BFFF;' id=\"" + file_md5 + "-ShowFile\" onclick='QtrShowFile(\"" + file_md5 + "\")'>Show File</button>\n" +
                "</div>\n";
        } else if( report["DATABASE"] !== undefined ) {
            // DATABASE ENTRY
            entry_specific_rows += "<tr><td>Database: </td><td> " + report["DATABASE"] + "</td></tr>\n";
            entry_specific_rows += "<tr><td>Table: </td><td> " + report["TABLE"] + "</td></tr>\n";
            entry_specific_rows += "<tr><td>Row: </td><td> " + report["ROW"] + "</td></tr>\n";
            entry_specific_rows += "<tr><td style=\"vertical-align: middle;\">Threat name: </td><td>" + report["THREAT_NAME"] + " <button class='copyThreatBtn btn btn-sm bg-transparent text-info fw-bold ms-2 me-3 rounded-3' style='border: 1px solid #00BFFF; background-color: transparent;' data-threat=\"" + report["THREAT_NAME"] + "\">&#x1F4CB;</button> <a href=\"https://threats.quttera.com\" target=\"_blank\" rel=\"noopener noreferrer\"><b>Threat Encyclopedia</b></a> </td></tr>\n";
            entry_specific_rows += "<tr><td>Threat: </td><td> " + threat + "</td></tr>\n";
            
            action_buttons = "";  // No action buttons for database entries
        }

        var sev_tag = 'other';
        if ( severity.indexOf("mal") >= 0 )       sev_tag = 'malicious';
        else if ( severity.indexOf("pot") >= 0 )  sev_tag = 'pot-suspicious';
        else if ( severity.indexOf("susp") >= 0 ) sev_tag = 'suspicious';

        document.getElementById("detected_threats_report").innerHTML += 
            "<div class='" + alert_type + "' data-severity='" + sev_tag + "'>\n"+

                "<table class='table'>\n" +
                    "<tr><td>Severity: </td><td> " + QtrSeverityLabel(report["SEVERITY"]) + "</td></tr>\n" +
                    "<tr><td>Engine: </td><td> " + report["ENGINE"] + "</td></tr>\n" +
                    entry_specific_rows +
                    "<tr><td>Threat signature: </td><td> " + threat_sig + "</td></tr>\n" +
                "</table>\n" + 
                action_buttons +
                "</div>\n";
    }

    function QtrAddToIgnoredThreatsReport( report )
    {
        var alert_type = "alert alert-info";
        var severity   = report["SEVERITY"].toLowerCase();

        if( severity.indexOf("malicious") >= 0 ){
            alert_type = "alert alert-danger";
        }else if( severity.indexOf("susp") >= 0 ){
            alert_type = "alert alert-warning";
        }

        var threat      = report["THREAT"].substr(0,20); 
        var filename    = QtrStripFilePath(report["FILE"],60);
        var file_md5    = report["FILE_MD5"];
        var threat_sig  = report["THREAT_SIG"];
        var copyBtnId   = "copyBtn-" + file_md5 + "-" + threat_sig;

        var fix_rows = "";
        if( report["FIX_ENABLED"] !== undefined ){
            fix_rows += "<tr><td>Auto-fix enabled: </td><td> " + report["FIX_ENABLED"] + " <a href=\"admin.php?page=quttera_wm_scanner_settings#pane-scanner\">Edit in settings</a></td></tr>\n";
        }
        if( report["FIX_SUCCEEDED"] !== undefined ){
            fix_rows += "<tr><td>Fix Succeeded: </td><td> " + report["FIX_SUCCEEDED"] + "</td></tr>\n";
        }

        document.getElementById("ignored_threats_report").innerHTML += 
            "</br>\n" +
            "<div class='" + alert_type + "'>\n"+
                "<table class='table'>\n" +
                    "<tr><td>Severity: </td><td> " + QtrSeverityLabel(report["SEVERITY"]) + "</td></tr>\n" +
                    "<tr><td>File: </td><td> " + filename + "</td></tr>\n" +
                    "<tr><td>File signature: </td><td> " + report["FILE_MD5"] + "</td></tr>\n" +
                    "<tr><td>Threat signature: </td><td> " + report["THREAT_SIG"] + "</td></tr>\n" +
                    "<tr><td style=\"vertical-align: middle;\">Threat name: </td><td> <a href=\"https://threats.quttera.com\" target=\"_blank\" rel=\"noopener noreferrer\">" + report["THREAT_NAME"] + "</a> <button class='copyThreatBtn btn btn-sm bg-transparent text-info fw-bold me-5 rounded-3' style='border: 1px solid #00BFFF; background-color: transparent;' data-threat=\"" + report["THREAT_NAME"] + "\" id='" + copyBtnId + "'>&#x1F4CB; Copy</button></td></tr>\n" +
                    "<tr><td>Threat: </td><td> " + threat  + "</td></tr>\n" +
                    "<tr><td>Details: </td><td> " + report["DETAILS"] + "</td></tr>\n" +
                    fix_rows +
                "</table>\n" + 
                "<div class='btn-group btn-group-xs'>\n" + 
                "<button type='button' class='btn btn-sm bg-white border text-info fw-bold m-1 rounded-3' style='border-color: #00BFFF;' onclick='QtrRemoveFromIgnoreList(\"" + file_md5 + "\",\"" + threat_sig + "\")'>Remove from Ignore List</button>\n" +
                "</div>\n";
           "</div>\n";
    }



    function QtrReloadIgnoredThreatsReport ( )
    {
        console.log("QtrReloadIgnoredThreatsReport");

        QtrShowEmptyIgnoreList();

        jQuery.ajax({
            data: {
                action: 'scanner-get_ignored_threats',
                _wpnonce: '<?php echo $nonce; ?>',
            }, 
            success: function(r) {
                //console.log(r);
                var threats = jQuery.parseJSON(r);

                if( Array.isArray(threats) ){
                    QtrCleanIgnoreThreatsReport();
                    threats_to_show = 100;

                    if( threats_to_show > threats.length ){
                        threats_to_show = threats.length;
                    }

                    if( threats_to_show != 0 )
                    {
                        for(var i = 0; i < threats_to_show; i++ )
                        {
                            QtrAddToIgnoredThreatsReport( threats[i] );
                        }
                    }
                    else
                    {
                        console.log("Ignored list is clean");
                        QtrShowEmptyIgnoreList();
                    }
                }else{
                    console.log("Retrieved invalid output: " + r);
                }
            }//end of success function
        });
    }


    function QtrWhitelistFile( file_sig )
    {
         document.getElementById(file_sig).innerHTML = "<center>Working</center>";
         jQuery.ajax({
            data: {
                action: 'scanner-whitelist_file',
                _wpnonce: '<?php echo $nonce; ?>',
                FILE_MD5: file_sig,
            }, 
            success: function(r) {
                console.log(r);
                console.log("QtrWhitelistFile operation succeeded");
                QtrReloadDetectedThreatsReport ( );
            }//end of success function
        });
       
    }

    function QtrWhitelistThreat(file,threat)
    {
        jQuery.ajax({
            data: {
                action: 'scanner-whitelist_threat',
                _wpnonce: '<?php echo $nonce; ?>',
                FILE_MD5: file,
                THREAT_SIG: threat,
            }, 
            success: function(r) {
                console.log(r);
                console.log("QtrWhitelistThreat: operation succeeded" );
                QtrReloadDetectedThreatsReport ( );
            }//end of success function
        });
    }



    function QtrShowEmptyIgnoreList ( )
    {
        /*
         * First two lines used to refresh element if it is shown
         */
        /*
        document.getElementById('ignored_threats_report').style.display = 'none';
        document.getElementById('ignored_threats_report').style.display = 'block';
        document.getElementById("ignored_threats_report").innerHTML = "<center><p>No entries have been found</p></center>";
        */
    }


    function QtrCleanIgnoreThreatsReport ( )
    {
        document.getElementById("ignored_threats_report").innerHTML = "";
    }


    function QtrIgnoreThreat(file,threat)
    {
        jQuery.ajax({
            data: {
                action: 'scanner-ignore_threat',
                _wpnonce: '<?php echo $nonce; ?>',
                FILE_MD5: file,
                THREAT_SIG: threat,
            }, 
            success: function(r) {
                /* 
                 * refresh content of the tab
                 */
                QtrReloadDetectedThreatsReport ( );
            }//end of success function
        });
    }


    function QtrRemoveFromIgnoreList(file,threat)
    {
        jQuery.ajax({
            data: {
                action: 'scanner-unignore_threat',
                _wpnonce: '<?php echo $nonce; ?>',
                FILE_MD5: file,
                THREAT_SIG: threat,
            }, 
            success: function(r) {
                /* 
                 * refresh content of the tab
                 */
                QtrReloadIgnoredThreatsReport();
            }//end of success function
        });
    }


    function QtrRunInternalScan ( level ) 
    {
        QtrLogMessage ("INFO","Submitting internal scan request");

        jQuery.ajax({
            data: {
                action: 'scanner-run_internal_scan',
                _wpnonce: '<?php echo $nonce; ?>',
            }, 


            timeout: 20000, // sets timeout to 20 seconds, at start we do expensive operations like loading signatures and preparing scan, so it may take more time than default WP timeout

            error: function(jqXHR, textStatus){
                QtrLogMessage ("INFO","Internal scan request submitted");
            },
            success: function(r) {
                QtrLogMessage ("INFO","Operation succeeded. Internal scan started");
            }//end of success function
        });

        QtrReloadExecutionStatus();
    };

    function QtrShowFile( path )
    {        
        QtrLogMessage ("INFO","show file " + path );

        jQuery.ajax({
            data: {
                action: 'scanner-show_file',
                FILE: path,
                _wpnonce: '<?php echo $nonce; ?>',
            },

            timeout: 60000, // sets timeout to 60 seconds

            error: function(jqXHR, textStatus){
                QtrLogMessage ("INFO","Show file request submitted but failed");
            },
            success: function(r) {
                //console.log(r);
                var data = r;
                var winPrint = window.open('', '', 'left=0,top=0,width=800,height=600,toolbar=0,scrollbars=1,status=0');

                if( data.length < 1024 ){
                    /*
                     *  rendering of very big files killing Google Chrome
                     */
                    winPrint.document.write("<script src=\"https://cdn.rawgit.com/google/code-prettify/master/loader/run_prettify.js\"><\/script>");
                }

                data = data.replace(/</g,"&lt;");
                data = data.replace(/>/g,"&gt;");
                //console.log(data);
                winPrint.document.write("<pre class=\"prettyprint\"><code>\r\n" + data + "\r\n</code></pre>");
                winPrint.document.close();
            }//end of success function
        });
    }

    function QtrLogMessage(severity, message)
    {
        if( !severity || !message ){
            return ;
        }

        console.log( severity + ": " + message );
    }


    function QtrUpdateExecutionStats( counters )
    {
        var start = new Date( counters["START_TIME"] * 1000 );
	    var ds = start.toDateString();
	    var ts = start.toTimeString();
        document.getElementById("scan_start_time").innerHTML = ds + " " + ts;
        
        // Determine scan phase based on state
        var scanPhase = "Ready for Scan";
        if (counters["STATE"] === "files_scanning") {
            scanPhase = "Scanning Files...";
        } else if (counters["STATE"] === "database_scanning") {
            scanPhase = "Scanning Database...";
        } else if (counters["STATE"] === "complete") {
            scanPhase = "Scan Complete";
        } else if (counters["STATE"] === "stopped") {
            scanPhase = "Scan Stopped";
        }
        
        // Update phase display
        var phaseElement = document.getElementById("scan_phase");
        if (phaseElement) {
            phaseElement.innerHTML = scanPhase;
            // Change color based on phase
            if (scanPhase.indexOf("Complete") >= 0) {
                phaseElement.style.color = "#28a745"; // Green
            } else if (scanPhase.indexOf("Stopped") >= 0) {
                phaseElement.style.color = "#dc3545"; // Red
            } else {
                phaseElement.style.color = "#00BFFF"; // Blue (scanning)
            }
        }
        
        // FILE SCAN COUNTERS
        document.getElementById("total_scanned_files").innerHTML = counters["TOTAL"] || 0;
        document.getElementById("scanned_clean_files").innerHTML = counters["CLEAN"] || 0;
        document.getElementById("scanned_pos_suspicious_files").innerHTML = counters["POT_SUSPICIOUS"] || 0;
        document.getElementById("scanned_suspicious_files").innerHTML = counters["SUSPICIOUS"] || 0;
        document.getElementById("scanned_malicious_files").innerHTML = counters["MALICIOUS"] || 0;
        
        // DATABASE SCAN COUNTERS
        document.getElementById("total_scanned_rows").innerHTML = counters["ROWS_TOTAL"] || 0;
        document.getElementById("scanned_clean_rows").innerHTML = counters["ROWS_CLEAN"] || 0;
        document.getElementById("scanned_pos_suspicious_rows").innerHTML = counters["ROWS_POT_SUSPICIOUS"] || 0;
        document.getElementById("scanned_suspicious_rows").innerHTML = counters["ROWS_SUSPICIOUS"] || 0;
        document.getElementById("scanned_malicious_rows").innerHTML = counters["ROWS_MALICIOUS"] || 0;
    }


    /**
     * @brief       cut off too long parts of path to shorter form with dots
     * @param[in]   path    - path to convert
     * @param[in]   maxlen  - maximal permitted length
     * @return      converted path
     */
    function QtrStripFilePath( path,maxlen )
    {
        if( path.length <= maxlen ){
            return path;
        }

        name_pos        = path.lastIndexOf("/");
        name            = path.substring( name_pos );
        path_part_end   = maxlen - name.length - 5;
        path_part       = path.substring(0,path_part_end) + "/..." + name;
        return path_part;
    }

    /**
     * @brief       Copy text to clipboard buffer
     * @param[in]   text    - text to copy
     * @param[in]   element - button element (optional, for visual feedback)
     * @return      none
     */
    function QtrCopyToClipboard( text, element )
    {
        if ( navigator.clipboard && window.isSecureContext ) {
            // Use modern Clipboard API if available
            navigator.clipboard.writeText(text).then(function() {
                QtrLogMessage("INFO", "Threat name copied to clipboard: " + text);
                QtrShowCopyFeedback(element);
            }).catch(function(err) {
                console.error("Failed to copy: ", err);
                QtrLogMessage("ERROR", "Failed to copy threat name");
            });
        } else {
            // Fallback for older browsers
            var textArea = document.createElement("textarea");
            textArea.value = text;
            textArea.style.position = "fixed";
            textArea.style.left = "-999999px";
            textArea.style.top = "-999999px";
            document.body.appendChild(textArea);
            textArea.focus();
            textArea.select();
            try {
                document.execCommand('copy');
                QtrLogMessage("INFO", "Threat name copied to clipboard: " + text);
                QtrShowCopyFeedback(element);
            } catch (err) {
                console.error("Fallback copy failed: ", err);
                QtrLogMessage("ERROR", "Failed to copy threat name");
            }
            document.body.removeChild(textArea);
        }
    }

    /**
     * @brief       Show visual feedback when copy succeeds
     * @param[in]   element - button element
     * @return      none
     */
    function QtrShowCopyFeedback( element )
    {
        if ( element ) {
            var originalText = jQuery(element).html();
            // Apply Upgrade style (clicked state) - #00BFFF background with white text
            jQuery(element).css("background-color", "#00BFFF").css("border-color", "#00BFFF");
            jQuery(element).removeClass('bg-transparent text-info').addClass('text-white');
            jQuery(element).html("&#x2713; Copied!");
            
            setTimeout(function() {
                // Restore transparent style (default state)
                jQuery(element).css("background-color", "transparent").css("border-color", "#00BFFF");
                jQuery(element).addClass('bg-transparent text-info').removeClass('text-white');
                jQuery(element).html(originalText);
            }, 2000);
        }
    }
</script>

