<!DOCTYPE html>
<html lang="tr">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>{{ _('devices') }} - iAccess Terminal</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.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: #667eea;
            --secondary-color: #764ba2;
            --success-color: #28a745;
            --warning-color: #ffc107;
            --danger-color: #dc3545;
            --info-color: #17a2b8;
            --dark-color: #343a40;
            --light-color: #f8f9fa;
        }

        body {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
        }

        .navbar {
            background: rgba(255, 255, 255, 0.95) !important;
            backdrop-filter: blur(10px);
            box-shadow: 0 2px 20px rgba(0, 0, 0, 0.1);
        }

        .navbar-brand {
            font-weight: 700;
            color: var(--primary-color) !important;
        }

        .nav-link {
            color: var(--dark-color) !important;
            font-weight: 500;
            transition: all 0.3s ease;
        }

        .nav-link:hover {
            color: var(--primary-color) !important;
            transform: translateY(-1px);
        }

        .main-container {
            margin-top: 80px;
            padding: 20px;
        }

        .devices-card {
            background: rgba(255, 255, 255, 0.95);
            border-radius: 20px;
            box-shadow: 0 15px 35px rgba(0, 0, 0, 0.1);
            backdrop-filter: blur(10px);
            border: 1px solid rgba(255, 255, 255, 0.2);
            overflow: hidden;
        }

        .card-header-modern {
            background: linear-gradient(135deg, var(--primary-color), var(--secondary-color));
            color: white;
            padding: 25px 30px;
            border: none;
        }

        .card-header-modern h2 {
            margin: 0;
            font-size: 1.8rem;
            font-weight: 700;
        }

        .card-body-modern {
            padding: 30px;
        }

        .status-indicator {
            width: 12px;
            height: 12px;
            border-radius: 50%;
            display: inline-block;
            margin-right: 8px;
            box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
        }

        .status-connected { 
            background-color: var(--success-color);
            animation: pulse 2s infinite;
        }

        .status-disconnected { 
            background-color: var(--danger-color);
        }

        .status-unknown { 
            background-color: #6c757d;
        }

        @keyframes pulse {
            0% { opacity: 1; }
            50% { opacity: 0.7; }
            100% { opacity: 1; }
        }

        .table-modern {
            border-radius: 15px;
            overflow: hidden;
            box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);
        }

        .table-modern thead th {
            background: linear-gradient(135deg, var(--primary-color), var(--secondary-color));
            color: white;
            border: none;
            font-weight: 600;
            padding: 15px;
            text-transform: none;
            letter-spacing: 0.5px;
            font-size: 0.9rem;
        }

        .table-modern tbody tr {
            transition: all 0.3s ease;
            border-bottom: 1px solid #e9ecef;
        }

        .table-modern tbody tr:hover {
            background-color: rgba(102, 126, 234, 0.1);
            transform: scale(1.01);
        }

        .table-modern tbody td {
            padding: 15px;
            vertical-align: middle;
            border: none;
        }

        .btn-modern {
            border-radius: 10px;
            padding: 8px 16px;
            font-weight: 600;
            font-size: 0.85rem;
            transition: all 0.3s ease;
            border: none;
            text-transform: none;
            letter-spacing: 0.5px;
        }

        .btn-modern:hover {
            transform: translateY(-2px);
            box-shadow: 0 5px 15px rgba(0, 0, 0, 0.2);
        }

        .btn-success-modern {
            background: linear-gradient(135deg, var(--success-color), #20c997);
            color: white;
        }

        .btn-danger-modern {
            background: linear-gradient(135deg, var(--danger-color), #e74c3c);
            color: white;
        }

        .btn-primary-modern {
            background: linear-gradient(135deg, var(--primary-color), var(--secondary-color));
            color: white;
        }

        .btn-warning-modern {
            background: linear-gradient(135deg, var(--warning-color), #fd7e14);
            color: white;
        }

        .btn-info-modern {
            background: linear-gradient(135deg, var(--info-color), #0dcaf0);
            color: white;
        }

        .btn-secondary-modern {
            background: linear-gradient(135deg, #6c757d, #5a6268);
            color: white;
        }

        .btn-secondary-modern:hover {
            background: linear-gradient(135deg, #5a6268, #495057);
            color: white;
        }

        .btn-group .btn {
            margin: 0;
            border-radius: 0;
        }

        .btn-group .btn:first-child {
            border-radius: 8px 0 0 8px;
        }

        .btn-group .btn:last-child {
            border-radius: 0 8px 8px 0;
        }

        .btn-group .btn:only-child {
            border-radius: 8px;
        }

        .btn-group {
            box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
        }

        .status-badge {
            padding: 6px 12px;
            border-radius: 20px;
            font-size: 0.8rem;
            font-weight: 600;
            text-transform: none;
        }

        .status-badge.connected {
            background: rgba(40, 167, 69, 0.1);
            color: var(--success-color);
        }

        .status-badge.disconnected {
            background: rgba(220, 53, 69, 0.1);
            color: var(--danger-color);
        }

        .status-badge.unknown {
            background: rgba(108, 117, 125, 0.1);
            color: #6c757d;
        }

        .server-status-card {
            background: linear-gradient(135deg, rgba(102, 126, 234, 0.1), rgba(118, 75, 162, 0.1));
            border: 1px solid rgba(102, 126, 234, 0.2);
            border-radius: 15px;
            padding: 20px;
            margin-bottom: 25px;
        }

        .server-status-card h6 {
            color: var(--primary-color);
            font-weight: 600;
            margin-bottom: 15px;
            display: flex;
            align-items: center;
        }

        .server-status-card h6 i {
            margin-right: 8px;
        }

        .status-item {
            display: flex;
            align-items: center;
            margin-bottom: 10px;
        }

        .status-item:last-child {
            margin-bottom: 0;
        }

        .status-label {
            font-weight: 600;
            color: var(--dark-color);
            margin-right: 10px;
            min-width: 120px;
        }

        .status-value {
            background: rgba(255, 255, 255, 0.8);
            padding: 4px 12px;
            border-radius: 20px;
            font-size: 0.85rem;
            font-weight: 600;
        }

        .floating-action-btn {
            position: fixed;
            bottom: 30px;
            right: 30px;
            z-index: 1000;
            border-radius: 50%;
            width: 60px;
            height: 60px;
            background: linear-gradient(135deg, var(--success-color), #20c997);
            color: white;
            border: none;
            box-shadow: 0 5px 20px rgba(40, 167, 69, 0.4);
            transition: all 0.3s ease;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 1.5rem;
            text-decoration: none !important;
        }

        .floating-action-btn:hover {
            transform: scale(1.1);
            box-shadow: 0 8px 25px rgba(40, 167, 69, 0.6);
            color: white;
        }

        .modal-modern .modal-content {
            border-radius: 20px;
            border: none;
            box-shadow: 0 15px 35px rgba(0, 0, 0, 0.2);
        }

        .modal-modern .modal-header {
            background: linear-gradient(135deg, var(--primary-color), var(--secondary-color));
            color: white;
            border-radius: 20px 20px 0 0;
            border: none;
        }

        .modal-modern .modal-title {
            font-weight: 600;
        }

        .modal-modern .modal-body {
            padding: 30px;
        }

        .form-control-modern {
            border-radius: 12px;
            border: 2px solid #e9ecef;
            padding: 12px 15px;
            transition: all 0.3s ease;
        }

        .form-control-modern:focus {
            border-color: var(--primary-color);
            box-shadow: 0 0 0 0.2rem rgba(102, 126, 234, 0.25);
        }

        @media (max-width: 768px) {
            .main-container {
                margin-top: 60px;
                padding: 10px;
            }
            
            .card-body-modern {
                padding: 20px;
            }
            
            .card-header-modern {
                padding: 20px;
            }
            
            .card-header-modern h2 {
                font-size: 1.5rem;
            }
            
            .table-modern {
                font-size: 0.9rem;
            }
            
            .floating-action-btn {
                bottom: 20px;
                right: 20px;
                width: 50px;
                height: 50px;
                font-size: 1.2rem;
            }
        }
    </style>
</head>
<body>
    <!-- Navigation -->
    <nav class="navbar navbar-expand-lg fixed-top">
        <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>
            
            <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNav">
                <span class="navbar-toggler-icon"></span>
            </button>
            
            <div class="collapse navbar-collapse" id="navbarNav">
                <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_title') }}
                        </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 %}
                                {% if user.profile_image.startswith('@') %}
                                  {% set imgfile = user.profile_image[1:] %}
                                  <img src="{{ url_for('static', filename='uploads/' + imgfile) }}" 
                                {% else %}
                                  <img src="{{ url_for('static', filename='uploads/' + user.profile_image) }}" 
                                {% endif %}
                                      alt="Profil Resmi" class="rounded-circle me-2" width="32" height="32" style="object-fit: cover;">
                            {% else %}
                                <img src="{{ url_for('static', filename='img/default-avatar.png') }}" 
                                    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>

    <!-- Main Content -->
    <div class="main-container">
        <div class="container">
            <div class="devices-card">
                <div class="card-header-modern">
                    <div class="d-flex justify-content-between align-items-center">
                        <h2><i class="fas fa-microchip me-2"></i>{{ _('devices') }}</h2>
            <div>
                            <a href="{{ url_for('home') }}" class="btn btn-secondary-modern btn-modern">
                                <i class="fas fa-arrow-left me-1"></i>{{ _('back') }}
                </a>
                        </div>
            </div>
        </div>
        
                <div class="card-body-modern">
                    <!-- Search Filter -->
                    <div class="row mb-4">
                        <div class="col-md-6">
                            <div class="input-group">
                                <span class="input-group-text">
                                    <i class="fas fa-search"></i>
                                </span>
                                <input type="text" class="form-control" id="searchFilter" placeholder="{{ _('device_search_placeholder') }}">
                            </div>
                        </div>
                        <div class="col-md-6 text-end">
                            <button class="btn btn-secondary-modern btn-modern" onclick="clearFilter()">
                                <i class="fas fa-times me-1"></i>{{ _('clear') }}
            </button>
                        </div>
        </div>
        
                    <!-- Devices Table -->
                    <div class="table-responsive">
                        <table class="table table-modern">
                            <thead>
                <tr>
                    <th>{{ _('device_serial') }}</th>
                    <th>{{ _('device_name') }}</th>
                    <th>{{ _('firmware') }}</th>
                    <th>{{ _('device_ip') }}</th>
                    <th>{{ _('connection_status') }}</th>
                    <th>{{ current_language == 'tr' and 'Kripto Haberleşme' or 'Crypto Communication' }}</th>
                    <th>{{ current_language == 'tr' and 'Son Yanıt' or 'Last Response' }}</th>
                    <th class="text-center">{{ _('actions') }}</th>
                </tr>
            </thead>
            <tbody>
                {% for cihaz in cihazlar %}
                <tr data-device-id="{{ cihaz.id }}" style="cursor: pointer;">
                    <td>
                        <code>{{ cihaz.seri_no if cihaz.seri_no else cihaz.id }}</code>
                    </td>
                    <td>{{ cihaz.ad if cihaz.ad else (cihaz.device_name if cihaz.device_name else '') }}</td>
                    <td>
                        <span class="badge bg-primary">{{ cihaz.firmware_version if cihaz.firmware_version else 'N/A' }}</span>
                    </td>
                    <td>
                        {% if cihaz.is_connected and cihaz.id in connected_device_ips %}
                            <code class="text-success">{{ connected_device_ips[cihaz.id] }}</code>
                            <small class="text-muted d-block">({{ _('connected') }})</small>
                        {% elif cihaz.ip_adresi or cihaz.ip_address %}
                            <code>{{ cihaz.ip_adresi if cihaz.ip_adresi else cihaz.ip_address }}</code>
                        {% elif cihaz.device_id in connected_device_ips %}
                            <code class="text-success">{{ connected_device_ips[cihaz.device_id] }}</code>
                            <small class="text-muted d-block">({{ _('connected') }})</small>
                        {% else %}
                            <span class="text-muted">-</span>
                        {% endif %}
                    </td>
                    <td>
                        <div class="d-flex align-items-center">
                            <span class="status-indicator {% if cihaz.is_connected %}status-connected{% else %}status-disconnected{% endif %}" id="status-{{ cihaz.id|string }}"></span>
                            <span class="status-badge {% if cihaz.is_connected %}connected{% else %}disconnected{% endif %}" id="status-text-{{ cihaz.id|string }}">
                                {% if cihaz.is_connected %}{{ _('connected') }}{% else %}{{ _('disconnected') }}{% endif %}
                            </span>
                        </div>
                    </td>
                    <td>
                        {% if cihaz.last_response_time %}
                            <div class="d-flex flex-column">
                                <small class="text-muted" style="font-family: 'Courier New', monospace; font-size: 0.75rem;">
                                    <i class="fas fa-clock me-1"></i>{{ cihaz.last_response_time }}
                                </small>
                                {% if cihaz.response_age_minutes is defined %}
                                    <small class="{% if cihaz.response_age_minutes < 5 %}text-success{% elif cihaz.response_age_minutes < 15 %}text-warning{% else %}text-danger{% endif %}" style="font-size: 0.7rem;">
                                        {% if cihaz.response_age_minutes < 1 %}
                                            {{ current_language == 'tr' and 'Az önce' or 'Just now' }}
                                        {% elif cihaz.response_age_minutes < 60 %}
                                            {{ cihaz.response_age_minutes }} {{ current_language == 'tr' and 'dk önce' or 'min ago' }}
                                        {% else %}
                                            {{ (cihaz.response_age_minutes / 60)|round|int }} {{ current_language == 'tr' and 'saat önce' or 'hr ago' }}
                                        {% endif %}
                                    </small>
                                {% endif %}
                            </div>
                        {% else %}
                            <small class="text-muted">
                                <i class="fas fa-question-circle me-1"></i>{{ current_language == 'tr' and 'Bilinmiyor' or 'Unknown' }}
                            </small>
                        {% endif %}
                    </td>
                    <td class="text-center">
                        <div class="btn-group" role="group" aria-label="Device actions">
                            <button class="btn btn-success-modern btn-modern btn-sm" onclick="event.stopPropagation(); toggleAC('{{ cihaz.id }}')" title="{{ _('open_gate') }}">
                                <i class="fas fa-door-open"></i>
                            </button>
                            <a href="{{ url_for('device_settings', device_id=cihaz.id) }}" class="btn btn-warning-modern btn-modern btn-sm" onclick="event.stopPropagation();" title="{{ _('device_settings') }}">
                                <i class="fas fa-cog"></i>
                            </a>
                            <a href="{{ url_for('edit_user_device', device_id=cihaz.id) }}" class="btn btn-info-modern btn-modern btn-sm" onclick="event.stopPropagation();" title="{{ _('edit') }}">
                                <i class="fas fa-edit"></i>
                            </a>
                            <a href="{{ url_for('device_cards_page', device_id=cihaz.id) }}" class="btn btn-secondary-modern btn-modern btn-sm" onclick="event.stopPropagation();" title="RFID">
                                <i class="fas fa-id-card"></i>
                            </a>
                            <a href="{{ url_for('device_logs', device_id=cihaz.id) }}" class="btn btn-secondary-modern btn-modern btn-sm" onclick="event.stopPropagation();" title="Logs">
                                <i class="fas fa-file-alt"></i>
                            </a>
                            <button class="btn btn-success-modern btn-modern btn-sm" onclick="event.stopPropagation(); syncDeviceTime('{{ cihaz.id }}')" title="{{ _('rtc_datetime') }}">
                                <i class="fas fa-clock"></i>
                            </button>
                            {% if is_admin %}
                            <button class="btn btn-danger-modern btn-modern btn-sm" onclick="event.stopPropagation(); deleteDevice('{{ cihaz.id }}', '{{ cihaz.ad }}')" title="{{ _('delete_device') }}">
                                <i class="fas fa-trash"></i>
                            </button>
                            {% endif %}
                        </div>
                    </td>
                </tr>
                {% endfor %}
            </tbody>
        </table>
    </div>
</div>
            </div>
        </div>
    </div>

    <!-- Floating Action Button -->
    <a href="{{ url_for('cihaz_ekle') }}" class="floating-action-btn" title="{{ _('add_device') }}">
        <i class="fas fa-plus"></i>
    </a>


    <!-- Message Modal -->
    <div class="modal fade modal-modern" id="messageModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                    <h5 class="modal-title"><i class="fas fa-paper-plane me-2"></i>{{ _('send_message_to_device') }}</h5>
                    <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <form id="messageForm">
                    <div class="mb-3">
                            <label for="messageText" class="form-label">{{ _('message') }}:</label>
                            <textarea class="form-control form-control-modern" id="messageText" rows="4" 
                                      placeholder="{{ _('message_placeholder') }}"></textarea>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                    <button type="button" class="btn btn-secondary-modern btn-modern" data-bs-dismiss="modal">
                        <i class="fas fa-times me-1"></i>{{ _('cancel') }}
                    </button>
                    <button type="button" class="btn btn-primary-modern btn-modern" id="sendMessageBtn">
                        <i class="fas fa-paper-plane me-1"></i>{{ _('send') }}
                    </button>
            </div>
        </div>
    </div>
</div>

    <!-- Info Modal -->
    <div class="modal fade modal-modern" id="deviceInfoModal" tabindex="-1">
      <div class="modal-dialog">
        <div class="modal-content">
          <div class="modal-header">
            <h5 class="modal-title"><i class="fas fa-info-circle me-2"></i>Cihaz Bilgisi</h5>
            <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
          </div>
          <div class="modal-body">
            <div id="deviceInfoContent">{{ _('loading') }}</div>
          </div>
          <div class="modal-footer">
            <button type="button" class="btn btn-secondary-modern btn-modern" data-bs-dismiss="modal">{{ _('close') if _('close') else 'Close' }}</button>
          </div>
        </div>
      </div>
    </div>

    <!-- Device Logs Modal -->
    <div class="modal fade" id="deviceLogsModal" tabindex="-1" aria-labelledby="deviceLogsModalLabel" aria-hidden="true">
      <div class="modal-dialog modal-xl modal-dialog-scrollable">
        <div class="modal-content">
          <div class="modal-header">
            <h5 class="modal-title" id="deviceLogsModalLabel">Device Logs</h5>
            <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
          </div>
          <div class="modal-body">
            <div id="deviceLogsContent">
              <div class="text-center text-muted"><i class="fas fa-spinner fa-spin me-2"></i>Loading...</div>
            </div>
          </div>
          <div class="modal-footer">
            <button type="button" class="btn btn-secondary-modern btn-modern" data-bs-dismiss="modal">{{ _('close') or 'Close' }}</button>
          </div>
        </div>
      </div>
    </div>


    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>
    <script>
    // Kullanıcı UUID'sini template'den al
    const userUUID = '{{ user.user_uuid if user and user.user_uuid else "" }}';
    let currentDeviceId = null;
    let cardsModal = null;

// Satır tıklama ile popup cihaz bilgisi göster
function goToDetails(deviceId) {
    showDeviceInfo(deviceId);
}


// Turnikeyi Aç - Erişim Ver fonksiyonu - Hiçbir şekilde bloklanmaz
function toggleAC(deviceId) {
    // Sunucu tarafında admin UUID ile log + grantaccess yapılır
    fetch('/api/admin/open-device', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ device_id: deviceId })
    }).then(()=>{}).catch(()=>{});
}

// Cihaz düzenleme fonksiyonu
function editDevice(deviceId) {
    // edit_user_device sayfasına yönlendir
    window.location.href = '/device/edit/user/' + deviceId;
}

// Cihaz silme fonksiyonu
function deleteDevice(deviceId, deviceName) {
    if (confirm('Cihazı silmek istediğinizden emin misiniz?\n\nCihaz: ' + deviceName + '\nID: ' + deviceId + '\n\nBu işlem geri alınamaz!')) {
        window.location.href = '/device/delete/' + deviceId;
    }
}

// Arama filtresi
document.getElementById('searchFilter').addEventListener('input', function() {
    const searchTerm = this.value.toLowerCase();
    const rows = document.querySelectorAll('tbody tr');
    
    rows.forEach(row => {
        const text = row.textContent.toLowerCase();
        if (text.includes(searchTerm)) {
            row.style.display = '';
                } else {
            row.style.display = 'none';
        }
    });
});

// Filtreyi temizle
function clearFilter() {
    document.getElementById('searchFilter').value = '';
    const rows = document.querySelectorAll('tbody tr');
    rows.forEach(row => {
        row.style.display = '';
    });
}

// Manuel durum güncelleme fonksiyonu
function forceUpdateStatus() {
    updateAllDeviceStatuses();
}

// Mesaj gönderme
document.getElementById('sendMessageBtn').addEventListener('click', function() {
    const message = document.getElementById('messageText').value.trim();
    if (!message) {
                alert('{{ _("please_enter_message") }}');
        return;
    }
    
    if (!currentDeviceId) {
                alert('{{ _("device_id_not_found") }}');
        return;
    }
    
    const form = document.createElement('form');
    form.method = 'POST';
    form.action = `/device/send/${currentDeviceId}`;
    
    const messageInput = document.createElement('input');
    messageInput.type = 'hidden';
    messageInput.name = 'message';
    messageInput.value = message;
    
    form.appendChild(messageInput);
    document.body.appendChild(form);
    form.submit();
    
    messageModal.hide();
    document.getElementById('messageText').value = '';
});

// Gerçek zamanlı cihaz durumu kontrolü
function updateAllDeviceStatuses() {
    const deviceRows = document.querySelectorAll('[data-device-id]');
    
    deviceRows.forEach(row => {
        const deviceId = row.getAttribute('data-device-id');
        // Satır klik ile popup aç
        row.addEventListener('click', () => goToDetails(deviceId));
        const statusIndicator = row.querySelector('.status-indicator');
        const statusText = row.querySelector('.status-text');
        
        if (deviceId && statusIndicator && statusText) {
            fetch(`/api/device/status/${deviceId}`)
                .then(response => response.json())
                .then(data => {
                    if (data.connected) {
                        statusIndicator.className = 'status-indicator status-connected';
                        statusText.textContent = '{{ _("connected") }}';
                        statusText.className = 'status-badge connected';
                    } else {
                        statusIndicator.className = 'status-indicator status-disconnected';
                        statusText.textContent = '{{ _("disconnected") }}';
                        statusText.className = 'status-badge disconnected';
                    }
                })
                .catch(error => {
                    console.error('Cihaz durumu kontrol hatası:', error);
                    statusIndicator.className = 'status-indicator status-unknown';
                    statusText.textContent = '{{ _("unknown") }}';
                    statusText.className = 'status-badge unknown';
                });
        }
    });
}

// Her 5 saniyede bir cihaz durumlarını güncelle
setInterval(updateAllDeviceStatuses, 5000);

// Sayfa yüklendiğinde ilk kontrolü yap
document.addEventListener('DOMContentLoaded', function() {
    updateAllDeviceStatuses();
});

// Cihaz bilgi modalını göster
async function showDeviceInfo(deviceId) {
    try {
        const resp = await fetch(`/api/deviceinfo/${deviceId}`);
        const data = await resp.json();
        const container = document.getElementById('deviceInfoContent');
        if (!data.success || !data.info) {
            container.innerHTML = `<div class="alert alert-danger">{{ _('loading_error') }}</div>`;
        } else {
            const info = data.info;
            const dd = info.device_data || {};
            const di = info.device_info || {};
            // Ağ: ETH ve WiFi durumları (dhcp alanları dizi olarak gelebilir)
            const ethDhcpArr = Array.isArray(dd.ethdhcp) ? dd.ethdhcp : null;
            const ethStaticArr = Array.isArray(dd.ethstatic) ? dd.ethstatic : null;
            const wifiDhcpArr = Array.isArray(dd.wifidhcp) ? dd.wifidhcp : null;
            const wifiStaticArr = Array.isArray(dd.wifistatic) ? dd.wifistatic : null;

            const ethMode = ethDhcpArr ? 'DHCP' : (ethStaticArr ? 'Static' : '-');
            const wifiMode = wifiDhcpArr ? 'DHCP' : (wifiStaticArr ? 'Static' : '-');

            const ethIp = ethDhcpArr ? (ethDhcpArr[0] || '-') : (ethStaticArr ? (ethStaticArr[0] || '-') : (di.ip_address || '-'));
            const ethMask = ethDhcpArr ? (ethDhcpArr[2] || '-') : (ethStaticArr ? (ethStaticArr[1] || '-') : '-');
            const ethGw = ethDhcpArr ? (ethDhcpArr[1] || '-') : (ethStaticArr ? (ethStaticArr[2] || '-') : '-');
            const ethDns = ethDhcpArr ? (ethDhcpArr[3] || '-') : (ethStaticArr ? (ethStaticArr[3] || '-') : '-');

            const wifiIp = wifiDhcpArr ? (wifiDhcpArr[0] || '-') : (wifiStaticArr ? (wifiStaticArr[0] || '-') : '-');
            const wifiMask = wifiDhcpArr ? (wifiDhcpArr[2] || '-') : (wifiStaticArr ? (wifiStaticArr[1] || '-') : '-');
            const wifiGw = wifiDhcpArr ? (wifiDhcpArr[1] || '-') : (wifiStaticArr ? (wifiStaticArr[2] || '-') : '-');
            const wifiDns = wifiDhcpArr ? (wifiDhcpArr[3] || '-') : (wifiStaticArr ? (wifiStaticArr[3] || '-') : '-');

            // RS485
            const rs485 = dd.rs485Baudrate || dd.rs485baud || '-';
            // Bellek (heapfree)
            const heapFree = dd.heapfree !== undefined ? dd.heapfree : (dd.data && dd.data.heapfree !== undefined ? dd.data.heapfree : '-');
            // Cihaz hata kodları (bitmask)
            const devErrRaw = (dd.deviceErrors !== undefined) ? dd.deviceErrors : ((dd.deviceerrors !== undefined) ? dd.deviceerrors : (dd.data && dd.data.deviceErrors !== undefined ? dd.data.deviceErrors : 0));
            const devErrVal = (typeof devErrRaw === 'string') ? (devErrRaw.trim().toLowerCase().startsWith('0x') ? parseInt(devErrRaw, 16) : parseInt(devErrRaw, 10)) : (parseInt(devErrRaw || 0, 10));
            // Terminal modu
            const term = (dd.isTerminal === true) ? 'Yes' : (dd.isTerminal === false ? 'No' : '-');
            // Saat
            const ts = dd.timestamp || di.last_update || '-';
            // Firmware
            const fw = di.firmware_version || dd.version || 'N/A';
            // Remote target
            const remote = dd.remotetarget || (dd.data && dd.data.remotetarget) || '-';
            // Log bilgileri
            const logSize = (dd.logSize !== undefined) ? dd.logSize : ((dd.logsize !== undefined) ? dd.logsize : ((dd.data && (dd.data.logSize !== undefined || dd.data.logsize !== undefined)) ? (dd.data.logSize ?? dd.data.logsize) : '-'));
            const logFileSizeBytesRaw = (dd.logFileSize !== undefined) ? dd.logFileSize : ((dd.logfilesize !== undefined) ? dd.logfilesize : ((dd.data && (dd.data.logFileSize !== undefined || dd.data.logfilesize !== undefined)) ? (dd.data.logFileSize ?? dd.data.logfilesize) : null));
            let logFileSizeDisplay = '-';
            if (logFileSizeBytesRaw !== null && logFileSizeBytesRaw !== undefined) {
                const bytesNum = (typeof logFileSizeBytesRaw === 'number') ? logFileSizeBytesRaw : parseFloat(logFileSizeBytesRaw);
                if (!isNaN(bytesNum)) {
                    logFileSizeDisplay = (bytesNum / 1024).toFixed(3) + ' KB';
                }
            }
            container.innerHTML = `
              <ul class="list-group">
                <li class="list-group-item d-flex justify-content-between"><span>Device ID</span><strong>${di.device_id || deviceId}</strong></li>
                <li class="list-group-item d-flex justify-content-between"><span>Firmware</span><strong>${fw}</strong></li>
                <li class="list-group-item"><strong>Ethernet</strong><div class="mt-1 small">Mode: <b>${ethMode}</b>${ethMode!=='-' ? `, IP: <code>${ethIp}</code>, Netmask: <code>${ethMask}</code>, GW: <code>${ethGw}</code>, DNS: <code>${ethDns}</code>` : ''}</div></li>
                <li class="list-group-item"><strong>WiFi</strong><div class="mt-1 small">Mode: <b>${wifiMode}</b>${wifiMode!=='-' ? `, IP: <code>${wifiIp}</code>, Netmask: <code>${wifiMask}</code>, GW: <code>${wifiGw}</code>, DNS: <code>${wifiDns}</code>` : ''}</div></li>
                <li class="list-group-item">
                  <strong>{{ _('device_errors') }}</strong>
                  <div class="mt-1 small" id="deviceErrorsList"></div>
                </li>
                <li class="list-group-item d-flex justify-content-between"><span>RS485 Baudrate</span><strong>${rs485}</strong></li>
                <li class="list-group-item d-flex justify-content-between"><span>Free Heap</span><strong>${heapFree}</strong></li>
                <li class="list-group-item d-flex justify-content-between"><span>Log Size</span><strong>${logSize}</strong></li>
                <li class="list-group-item d-flex justify-content-between"><span>Log File Size</span><strong>${logFileSizeDisplay}</strong></li>
                <li class="list-group-item d-flex justify-content-between"><span>Terminal Mode</span><strong>${term}</strong></li>
                <li class="list-group-item d-flex justify-content-between"><span>Device Time</span><strong>${ts}</strong></li>
                <li class="list-group-item d-flex justify-content-between"><span>Remote Target</span><strong>${remote}</strong></li>
              </ul>`;
 
                 const ERRORS = [
                   {mask: 0x01, key: 'device_error_rfid'},
                   {mask: 0x02, key: 'device_error_i2crtcperipheral'},
                   {mask: 0x04, key: 'device_error_rtcclockwrong'},
                   {mask: 0x08, key: 'device_error_uart'},
                   {mask: 0x10, key: 'device_error_alarm_standart'},
                   {mask: 0x20, key: 'device_error_log_unsuf'},
                   {mask: 0x40, key: 'device_error_parameter_error'},
                   {mask: 0x80, key: 'device_error_ethernet'},
                   {mask: 0x100, key: 'device_error_backup'}
                 ];
                 const ERR_LABELS = {
                   'device_error_rfid': "{{ _('device_error_rfid') }}",
                   'device_error_i2crtcperipheral': "{{ _('device_error_i2crtcperipheral') }}",
                   'device_error_rtcclockwrong': "{{ _('device_error_rtcclockwrong') }}",
                   'device_error_uart': "{{ _('device_error_uart') }}",
                   'device_error_alarm_standart': "{{ _('device_error_alarm_standart') }}",
                   'device_error_log_unsuf': "{{ _('device_error_log_unsuf') }}",
                   'device_error_parameter_error': "{{ _('device_error_parameter_error') }}",
                   'device_error_ethernet': "{{ _('device_error_ethernet') }}",
                   'device_error_backup': "{{ _('device_error_backup') }}"
                 };
                 function decodeErrors(val) {
                   if (!val || isNaN(val) || val <= 0) return "{{ _('no_errors') }}";
                   const active = ERRORS.filter(e => (val & e.mask) !== 0).map(e => ERR_LABELS[e.key]);
                                       return active.length ? active.map(t => `• ${t}`).join('<br>') : "{{ _('no_errors') }}";
                 }
                 // İlk gösterim
                 document.getElementById('deviceErrorsList').innerHTML = decodeErrors(devErrVal);
         }
         const modal = new bootstrap.Modal(document.getElementById('deviceInfoModal'));
         modal.show();
     } catch (e) {
         document.getElementById('deviceInfoContent').innerHTML = `<div class=\"alert alert-danger\">${e}</div>`;
         const modal = new bootstrap.Modal(document.getElementById('deviceInfoModal'));
         modal.show();
     }
 }
 
 // Cihaz loglarını göster (readlog ile cihazdan al)
 async function showDeviceLogs(deviceId) {
   try {
     const modalEl = document.getElementById('deviceLogsModal');
     const modal = new bootstrap.Modal(modalEl);
     document.getElementById('deviceLogsModalLabel').textContent = `Device Logs - ${deviceId}`;
     const content = document.getElementById('deviceLogsContent');
     content.innerHTML = '<div class="text-center text-muted"><i class="fas fa-spinner fa-spin me-2"></i>Loading...</div>';
     modal.show();
     const resp = await fetch(`/api/device_readlog/${encodeURIComponent(deviceId)}`, { method: 'POST' });
     const data = await resp.json();
     if (!data.success) {
       content.innerHTML = `<div class="alert alert-danger">${data.message || 'Error'}</div>`;
       return;
     }
     const entries = Array.isArray(data.entries) ? data.entries : [];
     if (entries.length > 0) {
       // access_logs görünümüne benzer tablo
       let html = '<div class="table-responsive"><table class="table table-modern align-middle"><thead><tr>'+
                  '<th>#</th><th>{{ _("device_name") or "Device" }}</th><th>UUID</th><th>{{ _("access_type") or "Type" }}</th><th>{{ _("status") or "Status" }}</th><th>{{ _("time") or "Time" }}</th></tr></thead><tbody>';
       entries.forEach((e, idx) => {
         const granted = (e.isgranted === 1 || e.isgranted === true);
         const statusBadge = granted ? '<span class="badge bg-success">{{ _("IZIN_VERILDI") or "Granted" }}</span>' : '<span class="badge bg-danger">{{ _("IZIN_VERILMEDI") or "Denied" }}</span>';
         const atype = (e.type || '').toUpperCase();
         const termBadge = (e.isterminal === true ? '<span class="badge bg-secondary">TERM</span>' : (e.isterminal === false ? '<span class="badge bg-info">MOBILE</span>' : ''));
         html += `<tr>
           <td>${idx+1}</td>
           <td>${e.deviceid || ''}</td>
           <td><code>${e.uuid || ''}</code></td>
           <td><span class="badge bg-primary">${atype}</span> ${termBadge}</td>
           <td>${statusBadge}</td>
           <td>${e.timestamp || ''}</td>
         </tr>`;
       });
       html += '</tbody></table></div>';
       content.innerHTML = html;
     } else {
       // Kayıt bulunamadı: access logs tablo iskeletiyle boş durum
       let html = '<div class="table-responsive"><table class="table table-modern align-middle"><thead><tr>'+
                  '<th>#</th><th>{{ _("device_name") or "Device" }}</th><th>UUID</th><th>{{ _("access_type") or "Type" }}</th><th>{{ _("status") or "Status" }}</th><th>{{ _("time") or "Time" }}</th></tr></thead>'+
                  '<tbody><tr><td colspan="6" class="text-center text-muted py-4">{{ _("no_logs") or "No logs found" }}</td></tr></tbody></table></div>';
       content.innerHTML = html;
     }
   } catch (e) {
     const content = document.getElementById('deviceLogsContent');
     content.innerHTML = `<div class="alert alert-danger">Beklenmeyen hata</div>`;
   }
 }
 
 // Cihaz saatini bilgisayar saatine saniye hassasiyetinde eşitle
 async function syncDeviceTime(deviceId) {
   try {
     const now = new Date();
     const payload = {
       day: now.getDate(),
       month: now.getMonth() + 1,
       year: now.getFullYear() % 100,
       wday: now.getDay(),
       hour: now.getHours(),
       minute: now.getMinutes(),
       second: now.getSeconds()
     };
     const body = { command: 'setdatetime', data: payload };
     console.log('Sending setdatetime command:', body);
     const resp = await fetch(`/api/device_command/${deviceId}`, {
       method: 'POST',
       headers: { 'Content-Type': 'application/json' },
       body: JSON.stringify(body)
     });
     const data = await resp.json();
     if (!data.success) {
       alert('Saat eşitleme başarısız: ' + (data.message || 'Unknown error'));
       return;
     }
     alert('Saat eşitlendi');
   } catch (e) {
     console.error('syncDeviceTime error', e);
     alert('Saat eşitleme sırasında hata oluştu');
   }
 }
 </script>
 </body>
 </html> 