<?php
/**
 * Bild-Cache Verwaltung
 * Zeigt Cache-Statistiken und ermöglicht Verwaltung
 */

require_once __DIR__ . '/image_cache_manager.php';

$imageCache = new ImageCacheManager();

// Aktionen verarbeiten
if (isset($_GET['action'])) {
    switch ($_GET['action']) {
        case 'cleanup':
            $deleted = $imageCache->cleanupOldCache(30); // 30 Tage
            $message = "✅ $deleted alte Bilder gelöscht";
            break;
            
        case 'clear_all':
            // Lösche alle Bilder
            require_once __DIR__ . '/../config/database.php';
            $db = new Database();
            $conn = $db->getConnection();
            
            // Hole alle Dateinamen
            $stmt = $conn->query("SELECT filename FROM cached_images");
            $files = $stmt->fetchAll(PDO::FETCH_COLUMN);
            
            $deleted = 0;
            foreach ($files as $filename) {
                $filepath = __DIR__ . '/../cache/images/' . $filename;
                if (file_exists($filepath)) {
                    unlink($filepath);
                    $deleted++;
                }
            }
            
            // Lösche Datenbank-Einträge
            $conn->exec("DELETE FROM cached_images");
            
            $message = "✅ Alle $deleted Bilder gelöscht";
            break;
            
        case 'delete_single':
            if (isset($_GET['lgfoto_id'])) {
                $lgfotoId = $_GET['lgfoto_id'];
                $imageCache->deleteCachedImage($lgfotoId);
                $message = "✅ Bild LGFOTO_ID $lgfotoId gelöscht";
            }
            break;
    }
}

// Hole Cache-Statistiken
$stats = $imageCache->getCacheStats();

// Hole aktuelle Bilder
require_once __DIR__ . '/../config/database.php';
$db = new Database();
$conn = $db->getConnection();

$stmt = $conn->query("
    SELECT ci.*, a.name as autohaus_name 
    FROM cached_images ci 
    LEFT JOIN appointments ap ON ci.appointment_id = ap.id 
    LEFT JOIN autohaus a ON ap.autohaus_id = a.id 
    ORDER BY ci.created_at DESC 
    LIMIT 50
");
$images = $stmt->fetchAll(PDO::FETCH_ASSOC);

?>
<!DOCTYPE html>
<html lang="de">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Bild-Cache Verwaltung</title>
    <style>
        body { font-family: Arial, sans-serif; margin: 20px; }
        .stats { background: #f8f9fa; padding: 15px; border-radius: 5px; margin-bottom: 20px; }
        .stats h3 { margin-top: 0; }
        .stats-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 15px; }
        .stat-item { background: white; padding: 10px; border-radius: 3px; border-left: 4px solid #007bff; }
        .stat-value { font-size: 24px; font-weight: bold; color: #007bff; }
        .stat-label { font-size: 12px; color: #666; }
        .actions { margin-bottom: 20px; }
        .btn { padding: 8px 16px; margin: 5px; border: none; border-radius: 3px; cursor: pointer; text-decoration: none; display: inline-block; }
        .btn-primary { background: #007bff; color: white; }
        .btn-danger { background: #dc3545; color: white; }
        .btn-warning { background: #ffc107; color: black; }
        .btn-success { background: #28a745; color: white; }
        .images-table { width: 100%; border-collapse: collapse; margin-top: 20px; }
        .images-table th, .images-table td { padding: 8px; text-align: left; border-bottom: 1px solid #ddd; }
        .images-table th { background: #f8f9fa; }
        .image-preview { width: 60px; height: 45px; object-fit: cover; border-radius: 3px; }
        .message { padding: 10px; margin: 10px 0; border-radius: 3px; }
        .message.success { background: #d4edda; color: #155724; border: 1px solid #c3e6cb; }
    </style>
</head>
<body>
    <h1>🖼️ Bild-Cache Verwaltung</h1>
    
    <?php if (isset($message)): ?>
        <div class="message success"><?= htmlspecialchars($message) ?></div>
    <?php endif; ?>
    
    <div class="stats">
        <h3>📊 Cache-Statistiken</h3>
        <div class="stats-grid">
            <div class="stat-item">
                <div class="stat-value"><?= $stats['total_images'] ?></div>
                <div class="stat-label">Gespeicherte Bilder</div>
            </div>
            <div class="stat-item">
                <div class="stat-value"><?= number_format($stats['total_size_dir'] / 1024 / 1024, 1) ?> MB</div>
                <div class="stat-label">Gesamtgröße</div>
            </div>
            <div class="stat-item">
                <div class="stat-value"><?= number_format($stats['avg_size'] / 1024, 0) ?> KB</div>
                <div class="stat-label">Durchschnittsgröße</div>
            </div>
            <div class="stat-item">
                <div class="stat-value"><?= $stats['oldest'] ? date('d.m.Y', strtotime($stats['oldest'])) : '-' ?></div>
                <div class="stat-label">Ältestes Bild</div>
            </div>
            <div class="stat-item">
                <div class="stat-value"><?= $stats['newest'] ? date('d.m.Y', strtotime($stats['newest'])) : '-' ?></div>
                <div class="stat-label">Neuestes Bild</div>
            </div>
        </div>
    </div>
    
    <div class="actions">
        <h3>🔧 Aktionen</h3>
        <a href="?action=cleanup" class="btn btn-warning" onclick="return confirm('Alte Bilder (>30 Tage) löschen?')">Alte Bilder bereinigen</a>
        <a href="?action=clear_all" class="btn btn-danger" onclick="return confirm('ALLE Bilder löschen? Diese Aktion kann nicht rückgängig gemacht werden!')">Alle Bilder löschen</a>
        <a href="test_session_renewal.php" class="btn btn-primary">Session-Erneuerung testen</a>
        <a href="test_image_proxy.php" class="btn btn-success">Image Proxy testen</a>
        <a href="../admin/appointments.php" class="btn btn-primary">Zurück zu Appointments</a>
    </div>
    
    <h3>📋 Aktuelle Bilder (letzte 50)</h3>
    <table class="images-table">
        <thead>
            <tr>
                <th>Vorschau</th>
                <th>LGFOTO_ID</th>
                <th>Autohaus</th>
                <th>Appointment ID</th>
                <th>Größe</th>
                <th>Typ</th>
                <th>Erstellt</th>
                <th>Aktionen</th>
            </tr>
        </thead>
        <tbody>
            <?php foreach ($images as $image): ?>
                <tr>
                    <td>
                        <img src="resy_image_proxy.php?lgfoto_id=<?= htmlspecialchars($image['lgfoto_id']) ?>&appointment_id=<?= $image['appointment_id'] ?>" 
                             class="image-preview" 
                             alt="Vorschau">
                    </td>
                    <td><?= htmlspecialchars($image['lgfoto_id']) ?></td>
                    <td><?= htmlspecialchars($image['autohaus_name'] ?? 'Unbekannt') ?></td>
                    <td><?= $image['appointment_id'] ?></td>
                    <td><?= number_format($image['file_size'] / 1024, 1) ?> KB</td>
                    <td><?= htmlspecialchars($image['content_type']) ?></td>
                    <td><?= date('d.m.Y H:i', strtotime($image['created_at'])) ?></td>
                    <td>
                        <a href="?action=delete_single&lgfoto_id=<?= $image['lgfoto_id'] ?>" 
                           class="btn btn-danger" 
                           onclick="return confirm('Bild LGFOTO_ID <?= $image['lgfoto_id'] ?> löschen?')"
                           style="padding: 4px 8px; font-size: 12px;">Löschen</a>
                    </td>
                </tr>
            <?php endforeach; ?>
        </tbody>
    </table>
    
    <?php if (empty($images)): ?>
        <p style="text-align: center; color: #666; margin: 40px 0;">Keine Bilder im Cache gefunden.</p>
    <?php endif; ?>
</body>
</html>
