<!DOCTYPE html>
<html lang="{{ current_language }}">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>{{ _('device_logs_title') }} - iAccess</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.3/font/bootstrap-icons.css" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
    <style>
        :root {
            --primary-color: #4a90e2;
            --secondary-color: #f8f9fa;
            --success-color: #28a745;
            --danger-color: #dc3545;
            --warning-color: #ffc107;
            --info-color: #17a2b8;
        }
        
        body {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
        }
        
        .main-container {
            margin-top: 80px;
            padding: 2rem 0;
        }
        
        .card {
            border: none;
            border-radius: 15px;
            box-shadow: 0 10px 30px rgba(0, 0, 0, 0.1);
            backdrop-filter: blur(10px);
            background: rgba(255, 255, 255, 0.95);
        }
        
        .card-header-modern {
            background: linear-gradient(135deg, var(--primary-color), #357abd);
            color: white;
            border-radius: 15px 15px 0 0 !important;
            padding: 1.5rem;
            border: none;
        }
        
        .page-title {
            margin: 0;
            font-size: 2rem;
            font-weight: 700;
            text-shadow: 0 2px 4px rgba(0, 0, 0, 0.3);
        }
        
        .btn-modern {
            border-radius: 10px;
            padding: 0.75rem 1.5rem;
            font-weight: 600;
            transition: all 0.3s ease;
            border: none;
            box-shadow: 0 4px 15px rgba(0, 0, 0, 0.1);
        }
        
        .btn-back {
            background: linear-gradient(135deg, #6c757d, #5a6268);
            color: white;
        }
        
        .btn-back:hover {
            background: linear-gradient(135deg, #5a6268, #495057);
            color: white;
            transform: translateY(-2px);
            box-shadow: 0 6px 20px rgba(0, 0, 0, 0.15);
        }
        
        .btn-success {
            background: linear-gradient(135deg, var(--success-color), #20c997);
            color: white;
        }
        
        .btn-success:hover {
            background: linear-gradient(135deg, #218838, #1ea085);
            color: white;
            transform: translateY(-2px);
            box-shadow: 0 6px 20px rgba(0, 0, 0, 0.15);
        }
        
        .btn-danger {
            background: linear-gradient(135deg, var(--danger-color), #c82333);
            color: white;
        }
        
        .btn-danger:hover {
            background: linear-gradient(135deg, #c82333, #a71e2a);
            color: white;
            transform: translateY(-2px);
            box-shadow: 0 6px 20px rgba(0, 0, 0, 0.15);
        }
        
        .btn-info {
            background: linear-gradient(135deg, var(--info-color), #138496);
            color: white;
        }
        
        .btn-info:hover {
            background: linear-gradient(135deg, #138496, #117a8b);
            color: white;
            transform: translateY(-2px);
            box-shadow: 0 6px 20px rgba(0, 0, 0, 0.15);
        }
        
        .table-modern {
            border-radius: 10px;
            overflow: hidden;
            box-shadow: 0 4px 15px rgba(0, 0, 0, 0.1);
        }
        
        .table-modern thead th {
            background: linear-gradient(135deg, var(--primary-color), #357abd);
            color: white;
            border: none;
            padding: 1rem;
            font-weight: 600;
            text-transform: uppercase;
            font-size: 0.9rem;
            letter-spacing: 0.5px;
        }
        
        .table-modern tbody tr {
            transition: all 0.3s ease;
        }
        
        .table-modern tbody tr:hover {
            background-color: rgba(74, 144, 226, 0.1);
            transform: scale(1.01);
        }
        
        .table-modern tbody td {
            padding: 1rem;
            border: none;
            border-bottom: 1px solid #e9ecef;
            vertical-align: middle;
        }
        
        .badge {
            padding: 0.5rem 1rem;
            border-radius: 20px;
            font-weight: 600;
            font-size: 0.8rem;
        }
        
        .badge-success {
            background: linear-gradient(135deg, var(--success-color), #1e7e34);
            color: white;
        }
        
        .badge-danger {
            background: linear-gradient(135deg, var(--danger-color), #c82333);
            color: white;
        }
        
        .badge-warning {
            background: linear-gradient(135deg, var(--warning-color), #e0a800);
            color: #212529;
        }
        
        .badge-info {
            background: linear-gradient(135deg, var(--info-color), #138496);
            color: white;
        }
        
        .access-type {
            font-weight: 600;
            padding: 0.25rem 0.75rem;
            border-radius: 15px;
            font-size: 0.8rem;
            display: inline-block;
            vertical-align: middle;
        }
        
        .access-type-container {
            display: flex;
            align-items: center;
            gap: 0.5rem;
        }
        
        .access-nfc { background-color: #e3f2fd; color: #1976d2; }
        .access-button { background-color: #f3e5f5; color: #7b1fa2; }
        .access-tcpserver { background-color: #e8f5e8; color: #388e3c; }
        .access-tcpclient { background-color: #fff3e0; color: #f57c00; }
        .access-ble { background-color: #fce4ec; color: #c2185b; }
        .access-rs485 { background-color: #f1f8e9; color: #689f38; }
        .access-unknown { background-color: #f5f5f5; color: #757575; }
        
        .timestamp {
            font-family: 'Courier New', monospace;
            font-size: 0.9rem;
            color: #6c757d;
        }
        
        .user-info {
            font-weight: 600;
            color: var(--primary-color);
        }
        
        .device-id {
            font-family: 'Courier New', monospace;
            font-weight: 600;
            color: #495057;
        }
        
        .empty-state {
            text-align: center;
            padding: 3rem;
            color: #6c757d;
        }
        
        .empty-state i {
            font-size: 4rem;
            margin-bottom: 1rem;
            opacity: 0.5;
        }
    </style>
</head>
<body>
    <nav class="navbar navbar-expand-lg fixed-top" style="background: rgba(255, 255, 255, 0.95); backdrop-filter: blur(10px); box-shadow: 0 2px 20px rgba(0,0,0,0.1);">
        <div class="container">
            <a class="navbar-brand" href="https://monicont.com" target="_blank">
                <img src="{{ url_for('static', filename='img/monicont_logo.png') }}" alt="Logo" style="width: 120px; height: auto;" class="me-3">
            </a>
            <div class="collapse navbar-collapse show">
                <ul class="navbar-nav me-auto">
                    <li class="nav-item"><a class="nav-link" href="{{ url_for('home') }}"><i class="fas fa-home me-1"></i>{{ _('dashboard') }}</a></li>
                    <li class="nav-item"><a class="nav-link active" href="{{ url_for('devices') }}"><i class="fas fa-microchip me-1"></i>{{ _('devices') }}</a></li>
                    <li class="nav-item"><a class="nav-link" href="{{ url_for('users') }}"><i class="fas fa-users me-1"></i>{{ _('users_title') }}</a></li>
                    <li class="nav-item"><a class="nav-link" href="{{ url_for('access_logs') }}"><i class="fas fa-clipboard-list me-1"></i>{{ _('access_logs') }}</a></li>
                </ul>
                <ul class="navbar-nav">
                    <li class="nav-item dropdown">
                        <a class="nav-link dropdown-toggle d-flex align-items-center" href="#" id="userDropdown" role="button" data-bs-toggle="dropdown">
                            {% if user and user['profile_image'] %}
                                {% set imgsrc = user['profile_image'] %}
                                {% if imgsrc and imgsrc[0] == '@' %}
                                    {% set imgfile = imgsrc[1:] %}
                                    <img src="{{ url_for('static', filename='img/' + imgfile) }}?v={{ static_bust }}" alt="Profil Resmi" class="rounded-circle me-2" width="32" height="32" style="object-fit: cover;">
                                {% else %}
                                    <img src="{{ url_for('static', filename='uploads/' + (imgsrc or '')) }}?v={{ static_bust }}" alt="Profil Resmi" class="rounded-circle me-2" width="32" height="32" style="object-fit: cover;">
                                {% endif %}
                            {% else %}
                                <img src="{{ url_for('static', filename='img/default-avatar.png') }}?v={{ static_bust }}" alt="Profil Resmi" class="rounded-circle me-2" width="32" height="32" style="object-fit: cover;">
                            {% endif %}
                            <div class="d-flex flex-column">
                                <span class="fw-bold">{{ user_name }}</span>
                                {% if user and user['company'] %}
                                    <small class="text-muted">{{ user['company'] }}</small>
                                {% endif %}
                            </div>
                        </a>
                        <ul class="dropdown-menu dropdown-menu-end" aria-labelledby="userDropdown">
                            <li><a class="dropdown-item" href="{{ url_for('profile') }}"><i class="fas fa-user me-2"></i>{{ _('profile') }}</a></li>
                            <li><hr class="dropdown-divider"></li>
                            <li><a class="dropdown-item" href="{{ url_for('logout') }}"><i class="fas fa-sign-out-alt me-2"></i>{{ _('logout') }}</a></li>
                        </ul>
                    </li>
                </ul>
            </div>
        </div>
    </nav>
    <div class="main-container">
        <div class="container">
            <div class="card">
                <div class="card-header-modern">
                    <div class="d-flex justify-content-between align-items-center">
                        <h1 class="page-title">
                            <i class="bi bi-clock-history me-3"></i>{{ _('device_logs_title') }} - {{ device_id }}
                        </h1>
                        <div class="d-flex gap-2">
                            <button class="btn btn-modern btn-info" onclick="location.reload()" title="{{ _('device_info_refresh') or _('refresh_status') }}">
                                <i class="bi bi-arrow-clockwise me-2"></i>{{ _('device_info_refresh') or _('refresh_status') }}
                            </button>
                            <button id="downloadPdfBtn" class="btn btn-modern btn-success" onclick="downloadPdf()">
                                <i class="bi bi-file-pdf me-2"></i>{{ _('download_pdf') }}
                            </button>
                            <button id="deleteAllLogsBtn" class="btn btn-modern btn-danger" onclick="deleteAllLogs()">
                                <i class="bi bi-trash me-2"></i>{{ _('clear_logs') or _('clear') }}
                            </button>
                            <a href="{{ url_for('devices') }}" class="btn btn-modern btn-back">
                                <i class="bi bi-arrow-left me-2"></i>{{ _('back_to_devices') or _('back') }}
                            </a>
                        </div>
                    </div>
                </div>
                
                <!-- Filtreleme Bölümü -->
                <div class="card-body border-bottom bg-light">
                    <div class="row g-3 align-items-end">
                        <div class="col-md-8">
                            <div class="input-group">
                                <span class="input-group-text bg-white border-end-0">
                                    <i class="bi bi-search text-muted"></i>
                                </span>
                                <input type="text" 
                                       id="searchInput"
                                       class="form-control border-start-0" 
                                       placeholder="{{ _('filter_placeholder') }}" 
                                       value="{{ request.args.get('adsoyad', '') }}">
                                <a href="{{ url_for('device_logs', device_id=device_id) }}" 
                                   class="btn btn-outline-secondary border-start-0" 
                                   title="{{ _('clear_filter') or 'Clear Filter' }}">
                                    <i class="bi bi-x-circle"></i>
                                </a>
                            </div>
                        </div>
                    </div>
                </div>
                
                <div class="card-body p-0">
                    {% if logs %}
                        <div class="table-responsive">
                            <table class="table table-modern">
                                <thead>
                                    <tr>
                                        <th>{{ _('device_id') }}</th>
                                        <th>{{ _('user_name') }}</th>
                                        <th>{{ _('device_name') }}</th>
                                        <th>UUID</th>
                                        <th>{{ _('access_type') }}</th>
                                        <th>{{ _('status') }}</th>
                                        <th>{{ _('date_time') }}</th>
                                        
                                    </tr>
                                </thead>
                                <tbody>
                                    {% for log in logs %}
                                    <tr>
                                        <td><span class="device-id">{{ log.device_id }}</span></td>
                                        <td>
                                            {% if log.user_name %}
                                                <span class="user-info">{{ log.user_name }}</span>
                                            {% else %}
                                                <span class="text-muted">Bilinmeyen Kullanıcı</span>
                                            {% endif %}
                                        </td>
                                        <td>
                                            {% if log.device_name %}
                                                <span class="device-info">{{ log.device_name }}</span>
                                            {% else %}
                                                <span class="text-muted">{{ log.device_id }}</span>
                                            {% endif %}
                                        </td>
                                        <td><code>{{ log.card_uuid or 'N/A' }}</code></td>
                                        <td>
                                            {% 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')
                                            } %}
                                            {% if log.access_type %}
                                                {% set type_info = access_types.get(log.access_type|int, ('UNKNOWN', 'access-unknown')) %}
                                                <div class="access-type-container">
                                                    {% if log.access_type == 1 or log.access_type == '1' %}
                                                        <img src="{{ url_for('static', filename='img/access_nfc.png') }}" alt="NFC" width="20" height="20">
                                                    {% elif log.access_type == 2 or log.access_type == '2' %}
                                                        <img src="{{ url_for('static', filename='img/access_button.png') }}" alt="BUTTON" width="20" height="20">
                                                    {% elif log.access_type == 3 or log.access_type == '3' %}
                                                        <img src="{{ url_for('static', filename='img/access_tcpserver.png') }}" alt="TCP SERVER" width="20" height="20">
                                                    {% elif log.access_type == 4 or log.access_type == '4' %}
                                                        <img src="{{ url_for('static', filename='img/access_tcpclient.png') }}" alt="TCP CLIENT" width="20" height="20">
                                                    {% elif log.access_type == 5 or log.access_type == '5' %}
                                                        <img src="{{ url_for('static', filename='img/access_ble.png') }}" alt="BLE" width="20" height="20">
                                                    {% elif log.access_type == 6 or log.access_type == '6' %}
                                                        <img src="{{ url_for('static', filename='img/access_rs485.png') }}" alt="RS485" width="20" height="20">
                                                    {% else %}
                                                        <i class="bi bi-question-circle text-muted"></i>
                                                    {% endif %}
                                                    <span class="access-type {{ type_info[1] }}">{{ type_info[0] }}</span>
                                                </div>
                                            {% else %}
                                                <div class="d-flex align-items-center">
                                                    <i class="bi bi-clock-history me-2 text-muted"></i>
                                                    <span class="access-type fw-bold">{{ log.access_type or 'UNKNOWN' }}</span>
                                                </div>
                                            {% endif %}
                                        </td>
                                        <td>
                                            {% if log.is_granted %}
                                                <span class="badge badge-success">
                                                    <i class="bi bi-check-circle me-1"></i>{{ _('IZIN_VERILDI') or 'İzin Verildi' }}
                                                </span>
                                            {% else %}
                                                <span class="badge badge-danger">
                                                    <i class="bi bi-x-circle me-1"></i>{{ _('IZIN_VERILMEDI') or 'İzin Verilmedi' }}
                                                </span>
                                            {% endif %}
                                        </td>
                                        <td>
                                            <span class="timestamp">
                                                {% if log.source == 'new' %}
                                                    {{ log.timestamp|datetime }}
                                                {% else %}
                                                    {{ log.timestamp }}
                                                {% endif %}
                                            </span>
                                        </td>
                                        
                                    </tr>
                                    {% endfor %}
                                </tbody>
                            </table>
                        </div>
                        
                        <!-- Pagination kaldırıldı -->
                    {% else %}
                        <div class="empty-state">
                            <i class="bi bi-clock-history"></i>
                            <h3 class="mt-3 text-muted">{{ _('no_device_logs') }}</h3>
                            <p class="text-muted">{{ _('no_device_logs_description') }}</p>
                        </div>
                    {% endif %}
                </div>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>
    
    <script>
        function downloadPdf() {
            // PDF indirme butonunu devre dışı bırak
            const btn = document.getElementById('downloadPdfBtn');
            const originalText = btn.innerHTML;
            btn.disabled = true;
            btn.innerHTML = '<i class="bi bi-hourglass-split me-2"></i>İndiriliyor...';
            
            // PDF'i indir (cihaz özel route)
            window.location.href = '/device-logs/' + encodeURIComponent('{{ device_id }}') + '/download';
            
            // 3 saniye sonra butonu tekrar aktif et
            setTimeout(() => {
                btn.disabled = false;
                btn.innerHTML = originalText;
            }, 3000);
        }
        
        function deleteAllLogs() {
            if (confirm('Tüm cihaz loglarını silmek istediğinizden emin misiniz? Bu işlem geri alınamaz!')) {
                const btn = document.getElementById('deleteAllLogsBtn');
                const originalText = btn.innerHTML;
                btn.disabled = true;
                btn.innerHTML = '<i class="bi bi-hourglass-split me-2"></i>Siliniyor...';
                
                fetch('/api/device-logs/' + encodeURIComponent('{{ device_id }}') + '/clear', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({})
                })
                .then(response => response.json())
                .then(data => {
                    alert('Tüm cihaz logları başarıyla silindi!');
                    location.reload();
                })
                .catch(error => {
                    console.error('Error:', error);
                    alert('Bir hata oluştu!');
                })
                .finally(() => {
                    btn.disabled = false;
                    btn.innerHTML = originalText;
                });
            }
        }
        
        function deleteLog(logId, source) {
            if (confirm('Bu cihaz logunu silmek istediğinizden emin misiniz?')) {
                fetch('/api/delete-log', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({
                        log_id: logId,
                        source: source,
                        device_id: '{{ device_id }}'
                    })
                })
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        alert('Cihaz logu başarıyla silindi! Sayfayı manuel olarak yenileyin.');
                        // location.reload(); // Manuel yenileme için kaldırıldı
                    } else {
                        alert('Hata: ' + data.message);
                    }
                })
                .catch(error => {
                    console.error('Error:', error);
                    alert('Bir hata oluştu!');
                });
            }
        }

        // Real-time güncelleme
        let lastUpdateTime = Date.now();
        
        function checkForUpdates() {
            fetch('/api/check-updates?last_update=' + lastUpdateTime)
                .then(response => response.json())
                .then(data => {
                    if (data.has_updates) {
                        // Sayfayı yenile
                        location.reload();
                    }
                })
                .catch(error => {
                    console.log('Update check failed:', error);
                });
        }

        // Otomatik yenileme devre dışı bırakıldı
        // setInterval(checkForUpdates, 5000);

        // Delete buttons delegation
        document.addEventListener('click', function(e) {
            const btn = e.target.closest('.delete-log-btn');
            if (!btn) return;
            const id = btn.getAttribute('data-log-id');
            const src = btn.getAttribute('data-source');
            deleteLog(id, src);
        });
    </script>
    <script>
        document.addEventListener('DOMContentLoaded', function() {
            // Real-time search filtering
            const searchInput = document.getElementById('searchInput');
            const tableRows = document.querySelectorAll('.table-modern tbody tr');
            
            if (searchInput && tableRows.length > 0) {
                let searchTimeout;
                
                searchInput.addEventListener('input', function() {
                    const searchTerm = this.value.toLowerCase().trim();
                    
                    // Debounce search for performance
                    clearTimeout(searchTimeout);
                    searchTimeout = setTimeout(() => {
                        tableRows.forEach(row => {
                            const rowText = row.textContent.toLowerCase();
                            if (searchTerm === '' || rowText.includes(searchTerm)) {
                                row.style.display = '';
                            } else {
                                row.style.display = 'none';
                            }
                        });
                        
                        // Update visible count
                        const visibleRows = Array.from(tableRows).filter(row => row.style.display !== 'none');
                        console.log(`Showing ${visibleRows.length} of ${tableRows.length} logs`);
                    }, 300);
                });
            }
        });
    </script>
</body>
</html> 