<?php
header('Content-Type: text/html; charset=utf-8');
error_reporting(0);
$path="../../";include("../../map.php");
// JSON dosyasındaki log verilerini al
function getLogs($date = null) {
    $logDir = findDirectoryPath("deppo").'/logs';
    $logFiles = glob($logDir . "/log_*.json");
    $logs = [];
    foreach ($logFiles as $logFile) {
        $fileData = json_decode(file_get_contents($logFile), true);
        foreach ($fileData as $log) {
            if ($date === null || strpos($log['timestamp'], $date) === 0) {
                $logs[] = $log;
            }
        }
    }
    usort($logs, function($a, $b) {
        return strtotime($b['timestamp']) - strtotime($a['timestamp']); // Yeni tarih önce
    });
    return $logs;
}
// Logları temizle
function clearLogs() {
    $logDir = findDirectoryPath("deppo").'/logs';  // Log dosyasının bulunduğu dizin
    $logFiles = glob($logDir . "/log_*.json");
    
    foreach ($logFiles as $logFile) {
        unlink($logFile);  // Her log dosyasını sil
    }
}
// Tarih filtrelemesi varsa, seçilen tarih verisini al
$dateFilter = isset($_GET['date']) ? $_GET['date'] : null;
$logs = getLogs($dateFilter);
// Log Temizle isteği
if (isset($_GET['clearLogs'])) {
    clearLogs();
    echo json_encode(["status" => "success", "message" => "Loglar temizlendi."]);
    exit;
}
// Log İndir isteği
if (isset($_GET['downloadLogs'])) {
    $logs = getLogs();  // Tüm logları al
    $filename = 'logs_' . date('Y-m-d_H-i-s') . '.json';
    header('Content-Disposition: attachment; filename="' . $filename . '"');
    header('Content-Type: application/json');
    echo json_encode($logs);
    exit;
}
?>
<!DOCTYPE html>
<html lang="tr">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Log Viewer</title>
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css">
	<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
	<link rel="stylesheet" type="text/css" href="//cdn.datatables.net/1.10.12/css/jquery.dataTables.min.css" />
	<script src="//cdn.datatables.net/1.10.12/js/jquery.dataTables.min.js"></script>
</head>
<body>
<div class="mt-4">
  
    <!-- Tarih aralığına göre filtreleme formu ve arama ikonu -->
    <form id="filterForm" class="mb-4 d-flex justify-content-between">
        <div>
            <label for="date" class="mr-2">Tarih Seçin:</label>
            <input type="date" name="date" id="date" class="form-control d-inline-block w-auto" value="<?= $dateFilter ?>">
        </div>
        <div style="display:none">
            <label for="search" class="mr-2">Kelime Ara:</label>
            <input type="text" name="search" id="search" class="form-control d-inline-block w-auto" placeholder="Kelime ara...">
        </div>
        <div>
            <button type="submit" class="btn btn-primary ml-2">Filtrele</button>
            <button type="button" id="downloadBtn" class="btn btn-success ml-2">Logları İndir</button>
            <button type="button" id="clearLogsBtn" class="btn btn-danger ml-2">Logları Temizle</button>
        </div>
    </form>
    <!-- Logların listelendiği tablo -->
    <table id="logsTable" class="table table-striped">
        <thead>
            <tr>
                <th scope="col">Kullanıcı</th>
                <th scope="col">IP Adresi</th>
                <th scope="col">İşlem</th>
                <th scope="col">Bilgi</th>
                <th scope="col">Zaman</th>
            </tr>
        </thead>
        <tbody>
            <?php foreach ($logs as $log): ?>
                <tr class="bg-<?= $log['action_color'] ?> text-white">
                    <td><?= $log['user'] ?> #<?= $log['user_id'] ?></td>
                    <td><?= $log['ip'] ?></td>
                    <td><?= ihb($log['action']) ?></td>
                    <td><?= $log['additional_info'] ?></td>
                    <td><?= $log['timestamp'] ?></td>
                </tr>
            <?php endforeach; ?>
        </tbody>
    </table>
</div>
<script>
$(document).ready(function () {
    // DataTable'ı başlat
    var table = $('#logsTable').DataTable({
        "paging": true,
        "searching": true,
        "info": true,
        "pageLength": 10  // Sayfa başına 10 log göster
    });
    // Filtreleme formunu gönderme
    $('#filterForm').submit(function(event) {
        event.preventDefault();
        var date = $('#date').val();
        var search = $('#search').val();
        
        // Ajax isteğiyle filtreleme yap
        $.ajax({
            url: 'logs.php',
            type: 'GET',
            data: {date: date, search: search},
            success: function(response) {
                // Yeni logları yerel olarak al
                var newLogs = $(response).find('tbody').html();
                $('#logsTable tbody').html(newLogs);  // Tabloyu güncelle
                table.destroy();
                table = $('#logsTable').DataTable({
                    "paging": true,
                    "searching": true,
                    "info": true,
                    "pageLength": 10
                });
            }
        });
    });
    // Kelime arama işlevi
    $('#search').on('input', function() {
        var searchValue = $(this).val();
        table.search(searchValue).draw();  // DataTable üzerinde arama yap
    });
    // Logları indir
    $('#downloadBtn').click(function() {
        window.location.href = 'logs.php?downloadLogs=true';  // Logları indir
    });
    // Logları temizle
    $('#clearLogsBtn').click(function() {
        $.ajax({
            url: 'logs.php',
            type: 'GET',
            data: {clearLogs: true},
            success: function(response) {
                alert('Loglar temizlendi!');
                location.reload();  // Sayfayı yenile
            }
        });
    });
});
</script>
</body>
</html>