<?php echo message_box('success') ?>
<?php echo message_box('error') ?>

<div class="space-y-6">
    <div class="rounded-2xl border border-border bg-card shadow-sm">
        <div class="flex flex-col gap-3 border-b border-border px-5 py-4 md:flex-row md:items-center md:justify-between">
            <div>
                <p class="text-xs font-semibold uppercase tracking-wide text-muted-foreground"><?= lang('settings') ?></p>
                <h2 class="text-lg font-semibold text-foreground"><?= lang('database_backup') ?></h2>
                <p class="text-sm text-muted-foreground"><?= lang('manage') . ' ' . lang('database_backup') ?></p>
            </div>
            <div class="flex flex-wrap items-center gap-2">
                <?= btn_modal(
                    'admin/settings/restore_database',
                    lang('restore_database'),
                    lang('restore_database'),
                    'md',
                    'upload-cloud',
                    array('class' => 'inline-flex items-center gap-2 rounded-lg border border-border bg-card px-3 py-2 text-xs font-semibold text-foreground hover:bg-muted')
                ) ?>
                <form id="dbBackupForm" action="<?= base_url() ?>admin/settings/db_backup" method="post" class="inline-flex">
                    <?php if (config_item('csrf_protection')) : ?>
                        <input type="hidden" name="<?= $this->security->get_csrf_token_name(); ?>" value="<?= $this->security->get_csrf_hash(); ?>">
                    <?php endif; ?>
                    <button id="dbBackupBtn" type="button" class="inline-flex items-center gap-2 rounded-lg bg-indigo-600 px-3 py-2 text-xs font-semibold text-white shadow-sm hover:bg-indigo-500">
                        <i data-lucide="download" class="h-4 w-4"></i>
                        <?= lang('database_backup') ?>
                    </button>
                </form>
            </div>
        </div>
        <div class="p-5">
            <div id="dbBackupProgress" class="mb-5 hidden rounded-xl border border-border bg-muted/20 p-4">
                <div class="flex items-center justify-between gap-3">
                    <div>
                        <div class="text-sm font-semibold text-foreground">Database backup in progress</div>
                        <div id="dbBackupProgressText" class="text-xs text-muted-foreground">Waiting to start</div>
                    </div>
                    <div id="dbBackupProgressPercent" class="text-sm font-semibold text-foreground">0%</div>
                </div>
                <div class="mt-3 h-2 overflow-hidden rounded-full bg-muted">
                    <div id="dbBackupProgressBar" class="h-full w-0 rounded-full bg-indigo-600 transition-all duration-300"></div>
                </div>
                <div id="dbBackupProgressDetail" class="mt-2 text-xs text-muted-foreground"></div>
            </div>
            <div class="overflow-x-auto rounded-xl border border-border">
                <table id="backup" class="min-w-full text-sm" cellspacing="0" cellpadding="0">
                    <thead class="bg-muted/40 text-xs uppercase tracking-wide text-muted-foreground">
                        <tr>
                            <th class="px-4 py-3 text-left font-semibold"><?= lang('date'); ?></th>
                            <th class="px-4 py-3 text-left font-semibold"><?= lang('file_name'); ?></th>
                            <th class="col-options no-sort px-4 py-3 text-right font-semibold"><?= lang('action'); ?></th>
                        </tr>
                    </thead>
                    <tbody class="divide-y divide-border">
                        <?php
                        if (isset($backups)) {
                            if (!empty($backups)) {
                                arsort($backups);
                                foreach ($backups as $file):
                                    $filename = explode("_", $file);
                                    ?>
                                    <tr>
                                        <td class="px-4 py-3 text-foreground"><?php echo str_replace('.zip', ' &nbsp ', $filename[1]); ?><?php echo str_replace('.zip', ' &nbsp  ', $filename[2]); ?></td>
                                        <td class="px-4 py-3 text-foreground"><?php echo str_replace('-', ' &nbsp ', $filename[0]); ?></td>
                                        <td class="px-4 py-3">
                                            <div class="flex items-center gap-0">
                                                <a data-toggle="tooltip" data-placement="top"
                                                   class="inline-flex items-center rounded-md border mb-1 gap-1 border-border px-2.5 py-1.5 text-xs font-semibold text-foreground hover:bg-muted"
                                                   href="<?= base_url() ?>admin/settings/download_backup/<?= $file ?>"
                                                   title="<?= lang('download'); ?>">
                                                    <i data-lucide="download" class="h-3.5 w-3.5"></i>
													<?= lang('download'); ?>
                                                </a>
                                                <?= btn_delete('admin/settings/delete_backup/' . $file) ?>
                                            </div>
                                        </td>
                                    </tr>
                                <?php endforeach;
                            }
                        } else { ?>
                            <tr>
                                <td colspan="3" class="px-4 py-6 text-center text-sm text-muted-foreground"><?= $this->lang->line('application_no_backups'); ?></td>
                            </tr>
                        <?php } ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</div>

<script type="text/javascript">
    (function () {
        var form = document.getElementById('dbBackupForm');
        var button = document.getElementById('dbBackupBtn');
        var progressBox = document.getElementById('dbBackupProgress');
        var progressText = document.getElementById('dbBackupProgressText');
        var progressPercent = document.getElementById('dbBackupProgressPercent');
        var progressBar = document.getElementById('dbBackupProgressBar');
        var progressDetail = document.getElementById('dbBackupProgressDetail');
        if (!form || !button) {
            return;
        }

        function setProgress(data) {
            var percent = Math.max(0, Math.min(100, parseInt(data.progress || 0, 10)));
            if (progressBox) {
                progressBox.classList.remove('hidden');
            }
            if (progressText) {
                progressText.textContent = data.message || 'Working...';
            }
            if (progressPercent) {
                progressPercent.textContent = percent + '%';
            }
            if (progressBar) {
                progressBar.style.width = percent + '%';
            }
            if (progressDetail) {
                progressDetail.textContent = data.details || '';
            }
        }

        function parseLines(text, lastIndex) {
            var chunk = text.slice(lastIndex.value);
            lastIndex.value = text.length;
            chunk.split(/\r?\n/).forEach(function (line) {
                if (!line.trim()) {
                    return;
                }
                try {
                    var payload = JSON.parse(line);
                    setProgress(payload);
                    if (payload.status === false && payload.message) {
                        progressDetail.textContent = payload.message;
                    }
                } catch (e) {
                }
            });
        }

        button.addEventListener('click', function () {
            button.disabled = true;
            button.classList.add('opacity-70', 'cursor-not-allowed');
            setProgress({progress: 0, message: 'Starting backup...', details: 'Preparing database tables'});

            var xhr = new XMLHttpRequest();
            var lastIndex = { value: 0 };
            xhr.open('POST', form.action, true);
            xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
            xhr.onreadystatechange = function () {
                if (xhr.readyState >= 3) {
                    parseLines(xhr.responseText || '', lastIndex);
                }
            };
            xhr.onload = function () {
                parseLines(xhr.responseText || '', lastIndex);
                try {
                    var finalLine = (xhr.responseText || '').trim().split(/\r?\n/).pop();
                    if (finalLine) {
                        var finalPayload = JSON.parse(finalLine);
                        setProgress(finalPayload);
                        if (finalPayload.status) {
                            progressText.textContent = 'Backup completed';
                            progressDetail.textContent = finalPayload.file || '';
                            setTimeout(function () {
                                window.location.reload();
                            }, 1200);
                        } else {
                            progressText.textContent = 'Backup failed';
                        }
                    }
                } catch (e) {
                }
                button.disabled = false;
                button.classList.remove('opacity-70', 'cursor-not-allowed');
            };
            xhr.onerror = function () {
                if (progressText) {
                    progressText.textContent = 'Backup failed';
                }
                if (progressDetail) {
                    progressDetail.textContent = 'The request could not be completed.';
                }
                button.disabled = false;
                button.classList.remove('opacity-70', 'cursor-not-allowed');
            };
            xhr.send(new FormData(form));
        });
    })();
</script>
