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

// Get user info
$user_id = $_SESSION['user_id'];
$sql = "SELECT username, email, role FROM users WHERE id = $user_id";
$result = $con->query($sql);
$user = $result ? $result->fetch_assoc() : null;

// If user not found, create empty user array to prevent sidebar errors
if (!$user) {
    $user = [
        'username' => 'Unknown',
        'email' => '',
        'role' => 'user'
    ];
}

// Layout variables
$page_title = 'DMAppsESP - Cihaz Logları';
$breadcrumb_title = 'Cihaz Logları';
$current_page = 'devices';
$extra_css = '<style>
    .logs-container {
        background: white;
        border-radius: 15px;
        padding: 20px;
        margin-bottom: 20px;
        box-shadow: 0 4px 20px rgba(0,0,0,0.1);
    }
    .logs-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 20px;
        flex-wrap: wrap;
        gap: 10px;
    }
    .logs-filters {
        display: flex;
        gap: 10px;
        flex-wrap: wrap;
        align-items: center;
    }
    .logs-filters select,
    .logs-filters input {
        padding: 8px 12px;
        border: 1px solid #ddd;
        border-radius: 5px;
        font-size: 14px;
    }
    .logs-filters button {
        padding: 8px 16px;
        border: none;
        border-radius: 5px;
        cursor: pointer;
        font-size: 14px;
        transition: background-color 0.3s;
    }
    .logs-filters .btn-primary {
        background: #007bff;
        color: white;
    }
    .logs-filters .btn-primary:hover {
        background: #0056b3;
    }
    .logs-filters .btn-secondary {
        background: #6c757d;
        color: white;
    }
    .logs-filters .btn-secondary:hover {
        background: #5a6268;
    }
    .logs-filters .btn-danger {
        background: #dc3545;
        color: white;
    }
    .logs-filters .btn-danger:hover {
        background: #c82333;
    }
    .logs-stats {
        display: grid;
        grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
        gap: 15px;
        margin-bottom: 20px;
    }
    .log-stat {
        background: #f8f9fa;
        border-radius: 8px;
        padding: 15px;
        text-align: center;
        border-left: 4px solid #007bff;
    }
    .log-stat .value {
        font-size: 24px;
        font-weight: bold;
        color: #007bff;
        margin-bottom: 5px;
    }
    .log-stat .label {
        font-size: 12px;
        color: #6c757d;
    }
    .logs-table {
        max-height: 600px;
        overflow-y: auto;
        border: 1px solid #dee2e6;
        border-radius: 8px;
    }
    .logs-table table {
        margin-bottom: 0;
    }
    .logs-table th {
        background-color: #f8f9fa;
        position: sticky;
        top: 0;
        z-index: 10;
    }
    .log-item {
        font-family: monospace;
        font-size: 12px;
        padding: 8px;
        border-bottom: 1px solid #eee;
        transition: background-color 0.2s;
    }
    .log-item:hover {
        background-color: #f8f9fa;
    }
    .log-item.error {
        border-left: 4px solid #dc3545;
        background-color: #fff5f5;
    }
    .log-item.warning {
        border-left: 4px solid #ffc107;
        background-color: #fffdf5;
    }
    .log-item.info {
        border-left: 4px solid #17a2b8;
        background-color: #f0f8ff;
    }
    .log-item.debug {
        border-left: 4px solid #6c757d;
        background-color: #f8f9fa;
    }
    .log-level {
        display: inline-block;
        padding: 2px 6px;
        border-radius: 3px;
        font-size: 10px;
        font-weight: bold;
        margin-right: 8px;
        min-width: 50px;
        text-align: center;
    }
    .log-level.error {
        background-color: #dc3545;
        color: white;
    }
    .log-level.warning {
        background-color: #ffc107;
        color: #212529;
    }
    .log-level.info {
        background-color: #17a2b8;
        color: white;
    }
    .log-level.debug {
        background-color: #6c757d;
        color: white;
    }
    .log-timestamp {
        color: #6c757d;
        margin-right: 10px;
        font-size: 11px;
        white-space: nowrap;
    }
    .log-message {
        color: #333;
        word-break: break-word;
    }
    .log-details {
        color: #6c757d;
        font-size: 11px;
        margin-top: 2px;
    }
    .pagination {
        display: flex;
        justify-content: center;
        margin-top: 20px;
        gap: 5px;
    }
    .pagination button {
        padding: 8px 12px;
        border: 1px solid #ddd;
        background: white;
        cursor: pointer;
        border-radius: 3px;
        transition: background-color 0.2s;
    }
    .pagination button:hover {
        background: #f8f9fa;
    }
    .pagination button.active {
        background: #007bff;
        color: white;
        border-color: #007bff;
    }
    .pagination button:disabled {
        background: #f8f9fa;
        color: #6c757d;
        cursor: not-allowed;
    }
    .log-search {
        position: relative;
        margin-bottom: 15px;
    }
    .log-search input {
        padding-left: 35px;
        width: 300px;
    }
    .log-search .search-icon {
        position: absolute;
        left: 10px;
        top: 50%;
        transform: translateY(-50%);
        color: #6c757d;
    }
    .auto-refresh {
        display: flex;
        align-items: center;
        gap: 10px;
    }
    .auto-refresh input[type="checkbox"] {
        margin-right: 5px;
    }
    .refresh-indicator {
        display: inline-block;
        width: 12px;
        height: 12px;
        border-radius: 50%;
        background-color: #28a745;
        margin-left: 5px;
        animation: pulse 2s infinite;
    }
    @keyframes pulse {
        0% { opacity: 1; }
        50% { opacity: 0.5; }
        100% { opacity: 1; }
    }
    .log-export {
        display: flex;
        gap: 5px;
    }
    .log-export button {
        padding: 6px 12px;
        font-size: 12px;
    }
</style>';

$extra_js = '<script>
let currentPage = 1;
let totalPages = 1;
let autoRefreshInterval = null;
let currentFilters = {
    device_id: "",
    level: "",
    date_from: "",
    date_to: "",
    search: ""
};

// Sayfa yüklendiğinde başlat
document.addEventListener("DOMContentLoaded", function() {
    loadDevices();
    loadLogs();
    
    // Filtre değişiminde logları yenile
    document.getElementById("applyFilters").addEventListener("click", applyFilters);
    document.getElementById("clearFilters").addEventListener("click", clearFilters);
    document.getElementById("refreshLogs").addEventListener("click", loadLogs);
    document.getElementById("exportLogs").addEventListener("click", exportLogs);
    
    // Otomatik yenileme
    document.getElementById("autoRefresh").addEventListener("change", toggleAutoRefresh);
    
    // Arama
    document.getElementById("searchInput").addEventListener("keyup", function(e) {
        if (e.key === "Enter") {
            applyFilters();
        }
    });
});

function loadDevices() {
    fetch("api/devices.php?action=list")
        .then(response => response.json())
        .then(data => {
            const select = document.getElementById("deviceFilter");
            select.innerHTML = "<option value=\"\">Tüm Cihazlar</option>";
            
            if (data.devices) {
                data.devices.forEach(device => {
                    select.innerHTML += `<option value="${device.id}">${device.name} (${device.device_id})</option>`;
                });
            }
        });
}

function applyFilters() {
    currentFilters = {
        device_id: document.getElementById("deviceFilter").value,
        level: document.getElementById("levelFilter").value,
        date_from: document.getElementById("dateFrom").value,
        date_to: document.getElementById("dateTo").value,
        search: document.getElementById("searchInput").value
    };
    
    currentPage = 1;
    loadLogs();
}

function clearFilters() {
    document.getElementById("deviceFilter").value = "";
    document.getElementById("levelFilter").value = "";
    document.getElementById("dateFrom").value = "";
    document.getElementById("dateTo").value = "";
    document.getElementById("searchInput").value = "";
    
    applyFilters();
}

function loadLogs() {
    const params = new URLSearchParams({
        page: currentPage,
        device_id: currentFilters.device_id,
        level: currentFilters.level,
        date_from: currentFilters.date_from,
        date_to: currentFilters.date_to,
        search: currentFilters.search
    });
    
    fetch(`api/device_logs.php?action=list&${params}`)
        .then(response => response.json())
        .then(data => {
            updateLogsTable(data.logs);
            updateStats(data.stats);
            updatePagination(data.pagination);
        })
        .catch(error => {
            console.error("Loglar yüklenemedi:", error);
        });
}

function updateLogsTable(logs) {
    const container = document.getElementById("logsTable");
    let html = "";
    
    if (logs && logs.length > 0) {
        logs.forEach(log => {
            const levelClass = log.level.toLowerCase();
            const levelLabel = getLevelLabel(log.level);
            
            html += `<div class="log-item ${levelClass}">`;
            html += `<span class="log-level ${levelClass}">${levelLabel}</span>`;
            html += `<span class="log-timestamp">${formatTimestamp(log.created_at)}</span>`;
            html += `<span class="log-message">${escapeHtml(log.message)}</span>`;
            
            if (log.device_name) {
                html += `<div class="log-details">Cihaz: ${log.device_name} (${log.device_id})</div>`;
            }
            
            if (log.user_name) {
                html += `<div class="log-details">Kullanıcı: ${log.user_name}</div>`;
            }
            
            html += `</div>`;
        });
    } else {
        html = "<div class=\"text-center text-muted p-4\">Log bulunamadı.</div>";
    }
    
    container.innerHTML = html;
}

function updateStats(stats) {
    document.getElementById("totalLogs").textContent = stats.total || 0;
    document.getElementById("errorLogs").textContent = stats.error || 0;
    document.getElementById("warningLogs").textContent = stats.warning || 0;
    document.getElementById("infoLogs").textContent = stats.info || 0;
}

function updatePagination(pagination) {
    currentPage = pagination.current_page;
    totalPages = pagination.total_pages;
    
    const container = document.getElementById("pagination");
    let html = "";
    
    // Önceki butonu
    html += `<button onclick="changePage(${currentPage - 1})" ${currentPage <= 1 ? "disabled" : ""}>Önceki</button>`;
    
    // Sayfa numaraları
    const startPage = Math.max(1, currentPage - 2);
    const endPage = Math.min(totalPages, currentPage + 2);
    
    for (let i = startPage; i <= endPage; i++) {
        const activeClass = i === currentPage ? "active" : "";
        html += `<button onclick="changePage(${i})" class="${activeClass}">${i}</button>`;
    }
    
    // Sonraki butonu
    html += `<button onclick="changePage(${currentPage + 1})" ${currentPage >= totalPages ? "disabled" : ""}>Sonraki</button>`;
    
    container.innerHTML = html;
}

function changePage(page) {
    if (page < 1 || page > totalPages) return;
    currentPage = page;
    loadLogs();
}

function toggleAutoRefresh() {
    const checkbox = document.getElementById("autoRefresh");
    const indicator = document.getElementById("refreshIndicator");
    
    if (checkbox.checked) {
        // Otomatik yenilemeyi başlat
        autoRefreshInterval = setInterval(loadLogs, 5000);
        indicator.style.display = "inline-block";
    } else {
        // Otomatik yenilemeyi durdur
        if (autoRefreshInterval) {
            clearInterval(autoRefreshInterval);
            autoRefreshInterval = null;
        }
        indicator.style.display = "none";
    }
}

function exportLogs() {
    const format = document.getElementById("exportFormat").value;
    const params = new URLSearchParams({
        device_id: currentFilters.device_id,
        level: currentFilters.level,
        date_from: currentFilters.date_from,
        date_to: currentFilters.date_to,
        search: currentFilters.search,
        format: format
    });
    
    const url = `api/device_logs.php?action=export&${params}`;
    window.open(url, "_blank");
}

function getLevelLabel(level) {
    const labels = {
        "ERROR": "HATA",
        "WARNING": "UYARI",
        "INFO": "BİLGİ",
        "DEBUG": "DEBUG"
    };
    return labels[level] || level;
}

function formatTimestamp(timestamp) {
    const date = new Date(timestamp);
    return date.toLocaleString("tr-TR", {
        year: "numeric",
        month: "2-digit",
        day: "2-digit",
        hour: "2-digit",
        minute: "2-digit",
        second: "2-digit"
    });
}

function escapeHtml(text) {
    const div = document.createElement("div");
    div.textContent = text;
    return div.innerHTML;
}

// Klavye kısayolları
document.addEventListener("keydown", function(e) {
    if (e.ctrlKey || e.metaKey) {
        switch(e.key) {
            case "r":
                e.preventDefault();
                loadLogs();
                break;
            case "f":
                e.preventDefault();
                document.getElementById("searchInput").focus();
                break;
            case "e":
                e.preventDefault();
                exportLogs();
                break;
        }
    }
});
</script>';

require_once 'layouts/header.php';
?>

<div class="logs-container">
    <div class="logs-header">
        <h2 class="mb-0">Cihaz Logları</h2>
        <div class="logs-filters">
            <div class="log-search">
                <span class="search-icon">🔍</span>
                <input type="text" id="searchInput" placeholder="Log içinde ara..." class="form-control">
            </div>
            <select id="deviceFilter">
                <option value="">Tüm Cihazlar</option>
                <!-- Cihazlar JavaScript ile yüklenecek -->
            </select>
            <select id="levelFilter">
                <option value="">Tüm Seviyeler</option>
                <option value="ERROR">Hata</option>
                <option value="WARNING">Uyarı</option>
                <option value="INFO">Bilgi</option>
                <option value="DEBUG">Debug</option>
            </select>
            <input type="date" id="dateFrom" value="<?php echo date('Y-m-d', strtotime('-7 days')); ?>">
            <input type="date" id="dateTo" value="<?php echo date('Y-m-d'); ?>">
            <button class="btn btn-primary" onclick="applyFilters()">Filtrele</button>
            <button class="btn btn-secondary" onclick="clearFilters()">Temizle</button>
            <button class="btn btn-primary" onclick="loadLogs()">🔄 Yenile</button>
            <div class="auto-refresh">
                <input type="checkbox" id="autoRefresh">
                <label for="autoRefresh">Otomatik Yenile</label>
                <span id="refreshIndicator" style="display: none;" class="refresh-indicator"></span>
            </div>
        </div>
    </div>
    
    <!-- Log İstatistikleri -->
    <div class="logs-stats">
        <div class="log-stat">
            <div class="value" id="totalLogs">0</div>
            <div class="label">Toplam Log</div>
        </div>
        <div class="log-stat">
            <div class="value" id="errorLogs">0</div>
            <div class="label">Hata</div>
        </div>
        <div class="log-stat">
            <div class="value" id="warningLogs">0</div>
            <div class="label">Uyarı</div>
        </div>
        <div class="log-stat">
            <div class="value" id="infoLogs">0</div>
            <div class="label">Bilgi</div>
        </div>
    </div>
    
    <!-- Log Tablosu -->
    <div class="logs-table">
        <table class="table table-striped">
            <thead>
                <tr>
                    <th>Seviye</th>
                    <th>Zaman</th>
                    <th>Mesaj</th>
                </tr>
            </thead>
            <tbody id="logsTable">
                <tr>
                    <td colspan="3" class="text-center text-muted p-4">Loglar yükleniyor...</td>
                </tr>
            </tbody>
        </table>
    </div>
    
    <!-- Sayfalama -->
    <div class="pagination" id="pagination">
        <!-- Sayfalama JavaScript ile doldurulacak -->
    </div>
    
    <!-- Dışa Aktarma -->
    <div class="logs-header">
        <div class="log-export">
            <label>Dışa Aktarma:</label>
            <select id="exportFormat">
                <option value="csv">CSV</option>
                <option value="json">JSON</option>
                <option value="txt">TXT</option>
            </select>
            <button class="btn btn-success" onclick="exportLogs()">📥 İndir</button>
            <button class="btn btn-danger" onclick="clearLogs()">🗑️ Temizle</button>
        </div>
    </div>
</div>

<?php require_once 'layouts/footer.php'; ?>
