<?php
/**
 * Backup and restore database - System Admin only
 */

require_once __DIR__ . '/../../includes/auth.php';
require_once __DIR__ . '/../../includes/audit.php';
require_once __DIR__ . '/../../includes/csrf.php';
require_once __DIR__ . '/../../includes/db-backup-export.php';

requireAuth();
requireSystemAdmin();

// Handle download request
if (isset($route_id) && $route_id === 'download') {
    require __DIR__ . '/backup-download.php';
    return;
}

$pageTitle = 'Backup & Restore';
$currentPage = 'system';

// Get existing backups
$backupDir = __DIR__ . '/../../backups';
$backups = [];
if (is_dir($backupDir)) {
    $files = glob($backupDir . '/*.sql');
    foreach ($files as $file) {
        $backups[] = [
            'name' => basename($file),
            'path' => $file,
            'size' => filesize($file),
            'modified' => filemtime($file),
        ];
    }
    usort($backups, function($a, $b) {
        return $b['modified'] - $a['modified'];
    });
}

$totalBackupSize = array_sum(array_column($backups, 'size'));

require_once __DIR__ . '/../../includes/system-ops-helpers.php';
$backupFresh = nazareth_backup_freshness_summary($backupDir);

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (!nazareth_csrf_validate()) {
        header('Location: ' . BASE_PATH . '/system/backup?toast_error=' . urlencode('Invalid security token. Refresh the page and try again.'));
        exit;
    }

    $postAction = $_POST['action'] ?? '';

    if ($postAction === 'backup') {
        try {
            if (!is_dir($backupDir)) {
                mkdir($backupDir, 0755, true);
            }

            $backupFile = $backupDir . '/backup_' . date('Y-m-d_His') . '.sql';
            if (!isset($pdo)) {
                require_once __DIR__ . '/../../config/database.php';
            }
            $dbHost = $db_host ?? '127.0.0.1';
            $dbName = $db_name ?? 'nazareth';
            $dbUser = $db_user ?? 'root';
            $dbPass = $db_pass ?? '';

            $dumpOk = false;
            $viaPhp = false;
            foreach (nazareth_mysqldump_binary_candidates() as $bin) {
                $result = nazareth_run_mysqldump($bin, $dbHost, $dbUser, $dbPass, $dbName, $backupFile);
                if ($result['ok']) {
                    $dumpOk = true;
                    break;
                }
                if (is_file($backupFile)) {
                    @unlink($backupFile);
                }
            }

            if (!$dumpOk) {
                $viaPhp = true;
                try {
                    nazareth_export_database_pdo($pdo, $backupFile);
                    $dumpOk = !nazareth_sql_dump_file_looks_invalid($backupFile);
                } catch (Throwable $e) {
                    if (is_file($backupFile)) {
                        @unlink($backupFile);
                    }
                    header('Location: ' . BASE_PATH . '/system/backup?toast_error=' . urlencode('Backup failed: ' . $e->getMessage()));
                    exit;
                }
            }

            if (!$dumpOk || !is_file($backupFile)) {
                if (is_file($backupFile)) {
                    @unlink($backupFile);
                }
                header('Location: ' . BASE_PATH . '/system/backup?toast_error=' . urlencode(
                    'Backup failed. mysqldump could not connect (try host ' . $dbHost . ' in config/database.php) or write to backups/. Check that mysqldump is installed for the web user, or use PHP export.'
                ));
                exit;
            }

            $fileSize = (int) filesize($backupFile);
            $backupFileName = basename($backupFile);
            logBackupCreated($_SESSION['user_id'], $backupFileName);
            $sizeLabel = nazareth_backup_format_bytes($fileSize);
            $toast = 'Backup created: ' . $backupFileName . ' (' . $sizeLabel . ')';
            if ($viaPhp) {
                $toast .= ' — exported via PHP (mysqldump unavailable or failed).';
            }
            header('Location: ' . BASE_PATH . '/system/backup?toast=' . urlencode($toast));
            exit;
        } catch (Exception $e) {
            header('Location: ' . BASE_PATH . '/system/backup?toast_error=' . urlencode($e->getMessage()));
            exit;
        }
    }

    if ($postAction === 'delete_backup') {
        $pwd = (string) ($_POST['confirm_password'] ?? '');
        if (!nazareth_verify_current_user_password($pdo, $pwd)) {
            header('Location: ' . BASE_PATH . '/system/backup?toast_error=' . urlencode('Incorrect password. Backup file was not deleted.'));
            exit;
        }

        $fileName = $_POST['file'] ?? '';
        if ($fileName && preg_match('/^[a-zA-Z0-9._-]+\.sql$/', $fileName)) {
            $filePath = $backupDir . '/' . $fileName;
            if (file_exists($filePath) && is_file($filePath) && unlink($filePath)) {
                header('Location: ' . BASE_PATH . '/system/backup?toast=' . urlencode('Backup deleted successfully.'));
                exit;
            }
        }
        header('Location: ' . BASE_PATH . '/system/backup?toast_error=' . urlencode('Failed to delete backup file.'));
        exit;
    }

    header('Location: ' . BASE_PATH . '/system/backup?toast_error=' . urlencode('Unknown action.'));
    exit;
}

require_once __DIR__ . '/../../includes/system-header.php';
?>

<div class="header">
    <h1>Backup & Restore</h1>
    <div class="header-actions">
        <a href="<?= BASE_PATH ?>/system" class="link-muted">← Dashboard</a>
        <a href="<?= BASE_PATH ?>/logout">Logout</a>
    </div>
</div>

<?php if ($backupFresh['level'] === 'critical'): ?>
<div class="card" style="border: 2px solid #f43f5e; background: #fff1f2; margin-bottom: 1rem;">
    <p style="margin: 0; color: #9f1239; font-weight: 600;">⚠️ Latest database backup is over 30 days old.</p>
    <p style="margin: 0.5rem 0 0; color: #64748b; font-size: 0.875rem;">Create a new backup below and store a copy off-site.</p>
</div>
<?php elseif ($backupFresh['level'] === 'warn'): ?>
<div class="card" style="border: 2px solid #fb923c; background: #fff7ed; margin-bottom: 1rem;">
    <p style="margin: 0; color: #c2410c; font-weight: 600;">Latest backup is older than 7 days.</p>
    <p style="margin: 0.5rem 0 0; color: #64748b; font-size: 0.875rem;">Consider scheduling regular exports to <code>backups/</code>.</p>
</div>
<?php elseif ($backupFresh['level'] === 'none'): ?>
<div class="card" style="border: 1px solid #cbd5e1; background: #f8fafc; margin-bottom: 1rem;">
    <p style="margin: 0; color: #475569;">No <code>*.sql</code> files found in <code>backups/</code> yet.</p>
</div>
<?php endif; ?>

<!-- Summary Stats -->
<div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 1rem; margin-bottom: 1.5rem;">
    <div class="card" style="background: #f8fafc;">
        <div style="font-size: 0.875rem; color: #64748b; margin-bottom: 0.5rem;">Total Backups</div>
        <div style="font-size: 1.75rem; font-weight: 600; color: #1e293b;"><?= count($backups) ?></div>
    </div>
    <div class="card" style="background: #f8fafc;">
        <div style="font-size: 0.875rem; color: #64748b; margin-bottom: 0.5rem;">Total Size</div>
        <div style="font-size: 1.75rem; font-weight: 600; color: #1e293b;"><?= htmlspecialchars(nazareth_backup_format_bytes((int) $totalBackupSize)) ?></div>
    </div>
    <?php if (!empty($backups)): ?>
    <div class="card" style="background: #f8fafc;">
        <div style="font-size: 0.875rem; color: #64748b; margin-bottom: 0.5rem;">Latest Backup</div>
        <div style="font-size: 0.875rem; font-weight: 500; color: #1e293b;"><?= date('Y-m-d H:i', $backups[0]['modified']) ?></div>
    </div>
    <?php endif; ?>
</div>

<div class="card">
    <h2 style="margin-top: 0; margin-bottom: 1rem;">Create Backup</h2>
    <p class="text-muted" style="margin-bottom: 1rem;">Export the database to a SQL file for backup purposes. Backups are stored in the <code>backups/</code> directory.</p>
    <form method="post" action="" onsubmit="this.querySelector('button').textContent = 'Creating...'; this.querySelector('button').disabled = true;">
        <?= nazareth_csrf_field() ?>
        <input type="hidden" name="action" value="backup">
        <button type="submit" class="btn">
            <svg width="16" height="16" fill="none" stroke="currentColor" viewBox="0 0 24 24" style="margin-right: 0.5rem; display: inline-block; vertical-align: middle;">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 16v1a3 3 0 003 3h10a3 3 0 003-3v-1m-4-4l-4 4m0 0l-4-4m4 4V4"/>
            </svg>
            Create Database Backup
        </button>
    </form>
</div>

<?php if (!empty($backups)): ?>
<div class="card">
    <h2 style="margin-top: 0; margin-bottom: 1rem;">Backup History</h2>
    <div class="table-wrap">
        <table>
            <thead>
                <tr>
                    <th>File Name</th>
                    <th style="text-align: right;">Size</th>
                    <th>Created</th>
                    <th style="text-align: center;">Actions</th>
                </tr>
            </thead>
            <tbody>
                <?php foreach ($backups as $backup): ?>
                <tr>
                    <td>
                        <div style="display: flex; align-items: center; gap: 0.5rem;">
                            <svg width="16" height="16" fill="none" stroke="currentColor" viewBox="0 0 24 24" style="color: #94a3b8;">
                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z"/>
                            </svg>
                            <span style="font-weight: 500; font-family: monospace; font-size: 0.875rem;"><?= htmlspecialchars($backup['name']) ?></span>
                        </div>
                    </td>
                    <td style="text-align: right; color: #64748b;">
                        <?php
                        $sz = (int) ($backup['size'] ?? 0);
                        echo htmlspecialchars(nazareth_backup_format_bytes($sz));
                        if (nazareth_sql_dump_file_looks_invalid($backup['path'])) {
                            echo ' <span style="color:#b45309;font-size:0.75rem;" title="This file may be an error log or empty export">⚠ suspect</span>';
                        }
                        ?>
                    </td>
                    <td style="color: #64748b;"><?= date('Y-m-d H:i:s', $backup['modified']) ?></td>
                    <td style="text-align: center;">
                        <a href="<?= BASE_PATH ?>/system/backup/download?file=<?= urlencode($backup['name']) ?>" class="btn btn-sm btn-outline">Download</a>
                        <form method="post" style="display: inline-flex; flex-wrap: wrap; align-items: center; gap: 0.35rem; max-width: 22rem; justify-content: flex-end;" onsubmit="return confirm('Delete this backup file?');">
                            <?= nazareth_csrf_field() ?>
                            <input type="hidden" name="action" value="delete_backup">
                            <input type="hidden" name="file" value="<?= htmlspecialchars($backup['name']) ?>">
                            <input type="password" name="confirm_password" required autocomplete="current-password" placeholder="Your password" style="padding: 0.25rem 0.5rem; font-size: 0.8125rem; max-width: 9rem;">
                            <button type="submit" class="btn btn-sm btn-outline-danger">Delete</button>
                        </form>
                    </td>
                </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
    </div>
</div>
<?php endif; ?>

<div class="card" style="border: 1px solid #fecaca; background: #fef2f2;">
    <h2 style="margin-top: 0; margin-bottom: 1rem; color: #991b1b;">⚠️ Restore from Backup</h2>
    <p class="text-muted" style="margin-bottom: 1rem; color: #991b1b;"><strong>Warning:</strong> Restoring will replace all current data. Use with caution!</p>
    <p class="text-muted" style="margin-bottom: 1rem;">To restore a backup, use phpMyAdmin or MySQL command line tools. This feature requires server-level access.</p>
    <div style="background: #1e293b; color: #e2e8f0; padding: 1rem; border-radius: 6px; font-family: monospace; font-size: 0.875rem; margin-top: 1rem;">
        <div style="color: #94a3b8; margin-bottom: 0.5rem;">Command line restore:</div>
        <code style="color: #e2e8f0;">mysql -u root -p nazareth &lt; backups/backup_file.sql</code>
    </div>
    <?php if (!empty($backups)): ?>
    <div style="margin-top: 1rem; padding-top: 1rem; border-top: 1px solid #fecaca;">
        <p style="font-size: 0.875rem; color: #991b1b; margin-bottom: 0.5rem;"><strong>Available backups:</strong></p>
        <ul style="margin: 0; padding-left: 1.5rem; color: #991b1b; font-size: 0.875rem;">
            <?php foreach (array_slice($backups, 0, 5) as $backup): ?>
            <li style="font-family: monospace;"><?= htmlspecialchars($backup['name']) ?></li>
            <?php endforeach; ?>
            <?php if (count($backups) > 5): ?>
            <li style="color: #64748b;">... and <?= count($backups) - 5 ?> more</li>
            <?php endif; ?>
        </ul>
    </div>
    <?php endif; ?>
</div>

<?php require_once __DIR__ . '/../../includes/system-footer.php'; ?>
