<!DOCTYPE html>
<html lang="{{ current_language }}">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>{{ _('users_title') }} - 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);
        }

        .nav-link.active {
            color: var(--primary-color) !important;
            background: rgba(102, 126, 234, 0.1) !important;
            border-radius: 8px;
        }

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

        .users-card {
            background: rgba(255, 255, 255, 0.95);
            backdrop-filter: blur(10px);
            border-radius: 20px;
            box-shadow: 0 20px 40px rgba(0, 0, 0, 0.1);
            border: none;
            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 {
            font-size: 1.8rem;
            font-weight: 700;
            margin: 0;
            text-shadow: 0 2px 4px rgba(0, 0, 0, 0.3);
        }

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

        .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-primary-modern {
            background: linear-gradient(135deg, var(--primary-color), var(--secondary-color));
            color: white;
        }

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

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

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

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

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

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

        .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: uppercase;
            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: 12px 14px;
            vertical-align: middle;
            border: none;
            white-space: nowrap;
        }

        .badge-modern {
            border-radius: 20px;
            padding: 4px 10px;
            font-weight: 600;
            font-size: 0.7rem;
            text-transform: uppercase;
            letter-spacing: 0.5px;
        }

        .empty-state {
            text-align: center;
            padding: 60px 30px;
            color: #6c757d;
        }

        .empty-state i {
            font-size: 4rem;
            margin-bottom: 20px;
            opacity: 0.5;
        }

        .progress-container {
            position: fixed;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            background: white;
            padding: 2rem;
            border-radius: 15px;
            box-shadow: 0 20px 40px rgba(0,0,0,0.3);
            z-index: 1000;
            display: none;
            min-width: 300px;
        }

        .progress-overlay {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0,0,0,0.5);
            z-index: 1040;
            display: none;
        }
        

        .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;
            }
        }
    </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" href="{{ url_for('devices') }}">
                            <i class="fas fa-microchip me-1"></i>{{ _('devices') }}
                        </a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link active" 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-list-alt 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 current_user and current_user.profile_image %}
                                {% if current_user.profile_image[0] == '@' %}
                                    {% set imgfile = current_user.profile_image[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/' + current_user.profile_image) }}?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 align-items-start">
                                <span class="fw-bold">{{ user_name }}</span>
                                {% if current_user and current_user.company %}
                                  <small class="text-muted">{{ current_user.company }}</small>
                                {% endif %}
                            </div>
                        </a>
                        <ul class="dropdown-menu">
                            <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="users-card">
                <div class="card-header-modern">
                    <div class="d-flex justify-content-between align-items-center">
                        <h2><i class="fas fa-users me-2"></i>{{ _('users_title') }}</h2>
                        <div>
                            <a href="{{ url_for('add_user') }}" class="btn btn-success-modern btn-modern me-2">
                                <i class="fas fa-user-plus me-2"></i>{{ _('user_add') or 'Kullanıcı Ekle' }}
                            </a>
                            <button id="formatCardsBtn" class="btn btn-danger-modern btn-modern me-2" onclick="formatCards()">
                                <i class="fas fa-trash me-2"></i>{{ _('delete_users') or 'Kullanıcıları Sil' }}
                            </button>
                            <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">
                            <form method="get" class="input-group">
                                <span class="input-group-text"><i class="fas fa-search"></i></span>
                                <input type="text" class="form-control" name="q" value="{{ request.args.get('q','') }}" placeholder="{{ _('user_search_placeholder') or 'Kullanıcı ara (ad, email, şirket...)' }}">
                                {% if request.args.get('page') %}
                                <input type="hidden" name="page" value="1">
                                {% endif %}
                                <button class="btn btn-primary-modern" type="submit">{{ _('filter') or 'Ara' }}</button>
                            </form>
                        </div>
                        <div class="col-md-6 text-end">
                            <button class="btn btn-secondary-modern btn-modern" onclick="clearUserFilter()">
                                <i class="fas fa-times me-1"></i>{{ _('clear_filter') or 'Temizle' }}
                            </button>
                        </div>
                    </div>
                    
                    <!-- Users Table -->
                    <div class="table-responsive">
                        <table class="table table-modern">
                            <thead>
                                <tr>
                                    <th>#</th>
                                    <th>{{ _('users_fullname') or 'Ad Soyad' }}</th>
                                    <th>{{ _('email') or 'E-posta' }}</th>
                                    <th>{{ _('company') or 'Şirket' }}</th>
                                    <th>{{ _('user_type') or 'Kullanıcı Tipi' }}</th>
                                    <th>{{ _('access_methods') or 'Erişim Yöntemleri' }}</th>
                                    <th>{{ _('authorized_devices') or 'Yetkili Cihazlar' }}</th>
                                    <th>{{ _('status') or 'Durum' }}</th>
                                    <th class="text-end">{{ _('actions') or 'İşlemler' }}</th>
                                </tr>
                            </thead>
                            <tbody id="usersTableBody">
                                {% for user in users %}
                                <tr data-user-id="{{ user.id }}" style="cursor: pointer;" onclick="window.location.href='{{ url_for('user_detail', user_id=user.id) }}'; return false;">
                                    <td>{{ loop.index }}</td>
                                    <td>
                                        <div class="d-flex align-items-center">
                                            {% if user.profile_image %}
                                                {% if user.profile_image[0] == '@' %}
                                                    {% set imgfile = user.profile_image[1:] %}
                                                    <img src="{{ url_for('static', filename='img/' + imgfile) }}" 
                                                         alt="Avatar" class="rounded-circle me-2" 
                                                         style="width: 40px; height: 40px; object-fit: cover;">
                                                {% else %}
                                                    <img src="{{ url_for('static', filename='uploads/' + user.profile_image) }}" 
                                                         alt="Avatar" class="rounded-circle me-2" 
                                                         style="width: 40px; height: 40px; object-fit: cover;">
                                                {% endif %}
                                            {% else %}
                                                <img src="{{ url_for('static', filename='img/default-avatar.png') }}" 
                                                     alt="Avatar" class="rounded-circle me-2" 
                                                     style="width: 40px; height: 40px; object-fit: cover;">
                                            {% endif %}
                                            <div>
                                                <strong>{{ user.full_name or '-' }}</strong>
                                                {% if user.phone %}
                                                    <br><small class="text-muted">{{ user.phone }}</small>
                                                {% endif %}
                                            </div>
                                        </div>
                                    </td>
                                    <td>{{ user.email or '-' }}</td>
                                    <td>{{ user.company or '-' }}</td>
                                    <td>
                                        {% set ut = (user.user_type or 'standard') %}
                                        {% if ut|lower == 'standard' %}{{ _('user_type_standard') }}
                                        {% elif ut|lower == 'personnel' %}{{ _('user_type_personnel') }}
                                        {% elif ut|lower == 'guest' %}{{ _('user_type_guest') }}
                                        {% else %}{{ ut|capitalize }}{% endif %}
                                     </td>
                                    <td>
                                        {% set methods = (user.access_type or '').split(',') %}
                                        {% if methods %}
                                            {% for m in methods %}
                                                {% if m %}
                                                <span class="badge bg-info me-1">{{ m|upper }}</span>
                                                {% endif %}
                                            {% endfor %}
                                        {% else %}
                                            <span class="text-muted">-</span>
                                        {% endif %}
                                    </td>
                                    <td>
                                        {% set udevs = user_devices_map.get(user.id, []) %}
                                        {% if udevs %}
                                            {% for d in udevs %}
                                                <div class="mb-1">
                                                    <span class="badge badge-modern bg-info me-1">{{ d.name }}</span>
                                                </div>
                                            {% endfor %}
                                        {% else %}
                                            <span class="text-muted">-</span>
                                        {% endif %}
                                    </td>
                                    <td>
                                        <span class="badge badge-modern bg-{{ 'success' if user.is_active else 'secondary' }}">
                                            <i class="fas fa-{{ 'check' if user.is_active else 'times' }} me-1"></i>
                                            {{ _('active') if user.is_active else (_('inactive') or 'Pasif') }}
                                        </span>
                                    </td>
                                    <td>
                                        <div class="btn-group btn-group-sm">
                                            <button class="btn btn-warning-modern btn-modern" onclick="event.stopPropagation(); editUser({{ user.id|int }}); return false;" title="{{ _('edit') or 'Düzenle' }}">
                                                <i class="fas fa-edit"></i>
                                            </button>
                                            {% if not user.is_admin %}
                                            <button class="btn btn-danger-modern btn-modern" onclick="event.stopPropagation(); deleteUser({{ user.id|int }}); return false;" title="{{ _('delete') or 'Sil' }}">
                                                <i class="fas fa-trash"></i>
                                            </button>
                                            {% endif %}
                                        </div>
                                    </td>
                                </tr>
                                {% else %}
                                <tr>
                                    <td colspan="9" class="empty-state">
                                        <i class="fas fa-inbox"></i>
                                        <br>{{ _('no_users') or 'Henüz kullanıcı bulunmamaktadır.' }}
                                    </td>
                                </tr>
                                {% endfor %}
                            </tbody>
                        </table>
                    </div>
                </div>
                {% if total_pages and total_pages > 1 %}
                <div class="card-body-modern pt-0">
                    <div class="d-flex justify-content-between align-items-center flex-wrap mb-2">
                        <div class="text-muted small">
                            {% if current_language == 'tr' %}
                                {{ display_start }}-{{ display_end }} arası gösteriliyor (toplam {{ total_users }})
                            {% else %}
                                Showing {{ display_start }}-{{ display_end }} of {{ total_users }}
                            {% endif %}
                        </div>
                        <nav aria-label="Users pagination">
                            <ul class="pagination mb-0">
                                <li class="page-item {% if current_page <= 1 %}disabled{% endif %}">
                                    <a class="page-link" href="{{ url_for('users', page=1, q=request.args.get('q')) }}">{% if current_language=='tr' %}İlk{% else %}First{% endif %}</a>
                                </li>
                                <li class="page-item {% if current_page <= 1 %}disabled{% endif %}">
                                    <a class="page-link" href="{{ url_for('users', page=(current_page-1), q=request.args.get('q')) }}">{% if current_language=='tr' %}Önceki{% else %}Prev{% endif %}</a>
                                </li>
                                {% set start_page = current_page-2 if current_page>3 else 1 %}
                                {% set end_page = current_page+2 if current_page<=(total_pages-2) else total_pages %}
                                {% for p in range(start_page, end_page+1) %}
                                    <li class="page-item {% if p == current_page %}active{% endif %}">
                                        <a class="page-link" href="{{ url_for('users', page=p, q=request.args.get('q')) }}">{{ p }}</a>
                                    </li>
                                {% endfor %}
                                <li class="page-item {% if current_page >= total_pages %}disabled{% endif %}">
                                    <a class="page-link" href="{{ url_for('users', page=(current_page+1), q=request.args.get('q')) }}">{% if current_language=='tr' %}Sonraki{% else %}Next{% endif %}</a>
                                </li>
                                <li class="page-item {% if current_page >= total_pages %}disabled{% endif %}">
                                    <a class="page-link" href="{{ url_for('users', page=total_pages, q=request.args.get('q')) }}">{% if current_language=='tr' %}Son{% else %}Last{% endif %}</a>
                                </li>
                            </ul>
                        </nav>
                    </div>
                </div>
                {% endif %}
            </div>
        </div>
    </div>

    <!-- Kart Listesi Bölümü -->
    <div class="container mt-4" id="cardsSection" style="display: none;">
        <div class="users-card">
            <div class="card-header-modern">
                <div class="d-flex justify-content-between align-items-center">
                    <h3><i class="fas fa-credit-card me-2"></i>{{ _('cards_on_device') or 'Cihazda Kayıtlı Kartlar' }}</h3>
                    <button class="btn btn-secondary-modern btn-modern" onclick="hideCards()">
                        <i class="fas fa-times me-2"></i>{{ _('device_info_close') or 'Kapat' }}
                    </button>
                </div>
            </div>
            <div class="card-body-modern">
                <div class="d-flex justify-content-between align-items-center mb-3">
                    <span class="badge badge-modern bg-primary fs-6" id="cardCount">0 {{ _('cards_found') or 'kart bulundu' }}</span>
                    <div class="input-group" style="max-width: 300px;">
                        <span class="input-group-text"><i class="fas fa-search"></i></span>
                        <input type="text" class="form-control" id="cardSearch" placeholder="{{ _('card_search_placeholder') or 'Kart ara...' }}">
                    </div>
                </div>
                <div class="table-responsive" style="max-height: 600px; overflow-y: auto;">
                    <table class="table table-modern" id="cardsTable">
                        <thead>
                            <tr>
                                <th>#</th>
                                <th>{{ _('card_uuid') or 'Kart UUID' }}</th>
                                <th>{{ _('users_username') or 'Kullanıcı Adı' }}</th>
                                <th>{{ _('users_region') or 'Yetki Bölgesi' }}</th>
                                <th>{{ _('server_mode') or 'Terminal Modu' }}</th>
                                <th>{{ _('actions') or 'İşlemler' }}</th>
                            </tr>
                        </thead>
                        <tbody id="cardsTableBody">
                            <!-- Kartlar buraya yüklenecek -->
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>

    <!-- Progress Overlay -->
    <div class="progress-overlay" id="progressOverlay"></div>
    <div class="progress-container" id="progressContainer">
        <h4 class="text-center mb-3">
            <i class="fas fa-cog fa-spin me-2"></i>{{ _('processing') or 'İşlem Yapılıyor...' }}
        </h4>
        <div class="progress mb-3">
            <div class="progress-bar progress-bar-striped progress-bar-animated" 
                 id="progressBar" 
                 role="progressbar" 
                 style="width: 0%">
            </div>
        </div>
        <p class="text-center mb-0" id="progressText">{{ _('please_wait') or 'Lütfen bekleyin...' }}</p>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        function clearUserFilter() { window.location.href='{{ url_for('users') }}'; }

        // Existing JavaScript functions...
        async function getCards() {
            console.log('getCards() fonksiyonu çağrıldı');
            const btn = document.getElementById('getCardsBtn');
            btn.disabled = true;
            btn.innerHTML = '<i class="fas fa-spinner fa-spin me-2"></i>Kartlar Alınıyor...';
            
            try {
                console.log('API çağrısı yapılıyor...');
                const response = await fetch('/api/get_cards', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    }
                });
                
                console.log('API yanıtı alındı:', response.status);
                const result = await response.json();
                console.log('API sonucu:', result);
                
                if (result.status === 'success') {
                    const cards = result.cards || [];
                    console.log('Kart sayısı:', cards.length);
                    if (cards.length > 0) {
                        displayCardsInModal(cards);
                    } else {
                        alert('Cihazda kayıtlı kart bulunamadı.');
                    }
                } else {
                    alert('Hata: ' + result.message);
                }
                
            } catch (error) {
                console.error('getCards hatası:', error);
                alert('Kart listesi alma hatası: ' + error.message);
            } finally {
                btn.disabled = false;
                btn.innerHTML = '<i class="fas fa-credit-card me-2"></i>Kart Listesi Al';
            }
        }
        
        function displayCardsInModal(cards) {
            const cardsSection = document.getElementById('cardsSection');
            const cardCount = document.getElementById('cardCount');
            const cardsTableBody = document.getElementById('cardsTableBody');
            const cardSearch = document.getElementById('cardSearch');
            
            // Kart sayısını güncelle
            cardCount.textContent = `${cards.length} kart bulundu`;
            
            // Tabloyu temizle ve kartları yükle
            cardsTableBody.innerHTML = '';
            cards.forEach((card, index) => {
                const row = document.createElement('tr');
                row.innerHTML = `
                    <td><strong>${index + 1}</strong></td>
                    <td><code class="text-primary">${card.card_uuid}</code></td>
                    <td>
                        <input type="text" class="form-control form-control-sm" 
                               value="${card.user_name || ''}" 
                               placeholder="Kullanıcı adı"
                               data-card-id="${card.id}"
                               data-field="user_name">
                    </td>
                    <td>
                        <input type="text" class="form-control form-control-sm" 
                               value="${card.authority_zone || ''}" 
                               placeholder="Yetki bölgesi"
                               data-card-id="${card.id}"
                               data-field="authority_zone">
                    </td>
                    <td>
                        <div class="form-check">
                            <input class="form-check-input" type="checkbox" 
                                   ${card.terminal_mode_access ? 'checked' : ''}
                                   data-card-id="${card.id}"
                                   data-field="terminal_mode_access">
                        </div>
                    </td>
                    <td>
                        <div class="btn-group" role="group">
                            <button class="btn btn-success-modern btn-modern btn-sm" onclick="saveCard(${card.id})">
                                <i class="fas fa-save"></i> Kaydet
                            </button>
                            <button class="btn btn-danger-modern btn-modern btn-sm" onclick="deleteCard(${card.id}, '${card.card_uuid}', ${card.terminal_mode_access})">
                                <i class="fas fa-trash"></i> Sil
                            </button>
                        </div>
                    </td>
                `;
                cardsTableBody.appendChild(row);
            });
            
            // Arama fonksiyonu
            cardSearch.addEventListener('input', function() {
                const searchTerm = this.value.toLowerCase();
                const rows = cardsTableBody.querySelectorAll('tr');
                
                rows.forEach((row, index) => {
                    const cardText = row.querySelector('code').textContent.toLowerCase();
                    if (cardText.includes(searchTerm)) {
                        row.style.display = '';
                    } else {
                        row.style.display = 'none';
                    }
                });
            });
            
            // Kart bölümünü göster
            cardsSection.style.display = 'block';
            
            // Sayfayı kart bölümüne kaydır
            cardsSection.scrollIntoView({ behavior: 'smooth' });
        }
        
        function hideCards() {
            const cardsSection = document.getElementById('cardsSection');
            cardsSection.style.display = 'none';
        }
        
        async function saveCard(cardId) {
            try {
                const row = document.querySelector(`[data-card-id="${cardId}"]`).closest('tr');
                
                const user_name = row.querySelector('[data-field="user_name"]').value;
                const authority_zone = row.querySelector('[data-field="authority_zone"]').value;
                const terminal_mode_access = row.querySelector('[data-field="terminal_mode_access"]').checked;
                
                const response = await fetch('/api/update_card', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({
                        card_id: cardId,
                        user_name: user_name,
                        authority_zone: authority_zone,
                        terminal_mode_access: terminal_mode_access
                    })
                });
                
                const result = await response.json();
                
                if (result.status === 'success') {
                    const saveBtn = row.querySelector('.btn-success-modern');
                    const originalText = saveBtn.innerHTML;
                    saveBtn.innerHTML = '<i class="fas fa-check"></i> Kaydedildi!';
                    saveBtn.classList.remove('btn-success-modern');
                    saveBtn.classList.add('btn-secondary-modern');
                    
                    setTimeout(() => {
                        saveBtn.innerHTML = originalText;
                        saveBtn.classList.remove('btn-secondary-modern');
                        saveBtn.classList.add('btn-success-modern');
                    }, 2000);
                } else {
                    alert('Hata: ' + result.message);
                }
                
            } catch (error) {
                console.error('Kart kaydetme hatası:', error);
                alert('Kart kaydetme hatası: ' + error.message);
            }
        }
        
        async function deleteCard(cardId, cardUuid, terminalModeAccess) {
            const message = terminalModeAccess 
                ? 'Bu kart sadece veritabanından silinecek (terminal modu aktif). Devam etmek istiyor musunuz?'
                : 'Bu kart hem veritabanından hem cihazdan silinecek. Devam etmek istiyor musunuz?';
            
            if (!confirm(message)) {
                return;
            }
            
            try {
                const response = await fetch('/api/delete_card', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({
                        card_id: cardId,
                        card_uuid: cardUuid,
                        terminal_mode_access: terminalModeAccess
                    })
                });
                
                const result = await response.json();
                
                if (result.status === 'success') {
                    const row = document.querySelector(`[data-card-id="${cardId}"]`).closest('tr');
                    row.remove();
                    
                    const cardCount = document.getElementById('cardCount');
                    const currentCount = parseInt(cardCount.textContent.split(' ')[0]);
                    cardCount.textContent = `${currentCount - 1} kart bulundu`;
                    
                    alert('Kart başarıyla silindi!');
                } else {
                    alert('Hata: ' + result.message);
                }
                
            } catch (error) {
                console.error('Kart silme hatası:', error);
                alert('Kart silme hatası: ' + error.message);
            }
        }
        
        async function formatCards() {
            if (!confirm('{{ _("confirm_delete_all_users") or "Tüm kullanıcıları silmek istediğinizden emin misiniz? Bu işlem geri alınamaz!" }}')) {
                return;
            }
            
            const btn = document.getElementById('formatCardsBtn');
            btn.disabled = true;
            btn.innerHTML = '<i class="fas fa-spinner fa-spin me-2"></i>{{ _("processing") or "İşlem Yapılıyor..." }}';
            
            try {
                const response = await fetch('/api/delete_all_users', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    }
                });
                
                const result = await response.json();
                
                if (result.status === 'success') {
                    alert('{{ _("all_users_deleted") or "Tüm kullanıcılar başarıyla silindi!" }}');
                    location.reload();
                } else {
                    alert('Hata: ' + result.message);
                }
                
            } catch (error) {
                alert('Format cards hatası: ' + error.message);
            } finally {
                btn.disabled = false;
                btn.innerHTML = '<i class="fas fa-trash me-2"></i>{{ _("delete_users") or "Kullanıcıları Sil" }}';
            }
        }
        
        // Kullanıcı yönetimi fonksiyonları
        function editUser(userId) {
            window.location.href = '/edit-user/' + userId;
        }
        
        function deleteUser(userId) {
            if (confirm('Bu kullanıcıyı silmek istediğinizden emin misiniz?')) {
                fetch('/delete-user/' + userId, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    }
                })
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        location.reload();
                    } else {
                        alert('Hata: ' + data.message);
                    }
                })
                .catch(error => {
                    alert('Silme işlemi başarısız: ' + error.message);
                });
            }
        }

    </script>
</body>
</html> 