<!DOCTYPE html>
<html lang="en">
<head>
    <style>
        body {
            font-family: Verdana, Geneva, sans-serif;
            font-size: 14px;
        }

        .wrapper {
            margin: 0 auto;
            display: block;
            background: #f0f0f0;
            width: 600px;
            border: 1px solid #e4e4e4;
            padding: 20px;
            border-radius: 4px;
            margin-top: 50px;
            text-align: center;
        }

        .wrapper h1 {
            text-align: center;
            font-size: 24px;
            color: red;
            margin-top: 0px;
        }

        .wrapper .upgrade_now {
            text-transform: uppercase;
            background: #82b440;
            color: #fff;
            padding: 15px 25px;
            border-radius: 3px;
            text-decoration: none;
            text-align: center;
            border: 0px;
            outline: 0px;
            cursor: pointer;
            font-size: 15px;
        }

        .wrapper .upgrade_now:hover, .wrapper .upgrade_now:active {
            background: #73a92d;
        }

        .upgrade_now_wrapper {
            margin: 0 auto;
            width: 100%;
            text-align: center;
            margin-top: 40px;
            margin-bottom: 40px;
        }

        .note {
            color: #636363;
        }

        .bold {
            font-weight: bold;
        }
    </style>
</head>
<body>
<?php
$filesVersion = (string) ($this->config->item('migration_version') ?? '');
$dbVersion = (string) ($this->_current_version ?? '');
?>
<div class="wrapper">
    <h1>
        Database upgrade is required.
    </h1>
    <p>You need to perform an database upgrade before proceed using ZiscoERP - Powerfull HR,Accounting,CRM System. Your
        files version is <?php echo wordwrap($filesVersion !== '' ? $filesVersion : '0', 1, '.', true); ?> and database
        version is <?php echo wordwrap($dbVersion !== '' ? $dbVersion : '0', 1, '.', true); ?></p>
    <p class="bold">Please make sure that you have backup of your database before perform an upgrade.</p>
    <div class="upgrade_now_wrapper">
        <button type="button" class="upgrade_now" id="upgrade_now">Upgrade now</button>
    </div>
    <div id="upgrade_progress_wrap" style="display:none; margin: 0 auto; width: 100%; max-width: 520px; text-align: left;">
        <div class="bold" id="upgrade_progress_label" style="margin-bottom: 8px;">Preparing update...</div>
        <div style="height: 10px; background: #ddd; border-radius: 999px; overflow: hidden;">
            <div id="upgrade_progress_bar" style="height: 100%; width: 0%; background: #82b440;"></div>
        </div>
        <div id="upgrade_progress_note" style="margin-top: 8px;" class="note">Waiting to start.</div>
        <div id="upgrade_long_note" style="display:none; margin-top: 8px;" class="note">Some database migrations add indexes to large tables. It is normal for those steps to stay on the same number for several minutes.</div>
    </div>
    <div id="upgrade_messages" style="margin-top: 20px;"></div>
    <small class="note">This message may shown if you uploaded files from newer version downloaded from CodeCanyon to
        your existing installation.</small>
</div>
<script>
(function () {
    var button = document.getElementById('upgrade_now');
    var progressWrap = document.getElementById('upgrade_progress_wrap');
    var progressBar = document.getElementById('upgrade_progress_bar');
    var progressLabel = document.getElementById('upgrade_progress_label');
    var progressNote = document.getElementById('upgrade_progress_note');
    var longNote = document.getElementById('upgrade_long_note');
    var messages = document.getElementById('upgrade_messages');
    var running = false;
    var csrfName = '<?= $this->security->get_csrf_token_name(); ?>';
    var csrfHash = '<?= $this->security->get_csrf_hash(); ?>';

    function setProgress(percent, label, note) {
        progressWrap.style.display = 'block';
        progressBar.style.width = percent + '%';
        progressLabel.textContent = label || 'Updating...';
        progressNote.textContent = note || '';
        longNote.style.display = /migration/i.test(note || '') ? 'block' : 'none';
    }

    function showMessage(text, color) {
        messages.innerHTML = '<div style="padding: 12px 14px; border-radius: 4px; background: ' + color + '; color: #fff;">' + text + '</div>';
    }

    function pollStatus(token) {
        var xhr = new XMLHttpRequest();
        xhr.open('GET', '<?= base_url('admin/auto_update/status/'); ?>' + encodeURIComponent(token), true);
        xhr.onreadystatechange = function () {
            if (xhr.readyState !== 4) {
                return;
            }
            if (xhr.status < 200 || xhr.status >= 300) {
                running = false;
                button.disabled = false;
                button.textContent = 'Upgrade now';
                showMessage(xhr.responseText || 'Unable to continue the upgrade.', '#dc3545');
                return;
            }

            var response;
            try {
                response = JSON.parse(xhr.responseText);
            } catch (e) {
                running = false;
                button.disabled = false;
                button.textContent = 'Upgrade now';
                showMessage(xhr.responseText || 'Unexpected response.', '#dc3545');
                return;
            }

            if (!response.success) {
                running = false;
                button.disabled = false;
                button.textContent = 'Upgrade now';
                showMessage(response.message || 'Upgrade failed.', '#dc3545');
                return;
            }

            setProgress(response.progress || 0, 'Updating database...', response.message || ('Version ' + response.current_version + ' of ' + response.latest_version));

            if (response.done) {
                showMessage('Database upgrade completed successfully.', '#28a745');
                progressNote.textContent = 'Finalizing...';
                setTimeout(function () {
                    window.location.reload();
                }, 2000);
                return;
            }

            if (response.status === 'failed') {
                running = false;
                button.disabled = false;
                button.textContent = 'Upgrade now';
                showMessage(response.message || 'Upgrade failed.', '#dc3545');
                return;
            }

            setTimeout(function () {
                pollStatus(token);
            }, 2500);
        };
        xhr.send();
    }

    function startUpdate() {
        var xhr = new XMLHttpRequest();
        xhr.open('POST', '<?= base_url('admin/auto_update/database'); ?>', true);
        xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
        xhr.onreadystatechange = function () {
            if (xhr.readyState !== 4) {
                return;
            }
            if (xhr.status < 200 || xhr.status >= 300) {
                running = false;
                button.disabled = false;
                button.textContent = 'Upgrade now';
                showMessage(xhr.responseText || 'Unable to continue the upgrade.', '#dc3545');
                return;
            }

            var response;
            try {
                response = JSON.parse(xhr.responseText);
            } catch (e) {
                running = false;
                button.disabled = false;
                button.textContent = 'Upgrade now';
                showMessage(xhr.responseText || 'Unexpected response.', '#dc3545');
                return;
            }

            if (!response.success) {
                running = false;
                button.disabled = false;
                button.textContent = 'Upgrade now';
                showMessage(response.message || 'Upgrade failed.', '#dc3545');
                return;
            }

            setProgress(response.progress || 0, 'Updating database...', response.message || ('Version ' + response.current_version + ' of ' + response.latest_version));

            if (response.done) {
                showMessage('Database upgrade completed successfully.', '#28a745');
                progressNote.textContent = 'Finalizing...';
                setTimeout(function () {
                    window.location.reload();
                }, 2000);
                return;
            }

            pollStatus(response.token);
        };
        xhr.send('auto_update=true&' + encodeURIComponent(csrfName) + '=' + encodeURIComponent(csrfHash));
    }

    button.addEventListener('click', function () {
        if (running) {
            return;
        }
        running = true;
        button.disabled = true;
        button.textContent = 'Please wait...';
        setProgress(0, 'Preparing update...', 'Starting database migration');
        startUpdate();
    });
})();
</script>
</body>
</html>
