<?php
// admin/empfaenger/import_log.php

session_start();
require_once __DIR__ . '/../../includes/init.php';
require_once __DIR__ . '/../../auth/AuthController.php';

$auth = new AuthController();
if (!$auth->isLoggedIn()) {
    header('Location: ' . $adminLoginPath);
    exit;
}

$db = Database::getInstance();

$listen = [];
$sqlLists = 'SELECT id, name FROM lists ORDER BY name ASC';
try {
    $list_stmt = $db->query($sqlLists);
    $listen = $list_stmt->fetchAll(PDO::FETCH_ASSOC);
    ErrorLogger::logSqlSuccess('import_log: load lists | SQL: ' . $sqlLists . ' | params: []');
} catch (Throwable $e) {
    ErrorLogger::logSqlError('import_log: load lists failed | SQL: ' . $sqlLists . ' | params: [] | error: ' . $e->getMessage());
    $listen = [];
}

$filter_list_id = $_GET['list_id'] ?? null;
$params = [];
$sql = 'SELECT il.*, l.name AS listen_name FROM import_log il LEFT JOIN lists l ON il.list_id = l.id';

if ($filter_list_id) {
    $sql .= ' WHERE il.list_id = ?';
    $params[] = $filter_list_id;
}

$sql .= ' ORDER BY il.created_at DESC LIMIT 100';
$logs = [];

try {
    $stmt = $db->prepare($sql);
    $stmt->execute($params);
    $logs = $stmt->fetchAll(PDO::FETCH_ASSOC);
    ErrorLogger::logSqlSuccess('import_log: load import entries | SQL: ' . $sql . ' | params: ' . json_encode($params, JSON_UNESCAPED_UNICODE));
} catch (Throwable $e) {
    ErrorLogger::logSqlError('import_log: load import entries failed | SQL: ' . $sql . ' | params: ' . json_encode($params, JSON_UNESCAPED_UNICODE) . ' | error: ' . $e->getMessage());
    $logs = [];
}

ob_start();
?>

<div class="container mt-4">
    <div class="page-header h2">Import-Log</div>

    <form method="get" class="row g-3 mb-3">
        <div class="col-md-4">
            <label for="list_id" class="form-label">Nach Liste filtern:</label>
            <select name="list_id" id="list_id" class="form-select">
                <option value="">Alle Listen</option>
                <?php foreach ($listen as $liste): ?>
                    <option value="<?= $liste['id'] ?>" <?= ($filter_list_id == $liste['id']) ? 'selected' : '' ?>>
                        <?= htmlspecialchars($liste['name']) ?>
                    </option>
                <?php endforeach; ?>
            </select>
        </div>
        <div class="col-md-2 align-self-end">
            <button type="submit" class="btn btn-secondary">Filtern</button>
        </div>
    </form>

    <table class="table table-bordered table-striped table-sm">
        <thead class="table-light">
            <tr>
                <th>#</th>
                <th>Datum</th>
                <th>Admin</th>
                <th>Liste</th>
                <th>Datei</th>
                <th>Importiert</th>
                <th>Duplikate</th>
                <th>Gesamt</th>
            </tr>
        </thead>
        <tbody>
            <?php if (count($logs) === 0): ?>
                <tr><td colspan="8" class="text-center">Keine Einträge gefunden.</td></tr>
            <?php else: ?>
                <?php foreach ($logs as $log): ?>
                    <tr>
                        <td><?= $log['id'] ?></td>
                        <td><?= date('d.m.Y H:i', strtotime($log['created_at'])) ?></td>
                        <td><?= htmlspecialchars($log['admin_user']) ?></td>
                        <td><?= htmlspecialchars($log['listen_name']) ?></td>
                        <td><?= htmlspecialchars($log['file_name']) ?></td>
                        <td><?= $log['imported'] ?></td>
                        <td><?= $log['duplicates'] ?></td>
                        <td><?= $log['total'] ?></td>
                    </tr>
                <?php endforeach; ?>
            <?php endif; ?>
        </tbody>
    </table>
</div>

<?php
$pageContent = ob_get_clean();
include_once __DIR__ . '/../template.php';
