<?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;
}

// Helper: Eğer sistemde ihb fonksiyonu yoksa hata vermesin
if (!function_exists('ihb')) { function ihb($text) { return htmlspecialchars($text); } }
?>
<!DOCTYPE html>
<html lang="tr">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Sistem Log Kayıtları</title>
    
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600&family=JetBrains+Mono:wght@400;500&display=swap" rel="stylesheet">
    
    <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.4.0/css/all.min.css">
    <link rel="stylesheet" type="text/css" href="//cdn.datatables.net/1.10.12/css/jquery.dataTables.min.css" />

    <style>
        :root {
            --bg-body: #f8f9fa;
            --text-main: #343a40;
            --text-muted: #6c757d;
            --border-radius: 8px;
        }

        body {
            background-color: var(--bg-body);
            font-family: 'Inter', sans-serif;
            color: var(--text-main);
            font-size: 0.9rem;
        }

        /* Form Elemanları */
        .form-control {
            border-radius: var(--border-radius);
            border: 1px solid #dee2e6;
            height: calc(1.5em + .75rem + 2px);
            box-shadow: none !important;
        }
        .form-control:focus {
            border-color: #80bdff;
            background-color: #fff;
        }

        /* Butonlar */
        .btn {
            border-radius: var(--border-radius);
            font-weight: 500;
            padding: 0.375rem 1rem;
            box-shadow: 0 2px 4px rgba(0,0,0,0.05);
            transition: all 0.2s;
        }
        .btn:hover { transform: translateY(-1px); box-shadow: 0 4px 6px rgba(0,0,0,0.1); }
        
        .btn-primary { background-color: #3b82f6; border-color: #3b82f6; }
        .btn-primary:hover { background-color: #2563eb; border-color: #2563eb; }
        
        .btn-success { background-color: #10b981; border-color: #10b981; }
        .btn-success:hover { background-color: #059669; border-color: #059669; }
        
        .btn-danger { background-color: #ef4444; border-color: #ef4444; }
        .btn-danger:hover { background-color: #dc2626; border-color: #dc2626; }

        /* Tablo Tasarımı */
        .dataTables_wrapper {
            background: #fff;
            padding: 20px;
            border-radius: 12px;
            box-shadow: 0 4px 20px rgba(0,0,0,0.03);
            border: 1px solid rgba(0,0,0,0.05);
        }

        table.dataTable { border-collapse: separate !important; border-spacing: 0 4px !important; }
        
        table.dataTable thead th {
            border-bottom: 2px solid #f1f5f9 !important;
            color: var(--text-muted);
            font-weight: 600;
            text-transform: uppercase;
            font-size: 0.75rem;
            letter-spacing: 0.5px;
            padding: 12px 10px;
        }

        /* Modernize Edilmiş Satır Renkleri (Soft Colors) */
        .log-row td {
            border-top: 1px solid #f1f5f9;
            border-bottom: 1px solid #f1f5f9;
            vertical-align: middle;
            padding: 12px 10px;
        }
        .log-row td:first-child { border-left: 4px solid transparent; border-top-left-radius: 6px; border-bottom-left-radius: 6px; }
        .log-row td:last-child { border-top-right-radius: 6px; border-bottom-right-radius: 6px; }

        /* Renk Varyasyonları */
        .log-row-success { background-color: #ecfdf5 !important; color: #065f46; }
        .log-row-success td:first-child { border-left-color: #10b981; }
        
        .log-row-danger { background-color: #fef2f2 !important; color: #991b1b; }
        .log-row-danger td:first-child { border-left-color: #ef4444; }
        
        .log-row-warning { background-color: #fffbeb !important; color: #92400e; }
        .log-row-warning td:first-child { border-left-color: #f59e0b; }
        
        .log-row-info { background-color: #eff6ff !important; color: #1e40af; }
        .log-row-info td:first-child { border-left-color: #3b82f6; }

        .log-row-primary { background-color: #eef2ff !important; color: #3730a3; }
        .log-row-primary td:first-child { border-left-color: #6366f1; }

        /* Özel Alanlar */
        .mono-font { font-family: 'JetBrains Mono', monospace; font-size: 0.85em; letter-spacing: -0.5px; }
        .user-id-badge { background: rgba(0,0,0,0.1); padding: 2px 6px; border-radius: 4px; font-weight: bold; font-size: 0.8em; }
        
        /* Pagination */
        .dataTables_paginate .paginate_button.current {
            background: #3b82f6 !important;
            color: white !important;
            border: none !important;
            border-radius: 4px !important;
        }
    </style>
    
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
    <script src="//cdn.datatables.net/1.10.12/js/jquery.dataTables.min.js"></script>
</head>
<body>

<div class="container-fluid mt-4 px-4">
  
    <div class="card border-0 shadow-sm mb-4" style="border-radius: 12px;">
        <div class="card-body py-3">
            <form id="filterForm" class="d-flex justify-content-between align-items-center mb-0">
                <div class="d-flex align-items-center">
                    <label for="date" class="mr-2 mb-0 font-weight-bold text-muted"><i class="far fa-calendar-alt mr-1"></i> Tarih:</label>
                    <input type="date" name="date" id="date" class="form-control form-control-sm d-inline-block w-auto" value="<?= $dateFilter ?>">
                    <button type="submit" class="btn btn-primary btn-sm ml-2">
                        <i class="fas fa-filter mr-1"></i> Filtrele
                    </button>
                </div>

                <div style="display:none">
                    <label for="search" class="mr-2">Ara:</label>
                    <input type="text" name="search" id="search" class="form-control" placeholder="...">
                </div>

                <div>
                    <button type="button" id="downloadBtn" class="btn btn-success btn-sm ml-2">
                        <i class="fas fa-download mr-1"></i> İndir
                    </button>
                    <button type="button" id="clearLogsBtn" class="btn btn-danger btn-sm ml-2">
                        <i class="fas fa-trash-alt mr-1"></i> Temizle
                    </button>
                </div>
            </form>
        </div>
    </div>

    <table id="logsTable" class="table table-hover">
        <thead>
            <tr>
                <th scope="col" width="15%">Kullanıcı</th>
                <th scope="col" width="12%">IP Adresi</th>
                <th scope="col" width="15%">İşlem</th>
                <th scope="col">Bilgi / Detay</th>
                <th scope="col" width="15%" class="text-right">Zaman</th>
            </tr>
        </thead>
        <tbody>
            <?php foreach ($logs as $log): 
                // Renk sınıfını belirle (Bootstrap bg- yerine özel soft sınıflarımızı kullanıyoruz)
                $color = isset($log['action_color']) ? $log['action_color'] : 'default';
                // Eski 'text-white' sınıfını kaldırdık çünkü artık soft renkler kullanıyoruz, koyu yazı lazım.
            ?>
                <tr class="log-row log-row-<?= $color ?>">
                    <td>
                        <div class="d-flex flex-column">
                            <span class="font-weight-bold"><?= $log['user'] ?></span>
                            <?php if(isset($log['user_id'])): ?>
                                <small><span class="user-id-badge">ID: <?= $log['user_id'] ?></span></small>
                            <?php endif; ?>
                        </div>
                    </td>
                    <td>
                        <span class="mono-font"><i class="fas fa-network-wired text-muted mr-1" style="font-size:0.8em"></i> <?= $log['ip'] ?></span>
                    </td>
                    <td>
                        <span class="font-weight-bold"><?= ihb($log['action']) ?></span>
                    </td>
                    <td>
                        <?= $log['additional_info'] ?>
                    </td>
                    <td class="text-right">
                        <span class="mono-font"><?= $log['timestamp'] ?></span>
                    </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": 15, // Biraz daha fazla veri gösterelim
        "ordering": false, // PHP tarafında sıraladık
        "language": {
            "sEmptyTable":     "Kayıt bulunamadı",
            "sInfo":           "_TOTAL_ kayıttan _START_ - _END_ arası",
            "sInfoEmpty":      "Kayıt yok",
            "sInfoFiltered":   "(_MAX_ kayıt içinden)",
            "sLengthMenu":     "Sayfada _MENU_ kayıt",
            "sLoadingRecords": "Yükleniyor...",
            "sProcessing":     "İşleniyor...",
            "sSearch":         "Ara:",
            "sZeroRecords":    "Eşleşen kayıt bulunamadı",
            "oPaginate": {
                "sFirst":    "İlk",
                "sLast":     "Son",
                "sNext":     "Sonraki",
                "sPrevious": "Önceki"
            }
        },
        "dom": '<"d-flex justify-content-between align-items-center mb-3"l f>rt<"d-flex justify-content-between align-items-center mt-3"i p>'
    });

    // Filtreleme (AJAX)
    $('#filterForm').submit(function(event) {
        event.preventDefault();
        var date = $('#date').val();
        var search = $('#search').val(); // Gizli input ama mantık korundu
        
        $.ajax({
            url: window.location.href.split('?')[0], // Parametreleri temizle
            type: 'GET',
            data: {date: date, search: search},
            success: function(response) {
                var newLogs = $(response).find('tbody').html();
                table.clear().destroy();
                $('#logsTable tbody').html(newLogs);
                
                // Tabloyu yeniden başlat (Aynı ayarlarla)
                table = $('#logsTable').DataTable({
                    "paging": true, "searching": true, "info": true, "pageLength": 15, "ordering": false,
                    "language": { "sEmptyTable": "Kayıt bulunamadı", "sInfo": "_TOTAL_ kayıttan _START_ - _END_ arası", "sSearch": "Ara:", "oPaginate": { "sNext": "Sonraki", "sPrevious": "Önceki" } },
                    "dom": '<"d-flex justify-content-between align-items-center mb-3"l f>rt<"d-flex justify-content-between align-items-center mt-3"i p>'
                });
            }
        });
    });

    // Arama Kutusu Bağlantısı
    $('#search').on('input', function() {
        table.search(this.value).draw();
    });

    // İndir
    $('#downloadBtn').click(function() {
        window.location.href = '?downloadLogs=true';
    });

    // Temizle
    $('#clearLogsBtn').click(function() {
        if(confirm("DİKKAT: Tüm log kayıtları silinecek. Emin misiniz?")) {
            $.ajax({
                url: window.location.href.split('?')[0],
                type: 'GET',
                data: {clearLogs: true},
                success: function(response) {
                    alert('Loglar başarıyla temizlendi.');
                    location.reload();
                }
            });
        }
    });
});
</script>
</body>
</html>