<?php ob_start(); ?>

<?php admin_content_header(__('admin.backup.title'), 'hard-drive'); ?>

<?php if (!$zipAvailable): ?>
<div class="alert alert-error">
    <strong><?= __('admin.backup.zip_warning') ?>:</strong> Die PHP-Erweiterung <code>zip</code> ist auf diesem Server nicht geladen.
    Backup-, Restore- und Update-Funktionen sind nicht verfügbar.
    Bitte aktivieren Sie die ZIP-Erweiterung oder wenden Sie sich an Ihren Hosting-Anbieter.
</div>
<?php endif; ?>

<style>
.backup-tabs { display:flex; gap:0; border-bottom:2px solid var(--border-color,#e5e7eb); margin-bottom:1.5rem; }
.backup-tab  { padding:0.625rem 1.25rem; font-weight:500; cursor:pointer; border-bottom:2px solid transparent; margin-bottom:-2px; color:var(--gray-500,#6b7280); font-size:0.9375rem; }
.backup-tab.active { color:var(--admin-primary,#2563eb); border-bottom-color:var(--admin-primary,#2563eb); }
.backup-panel { display:none; }
.backup-panel.active { display:block; }
.backup-info-box { background:var(--admin-bg,#f9fafb); border:1px solid var(--border-color,#e5e7eb); border-radius:8px; padding:1.25rem 1.5rem; margin-bottom:1.25rem; }
.backup-info-box h4 { margin:0 0 0.5rem; font-size:1rem; }
.backup-info-box p  { margin:0; color:var(--gray-600,#4b5563); font-size:0.9rem; line-height:1.6; }
.backup-warning { background:#fffbeb; border:1px solid #fcd34d; border-radius:8px; padding:1rem 1.25rem; margin-bottom:1.25rem; color:#92400e; font-size:0.9rem; line-height:1.6; }
.backup-warning strong { display:block; margin-bottom:0.25rem; }
.backup-meta { display:flex; flex-wrap:wrap; gap:1rem; margin-top:0.5rem; }
.backup-meta-item { font-size:0.85rem; color:var(--gray-500,#6b7280); }
.backup-meta-item strong { color:var(--gray-700,#374151); }
.backup-version-badge { display:inline-block; background:var(--admin-primary,#2563eb); color:#fff; border-radius:4px; padding:0.15rem 0.5rem; font-size:0.8rem; font-weight:600; }
</style>

<!-- Tab navigation -->
<div class="backup-tabs" id="backupTabs">
    <span class="backup-tab active" data-tab="tab-backup"><?= __('admin.backup.tab_backup') ?></span>
    <span class="backup-tab" data-tab="tab-restore"><?= __('admin.backup.tab_restore') ?></span>
    <span class="backup-tab" data-tab="tab-update"><?= __('admin.backup.tab_update') ?></span>
    <span class="backup-tab" data-tab="tab-ftp"><?= __('admin.ftp_backup.tab_ftp') ?></span>
</div>

<!-- ═══════════════════════════════════════════════════════════════════════════
     TAB 1: CREATE BACKUP
     ═══════════════════════════════════════════════════════════════════════════ -->
<div class="backup-panel active" id="tab-backup">

    <div class="backup-info-box">
        <h4><?= __('admin.backup.backup_title') ?></h4>
        <p>
            <?= __('admin.backup.backup_text') ?>
        </p>
        <div class="backup-meta">
            <span class="backup-meta-item"><strong><?= __('admin.backup.backup_version', ['version' => e($currentVersion)]) ?></strong></span>
            <span class="backup-meta-item"><strong><?= __('admin.backup.backup_includes') ?></strong></span>
            <span class="backup-meta-item"><strong><?= __('admin.backup.backup_format') ?></strong></span>
        </div>
    </div>

    <?php if ($zipAvailable): ?>
    <!--
        Wichtig: Das Backup-Create-Formular wird NICHT per nativem Form-POST abgesendet.
        Stattdessen nutzen wir fetch() im JS-Block unten.
        Begründung: Der Server antwortet mit Content-Disposition:attachment (Datei-Download).
        Ein nativer Form-POST würde die Seite NICHT neu laden – der LRA-Status bliebe
        dauerhaft im "laufend"-Zustand hängen.
        Mit fetch() können wir den Response prüfen, den Blob-Download auslösen und den
        LRA-Zustand nach Abschluss sauber zurücksetzen.
    -->
    <form id="backupCreateForm">
        <?= $csrf->field() ?>
        <p style="color:var(--gray-600,#4b5563);font-size:0.9rem;margin-bottom:1rem;">
            <?= __('admin.backup.backup_auto_download') ?>
        </p>
        <button type="submit" id="backupCreateBtn" class="btn btn-primary">
            ↓ &nbsp; <?= __('admin.backup.backup_btn') ?>
        </button>

        <!-- LRA-Status: wird eingeblendet wenn die Backup-Erstellung läuft -->
        <div class="lra-status" id="lraBackupStatus" role="status" aria-live="polite">
            <div class="lra-spinner" aria-hidden="true"></div>
            <div class="lra-status-body">
                <div class="lra-status-heading"><?= __('admin.backup.lra_backup_heading') ?></div>
                <ul class="lra-steps">
                    <li class="lra-step-current"><?= __('admin.backup.lra_backup_step1') ?></li>
                    <li><?= __('admin.backup.lra_backup_step2') ?></li>
                    <li><?= __('admin.backup.lra_backup_step3') ?></li>
                </ul>
            </div>
        </div>

        <!-- Fehlermeldung: nur bei fetch()-Fehler eingeblendet -->
        <div id="lraBackupError" class="alert alert-error" style="display:none;margin-top:0.75rem;" role="alert"></div>
    </form>
    <?php else: ?>
    <p class="form-hint" style="color:var(--admin-danger,#dc2626);">Backup nicht verfügbar – ZIP-Erweiterung fehlt.</p>
    <?php endif; ?>

</div>

<!-- ═══════════════════════════════════════════════════════════════════════════
     TAB 2: RESTORE
     ═══════════════════════════════════════════════════════════════════════════ -->
<div class="backup-panel" id="tab-restore">

    <div class="backup-info-box">
        <h4><?= __('admin.backup.restore_title') ?></h4>
        <p>
            <?= __('admin.backup.restore_text') ?>
        </p>
    </div>

    <div class="backup-warning">
        <strong>⚠ <?= __('admin.backup.restore_warning_title') ?></strong>
        <?= __('admin.backup.restore_warning_text') ?>
    </div>

    <?php if ($zipAvailable): ?>
    <form method="POST" action="<?= admin_url('backup/restore') ?>" enctype="multipart/form-data" class="admin-form">
        <?= $csrf->field() ?>

        <div class="form-card">
            <div class="form-group">
                <label for="backup_file"><?= __('admin.backup.restore_label') ?></label>
                <input type="file" id="backup_file" name="backup_file" accept=".zip" required>
                <small class="form-hint">
                    <?= __('admin.backup.restore_hint', ['maxMb' => (int)($maxZipMb ?? 200)]) ?>
                    <?php if (!empty($phpLimited)): ?>
                    <br><span style="color:var(--admin-warning-text,#92400e);"><?= __('admin.backup.php_limit_hint', ['maxMb' => (int)($maxZipMb ?? 200)]) ?></span>
                    <?php endif; ?>
                </small>
            </div>

            <button type="submit" class="btn btn-warning">
                <?= __('admin.backup.restore_btn') ?>
            </button>
        </div>
    </form>
    <?php else: ?>
    <p class="form-hint" style="color:var(--admin-danger,#dc2626);">Restore nicht verfügbar – ZIP-Erweiterung fehlt.</p>
    <?php endif; ?>

</div>

<!-- ═══════════════════════════════════════════════════════════════════════════
     TAB 3: CMS UPDATE
     ═══════════════════════════════════════════════════════════════════════════ -->
<div class="backup-panel" id="tab-update">

    <div class="backup-info-box">
        <h4><?= __('admin.backup.update_title') ?></h4>
        <p>
            <?= __('admin.backup.update_text') ?>
        </p>
        <div class="backup-meta">
            <span class="backup-meta-item"><strong><?= __('admin.backup.update_version', ['version' => e($currentVersion)]) ?></strong></span>
        </div>
    </div>

    <div class="backup-info-box" style="background:linear-gradient(135deg,#eef2ff 0%,#f0f9ff 100%); border-left:3px solid var(--admin-primary,#2563eb);">
        <h4 style="display:flex; align-items:center; gap:.5rem;">
            <?= render_icon('refresh-cw', 18) ?>
            Auto-Update-System verfügbar
        </h4>
        <p style="margin-bottom:.75rem;">
            Neu ab v3.4.1: Updates werden direkt aus der offiziellen Registry (itsweber.de) geladen,
            automatisch verifiziert (Ed25519 + SHA256), installiert und bei Fehler automatisch zurückgerollt.
            Kein manueller ZIP-Upload mehr nötig.
        </p>
        <a href="<?= admin_url('system/updates') ?>" class="btn btn-primary btn-sm">
            <?= render_icon('download', 14) ?>
            Updates jetzt prüfen
        </a>
    </div>

    <div class="backup-warning">
        <strong>⚠ <?= __('admin.backup.update_warning_title') ?></strong>
        <?= __('admin.backup.update_warning_text') ?>
    </div>

    <?php if ($zipAvailable): ?>
    <form method="POST" action="<?= admin_url('backup/update') ?>" enctype="multipart/form-data" class="admin-form">
        <?= $csrf->field() ?>

        <div class="form-card">
            <div class="form-group">
                <label for="update_file"><?= __('admin.backup.update_label') ?></label>
                <input type="file" id="update_file" name="update_file" accept=".zip" required>
                <small class="form-hint">
                    <?= __('admin.backup.update_hint', ['maxMb' => (int)($maxZipMb ?? 200)]) ?>
                    <?php if (!empty($phpLimited)): ?>
                    <br><span style="color:var(--admin-warning-text,#92400e);"><?= __('admin.backup.php_limit_hint', ['maxMb' => (int)($maxZipMb ?? 200)]) ?></span>
                    <?php endif; ?>
                </small>
            </div>

            <button type="submit" class="btn btn-primary">
                <?= __('admin.backup.update_btn') ?>
            </button>
        </div>
    </form>
    <?php else: ?>
    <p class="form-hint" style="color:var(--admin-danger,#dc2626);">Update nicht verfügbar – ZIP-Erweiterung fehlt.</p>
    <?php endif; ?>

</div>

<!-- ═══════════════════════════════════════════════════════════════════════════
     TAB 4: FTP BACKUP
     ═══════════════════════════════════════════════════════════════════════════ -->
<div class="backup-panel" id="tab-ftp">

    <div class="backup-info-box">
        <h4><?= __('admin.ftp_backup.title') ?></h4>
        <p>
            <?= __('admin.ftp_backup.description') ?>
        </p>
    </div>

    <?php if (!$ftpAvailable): ?>
    <div class="alert alert-error">
        <strong><?= __('admin.ftp_backup.error_ftp_disabled') ?>:</strong> <?= __('admin.ftp_backup.error_ftp_info') ?>
    </div>
    <?php else: ?>

    <form method="POST" action="<?= admin_url('backup/ftp/save') ?>" class="admin-form" id="ftpBackupForm">
        <?= $csrf->field() ?>

        <div class="form-card">
            <!-- FTP Connection Settings -->
            <fieldset>
                <legend><?= __('admin.ftp_backup.section_connection') ?></legend>

                <div class="form-group">
                    <label for="ftp_host"><?= __('admin.ftp_backup.label_host') ?></label>
                    <input type="text" id="ftp_host" name="ftp_host" value="<?= e($settings['host'] ?? '') ?>" placeholder="ftp.example.com" required>
                    <small class="form-hint"><?= __('admin.ftp_backup.hint_host') ?></small>
                </div>

                <div style="display:grid; grid-template-columns:repeat(auto-fit,minmax(200px,1fr)); gap:1rem;">
                    <div class="form-group">
                        <label for="ftp_port"><?= __('admin.ftp_backup.label_port') ?></label>
                        <input type="number" id="ftp_port" name="ftp_port" value="<?= e($settings['port'] ?? 21) ?>" min="1" max="65535">
                        <small class="form-hint"><?= __('admin.ftp_backup.hint_port') ?></small>
                    </div>

                    <div class="form-group">
                        <label for="ftp_user"><?= __('admin.ftp_backup.label_user') ?></label>
                        <input type="text" id="ftp_user" name="ftp_user" value="<?= e($settings['user'] ?? '') ?>" required>
                        <small class="form-hint"><?= __('admin.ftp_backup.hint_user') ?></small>
                    </div>
                </div>

                <div class="form-group">
                    <label for="ftp_pass"><?= __('admin.ftp_backup.label_pass') ?></label>
                    <div class="input-password-wrap">
                        <input type="password" id="ftp_pass" name="ftp_pass" placeholder="Passwort">
                        <button type="button" class="password-toggle" aria-label="<?= __('auth.login_show_password') ?>">
                            <span class="icon-eye"><?= icon('eye', 18) ?></span>
                            <span class="icon-eye-off" style="display:none"><?= icon('eye-off', 18) ?></span>
                        </button>
                    </div>
                    <small class="form-hint"><?= __('admin.ftp_backup.hint_pass') ?></small>
                </div>

                <div class="form-group">
                    <label for="ftp_path"><?= __('admin.ftp_backup.label_path') ?></label>
                    <input type="text" id="ftp_path" name="ftp_path" value="<?= e($settings['path'] ?? '/backups') ?>" placeholder="/backups">
                    <small class="form-hint"><?= __('admin.ftp_backup.hint_path') ?></small>
                </div>
            </fieldset>

            <!-- Backup Schedule & Retention -->
            <fieldset style="margin-top:2rem;">
                <legend><?= __('admin.ftp_backup.section_schedule') ?></legend>

                <div style="display:grid; grid-template-columns:repeat(auto-fit,minmax(200px,1fr)); gap:1rem;">
                    <div class="form-group">
                        <label for="ftp_schedule"><?= __('admin.ftp_backup.label_schedule') ?></label>
                        <select id="ftp_schedule" name="ftp_schedule">
                            <option value="manual" <?= ($settings['schedule'] ?? 'manual') === 'manual' ? 'selected' : '' ?>>
                                <?= __('admin.ftp_backup.schedule_manual') ?>
                            </option>
                            <option value="daily" <?= ($settings['schedule'] ?? '') === 'daily' ? 'selected' : '' ?>>
                                <?= __('admin.ftp_backup.schedule_daily') ?>
                            </option>
                            <option value="weekly" <?= ($settings['schedule'] ?? '') === 'weekly' ? 'selected' : '' ?>>
                                <?= __('admin.ftp_backup.schedule_weekly') ?>
                            </option>
                        </select>
                        <small class="form-hint"><?= __('admin.ftp_backup.hint_schedule') ?></small>
                    </div>

                    <div class="form-group">
                        <label for="ftp_daily_retain"><?= __('admin.ftp_backup.label_daily_retain') ?></label>
                        <input type="number" id="ftp_daily_retain" name="ftp_daily_retain" value="<?= e($settings['daily_retain'] ?? 7) ?>" min="1" max="365">
                        <small class="form-hint"><?= __('admin.ftp_backup.hint_daily_retain') ?></small>
                    </div>

                    <div class="form-group">
                        <label for="ftp_weekly_retain"><?= __('admin.ftp_backup.label_weekly_retain') ?></label>
                        <input type="number" id="ftp_weekly_retain" name="ftp_weekly_retain" value="<?= e($settings['weekly_retain'] ?? 4) ?>" min="1" max="52">
                        <small class="form-hint"><?= __('admin.ftp_backup.hint_weekly_retain') ?></small>
                    </div>
                </div>
            </fieldset>

            <!-- Backup Items -->
            <fieldset style="margin-top:2rem;">
                <legend><?= __('admin.ftp_backup.section_items') ?></legend>

                <div class="form-group">
                    <p class="form-hint"><?= __('admin.ftp_backup.hint_items') ?></p>
                    <div style="display:grid; grid-template-columns:repeat(auto-fit,minmax(200px,1fr)); gap:1rem;">
                        <label style="display:flex; align-items:center; gap:0.5rem;">
                            <input type="checkbox" name="ftp_items[]" value="database" <?= in_array('database', $settings['items'] ?? []) ? 'checked' : '' ?>>
                            <span><?= __('admin.ftp_backup.item_database') ?></span>
                        </label>
                        <label style="display:flex; align-items:center; gap:0.5rem;">
                            <input type="checkbox" name="ftp_items[]" value="uploads" <?= in_array('uploads', $settings['items'] ?? []) ? 'checked' : '' ?>>
                            <span><?= __('admin.ftp_backup.item_uploads') ?></span>
                        </label>
                        <label style="display:flex; align-items:center; gap:0.5rem;">
                            <input type="checkbox" name="ftp_items[]" value="themes" <?= in_array('themes', $settings['items'] ?? []) ? 'checked' : '' ?>>
                            <span><?= __('admin.ftp_backup.item_themes') ?></span>
                        </label>
                        <label style="display:flex; align-items:center; gap:0.5rem;">
                            <input type="checkbox" name="ftp_items[]" value="plugins" <?= in_array('plugins', $settings['items'] ?? []) ? 'checked' : '' ?>>
                            <span><?= __('admin.ftp_backup.item_plugins') ?></span>
                        </label>
                    </div>
                </div>
            </fieldset>

            <!-- Action Buttons -->
            <div class="form-actions" style="margin-top:2rem; display:flex; gap:1rem; flex-wrap:wrap;">
                <button type="button" id="ftpTestBtn" class="btn btn-secondary">
                    <?= __('admin.ftp_backup.btn_test') ?>
                </button>
                <button type="button" id="ftpBackupBtn" class="btn btn-primary">
                    <?= __('admin.ftp_backup.btn_backup') ?>
                </button>
                <button type="submit" class="btn btn-success">
                    <?= __('admin.ftp_backup.btn_save') ?>
                </button>
            </div>

            <!-- Test Result Message -->
            <div id="ftpTestResult" class="alert" style="display:none; margin-top:1rem;"></div>
        </div>
    </form>

    <?php endif; ?>

</div>

<script>
(function () {
    // ── Tab-Navigation ──────────────────────────────────────────────────────
    var tabs   = document.querySelectorAll('.backup-tab');
    var panels = document.querySelectorAll('.backup-panel');

    function activateTab(id) {
        tabs.forEach(function(t) { t.classList.toggle('active', t.dataset.tab === id); });
        panels.forEach(function(p) { p.classList.toggle('active', p.id === id); });
        if (history.replaceState) {
            history.replaceState(null, '', '#' + id.replace('tab-',''));
        }
    }

    tabs.forEach(function(tab) {
        tab.addEventListener('click', function() { activateTab(tab.dataset.tab); });
    });

    // Activate tab from URL hash on load
    var hash = window.location.hash.replace('#','');
    if (hash === 'restore') activateTab('tab-restore');
    else if (hash === 'update') activateTab('tab-update');
    else if (hash === 'ftp') activateTab('tab-ftp');

    // ── LRA: Backup-Erstellung (fetch-basiert) ────────────────────────────────
    // Problem des nativen Form-Submit:
    //   Der Server antwortet mit Content-Disposition:attachment. Damit lädt der
    //   Browser die Datei herunter, NAVIGIERT ABER NICHT WEG. Kein DOM-Reload →
    //   LRA-Zustand bleibt dauerhaft im "laufend"-Zustand hängen.
    // Lösung:
    //   fetch() übernimmt den Submit. Wir prüfen den Response-Header, lösen den
    //   Download über createObjectURL aus und setzen den LRA-Zustand danach sauber
    //   zurück. CSRF-Token wird via FormData automatisch mitgesendet (kein Server-
    //   seitiger Umbau nötig).
    var backupForm   = document.getElementById('backupCreateForm');
    var backupBtn    = document.getElementById('backupCreateBtn');
    var backupStat   = document.getElementById('lraBackupStatus');
    var backupErr    = document.getElementById('lraBackupError');
    var backupBtnOrig = backupBtn ? backupBtn.innerHTML : '';

    function resetBackupLra(success, errMsg) {
        if (backupStat) backupStat.classList.remove('lra-active');
        if (!backupBtn) return;
        backupBtn.disabled = false;
        if (success) {
            backupBtn.innerHTML = '✓ <?= __('admin.backup.lra_backup_done') ?>';
            backupBtn.style.background = '#16a34a';
            // Nach 4 s automatisch auf Originalzustand zurücksetzen
            setTimeout(function () {
                backupBtn.innerHTML  = backupBtnOrig;
                backupBtn.style.background = '';
            }, 4000);
            if (backupErr) backupErr.style.display = 'none';
        } else {
            backupBtn.innerHTML = backupBtnOrig;
            backupBtn.style.background = '';
            if (backupErr && errMsg) {
                backupErr.textContent = errMsg;
                backupErr.style.display = 'block';
            }
        }
    }

    if (backupForm && backupBtn) {
        backupForm.addEventListener('submit', function (e) {
            e.preventDefault();

            backupBtn.disabled = true;
            backupBtn.innerHTML = '<span class="lra-btn-spinner" aria-hidden="true"></span><?= __('admin.common.processing') ?>';
            if (backupStat) backupStat.classList.add('lra-active');
            if (backupErr) backupErr.style.display = 'none';

            fetch('<?= admin_url('backup/create') ?>', {
                method : 'POST',
                body   : new FormData(backupForm)
            })
            .then(function (res) {
                // Kein Content-Disposition-Header → Server hat auf einen Fehler
                // mit Redirect reagiert; fetch() ist dem Redirect gefolgt und hat
                // die Backup-Seite als HTML zurückgegeben.
                var cd = res.headers.get('Content-Disposition') || '';
                if (!cd || !res.ok) {
                    throw new Error('<?= __('admin.backup.lra_backup_error') ?>');
                }

                // Dateiname aus Content-Disposition auslesen
                var m = cd.match(/filename\s*=\s*"?([^";\r\n]+)"?/i);
                var filename = (m && m[1]) ? m[1].trim() : 'backup.zip';

                // ZIP-Blob laden, dann Download auslösen
                return res.blob().then(function (blob) {
                    return { blob: blob, filename: filename };
                });
            })
            .then(function (data) {
                var url = URL.createObjectURL(data.blob);
                var a   = document.createElement('a');
                a.href     = url;
                a.download = data.filename;
                document.body.appendChild(a);
                a.click();
                document.body.removeChild(a);
                // URL nach kurzer Verzögerung freigeben (Browser braucht Moment)
                setTimeout(function () { URL.revokeObjectURL(url); }, 2000);
                resetBackupLra(true);
            })
            .catch(function (err) {
                resetBackupLra(false, err.message || '<?= __('admin.backup.lra_backup_error') ?>');
            });
        });
    }

    // ── LRA: Restore-Upload-Formular (Tab 2) ───────────────────────────────
    // Nur Datei-Upload + Validierung – schnell, kein LRA-Overlay nötig.
    // Submit-Button wird trotzdem deaktiviert um Doppelklick zu verhindern.
    var restoreForm = document.querySelector('#tab-restore form');
    if (restoreForm) {
        var restoreBtn = restoreForm.querySelector('[type="submit"]');
        restoreForm.addEventListener('submit', function () {
            if (restoreBtn) {
                restoreBtn.disabled = true;
                restoreBtn.innerHTML = '<span class="lra-btn-spinner" aria-hidden="true"></span><?= __('admin.common.uploading') ?>';
            }
        });
    }

    // ── LRA: Update-Upload-Formular (Tab 3) ────────────────────────────────
    var updateForm = document.querySelector('#tab-update form');
    if (updateForm) {
        var updateBtn = updateForm.querySelector('[type="submit"]');
        updateForm.addEventListener('submit', function () {
            if (updateBtn) {
                updateBtn.disabled = true;
                updateBtn.innerHTML = '<span class="lra-btn-spinner" aria-hidden="true"></span><?= __('admin.common.uploading') ?>';
            }
        });
    }

    // ── FTP Backup (Tab 4) ──────────────────────────────────────────────────
    var ftpForm       = document.getElementById('ftpBackupForm');
    var ftpTestBtn    = document.getElementById('ftpTestBtn');
    var ftpBackupBtn  = document.getElementById('ftpBackupBtn');
    var ftpTestResult = document.getElementById('ftpTestResult');

    if (ftpTestBtn) {
        ftpTestBtn.addEventListener('click', function () {
            if (!ftpForm) return;

            ftpTestBtn.disabled = true;
            ftpTestBtn.innerHTML = '<span class="lra-btn-spinner" aria-hidden="true"></span><?= __('admin.common.processing') ?>';
            if (ftpTestResult) ftpTestResult.style.display = 'none';

            var formData = new FormData(ftpForm);

            fetch('<?= admin_url('backup/ftp/test') ?>', {
                method: 'POST',
                body: formData
            })
            .then(function (res) {
                return res.json();
            })
            .then(function (data) {
                if (ftpTestResult) {
                    ftpTestResult.textContent = data.success ? '✓ <?= __('admin.ftp_backup.test_success') ?>' : '✗ ' + (data.error || '<?= __('admin.ftp_backup.test_failed') ?>');
                    ftpTestResult.className = 'alert ' + (data.success ? 'alert-success' : 'alert-error');
                    ftpTestResult.style.display = 'block';
                }
            })
            .catch(function (err) {
                if (ftpTestResult) {
                    ftpTestResult.textContent = '✗ <?= __('admin.ftp_backup.test_error') ?>';
                    ftpTestResult.className = 'alert alert-error';
                    ftpTestResult.style.display = 'block';
                }
            })
            .finally(function () {
                ftpTestBtn.disabled = false;
                ftpTestBtn.innerHTML = '<?= __('admin.ftp_backup.btn_test') ?>';
            });
        });
    }

    if (ftpBackupBtn) {
        ftpBackupBtn.addEventListener('click', function () {
            if (!confirm('<?= __('admin.ftp_backup.confirm_backup') ?>')) {
                return;
            }

            ftpBackupBtn.disabled = true;
            ftpBackupBtn.innerHTML = '<span class="lra-btn-spinner" aria-hidden="true"></span><?= __('admin.common.processing') ?>';
            if (ftpTestResult) ftpTestResult.style.display = 'none';

            var formData = new FormData(ftpForm);

            fetch('<?= admin_url('backup/ftp/backup') ?>', {
                method: 'POST',
                body: formData
            })
            .then(function (res) {
                return res.text();
            })
            .then(function () {
                // Backup completed, page will redirect
                // Show a brief success message
                if (ftpTestResult) {
                    ftpTestResult.textContent = '✓ <?= __('admin.ftp_backup.backup_started') ?>';
                    ftpTestResult.className = 'alert alert-success';
                    ftpTestResult.style.display = 'block';
                }
                setTimeout(function () {
                    window.location.reload();
                }, 1500);
            })
            .catch(function (err) {
                ftpBackupBtn.disabled = false;
                ftpBackupBtn.innerHTML = '<?= __('admin.ftp_backup.btn_backup') ?>';
                if (ftpTestResult) {
                    ftpTestResult.textContent = '✗ <?= __('admin.ftp_backup.backup_error') ?>';
                    ftpTestResult.className = 'alert alert-error';
                    ftpTestResult.style.display = 'block';
                }
            });
        });
    }
}());
</script>

<?php $content = ob_get_clean(); include dirname(__DIR__) . '/layouts/admin.php'; ?>
