var dbName;
var dbUser;
var dbPassword;
var operationType;

function showStep(step) {
    document.getElementById('step1').style.display = step === 1 ? 'block' : 'none';
    document.getElementById('step2').style.display = step === 2 ? 'block' : 'none';
    document.getElementById('step3').style.display = step === 3 ? 'block' : 'none';
}

function createDatabase() {
    dbName = document.getElementById('dbName').value;
    dbUser = document.getElementById('dbUser').value;
    dbPassword = document.getElementById('dbPassword').value;
    operationType = document.getElementById('operationType').value;//0 create db , 1 no create it already exist

    if (dbName != "" && dbUser != "" && dbPassword != "") {
        if (operationType == 1) {//db already exist pass to next step
            showStep(2);
        } else {
            const xhr = new XMLHttpRequest();
            xhr.open('POST', 'versionAjaxController.php?do=createdb', true);
            xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
            xhr.onreadystatechange = function () {
                if (xhr.readyState === 4 && xhr.status === 200) {
                    alert(xhr.responseText);
                    showStep(2);
                }
            };
            xhr.send('dbName=' + encodeURIComponent(dbName) + '&dbUser=' + encodeURIComponent(dbUser) + '&dbPassword=' + encodeURIComponent(dbPassword));
        }
    }

}
function extractZip() {

    operationType = document.getElementById('operationType').value;
    versionName = document.getElementById('versionName').value;

    // Create the iframe
    var iframe = $('<iframe>')
            .attr('name', 'unZipFrame')
            .attr('id', 'unZipFrame')
            .attr('frameborder', '0')
            .attr('width', '100%')
            .attr('height', '500')
            .css('display', 'none');

    // Append the iframe to the body
    $("#statusUnZip").after(iframe);

    // Create the form
    var form = $('<form>')
            .attr('method', 'POST')
            .attr('target', iframe.attr('name'))
            .attr('action', 'versionAjaxController.php?do=extract')
            .attr('id', 'postToIframe')
            .append($('<input>').attr('type', 'hidden').attr('name', 'operationType').val(operationType))
            .append($('<input>').attr('type', 'hidden').attr('name', 'dbName').val(dbName))
            .append($('<input>').attr('type', 'hidden').attr('name', 'dbUser').val(dbUser))
            .append($('<input>').attr('type', 'hidden').attr('name', 'dbPassword').val(dbPassword))
            .append($('<input>').attr('type', 'hidden').attr('name', 'versionName').val(versionName));

    // Append the form to the body
    $('body').append(form);

    // Set the iframe src
    iframe.attr('src', 'versionAjaxController.php?do=extract');

    // Submit the form
    $('#postToIframe').submit().remove();

    // iframe.on('load', function () {
    //     const output = iframe.contents().find('body').text();
    //     const scripts = output.match(/<script>.*?<\/script>/g);
    //     scripts.forEach(script => {
    //         const func = script.match(/parent\.updateProgressUnzip\((.*?)\)/);
    //         if (func) {
    //             const args = func[1].split(',');
    //             updateProgressUnzip(args[0], args[1], args[2]);
    //         }
    //     });
    // });


}
function handledb() {
    operationType = document.getElementById('operationType').value;
    // Create the iframe
    var iframe = $('<iframe>')
            .attr('name', 'dbFrame')
            .attr('id', 'dbFrame')
            .attr('frameborder', '0')
            .attr('width', '100%')
            .attr('height', '500')
            .attr('body', "true")
            .css('display', 'none');

    // Append the iframe to the body
    $("#statusDB").after(iframe);

    // Create the form
    var form = $('<form>')
            .attr('method', 'POST')
            .attr('target', iframe.attr('name'))
            .attr('action', 'versionAjaxController.php?do=handeledb')
            .attr('id', 'postToIframe')
            .append($('<input>').attr('type', 'hidden').attr('name', 'operationType').val(operationType))
            .append($('<input>').attr('type', 'hidden').attr('name', 'dbName').val(dbName))
            .append($('<input>').attr('type', 'hidden').attr('name', 'dbUser').val(dbUser))
            .append($('<input>').attr('type', 'hidden').attr('name', 'dbPassword').val(dbPassword));

    // Append the form to the body
    $('body').append(form);

    // Set the iframe src
    iframe.attr('src', 'versionAjaxController.php?do=handeledb');

    // Submit the form
    $('#postToIframe').submit().remove();



}


function restoreFiles() {
    // Create the iframe
    var iframe = $('<iframe>')
            .attr('name', 'unZipFrame')
            .attr('id', 'unZipFrame')
            .attr('frameborder', '0')
            .attr('width', '100%')
            .attr('height', '500')
            .css('display', 'none');

    // Append the iframe to the body
    $("#statusUnZip").after(iframe);

    // Create the form
    var form = $('<form>')
            .attr('method', 'POST')
            .attr('target', iframe.attr('name'))
            .attr('action', 'versionAjaxController.php?do=restoreOldBackupFiles')
            .attr('id', 'postToIframe');

    // Append the form to the body
    $('body').append(form);

    // Set the iframe src
    iframe.attr('src', 'versionAjaxController.php?do=restoreOldBackupFiles');

    // Submit the form
    $('#postToIframe').submit().remove();
}
function restoreDB() {
    // Create the iframe
    var iframe = $('<iframe>')
            .attr('name', 'dbFrame')
            .attr('id', 'dbFrame')
            .attr('frameborder', '0')
            .attr('width', '100%')
            .attr('height', '500')
            .attr('body', "true")
            .css('display', 'none');

    // Append the iframe to the body
    $("#statusDB").after(iframe);

    // Create the form
    var form = $('<form>')
            .attr('method', 'POST')
            .attr('target', iframe.attr('name'))
            .attr('action', 'versionAjaxController.php?do=restoreOldBackupDB')
            .attr('id', 'postToIframe');
//            .append($('<input>').attr('type', 'hidden').attr('name', 'operationType').val(operationType))
//            .append($('<input>').attr('type', 'hidden').attr('name', 'dbName').val(dbName))
//            .append($('<input>').attr('type', 'hidden').attr('name', 'dbUser').val(dbUser))
//            .append($('<input>').attr('type', 'hidden').attr('name', 'dbPassword').val(dbPassword));

    // Append the form to the body
    $('body').append(form);

    // Set the iframe src
    iframe.attr('src', 'versionAjaxController.php?do=restoreOldBackupDB');

    // Submit the form
    $('#postToIframe').submit().remove();



}


function updateProgressDB(message, percent = 0) {
    document.getElementById('statusDB').innerHTML = message;
    document.getElementById('progressBarDB').style.width = percent + '%';
    if (percent == 100) {
        document.getElementById('statusDB').innerHTML = "Completed successfully.";
        $('#finishBtn').show();
}
}
// This function will be called from the PHP script to update progress
function updateProgressUnzip(currentFile, totalFiles, file) {
    let percentage = Math.round((currentFile / totalFiles) * 100);
    // Get total number of files from the message (if applicable)
    let statusDiv = document.getElementById('statusUnZip');
    statusDiv.innerHTML = currentFile + "/" + totalFiles + " (" + percentage + "%) - file: " + file;
    document.getElementById('progressBarUnZip').style.width = percentage + '%';

    if (percentage == 100) {
        statusDiv.innerHTML = "Completed successfully.";
        $('#unZipNext').show();
    }
}
