<?php
/**
 * Audit Log - Übersicht gelöschter Termine
 */

session_start();
require_once '../config/database.php';

// Check if user is logged in
if (!isset($_SESSION['admin_logged_in']) || !$_SESSION['admin_logged_in']) {
    header('Location: login.php');
    exit;
}

$db = new Database();
$conn = $db->getConnection();

// Get filter parameters
$date_from = $_GET['date_from'] ?? date('Y-m-01'); // First day of current month
$date_to = $_GET['date_to'] ?? date('Y-m-d');
$user_filter = $_GET['user'] ?? '';
$search = $_GET['search'] ?? '';

// Check if audit table exists
$table_check = $conn->query("SHOW TABLES LIKE 'deleted_appointments_audit'");
if ($table_check->rowCount() == 0) {
    // Table doesn't exist, redirect to setup
    header('Location: ../setup_audit_tables.php');
    exit;
}

// Build query
$where_conditions = ["deleted_at BETWEEN ? AND ?"];
$params = [$date_from . ' 00:00:00', $date_to . ' 23:59:59'];

if (!empty($user_filter)) {
    $where_conditions[] = "deleted_by_username = ?";
    $params[] = $user_filter;
}

if (!empty($search)) {
    $where_conditions[] = "(customer_name LIKE ? OR license_plate LIKE ? OR storage_number LIKE ?)";
    $search_param = "%$search%";
    $params[] = $search_param;
    $params[] = $search_param;
    $params[] = $search_param;
}

$where_clause = implode(' AND ', $where_conditions);

// Get deleted appointments
$sql = "
    SELECT * FROM deleted_appointments_audit 
    WHERE $where_clause 
    ORDER BY deleted_at DESC
    LIMIT 100
";

$stmt = $conn->prepare($sql);
$stmt->execute($params);
$deleted_appointments = $stmt->fetchAll();

// Get unique users for filter
$user_stmt = $conn->prepare("SELECT DISTINCT deleted_by_username FROM deleted_appointments_audit ORDER BY deleted_by_username");
$user_stmt->execute();
$users = $user_stmt->fetchAll(PDO::FETCH_COLUMN);

// Get statistics
$stats_sql = "
    SELECT 
        COUNT(*) as total_deleted,
        COUNT(CASE WHEN tire_cancelled = 1 THEN 1 END) as tire_cancelled_count,
        COUNT(DISTINCT deleted_by_username) as unique_users
    FROM deleted_appointments_audit 
    WHERE $where_clause
";

$stats_stmt = $conn->prepare($stats_sql);
$stats_stmt->execute($params);
$stats = $stats_stmt->fetch();
?>

<!DOCTYPE html>
<html lang="de">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Audit Log - Gelöschte Termine</title>
    <link rel="stylesheet" href="../assets/css/style.css">
    <link rel="stylesheet" href="../assets/css/volvo-theme.css">
    <link rel="stylesheet" href="assets/css/admin.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
    <style>
        .audit-container {
            max-width: 1400px;
            margin: 0 auto;
            padding: 2rem;
        }
        
        .audit-header {
            background: linear-gradient(135deg, #1e3a8a 0%, #3b82f6 100%);
            color: white;
            padding: 2rem;
            border-radius: 12px;
            margin-bottom: 2rem;
            box-shadow: 0 8px 25px rgba(0, 0, 0, 0.15);
        }
        
        .audit-title {
            font-size: 2rem;
            font-weight: 700;
            margin: 0 0 0.5rem 0;
            display: flex;
            align-items: center;
            gap: 1rem;
        }
        
        .audit-subtitle {
            font-size: 1.1rem;
            opacity: 0.9;
            margin: 0;
        }
        
        .stats-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 1rem;
            margin-bottom: 2rem;
        }
        
        .stat-card {
            background: white;
            padding: 1.5rem;
            border-radius: 8px;
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
            text-align: center;
        }
        
        .stat-number {
            font-size: 2rem;
            font-weight: 700;
            color: #1e3a8a;
            margin-bottom: 0.5rem;
        }
        
        .stat-label {
            color: #6b7280;
            font-size: 0.9rem;
            text-transform: uppercase;
            letter-spacing: 0.5px;
        }
        
        .filters {
            background: white;
            padding: 1.5rem;
            border-radius: 8px;
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
            margin-bottom: 2rem;
        }
        
        .filter-row {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 1rem;
            align-items: end;
        }
        
        .filter-group {
            display: flex;
            flex-direction: column;
        }
        
        .filter-group label {
            font-weight: 500;
            color: #374151;
            margin-bottom: 0.5rem;
        }
        
        .filter-group input,
        .filter-group select {
            padding: 0.75rem;
            border: 1px solid #d1d5db;
            border-radius: 6px;
            font-size: 0.9rem;
        }
        
        .audit-table {
            background: white;
            border-radius: 8px;
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
            overflow: hidden;
        }
        
        .table-header {
            background: #f8fafc;
            padding: 1rem 1.5rem;
            border-bottom: 1px solid #e5e7eb;
        }
        
        .table-title {
            font-size: 1.2rem;
            font-weight: 600;
            color: #374151;
            margin: 0;
        }
        
        .audit-table table {
            width: 100%;
            border-collapse: collapse;
        }
        
        .audit-table th {
            background: #f1f5f9;
            padding: 1rem;
            text-align: left;
            font-weight: 600;
            color: #374151;
            border-bottom: 1px solid #e5e7eb;
        }
        
        .audit-table td {
            padding: 1rem;
            border-bottom: 1px solid #f3f4f6;
            vertical-align: top;
        }
        
        .audit-table tr:hover {
            background: #f8fafc;
        }
        
        .customer-info {
            font-weight: 600;
            color: #1e3a8a;
        }
        
        .license-plate {
            background: #1e3a8a;
            color: white;
            padding: 0.25rem 0.5rem;
            border-radius: 4px;
            font-size: 0.8rem;
            font-weight: 600;
        }
        
        .deletion-info {
            font-size: 0.9rem;
            color: #6b7280;
        }
        
        .deletion-reason {
            max-width: 200px;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
        }
        
        .tire-status {
            display: inline-flex;
            align-items: center;
            gap: 0.25rem;
            padding: 0.25rem 0.5rem;
            border-radius: 4px;
            font-size: 0.8rem;
            font-weight: 500;
        }
        
        .tire-status.cancelled {
            background: #dcfce7;
            color: #166534;
        }
        
        .tire-status.not-cancelled {
            background: #fef3c7;
            color: #92400e;
        }
        
        .status-badge {
            padding: 0.25rem 0.5rem;
            border-radius: 4px;
            font-size: 0.8rem;
            font-weight: 500;
        }
        
        .status-pending {
            background: #fef3c7;
            color: #92400e;
        }
        
        .status-approved {
            background: #dcfce7;
            color: #166534;
        }
        
        .status-booked {
            background: #dbeafe;
            color: #1e40af;
        }
        
        .no-data {
            text-align: center;
            padding: 3rem;
            color: #6b7280;
        }
        
        .no-data i {
            font-size: 3rem;
            margin-bottom: 1rem;
            opacity: 0.5;
        }
        
        .btn {
            display: inline-flex;
            align-items: center;
            gap: 0.5rem;
            padding: 0.75rem 1.5rem;
            border: none;
            border-radius: 6px;
            font-weight: 500;
            text-decoration: none;
            cursor: pointer;
            transition: all 0.2s ease;
        }
        
        .btn-primary {
            background: #1e3a8a;
            color: white;
        }
        
        .btn-primary:hover {
            background: #1e40af;
        }
        
        .btn-secondary {
            background: #6b7280;
            color: white;
        }
        
        .btn-secondary:hover {
            background: #4b5563;
        }
        
        @media (max-width: 768px) {
            .audit-container {
                padding: 1rem;
            }
            
            .filter-row {
                grid-template-columns: 1fr;
            }
            
            .stats-grid {
                grid-template-columns: 1fr;
            }
            
            .audit-table {
                overflow-x: auto;
            }
            
            .audit-table table {
                min-width: 800px;
            }
        }
    </style>
</head>
<body>
    <div class="audit-container">
        <!-- Header -->
        <div class="audit-header">
            <h1 class="audit-title">
                <i class="fas fa-history"></i>
                Audit Log - Gelöschte Termine
            </h1>
            <p class="audit-subtitle">Vollständige Nachverfolgung aller gelöschten Termine und Reifen-Stornierungen</p>
        </div>
        
        <!-- Statistics -->
        <div class="stats-grid">
            <div class="stat-card">
                <div class="stat-number"><?php echo $stats['total_deleted']; ?></div>
                <div class="stat-label">Gelöschte Termine</div>
            </div>
            <div class="stat-card">
                <div class="stat-number"><?php echo $stats['tire_cancelled_count']; ?></div>
                <div class="stat-label">Reifen storniert</div>
            </div>
            <div class="stat-card">
                <div class="stat-number"><?php echo $stats['unique_users']; ?></div>
                <div class="stat-label">Aktive Benutzer</div>
            </div>
        </div>
        
        <!-- Filters -->
        <div class="filters">
            <form method="GET" class="filter-form">
                <div class="filter-row">
                    <div class="filter-group">
                        <label for="date_from">Von Datum:</label>
                        <input type="date" id="date_from" name="date_from" value="<?php echo htmlspecialchars($date_from); ?>">
                    </div>
                    <div class="filter-group">
                        <label for="date_to">Bis Datum:</label>
                        <input type="date" id="date_to" name="date_to" value="<?php echo htmlspecialchars($date_to); ?>">
                    </div>
                    <div class="filter-group">
                        <label for="user">Benutzer:</label>
                        <select id="user" name="user">
                            <option value="">Alle Benutzer</option>
                            <?php foreach ($users as $user): ?>
                                <option value="<?php echo htmlspecialchars($user); ?>" <?php echo $user_filter === $user ? 'selected' : ''; ?>>
                                    <?php echo htmlspecialchars($user); ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="filter-group">
                        <label for="search">Suche:</label>
                        <input type="text" id="search" name="search" value="<?php echo htmlspecialchars($search); ?>" placeholder="Kunde, Kennzeichen, Einlagerungsnummer">
                    </div>
                    <div class="filter-group">
                        <button type="submit" class="btn btn-primary">
                            <i class="fas fa-search"></i>
                            Filtern
                        </button>
                        <a href="audit_log.php" class="btn btn-secondary">
                            <i class="fas fa-times"></i>
                            Zurücksetzen
                        </a>
                    </div>
                </div>
            </form>
        </div>
        
        <!-- Audit Table -->
        <div class="audit-table">
            <div class="table-header">
                <h2 class="table-title">Gelöschte Termine (<?php echo count($deleted_appointments); ?> Einträge)</h2>
            </div>
            
            <?php if (empty($deleted_appointments)): ?>
                <div class="no-data">
                    <i class="fas fa-inbox"></i>
                    <h3>Keine gelöschten Termine gefunden</h3>
                    <p>Für den gewählten Zeitraum wurden keine gelöschten Termine gefunden.</p>
                </div>
            <?php else: ?>
                <table>
                    <thead>
                        <tr>
                            <th>Kunde</th>
                            <th>Event</th>
                            <th>Datum/Zeit</th>
                            <th>Einlagerung</th>
                            <th>Reifen-Status</th>
                            <th>Gelöscht von</th>
                            <th>Grund</th>
                            <th>Zeitstempel</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($deleted_appointments as $appointment): ?>
                            <tr>
                                <td>
                                    <div class="customer-info"><?php echo htmlspecialchars($appointment['customer_name']); ?></div>
                                    <div class="license-plate"><?php echo htmlspecialchars($appointment['license_plate']); ?></div>
                                </td>
                                <td><?php echo htmlspecialchars($appointment['event_name']); ?></td>
                                <td>
                                    <div><?php echo date('d.m.Y', strtotime($appointment['slot_date'])); ?></div>
                                    <div class="deletion-info"><?php echo date('H:i', strtotime($appointment['slot_time'])); ?></div>
                                </td>
                                <td>
                                    <?php if ($appointment['storage_number']): ?>
                                        <div><?php echo htmlspecialchars($appointment['storage_number']); ?></div>
                                        <?php if ($appointment['tire_order_date']): ?>
                                            <div class="deletion-info">Bestellt: <?php echo date('d.m.Y H:i', strtotime($appointment['tire_order_date'])); ?></div>
                                        <?php endif; ?>
                                    <?php else: ?>
                                        <span class="deletion-info">-</span>
                                    <?php endif; ?>
                                </td>
                                <td>
                                    <?php if ($appointment['storage_number'] && $appointment['tire_order_date']): ?>
                                        <span class="tire-status <?php echo $appointment['tire_cancelled'] ? 'cancelled' : 'not-cancelled'; ?>">
                                            <i class="fas fa-tire"></i>
                                            <?php echo $appointment['tire_cancelled'] ? 'Storniert' : 'Nicht storniert'; ?>
                                        </span>
                                    <?php else: ?>
                                        <span class="deletion-info">-</span>
                                    <?php endif; ?>
                                </td>
                                <td>
                                    <div><?php echo htmlspecialchars($appointment['deleted_by_username']); ?></div>
                                    <div class="deletion-info">ID: <?php echo $appointment['deleted_by_user_id']; ?></div>
                                </td>
                                <td>
                                    <div class="deletion-reason" title="<?php echo htmlspecialchars($appointment['deletion_reason']); ?>">
                                        <?php echo htmlspecialchars($appointment['deletion_reason'] ?: '-'); ?>
                                    </div>
                                </td>
                                <td>
                                    <div><?php echo date('d.m.Y', strtotime($appointment['deleted_at'])); ?></div>
                                    <div class="deletion-info"><?php echo date('H:i:s', strtotime($appointment['deleted_at'])); ?></div>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            <?php endif; ?>
        </div>
        
        <!-- Navigation -->
        <div style="margin-top: 2rem; text-align: center;">
            <a href="appointments.php" class="btn btn-primary">
                <i class="fas fa-arrow-left"></i>
                Zurück zu Terminen
            </a>
        </div>
    </div>
</body>
</html>
