<?php
/**
 * Valu-Basic — Backup (Backend)
 * Einfacher SQLite-Datei Download + Bilder-ZIP
 */
require_once 'config.php';
requireBackendAccess();

$sqlitePath = defined('SQLITE_PATH') ? SQLITE_PATH : dirname(__DIR__) . '/data/valu_basic.sqlite';

// ── SQLite Download ──────────────────────────────────────────────────────────
if (isset($_GET['action']) && $_GET['action'] === 'download_db') {
    if (!file_exists($sqlitePath)) {
        die('Datenbankdatei nicht gefunden: ' . htmlspecialchars($sqlitePath));
    }
    $filename = 'valu_basic_db_' . date('Y-m-d_H-i') . '.sqlite';
    header('Content-Type: application/octet-stream');
    header('Content-Disposition: attachment; filename="' . $filename . '"');
    header('Content-Length: ' . filesize($sqlitePath));
    header('Cache-Control: no-cache, no-store');
    header('Pragma: no-cache');
    readfile($sqlitePath);
    exit;
}

// ── Bilder-ZIP Download ──────────────────────────────────────────────────────
if (isset($_GET['action']) && $_GET['action'] === 'download_images') {
    $uploadDir = dirname(__DIR__) . '/upload/';
    if (!is_dir($uploadDir)) {
        die('Upload-Verzeichnis nicht gefunden.');
    }
    if (!class_exists('ZipArchive')) {
        die('ZipArchive nicht verfügbar auf diesem Server.');
    }

    $tmpZip = sys_get_temp_dir() . '/valu_basic_images_' . date('Y-m-d_H-i') . '.zip';
    $zip = new ZipArchive();
    if ($zip->open($tmpZip, ZipArchive::CREATE | ZipArchive::OVERWRITE) !== TRUE) {
        die('ZIP-Datei konnte nicht erstellt werden.');
    }

    $files = array_filter(scandir($uploadDir), fn($f) => $f !== '.' && $f !== '..' && is_file($uploadDir . $f));
    foreach ($files as $file) {
        $zip->addFile($uploadDir . $file, $file);
    }
    $zip->close();

    $filename = 'valu_basic_images_' . date('Y-m-d_H-i') . '.zip';
    header('Content-Type: application/zip');
    header('Content-Disposition: attachment; filename="' . $filename . '"');
    header('Content-Length: ' . filesize($tmpZip));
    header('Cache-Control: no-cache, no-store');
    readfile($tmpZip);
    unlink($tmpZip);
    exit;
}

// ── Statistiken ──────────────────────────────────────────────────────────────
$dbSize      = file_exists($sqlitePath) ? filesize($sqlitePath) : 0;
$dbSizeFmt   = $dbSize > 1048576 ? round($dbSize / 1048576, 2) . ' MB' : round($dbSize / 1024, 1) . ' KB';
$dbModified  = file_exists($sqlitePath) ? date('d.m.Y H:i', filemtime($sqlitePath)) : '—';

$uploadDir   = dirname(__DIR__) . '/upload/';
$imageFiles  = is_dir($uploadDir) ? array_filter(scandir($uploadDir), fn($f) => $f !== '.' && $f !== '..' && is_file($uploadDir . $f)) : [];
$imageCount  = count($imageFiles);
$imageSize   = 0;
foreach ($imageFiles as $f) $imageSize += filesize($uploadDir . $f);
$imageSizeFmt = $imageSize > 1048576 ? round($imageSize / 1048576, 2) . ' MB' : round($imageSize / 1024, 1) . ' KB';

try {
    $itemCount = $db->selectOne("SELECT COUNT(*) as c FROM wertsachen")['c'] ?? 0;
} catch (Exception $e) {
    $itemCount = '?';
}

$pageTitle = 'Backup';
include 'layout/header.php';
?>

<div class="backend-content">
    <div style="display:flex; align-items:center; justify-content:space-between; margin-bottom:24px; flex-wrap:wrap; gap:12px;">
        <h1 style="margin:0; font-size:1.5rem;">💾 Backup</h1>
    </div>

    <!-- Info-Box -->
    <div style="background:rgba(59,130,246,0.08); border:1.5px solid rgba(59,130,246,0.25); border-radius:12px; padding:16px 20px; margin-bottom:28px; font-size:14px; line-height:1.6; color:#1e40af;">
        <strong>ℹ️ So funktioniert das Backup in Valu-Basic:</strong><br>
        Lade die <strong>Datenbank</strong> (SQLite-Datei) und optional die <strong>Bilder</strong> herunter.
        Zum Wiederherstellen einfach die SQLite-Datei per FTP zurück in den <code>data/</code>-Ordner kopieren.
    </div>

    <!-- Statistiken -->
    <div style="display:grid; grid-template-columns:repeat(auto-fill, minmax(180px, 1fr)); gap:16px; margin-bottom:28px;">
        <div style="background:rgba(255,255,255,0.6); border:1px solid rgba(0,0,0,0.08); border-radius:12px; padding:18px; text-align:center;">
            <div style="font-size:28px; font-weight:700;"><?php echo $itemCount; ?></div>
            <div style="font-size:12px; color:#666; margin-top:4px;">Gegenstände</div>
        </div>
        <div style="background:rgba(255,255,255,0.6); border:1px solid rgba(0,0,0,0.08); border-radius:12px; padding:18px; text-align:center;">
            <div style="font-size:22px; font-weight:700;"><?php echo $dbSizeFmt; ?></div>
            <div style="font-size:12px; color:#666; margin-top:4px;">Datenbankgröße</div>
        </div>
        <div style="background:rgba(255,255,255,0.6); border:1px solid rgba(0,0,0,0.08); border-radius:12px; padding:18px; text-align:center;">
            <div style="font-size:22px; font-weight:700;"><?php echo $imageCount; ?></div>
            <div style="font-size:12px; color:#666; margin-top:4px;">Bilder (<?php echo $imageSizeFmt; ?>)</div>
        </div>
        <div style="background:rgba(255,255,255,0.6); border:1px solid rgba(0,0,0,0.08); border-radius:12px; padding:18px; text-align:center;">
            <div style="font-size:15px; font-weight:600;"><?php echo $dbModified; ?></div>
            <div style="font-size:12px; color:#666; margin-top:4px;">Letzte DB-Änderung</div>
        </div>
    </div>

    <!-- Download-Karten -->
    <div style="display:grid; grid-template-columns:repeat(auto-fill, minmax(300px, 1fr)); gap:20px;">

        <!-- Datenbank -->
        <div style="background:rgba(255,255,255,0.7); border:1px solid rgba(0,0,0,0.08); border-radius:16px; padding:28px; box-shadow:0 2px 12px rgba(0,0,0,0.06);">
            <h3 style="margin:0 0 10px; font-size:1rem;">🗄️ Datenbank</h3>
            <p style="font-size:13px; color:#666; margin:0 0 20px; line-height:1.5;">
                Alle Gegenstände, Kategorien, Orte und Einstellungen als SQLite-Datei (<code>.sqlite</code>).
            </p>
            <div style="font-size:12px; color:#888; margin-bottom:16px;">
                📦 <?php echo $dbSizeFmt; ?> &nbsp;·&nbsp; 🕐 <?php echo $dbModified; ?>
            </div>
            <a href="?action=download_db"
               style="display:inline-flex; align-items:center; gap:8px; padding:10px 20px; background:var(--accent, #3b82f6); color:#fff; border-radius:8px; text-decoration:none; font-size:14px; font-weight:600; transition:opacity 0.2s;"
               onmouseover="this.style.opacity='.85'" onmouseout="this.style.opacity='1'">
                ⬇️ Datenbank herunterladen
            </a>
        </div>

        <!-- Bilder -->
        <div style="background:rgba(255,255,255,0.7); border:1px solid rgba(0,0,0,0.08); border-radius:16px; padding:28px; box-shadow:0 2px 12px rgba(0,0,0,0.06);">
            <h3 style="margin:0 0 10px; font-size:1rem;">🖼️ Bilder</h3>
            <p style="font-size:13px; color:#666; margin:0 0 20px; line-height:1.5;">
                Alle hochgeladenen Bilder als ZIP-Archiv. Zum Wiederherstellen in den <code>upload/</code>-Ordner entpacken.
            </p>
            <div style="font-size:12px; color:#888; margin-bottom:16px;">
                📦 <?php echo $imageSizeFmt; ?> &nbsp;·&nbsp; 🖼️ <?php echo $imageCount; ?> Dateien
            </div>
            <?php if ($imageCount > 0): ?>
            <a href="?action=download_images"
               style="display:inline-flex; align-items:center; gap:8px; padding:10px 20px; background:var(--accent, #3b82f6); color:#fff; border-radius:8px; text-decoration:none; font-size:14px; font-weight:600; transition:opacity 0.2s;"
               onmouseover="this.style.opacity='.85'" onmouseout="this.style.opacity='1'">
                ⬇️ Bilder herunterladen
            </a>
            <?php else: ?>
            <span style="font-size:13px; color:#aaa;">Noch keine Bilder vorhanden.</span>
            <?php endif; ?>
        </div>

    </div>

    <!-- Wiederherstellung -->
    <div style="margin-top:28px; background:rgba(255,255,255,0.5); border:1px solid rgba(0,0,0,0.08); border-radius:12px; padding:20px;">
        <h3 style="margin:0 0 12px; font-size:0.95rem;">♻️ Wiederherstellung</h3>
        <ol style="font-size:13px; color:#555; margin:0; padding-left:20px; line-height:2;">
            <li>Backup-Datei (<code>.sqlite</code>) per FTP in den <code>data/</code>-Ordner hochladen</li>
            <li>Vorhandene <code>valu_basic.sqlite</code> dabei überschreiben</li>
            <li>Bilder-ZIP in den <code>upload/</code>-Ordner entpacken (bei Bedarf)</li>
            <li>Fertig — keine weiteren Schritte nötig</li>
        </ol>
    </div>

</div>

<?php include 'layout/footer.php'; ?>
