<!DOCTYPE html>
<html lang="tr">
<head>
    <meta charset="UTF-8">
    <title>Veri Tablosu</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
</head>
<body class="bg-light">
<!-- Sol üstte logo (her zaman sabit) -->
<!-- Sağ üstte language seçici (her zaman sabit) -->
<div style="position: fixed; top: 0; right: 0; z-index: 9999; margin: 12px 18px 0 0; text-align: right;">
    <div class="dropdown d-inline-block">
        <button class="btn btn-light btn-sm dropdown-toggle" type="button" id="langDropdown" data-bs-toggle="dropdown" aria-expanded="false">
            <i class="bi bi-translate me-1"></i>{{ _('language') }}
        </button>
        <ul class="dropdown-menu" aria-labelledby="langDropdown">
            <li><a class="dropdown-item" href="{{ url_for('set_lang', lang='tr') }}">{{ _('turkish') }}</a></li>
            <li><a class="dropdown-item" href="{{ url_for('set_lang', lang='en') }}">{{ _('english') }}</a></li>
        </ul>
    </div>
</div>
<div class="container" style="margin-top: 80px;">
    <div class="card shadow p-4">
        <div class="d-flex justify-content-between align-items-center mb-3">
            <h2 class="mb-0 text-primary" style="font-size: 1.2rem; white-space: nowrap; overflow: hidden; text-overflow: ellipsis;"><i class="bi bi-door-closed me-2"></i>{{ _('access_logs') }}</h2>
            <div class="d-flex align-items-center">
                <form method="get" class="d-flex align-items-center" style="gap: 0.5rem;">
                    <input type="text" name="adsoyad" class="form-control me-2" placeholder="{{ _('filter_placeholder') }}" value="{{ request.args.get('adsoyad', '') }}" style="max-width: 220px;">
                    <button type="submit" class="btn btn-info btn-sm me-2 minw-btn"><i class="bi bi-funnel me-1"></i>{{ _('filter') }}</button>
                    <a href="{{ url_for('istekler') }}" class="btn btn-primary btn-sm me-2 minw-btn"><i class="bi bi-list-check me-1"></i>{{ _('requests') }}</a>
                    <a href="#" class="btn btn-success btn-xs me-2 minw-btn custom-xs"><i class="bi bi-person-plus me-1"></i>{{ _('user_add') }}</a>
                    <a href="{{ url_for('devices') }}" class="btn btn-success btn-xs me-2 minw-btn custom-xs"><i class="bi bi-hdd-network me-1"></i>{{ _('devices') }}</a>
                    <a href="{{ url_for('users') }}" class="btn btn-warning btn-sm me-2 minw-btn"><i class="bi bi-pencil-square me-1"></i>{{ _('user_edit') }}</a>
                    <a href="{{ url_for('download_pdf', adsoyad=request.args.get('adsoyad', '')) }}" class="btn btn-outline-secondary btn-sm me-2 minw-btn"><i class="bi bi-file-earmark-pdf me-1"></i>{{ _('download_pdf') }}</a>
                    <a href="{{ url_for('logout') }}" class="btn btn-danger btn-sm minw-btn"><i class="bi bi-box-arrow-right me-1"></i>{{ _('logout') }}</a>
                </form>
            </div>
        </div>
        <table class="table table-bordered table-hover table-striped align-middle" style="border-collapse: separate; border-spacing: 0;">
            <thead class="table-dark" style="position: sticky; top: 0; z-index: 10;">
                <tr>
                    <th>
                        <a href="?sort=id&order={{ 'desc' if request.args.get('sort') == 'id' and request.args.get('order') == 'asc' else 'asc' }}{{ '&adsoyad=' + request.args.get('adsoyad') if request.args.get('adsoyad') else '' }}" class="text-white text-decoration-none">
                            {{ _('index') }}
                            {% if request.args.get('sort') == 'id' %}
                                <i class="bi bi-caret-{{ 'up' if request.args.get('order') == 'asc' else 'down' }}-fill"></i>
                            {% else %}
                                <i class="bi bi-caret-down"></i>
                            {% endif %}
                        </a>
                    </th>
                    <th>
                        <a href="?sort=ad&order={{ 'desc' if request.args.get('sort') == 'ad' and request.args.get('order') == 'asc' else 'asc' }}{{ '&adsoyad=' + request.args.get('adsoyad') if request.args.get('adsoyad') else '' }}" class="text-white text-decoration-none">
                            {{ _('name') }}
                            {% if request.args.get('sort') == 'ad' %}
                                <i class="bi bi-caret-{{ 'up' if request.args.get('order') == 'asc' else 'down' }}-fill"></i>
                            {% else %}
                                <i class="bi bi-caret-down"></i>
                            {% endif %}
                        </a>
                    </th>
                    <th>
                        <a href="?sort=bolge&order={{ 'desc' if request.args.get('sort') == 'bolge' and request.args.get('order') == 'asc' else 'asc' }}{{ '&adsoyad=' + request.args.get('adsoyad') if request.args.get('adsoyad') else '' }}" class="text-white text-decoration-none">
                            {{ _('region') }}
                            {% if request.args.get('sort') == 'bolge' %}
                                <i class="bi bi-caret-{{ 'up' if request.args.get('order') == 'asc' else 'down' }}-fill"></i>
                            {% else %}
                                <i class="bi bi-caret-down"></i>
                            {% endif %}
                        </a>
                    </th>
                    <th>
                        <a href="?sort=gecis_turu&order={{ 'desc' if request.args.get('sort') == 'gecis_turu' and request.args.get('order') == 'asc' else 'asc' }}{{ '&adsoyad=' + request.args.get('adsoyad') if request.args.get('adsoyad') else '' }}" class="text-white text-decoration-none">
                            {{ _('access_type') }}
                            {% if request.args.get('sort') == 'gecis_turu' %}
                                <i class="bi bi-caret-{{ 'up' if request.args.get('order') == 'asc' else 'down' }}-fill"></i>
                            {% else %}
                                <i class="bi bi-caret-down"></i>
                            {% endif %}
                        </a>
                    </th>
                    <th>
                        <a href="?sort=access_type&order={{ 'desc' if request.args.get('sort') == 'access_type' and request.args.get('order') == 'asc' else 'asc' }}{{ '&adsoyad=' + request.args.get('adsoyad') if request.args.get('adsoyad') else '' }}" class="text-white text-decoration-none">
                            {{ _('access_type_label') }}
                            {% if request.args.get('sort') == 'access_type' %}
                                <i class="bi bi-caret-{{ 'up' if request.args.get('order') == 'asc' else 'down' }}-fill"></i>
                            {% else %}
                                <i class="bi bi-caret-down"></i>
                            {% endif %}
                        </a>
                    </th>
                    <th>
                        <a href="?sort=is_granted&order={{ 'desc' if request.args.get('sort') == 'is_granted' and request.args.get('order') == 'asc' else 'asc' }}{{ '&adsoyad=' + request.args.get('adsoyad') if request.args.get('adsoyad') else '' }}" class="text-white text-decoration-none">
                            {{ _('status_label') }}
                            {% if request.args.get('sort') == 'is_granted' %}
                                <i class="bi bi-caret-{{ 'up' if request.args.get('order') == 'asc' else 'down' }}-fill"></i>
                            {% else %}
                                <i class="bi bi-caret-down"></i>
                            {% endif %}
                        </a>
                    </th>
                    <th>
                        <a href="?sort=timestamp&order={{ 'desc' if request.args.get('sort') == 'timestamp' and request.args.get('order') == 'asc' else 'asc' }}{{ '&adsoyad=' + request.args.get('adsoyad') if request.args.get('adsoyad') else '' }}" class="text-white text-decoration-none">
                            {{ _('date_time') }}
                            {% if request.args.get('sort') == 'timestamp' %}
                                <i class="bi bi-caret-{{ 'up' if request.args.get('order') == 'asc' else 'down' }}-fill"></i>
                            {% else %}
                                <i class="bi bi-caret-down"></i>
                            {% endif %}
                        </a>
                    </th>
                </tr>
            </thead>
            <tbody>
                {% for row in gecisler %}
                <tr>
                    <td>{{ row.id }}</td>
                    <td>{{ row.user_name or row.card_uuid }}</td>
                    <td>{{ row.device_name or row.device_id }}</td>
                    <td>
                        {% if row.source == 'new' %}
                            {% set access_types = {
                                1: ('NFC', 'access-nfc'),
                                2: ('BUTTON', 'access-button'),
                                3: ('TCP SERVER', 'access-tcpserver'),
                                4: ('TCP CLIENT', 'access-tcpclient'),
                                5: ('BLE', 'access-ble'),
                                6: ('RS485', 'access-rs485')
                            } %}
                            {% set type_info = access_types.get(row.access_type|int, ('UNKNOWN', 'access-unknown')) %}
                            {% if type_info[1] in ['access-nfc', 'access-button', 'access-tcpserver', 'access-tcpclient', 'access-ble'] %}
                                <img src="{{ url_for('static', filename='img/' + type_info[1] + '.png') }}" 
                                     alt="{{ _(type_info[0]) if _(type_info[0]) else type_info[0] }}" width="24" height="24">
                            {% else %}
                                <i class="bi bi-question-circle text-muted"></i>
                            {% endif %}
                            <span class="ms-2">{{ _(type_info[0]) if _(type_info[0]) else type_info[0] }}</span>
                        {% else %}
                            <img src="{{ url_for('static', filename='img/' + row.gecis_icon) }}" alt="{{ _(row.gecis_turu) }}" width="24" height="24">
                            <span class="ms-2">{{ _(row.gecis_turu) }}</span>
                        {% endif %}
                    </td>
                    <td>
                        {% if row.source == 'new' %}
                            {% set access_types = {
                                1: ('NFC', 'access-nfc'),
                                2: ('BUTTON', 'access-button'),
                                3: ('TCP SERVER', 'access-tcpserver'),
                                4: ('TCP CLIENT', 'access-tcpclient'),
                                5: ('BLE', 'access-ble'),
                                6: ('RS485', 'access-rs485')
                            } %}
                            {% set type_info = access_types.get(row.access_type|int, ('UNKNOWN', 'access-unknown')) %}
                            {% if type_info[1] in ['access-nfc', 'access-button', 'access-tcpserver', 'access-tcpclient', 'access-ble'] %}
                                <img src="{{ url_for('static', filename='img/' + type_info[1] + '.png') }}" 
                                     alt="{{ _(type_info[0]) if _(type_info[0]) else type_info[0] }}" width="20" height="20" class="me-2">
                            {% else %}
                                <i class="bi bi-question-circle text-muted"></i>
                            {% endif %}
                            <span class="ms-2">{{ _(type_info[0]) if _(type_info[0]) else type_info[0] }}</span>
                        {% else %}
                            <img src="{{ url_for('static', filename='img/' + row.gecis_icon) }}" alt="{{ _(row.gecis_turu) }}" width="20" height="20" class="me-2">
                            <span class="ms-2">{{ _(row.gecis_turu) }}</span>
                        {% endif %}
                    </td>
                    <td>
                        {% if row.is_granted %}
                            <img src="{{ url_for('static', filename='img/giris_yapildi.png') }}" alt="{{ _('IZIN_VERILDI') }}" width="24" height="24">
                            <span class="ms-2 small">{{ _('IZIN_VERILDI') }}</span>
                        {% else %}
                            <img src="{{ url_for('static', filename='img/izin_verilmedi.png') }}" alt="{{ _('IZIN_VERILMEDI') }}" width="24" height="24">
                            <span class="ms-2 small">{{ _('IZIN_VERILMEDI') }}</span>
                        {% endif %}
                    </td>
                    <td>
                        {% if row.source == 'new' %}
                            {{ row.timestamp|datetime }}
                        {% else %}
                            {{ row.timestamp }}
                        {% endif %}
                    </td>
                </tr>
                {% endfor %}
            </tbody>
        </table>
    </div>
</div>
{% if total_pages > 1 %}
<nav aria-label="Sayfalama" class="mt-3">
  <ul class="pagination justify-content-center">
    <li class="page-item {% if page == 1 %}disabled{% endif %}">
      <a class="page-link" href="?page={{ page-1 }}{{ '&adsoyad=' + request.args.get('adsoyad') if request.args.get('adsoyad') else '' }}{{ '&sort=' + request.args.get('sort') if request.args.get('sort') else '' }}{{ '&order=' + request.args.get('order') if request.args.get('order') else '' }}">&laquo;</a>
    </li>
    {% for p in range(1, total_pages+1) %}
      <li class="page-item {% if p == page %}active{% endif %}"><a class="page-link" href="?page={{ p }}{{ '&adsoyad=' + request.args.get('adsoyad') if request.args.get('adsoyad') else '' }}{{ '&sort=' + request.args.get('sort') if request.args.get('sort') else '' }}{{ '&order=' + request.args.get('order') if request.args.get('order') else '' }}">{{ p }}</a></li>
    {% endfor %}
    <li class="page-item {% if page == total_pages %}disabled{% endif %}">
      <a class="page-link" href="?page={{ page+1 }}{{ '&adsoyad=' + request.args.get('adsoyad') if request.args.get('adsoyad') else '' }}{{ '&sort=' + request.args.get('sort') if request.args.get('sort') else '' }}{{ '&order=' + request.args.get('order') if request.args.get('order') else '' }}">&raquo;</a>
    </li>
  </ul>
</nav>
{% endif %}
<!-- Bootstrap Icons -->
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.3/font/bootstrap-icons.min.css">
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>

<!-- Real-time güncelleme için JavaScript -->
<script>
let lastUpdateTime = new Date().getTime();
let updateInterval;

// Real-time güncelleme başlat
function startRealTimeUpdates() {
    
    // Her 3 saniyede bir güncelle
    updateInterval = setInterval(function() {
        updateGecislerTable();
    }, 3000);
}

// Geçişler tablosunu güncelle
function updateGecislerTable() {
    const currentUrl = new URL(window.location);
    const params = new URLSearchParams(currentUrl.search);
    
    // API parametrelerini hazırla
    const apiParams = new URLSearchParams();
    if (params.get('adsoyad')) apiParams.append('adsoyad', params.get('adsoyad'));
    if (params.get('page')) apiParams.append('page', params.get('page'));
    if (params.get('sort')) apiParams.append('sort', params.get('sort'));
    if (params.get('order')) apiParams.append('order', params.get('order'));
    
    fetch(`/api/gecisler/latest?${apiParams.toString()}`)
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                updateTableContent(data.data);
            } else {
                console.error('❌ API hatası:', data.message);
            }
        })
        .catch(error => {
            console.error('❌ Güncelleme hatası:', error);
        });
}

// Tablo içeriğini güncelle
function updateTableContent(data) {
    const tbody = document.querySelector('tbody');
    if (!tbody) return;
    
    // Yeni verileri oluştur
    let newContent = '';
    
    data.gecisler.forEach(row => {
        const gecisIcon = getGecisIcon(row.gecis_turu);
        const statusIcon = row.giris_durumu === 'GIRIS_YAPILDI' ? 
            'giris_yapildi.png' : 'izin_verilmedi.png';
        
        newContent += `
            <tr>
                <td>${row.id}</td>
                <td>${row.ad}</td>
                <td>${row.bolge}</td>
                <td>
                    <img src="/static/img/${gecisIcon}" alt="${row.gecis_turu}" width="24" height="24">
                    <span class="ms-2">${row.gecis_turu}</span>
                </td>
                <td>${row.notlar}</td>
                <td>
                    <img src="/static/img/${statusIcon}" alt="${row.giris_durumu}" width="24" height="24">
                    <span class="ms-2 small">${row.giris_durumu}</span>
                </td>
                <td>${row.zaman}</td>
            </tr>
        `;
    });
    
    // Tabloyu güncelle
    tbody.innerHTML = newContent;
    
    // Yeni kayıt varsa bildirim göster
    if (data.gecisler.length > 0) {
        const firstRow = data.gecisler[0];
        const rowTime = new Date(firstRow.zaman).getTime();
        
        if (rowTime > lastUpdateTime) {
            showNewRecordNotification(firstRow);
            lastUpdateTime = rowTime;
        }
    }
}

// Geçiş türüne göre icon döndür
function getGecisIcon(gecisTuru) {
    const iconMap = {
        'ACCESS_NFC': 'access_nfc.png',
        'ACCESS_BLE': 'access_ble.png',
        'ACCESS_BUTTON': 'access_button.png',
        'ACCESS_TCPCLIENT': 'access_tcpclient.png',
        'ACCESS_TCPSERVER': 'access_tcpserver.png'
    };
    return iconMap[gecisTuru] || 'access_nfc.png';
}

// Yeni kayıt bildirimi göster
function showNewRecordNotification(record) {
    // Bildirim oluştur
    const notification = document.createElement('div');
    notification.className = 'alert alert-success alert-dismissible fade show position-fixed';
    notification.style.cssText = 'top: 20px; right: 20px; z-index: 9999; min-width: 300px;';
    notification.innerHTML = `
        <strong>🆕 {{ _('access_logs') }}</strong><br>
        <small>${record.ad} - ${record.giris_durumu}</small>
        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
    `;
    
    document.body.appendChild(notification);
    
    // 5 saniye sonra otomatik kaldır
    setTimeout(() => {
        if (notification.parentNode) {
            notification.remove();
        }
    }, 5000);
}

// Sayfa yüklendiğinde real-time güncellemeyi başlat
document.addEventListener('DOMContentLoaded', function() {
    startRealTimeUpdates();
    
    // Sayfa kapatılırken interval'i temizle
    window.addEventListener('beforeunload', function() {
        if (updateInterval) {
            clearInterval(updateInterval);
        }
    });
});

// Manuel güncelleme butonu (gelecekte eklenebilir)
function manualRefresh() {
    updateGecislerTable();
}
</script>
<style>
.minw-btn {
  min-width: 90px;
  font-size: 12px;
  padding: 2px 10px;
  margin-bottom: 2px;
  white-space: nowrap;
  text-overflow: ellipsis;
  overflow: hidden;
}
@media (max-width: 600px) {
  .minw-btn { min-width: 70px; font-size: 12px; }
}
</style>
</body>
</html>
