<!DOCTYPE html>
<html lang="{{ current_language }}">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>{{ _('edit_user_title') }} - Gecis</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.7.2/font/bootstrap-icons.css" rel="stylesheet">
    <style>
        :root {
            --primary-color: #2c3e50;
            --secondary-color: #3498db;
            --accent-color: #e74c3c;
            --success-color: #27ae60;
            --warning-color: #f39c12;
            --light-bg: #ecf0f1;
            --dark-text: #2c3e50;
            --border-radius: 12px;
            --shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
        }

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

        .container {
            padding-top: 2rem;
            padding-bottom: 2rem;
        }

        .card {
            border: none;
            border-radius: var(--border-radius);
            box-shadow: var(--shadow);
            backdrop-filter: blur(10px);
            background: rgba(255, 255, 255, 0.95);
        }

        .card-header {
            background: linear-gradient(135deg, var(--primary-color), var(--secondary-color));
            color: white;
            border-radius: var(--border-radius) var(--border-radius) 0 0 !important;
            padding: 1.5rem;
            border: none;
        }

        .form-control, .form-select {
            border-radius: 8px;
            border: 2px solid #e9ecef;
            padding: 0.75rem 1rem;
            transition: all 0.3s ease;
        }

        .form-control:focus, .form-select:focus {
            border-color: var(--secondary-color);
            box-shadow: 0 0 0 0.2rem rgba(52, 152, 219, 0.25);
        }

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

        .btn-primary {
            background: linear-gradient(135deg, var(--secondary-color), #5dade2);
        }

        .btn-primary:hover {
            background: linear-gradient(135deg, #2980b9, var(--secondary-color));
            transform: translateY(-2px);
            box-shadow: 0 6px 12px rgba(0, 0, 0, 0.15);
        }

        .btn-secondary {
            background: linear-gradient(135deg, #95a5a6, #bdc3c7);
            color: var(--dark-text);
        }

        .btn-secondary:hover {
            background: linear-gradient(135deg, #7f8c8d, #95a5a6);
            transform: translateY(-2px);
        }

        .access-type-section {
            background: #f8f9fa;
            border-radius: 8px;
            padding: 1.5rem;
            margin: 1rem 0;
            border: 2px solid #e9ecef;
        }

        .access-type-item {
            background: white;
            border: 2px solid #e9ecef;
            border-radius: 8px;
            padding: 1rem;
            margin: 0.5rem 0;
            transition: all 0.3s ease;
            cursor: pointer;
        }

        .access-type-item:hover {
            border-color: var(--secondary-color);
            transform: translateY(-2px);
            box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
        }

        .access-type-item.selected {
            border-color: var(--secondary-color);
            background: rgba(52, 152, 219, 0.1);
        }

        .form-check-input:checked {
            background-color: var(--secondary-color);
            border-color: var(--secondary-color);
        }

        .user-type-badge {
            display: inline-block;
            padding: 0.25rem 0.75rem;
            border-radius: 20px;
            font-size: 0.875rem;
            font-weight: 500;
            margin: 0.25rem;
        }

        .badge-standard { background: #e3f2fd; color: #1976d2; }
        .badge-personnel { background: #f3e5f5; color: #7b1fa2; }
        .badge-guest { background: #fff3e0; color: #f57c00; }

        .icon-lg {
            font-size: 2rem;
            margin-bottom: 0.5rem;
        }

        .section-title {
            color: var(--primary-color);
            font-weight: 600;
            margin-bottom: 1rem;
            padding-bottom: 0.5rem;
            border-bottom: 2px solid var(--secondary-color);
        }

        .alert {
            border-radius: 8px;
            border: none;
        }

        .back-button {
            margin-bottom: 1.5rem;
        }
        
        .back-btn {
            background: rgba(255, 255, 255, 0.9);
            border: 2px solid #e9ecef;
            color: var(--dark-text);
            border-radius: 8px;
            padding: 0.5rem 1rem;
            font-weight: 500;
            transition: all 0.3s ease;
            text-decoration: none;
            display: inline-flex;
            align-items: center;
            gap: 0.5rem;
        }
        
        .back-btn:hover {
            background: rgba(255, 255, 255, 1);
            border-color: var(--secondary-color);
            color: var(--secondary-color);
            transform: translateY(-2px);
            box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
        }

        .device-selection-container {
            border: 2px solid #e9ecef;
            border-radius: 8px;
            background: white;
        }

        .device-selection-header {
            padding: 1rem;
            border-bottom: 1px solid #e9ecef;
            background: #f8f9fa;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        .device-list {
            max-height: 300px;
            overflow-y: auto;
            padding: 0;
        }

        .device-item {
            padding: 0.75rem 1rem;
            border-bottom: 1px solid #f1f3f4;
            transition: background-color 0.2s ease;
            cursor: pointer;
        }

        .device-item:hover {
            background-color: #f8f9fa;
        }

        .device-item:last-child {
            border-bottom: none;
        }

        .device-item.selected {
            background-color: rgba(52, 152, 219, 0.1);
            border-left: 4px solid var(--secondary-color);
        }

        .device-info {
            display: flex;
            justify-content: between;
            align-items: center;
            width: 100%;
        }

        .device-details {
            flex-grow: 1;
        }

        .device-name {
            font-weight: 600;
            color: var(--dark-text);
            margin-bottom: 0.25rem;
        }

        .device-meta {
            font-size: 0.875rem;
            color: #6c757d;
        }

        .device-status {
            text-align: right;
        }

        .status-badge {
            padding: 0.25rem 0.5rem;
            border-radius: 4px;
            font-size: 0.75rem;
            font-weight: 500;
        }

        .status-online {
            background: #d4edda;
            color: #155724;
        }

        .status-offline {
            background: #f8d7da;
            color: #721c24;
        }

        .device-type-badge {
            padding: 0.125rem 0.5rem;
            border-radius: 12px;
            font-size: 0.75rem;
            font-weight: 500;
            margin-left: 0.5rem;
        }

        .type-client {
            background: #e3f2fd;
            color: #1976d2;
        }

        .type-server {
            background: #f3e5f5;
            color: #7b1fa2;
        }

        /* Profil Resmi Stilleri */
        .profile-image-section {
            text-align: center;
        }

        .profile-image-preview {
            position: relative;
            width: 120px;
            height: 120px;
            margin: 0 auto 1rem;
            border-radius: 50%;
            overflow: hidden;
            border: 3px solid #e9ecef;
            cursor: pointer;
            transition: all 0.3s ease;
        }

        .profile-image-preview:hover {
            border-color: var(--secondary-color);
            transform: scale(1.05);
        }

        .profile-preview-img {
            width: 100%;
            height: 100%;
            object-fit: cover;
        }

        .upload-overlay {
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background: rgba(0, 0, 0, 0.7);
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            color: white;
            opacity: 0;
            transition: opacity 0.3s ease;
        }

        .profile-image-preview:hover .upload-overlay {
            opacity: 1;
        }

        .upload-overlay i {
            font-size: 2rem;
            margin-bottom: 0.5rem;
        }

        .upload-overlay span {
            font-size: 0.875rem;
            font-weight: 500;
        }

        .profile-image-actions {
            display: flex;
            gap: 0.5rem;
            justify-content: center;
        }

        @media (max-width: 768px) {
            .container {
                padding: 1rem;
            }
            
            .card-header {
                padding: 1rem;
            }
            
            .btn-modern {
                padding: 0.5rem 1.5rem;
            }
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="back-button">
            <a href="{{ url_for('users') }}" class="back-btn">
                <i class="bi bi-arrow-left"></i>{{ _('back_to_users') or 'Kullanıcılara Dön' }}
            </a>
        </div>
        <div class="row justify-content-center">
            <div class="col-lg-8">
                <!-- Flash Messages -->
                {% with messages = get_flashed_messages(with_categories=true) %}
                    {% if messages %}
                        {% for category, message in messages %}
                            <div class="alert alert-{{ 'danger' if category == 'error' else category }} alert-dismissible fade show" role="alert">
                                <i class="bi bi-{{ 'exclamation-triangle' if category == 'error' else 'check-circle' }} me-2"></i>
                                {{ message }}
                                <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                            </div>
                        {% endfor %}
                    {% endif %}
                {% endwith %}

                <div class="card">
                    <div class="card-header text-center">
                        <h2 class="mb-0">
                            <i class="bi bi-pencil-square me-3"></i>
                            {{ _('edit_user_title') or 'Kullanıcı Düzenle' }}
                        </h2>
                        <p class="mb-0 mt-2 opacity-75">{{ _('edit_user_subtitle') or 'Kullanıcı bilgilerini güncelleyin' }}</p>
                    </div>

                    <div class="card-body p-4">
                        <form method="POST" action="{{ url_for('edit_user', user_id=user.id) }}" id="editUserForm" enctype="multipart/form-data">
                            <!-- Kişisel Bilgiler -->
                            <div class="mb-4">
                                <h4 class="section-title">
                                    <i class="bi bi-person me-2"></i>{{ _('personal_info') or 'Kişisel Bilgiler' }}
                                </h4>
                                <div class="row">
                                    <div class="col-md-6 mb-3">
                                        <label for="full_name" class="form-label fw-bold">
                                            <i class="bi bi-person me-1"></i>{{ _('full_name') or 'Ad Soyad' }} *
                                        </label>
                                        <input type="text" class="form-control" id="full_name" name="full_name" value="{{ user.full_name or '' }}" required>
                                    </div>
                                    <div class="col-md-6 mb-3">
                                        <label for="phone" class="form-label fw-bold">
                                            <i class="bi bi-telephone me-1"></i>{{ _('phone') or 'Telefon' }}
                                        </label>
                                        <input type="tel" class="form-control" id="phone" name="phone" value="{{ user.phone or '' }}">
                                    </div>
                                </div>
                                
                                <!-- Profil Resmi -->
                                <div class="row">
                                    <div class="col-12 mb-3">
                                        <label class="form-label fw-bold">
                                            <i class="bi bi-image me-1"></i>{{ _('profile_image') or 'Profil Resmi' }}
                                        </label>
                                        <div class="profile-image-section">
                                            <div class="profile-image-preview" id="profileImagePreview">
                                                <img src="{% if user.profile_image %}{{ url_for('static', filename='uploads/' + user.profile_image) }}{% else %}/static/img/default-avatar.png{% endif %}" alt="Profil Resmi" id="previewImg" class="profile-preview-img">
                                                <div class="upload-overlay">
                                                    <i class="bi bi-camera"></i>
                                                    <span>{{ _('select_image') or 'Resim Seç' }}</span>
                                                </div>
                                            </div>
                                            <input type="file" class="form-control d-none" id="profile_image" name="profile_image" accept="image/*" onchange="previewProfileImage(event)">
                                            <div class="profile-image-actions mt-2">
                                                <button type="button" class="btn btn-outline-primary btn-sm" onclick="document.getElementById('profile_image').click()">
                                                    <i class="bi bi-upload me-1"></i>{{ _('upload_image') or 'Resim Yükle' }}
                                                </button>
                                                <button type="button" class="btn btn-outline-danger btn-sm" onclick="removeProfileImage()" id="removeImageBtn" {% if not user.profile_image %}style="display: none;"{% endif %}>
                                                    <i class="bi bi-trash me-1"></i>{{ _('remove_image') or 'Resmi Kaldır' }}
                                                </button>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>

                            <!-- Şirket Bilgisi -->
                            <div class="mb-4">
                                <h4 class="section-title">
                                    <i class="bi bi-building me-2"></i>{{ _('company_info') or 'Şirket Bilgisi' }}
                                </h4>
                                <div class="row">
                                    <div class="col-12 mb-3">
                                        <label for="company" class="form-label fw-bold">
                                            <i class="bi bi-building me-1"></i>{{ _('company') or 'Şirket' }} *
                                        </label>
                                        <input type="text" class="form-control" id="company" name="company" 
                                               placeholder="Şirket adını girin" 
                                               value="{{ user.company or '' }}" required>
                                    </div>
                                </div>
                            </div>

                            <!-- Kullanıcı Tipi -->
                            <div class="mb-4">
                                <h4 class="section-title">
                                    <i class="bi bi-person-badge me-2"></i>{{ _('user_type') or 'Kullanıcı Tipi' }}
                                </h4>
                                <div class="row">
                                    <div class="col-12 mb-3">
                                        <label for="user_type" class="form-label fw-bold">{{ _('user_category') or 'Kullanıcı Kategorisi' }}</label>
                                        <select class="form-select" id="user_type" name="user_type">
                                            <option value="standard" {% if user.user_type == 'standard' %}selected{% endif %}>
                                                {{ _('standard_user') or 'Standart Kullanıcı' }} - {{ _('normal_access') or 'Normal erişim yetkisi' }}
                                            </option>
                                            <option value="personnel" {% if user.user_type == 'personnel' %}selected{% endif %}>
                                                {{ _('personnel') or 'Personel' }} - {{ _('company_employee') or 'Şirket çalışanı' }}
                                            </option>
                                            <option value="guest" {% if user.user_type == 'guest' %}selected{% endif %}>
                                                {{ _('guest') or 'Misafir' }} - {{ _('temporary_access') or 'Geçici erişim' }}
                                            </option>
                                        </select>
                                    </div>
                                </div>
                            </div>

                            <!-- Kullanıcı Durumu -->
                            {% if not user.is_admin %}
                            <div class="mb-4">
                                <h4 class="section-title">
                                    <i class="bi bi-toggle2-on me-2"></i>{{ _('user_status') or 'Kullanıcı Durumu' }}
                                </h4>
                                <div class="row">
                                    <div class="col-12 mb-3">
                                        <div class="d-flex justify-content-between align-items-center">
                                            <div>
                                                <label class="form-label fw-bold mb-1">{{ _('account_status') or 'Hesap Durumu' }}</label>
                                                <p class="text-muted small mb-0">{{ _('account_status_info') or 'Kullanıcının sisteme erişim yetkisini kontrol eder' }}</p>
                                            </div>
                                            <div class="form-check form-switch form-switch-lg">
                                                <input class="form-check-input" type="checkbox" id="is_active" name="is_active" {% if user.is_active %}checked{% endif %}>
                                                <label class="form-check-label fw-bold" for="is_active" id="status_label">
                                                    <span class="{% if user.is_active %}text-success{% else %}text-muted{% endif %}">
                                                        {% if user.is_active %}{{ _('active') }}{% else %}{{ _('inactive') }}{% endif %}
                                                    </span>
                                                </label>
                                            </div>
                                        </div>
                                        <div class="alert alert-sm mt-2" id="status_info">
                                            {% if user.is_active %}
                                            <i class="bi bi-check-circle-fill text-success me-1"></i>
                                            <small>{{ _('user_can_access') }}</small>
                                            {% else %}
                                            <i class="bi bi-x-circle-fill text-muted me-1"></i>
                                            <small>{{ _('user_cannot_access') }}</small>
                                            {% endif %}
                                        </div>
                                    </div>
                                </div>
                            </div>
                            {% endif %}

                            <!-- Erişim Tipleri -->
                            <div class="mb-4">
                                <h4 class="section-title">
                                    <i class="bi bi-key me-2"></i>{{ _('access_methods') or 'Erişim Yöntemleri' }}
                                </h4>
                                <div class="access-type-section">
                                    <p class="text-muted mb-3">
                                        <i class="bi bi-info-circle me-1"></i>
                                        {{ _('access_methods_info') or 'Kullanıcının sisteme erişim için kullanabileceği yöntemleri seçin (birden fazla seçilebilir)' }}
                                    </p>
                                    
                                    <div class="row">
                                        <div class="col-md-6">
                                            <div class="access-type-item {% if 'mobile' in (user.access_type or '') %}selected{% endif %}" onclick="toggleAccessType('mobile')">
                                                <div class="form-check">
                                                    <input class="form-check-input" type="checkbox" value="mobile" id="access_mobile" name="access_types" {% if 'mobile' in (user.access_type or '') %}checked{% endif %}>
                                                    <label class="form-check-label w-100" for="access_mobile">
                                                        <div class="text-center">
                                                            <i class="bi bi-phone icon-lg text-primary"></i>
                                                            <h5 class="mb-2">{{ _('mobile_app') or 'Mobil Uygulama' }}</h5>
                                                            <p class="text-muted mb-0">{{ _('smartphone_access') or 'Akıllı telefon ile erişim' }}</p>
                                                        </div>
                                                    </label>
                                                </div>
                                            </div>
                                        </div>
                                        
                                        <div class="col-md-6">
                                            <div class="access-type-item {% if 'nfc' in (user.access_type or '') %}selected{% endif %}" onclick="toggleAccessType('nfc')">
                                                <div class="form-check">
                                                    <input class="form-check-input" type="checkbox" value="nfc" id="access_nfc" name="access_types" {% if 'nfc' in (user.access_type or '') %}checked{% endif %}>
                                                    <label class="form-check-label w-100" for="access_nfc">
                                                        <div class="text-center">
                                                            <i class="bi bi-credit-card icon-lg text-success"></i>
                                                            <h5 class="mb-2">{{ _('nfc_card') or 'NFC Kart' }}</h5>
                                                            <p class="text-muted mb-0">{{ _('physical_card_access') or 'Fiziksel kart ile erişim' }}</p>
                                                        </div>
                                                    </label>
                                                </div>
                                            </div>
                                        </div>
                                    </div>

                                    <!-- NFC UUID Alanı -->
                                     <div id="nfc_uuid_section" class="mt-3" style="{% if 'nfc' not in (user.access_type or '') %}display: none;{% endif %}">
                                         <div class="row">
                                             <div class="col-md-8">
                                                 <label for="card_uuid" class="form-label fw-bold">
                                                     <i class="bi bi-credit-card me-1"></i>{{ _('card_uuid') or 'Kart UUID' }}
                                                 </label>
                                                 <input type="text" class="form-control" id="card_uuid" name="card_uuid" placeholder="Örn: 0x12345678" value="{{ user.card_uuid or '' }}">
                                                 <small class="text-muted">{{ _('read_card_auto') or 'Kartı cihaza okutarak otomatik alabilirsiniz' }}</small>
                                             </div>
                                             <div class="col-md-4">
                                                 <label class="form-label">&nbsp;</label>
                                                 <div class="d-grid">
                                                     <button type="button" class="btn btn-outline-primary btn-modern" onclick="generateRandomUUID('card')">
                                                         <i class="bi bi-shuffle me-1"></i>{{ _('random') or 'Rastgele' }}
                                                     </button>
                                                 </div>
                                             </div>
                                         </div>
                                     </div>

                                     <!-- Mobil UUID Alanı -->
                                     <div id="mobile_uuid_section" class="mt-3" style="{% if 'mobile' not in (user.access_type or '') %}display: none;{% endif %}">
                                         <div class="row">
                                             <div class="col-md-8">
                                                 <label for="user_uuid" class="form-label fw-bold">
                                                     <i class="bi bi-phone me-1"></i>{{ _('mobile_uuid') or 'Mobil UUID' }}
                                                 </label>
                                                 <input type="text" class="form-control" id="user_uuid" name="user_uuid" placeholder="Örn: 1234567890123456" value="{{ user.user_uuid or '' }}" maxlength="16" pattern="\d{1,16}" oninput="this.value=this.value.replace(/[^0-9]/g,'').slice(0,16)">
                                                 <small class="text-muted">{{ _('unique_id_mobile') or 'Mobil uygulama için 16 haneli sayısal kimlik' }}</small>
                                             </div>
                                             <div class="col-md-4">
                                                 <label class="form-label">&nbsp;</label>
                                                 <div class="d-grid">
                                                     <button type="button" class="btn btn-outline-success btn-modern" onclick="generateRandomUUID('mobile')">
                                                         <i class="bi bi-shuffle me-1"></i>{{ _('random') or 'Rastgele' }}
                                                     </button>
                                                 </div>
                                             </div>
                                         </div>
                                         <div class="row mt-3">
                                             <div class="col-md-8">
                                                 <label for="mobile_password" class="form-label fw-bold">
                                                     <i class="bi bi-shield-lock me-1"></i>{{ _('mobile_password') or 'Mobil Şifre' }}
                                                 </label>
                                                 <div class="input-group">
                                                     <input type="password" class="form-control" id="mobile_password" name="mobile_password" placeholder="{{ _('mobile_password_placeholder') or 'Yeni şifre (boş bırakırsanız değişmez)' }}">
                                                     <button class="btn btn-outline-secondary" type="button" onclick="toggleMobilePasswordVisibility()">
                                                         <i class="bi bi-eye" id="mobile_pwd_eye"></i>
                                                     </button>
                                                     <button class="btn btn-outline-primary" type="button" onclick="fillTempMobilePassword()">
                                                         <i class="bi bi-key"></i>
                                                     </button>
                                                 </div>
                                                 <small class="text-muted d-block mt-1">{{ _('mobile_password_info') or 'Şifre girilirse güncellenir; boşsa mevcut kalır' }}</small>
                                                 <small class="d-block mt-1 {{ 'text-success' if user.password_hash and user.password_hash != 'no_login_required' else 'text-muted' }}">
                                                     <i class="bi {{ 'bi-check-circle' if user.password_hash and user.password_hash != 'no_login_required' else 'bi-dash-circle' }} me-1"></i>
                                                     {% if user.password_hash and user.password_hash != 'no_login_required' %}{{ _('password_set') if translations.get(current_language, {}).get('password_set') else _('saved') }}{% else %}{{ _('password_not_set') if translations.get(current_language, {}).get('password_not_set') else _('unknown') }}{% endif %}
                                                 </small>
                                             </div>
                                         </div>
                                     </div>
                                </div>
                            </div>

                            <!-- Yetkilendirilmiş Cihazlar -->
                             <div class="mb-4">
                                 <h4 class="section-title">
                                     <i class="bi bi-hdd-network me-2"></i>{{ _('authorized_devices') or 'Yetkilendirilmiş Cihazlar' }}
                                 </h4>
                                 
                                 <div class="alert alert-info">
                                     <i class="bi bi-info-circle me-2"></i>
                                     {{ _('authorized_devices_info') or 'Kullanıcının erişim yetkisi olacağı cihazları seçin (birden fazla seçilebilir)' }}
                                 </div>
                                 
                                 <!-- Arama ve Filtre -->
                                 <div class="mb-3">
                                     <div class="row">
                                         <div class="col-md-8">
                                             <div class="input-group">
                                                 <span class="input-group-text">
                                                     <i class="bi bi-search"></i>
                                                 </span>
                                                 <input type="text" class="form-control" id="device_search" placeholder="{{ _('search_devices') or 'Cihaz ara...' }}" onkeyup="filterDevices()" onkeydown="if(event.key==='Enter'){event.preventDefault();}">
                                             </div>
                                         </div>
                                         <div class="col-md-4">
                                             <select class="form-select" id="device_type_filter" onchange="filterDevices()">
                                                 <option value="">{{ _('all_devices') or 'Tüm Cihazlar' }}</option>
                                                 <option value="client">{{ _('client_devices') or 'Client Cihazlar' }}</option>
                                                 <option value="server">{{ _('server_devices') or 'Server Cihazlar' }}</option>
                                             </select>
                                         </div>
                                     </div>
                                 </div>
                                 
                                 <!-- Cihaz Listesi -->
                                 <div class="device-selection-container">
                                     <div class="device-selection-header">
                                         <div class="form-check">
                                             <input class="form-check-input" type="checkbox" id="select_all_devices" onchange="toggleAllDevices()">
                                             <label class="form-check-label fw-bold" for="select_all_devices">
                                                 {{ _('select_all') or 'Tümünü Seç' }}
                                             </label>
                                         </div>
                                         <small class="text-muted">
                                             <span id="selected_count">0</span> {{ _('devices_selected') or 'cihaz seçildi' }}
                                         </small>
                                     </div>
                                     
                                     <div class="device-list" id="device_list">
                                         <!-- Cihazlar buraya yüklenecek -->
                                         <div class="text-center py-4" id="loading_devices">
                                             <div class="spinner-border text-primary" role="status">
                                                 <span class="visually-hidden">{{ _('loading') or 'Yükleniyor...' }}</span>
                                             </div>
                                             <p class="mt-2 text-muted">Cihazlarınız yükleniyor...</p>
                                         </div>
                                     </div>
                                 </div>
                             </div>

                             <!-- Zaman Limitleri -->
                             <div class="mb-4">
                                 <div class="d-flex justify-content-between align-items-center mb-3">
                                     <h4 class="section-title mb-0">
                                         <i class="bi bi-clock me-2"></i>{{ _('time_limits') or 'Zaman Limitleri' }}
                                     </h4>
                                     <div class="form-check form-switch">
                                         <input class="form-check-input" type="checkbox" id="enable_time_limits" name="enable_time_limits" onchange="toggleTimeLimits()" {% if user.time_limit_start or user.time_limit_end %}checked{% endif %}>
                                         <label class="form-check-label fw-bold" for="enable_time_limits">
                                             {{ _('enable') or 'Etkinleştir' }}
                                         </label>
                                     </div>
                                 </div>
                                 
                                 <div id="time_limits_section" style="{% if not (user.time_limit_start or user.time_limit_end) %}display: none;{% endif %}">
                                     <div class="alert alert-info">
                                         <i class="bi bi-info-circle me-2"></i>
                                         {{ _('time_limits_info') or 'Kullanıcının sisteme erişebileceği tarih aralığını belirleyin' }}
                                     </div>
                                     <div class="row">
                                         <div class="col-md-6 mb-3">
                                             <label class="form-label fw-bold">
                                                 <i class="bi bi-calendar-check me-1"></i>{{ _('start_date_time') or 'Başlangıç Tarihi ve Saati' }}
                                             </label>
                                             <div class="row">
                                                 <div class="col-7">
                                                     <input type="date" class="form-control" id="start_date" name="start_date" value="{% if user.time_limit_start %}{{ user.time_limit_start.split('T')[0] }}{% endif %}">
                                                 </div>
                                                 <div class="col-5">
                                                     <input type="time" class="form-control" id="start_time" name="start_time" value="{% if user.time_limit_start %}{{ user.time_limit_start.split('T')[1] if 'T' in user.time_limit_start else '09:00' }}{% else %}09:00{% endif %}">
                                                 </div>
                                             </div>
                                         </div>
                                         <div class="col-md-6 mb-3">
                                             <label class="form-label fw-bold">
                                                 <i class="bi bi-calendar-x me-1"></i>{{ _('end_date_time') or 'Bitiş Tarihi ve Saati' }}
                                             </label>
                                             <div class="row">
                                                 <div class="col-7">
                                                     <input type="date" class="form-control" id="end_date" name="end_date" value="{% if user.time_limit_end %}{{ user.time_limit_end.split('T')[0] }}{% endif %}">
                                                 </div>
                                                 <div class="col-5">
                                                     <input type="time" class="form-control" id="end_time" name="end_time" value="{% if user.time_limit_end %}{{ user.time_limit_end.split('T')[1] if 'T' in user.time_limit_end else '18:00' }}{% else %}18:00{% endif %}">
                                                 </div>
                                             </div>
                                         </div>
                                     </div>
                                     
                                     <!-- Hızlı Seçenekler -->
                                     <div class="mb-3">
                                         <label class="form-label fw-bold">
                                             <i class="bi bi-lightning me-1"></i>{{ _('quick_options') or 'Hızlı Seçenekler' }}
                                         </label>
                                         <div class="btn-group w-100" role="group">
                                             <button type="button" class="btn btn-outline-primary btn-sm" onclick="setQuickDate(1)">{{ _('1_day') or '1 Gün' }}</button>
                                             <button type="button" class="btn btn-outline-primary btn-sm" onclick="setQuickDate(7)">{{ _('1_week') or '1 Hafta' }}</button>
                                             <button type="button" class="btn btn-outline-primary btn-sm" onclick="setQuickDate(30)">{{ _('1_month') or '1 Ay' }}</button>
                                             <button type="button" class="btn btn-outline-primary btn-sm" onclick="setQuickDate(90)">{{ _('3_months') or '3 Ay' }}</button>
                                             <button type="button" class="btn btn-outline-secondary btn-sm" onclick="clearDates()">{{ _('clear') or 'Temizle' }}</button>
                                         </div>
                                     </div>
                                 </div>
                             </div>

                            <!-- Submit Buttons -->
                            <div class="d-flex gap-3 justify-content-end">
                                <a href="{{ url_for('users') }}" class="btn btn-secondary btn-modern">
                                    <i class="bi bi-x-circle me-2"></i>{{ _('cancel') or 'İptal' }}
                                </a>
                                <button type="submit" class="btn btn-primary btn-modern">
                                    <i class="bi bi-check-circle me-2"></i>{{ _('update_user') or 'Kullanıcıyı Güncelle' }}
                                </button>
                            </div>
                        </form>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        // Erişim tipi seçimi
        function toggleAccessType(type) {
            const checkbox = document.getElementById('access_' + type);
            const container = checkbox.closest('.access-type-item');
            
            checkbox.checked = !checkbox.checked;
            
            if (checkbox.checked) {
                container.classList.add('selected');
            } else {
                container.classList.remove('selected');
            }
            
            // NFC seçildiğinde UUID alanını göster
            if (type === 'nfc') {
                const uuidSection = document.getElementById('nfc_uuid_section');
                if (checkbox.checked) {
                    uuidSection.style.display = 'block';
                } else {
                    uuidSection.style.display = 'none';
                    document.getElementById('card_uuid').value = '';
                }
            }
            
            // Mobil seçildiğinde UUID alanını göster
            if (type === 'mobile') {
                const uuidSection = document.getElementById('mobile_uuid_section');
                if (checkbox.checked) {
                    uuidSection.style.display = 'block';
                } else {
                    uuidSection.style.display = 'none';
                    document.getElementById('user_uuid').value = '';
                }
            }
        }

        // Rastgele UUID oluştur
        function generateRandomUUID(type) {
            const uuid = '0x' + Math.floor(Math.random() * 0xFFFFFFFF).toString(16).toUpperCase().padStart(8, '0');
            if (type === 'card') {
                document.getElementById('card_uuid').value = uuid;
            } else if (type === 'mobile') {
                let digits = '';
                while (digits.length < 16) {
                    digits += Math.floor(Math.random() * 10).toString();
                }
                document.getElementById('user_uuid').value = digits.slice(0,16);
            }
        }
        
        // Zaman limitleri toggle
        function toggleTimeLimits() {
            const checkbox = document.getElementById('enable_time_limits');
            const section = document.getElementById('time_limits_section');
            
            if (checkbox.checked) {
                section.style.display = 'block';
            } else {
                section.style.display = 'none';
                // Alanları temizle
                clearDates();
            }
        }
        
        // Hızlı tarih seçenekleri
        function setQuickDate(days) {
            const now = new Date();
            const startDate = new Date(now);
            const endDate = new Date(now);
            endDate.setDate(endDate.getDate() + days);
            
            // Tarih formatı: YYYY-MM-DD
            document.getElementById('start_date').value = startDate.toISOString().split('T')[0];
            document.getElementById('end_date').value = endDate.toISOString().split('T')[0];
        }
        
        // Tarihleri temizle
        function clearDates() {
            document.getElementById('start_date').value = '';
            document.getElementById('start_time').value = '09:00';
            document.getElementById('end_date').value = '';
            document.getElementById('end_time').value = '18:00';
        }

        // Form doğrulama
        document.getElementById('editUserForm').addEventListener('submit', function(e) {
            const accessTypes = document.querySelectorAll('input[name="access_types"]:checked');
            
            if (accessTypes.length === 0) {
                e.preventDefault();
                alert('En az bir erişim yöntemi seçmelisiniz!');
                return false;
            }

            // NFC seçildi ama UUID girilmedi
            const nfcSelected = document.getElementById('access_nfc').checked;
            const cardUUID = document.getElementById('card_uuid').value.trim();
            
            if (nfcSelected && !cardUUID) {
                e.preventDefault();
                alert('NFC erişimi için kart UUID\'si gereklidir!');
                document.getElementById('card_uuid').focus();
                return false;
            }
            
            // Mobil seçildi ama UUID girilmedi
            const mobileSelected = document.getElementById('access_mobile').checked;
            const userUUID = document.getElementById('user_uuid').value.trim();
            const mobilePassword = document.getElementById('mobile_password') ? document.getElementById('mobile_password').value.trim() : '';
            
            const uuidDigitsOnly = /^\d{1,16}$/.test(userUUID);
            if (mobileSelected && (!userUUID || !uuidDigitsOnly)) {
                e.preventDefault();
                alert('Mobil erişimi için 16 haneli sayısal UUID gereklidir!');
                document.getElementById('user_uuid').focus();
                return false;
            }
            // Edit ekranında şifre boş bırakılabilir (değiştirmemek için). Zorunlu değil.
            
            // Cihaz seçimi kontrolü
            if (selectedDevices.length === 0) {
                e.preventDefault();
                alert('En az bir cihaz seçmelisiniz!');
                return false;
            }
            
            // Seçili cihazları form'a ekle
            selectedDevices.forEach(deviceSerial => {
                const hiddenInput = document.createElement('input');
                hiddenInput.type = 'hidden';
                hiddenInput.name = 'selected_devices';
                hiddenInput.value = deviceSerial;
                this.appendChild(hiddenInput);
            });
        });

        // Cihaz yönetimi
        let allDevices = [];
        let selectedDevices = [];
        // Backend'den gelen ön-seçili cihazlar
        const preselectedDevices = {{ preselected_devices_json|safe if preselected_devices_json else '[]' }};

        // Cihazları yükle
        async function loadDevices() {
            try {
                const response = await fetch('/api/devices');
                const data = await response.json();
                
                if (data.success && data.devices && data.devices.length > 0) {
                    allDevices = data.devices;
                    // Ön-seçili cihazları yükle
                    if (Array.isArray(preselectedDevices) && preselectedDevices.length > 0) {
                        selectedDevices = Array.from(new Set(preselectedDevices.map(String)));
                    }
                    renderDevices();
                } else {
                    document.getElementById('device_list').innerHTML = 
                        '<div class="text-center py-5">' +
                        '<i class="bi bi-hdd-network" style="font-size: 3rem; color: #6c757d; opacity: 0.5;"></i>' +
                        '<h5 class="mt-3 text-muted">Henüz Cihaz Yok</h5>' +
                        '<p class="text-muted">Cihaz eklemek için <a href="/cihaz-ekle">buraya tıklayın</a></p>' +
                        '</div>';
                }
            } catch (error) {
                console.error('Cihaz yükleme hatası:', error);
                document.getElementById('device_list').innerHTML = 
                    '<div class="text-center py-5">' +
                    '<i class="bi bi-exclamation-triangle" style="font-size: 3rem; color: #dc3545; opacity: 0.7;"></i>' +
                    '<h5 class="mt-3 text-danger">Yükleme Hatası</h5>' +
                    '<p class="text-muted">Cihazlar yüklenirken bir hata oluştu. Lütfen sayfayı yenileyin.</p>' +
                    '<button class="btn btn-outline-primary btn-sm" onclick="loadDevices()">Tekrar Dene</button>' +
                    '</div>';
            }
        }

        // Cihazları render et
        function renderDevices() {
            const deviceList = document.getElementById('device_list');
            const searchTerm = document.getElementById('device_search').value.toLowerCase();
            const typeFilter = document.getElementById('device_type_filter').value;
            
            let filteredDevices = allDevices.filter(device => {
                const matchesSearch = device.ad.toLowerCase().includes(searchTerm) || 
                                    device.seri_no.toLowerCase().includes(searchTerm);
                const matchesType = !typeFilter || device.tcp_tipi === typeFilter;
                return matchesSearch && matchesType;
            });
            
            if (filteredDevices.length === 0) {
                deviceList.innerHTML = 
                    '<div class="text-center py-4">' +
                    '<i class="bi bi-search" style="font-size: 2rem; color: #6c757d; opacity: 0.5;"></i>' +
                    '<h6 class="mt-2 text-muted">Cihaz listesi yükleniyor...</h6>' +
                    '<small class="text-muted">Farklı arama terimleri deneyin</small>' +
                    '</div>';
                return;
            }
            
            deviceList.innerHTML = filteredDevices.map(device => `
                <div class="device-item ${selectedDevices.includes(device.seri_no) ? 'selected' : ''}" 
                     onclick="toggleDevice('${device.seri_no}')">
                    <div class="device-info">
                        <div class="form-check me-3">
                            <input class="form-check-input" type="checkbox" 
                                   id="device_${device.seri_no}" 
                                   name="selected_devices" 
                                   value="${device.seri_no}"
                                   ${selectedDevices.includes(device.seri_no) ? 'checked' : ''}
                                   onclick="event.stopPropagation(); toggleDevice('${device.seri_no}')">
                        </div>
                        <div class="device-details">
                            <div class="device-name">
                                ${device.ad}
                                <span class="device-type-badge type-${device.tcp_tipi}">
                                    ${device.tcp_tipi === 'client' ? 'Client' : 'Server'}
                                </span>
                            </div>
                            <div class="device-meta">
                                <i class="bi bi-hdd me-1"></i>${device.seri_no}
                                <i class="bi bi-globe ms-2 me-1"></i>${device.ip_adresi || 'N/A'}
                            </div>
                        </div>
                        <div class="device-status">
                            <span class="status-badge ${device.is_connected ? 'status-online' : 'status-offline'}">
                                ${device.is_connected ? '{{ _('online') }}' : '{{ _('offline') }}'}
                            </span>
                        </div>
                    </div>
                </div>
            `).join('');
            
            updateSelectedCount();
        }

        // Cihaz seçimini değiştir
        function toggleDevice(serialNo) {
            const index = selectedDevices.indexOf(serialNo);
            if (index > -1) {
                selectedDevices.splice(index, 1);
            } else {
                selectedDevices.push(serialNo);
            }
            renderDevices();
        }

        // Tüm cihazları seç/seçme
        function toggleAllDevices() {
            const selectAll = document.getElementById('select_all_devices').checked;
            const searchTerm = document.getElementById('device_search').value.toLowerCase();
            const typeFilter = document.getElementById('device_type_filter').value;
            
            let filteredDevices = allDevices.filter(device => {
                const matchesSearch = device.ad.toLowerCase().includes(searchTerm) || 
                                    device.seri_no.toLowerCase().includes(searchTerm);
                const matchesType = !typeFilter || device.tcp_tipi === typeFilter;
                return matchesSearch && matchesType;
            });
            
            if (selectAll) {
                filteredDevices.forEach(device => {
                    if (!selectedDevices.includes(device.seri_no)) {
                        selectedDevices.push(device.seri_no);
                    }
                });
            } else {
                filteredDevices.forEach(device => {
                    const index = selectedDevices.indexOf(device.seri_no);
                    if (index > -1) {
                        selectedDevices.splice(index, 1);
                    }
                });
            }
            
            renderDevices();
        }

        // Cihaz filtrele
        function filterDevices() {
            renderDevices();
            
            // "Tümünü Seç" checkbox'ını güncelle
            const searchTerm = document.getElementById('device_search').value.toLowerCase();
            const typeFilter = document.getElementById('device_type_filter').value;
            
            let filteredDevices = allDevices.filter(device => {
                const matchesSearch = device.ad.toLowerCase().includes(searchTerm) || 
                                    device.seri_no.toLowerCase().includes(searchTerm);
                const matchesType = !typeFilter || device.tcp_tipi === typeFilter;
                return matchesSearch && matchesType;
            });
            
            const allFilteredSelected = filteredDevices.length > 0 && 
                                      filteredDevices.every(device => selectedDevices.includes(device.seri_no));
            document.getElementById('select_all_devices').checked = allFilteredSelected;
        }

        // Seçili cihaz sayısını güncelle
        function updateSelectedCount() {
            document.getElementById('selected_count').textContent = selectedDevices.length;
        }

        // Profil resmi önizleme
       function previewProfileImage(event) {
           const file = event.target.files[0];
           const previewImg = document.getElementById('previewImg');
           const removeBtn = document.getElementById('removeImageBtn');
           
           if (file) {
               const reader = new FileReader();
               reader.onload = function(e) {
                   previewImg.src = e.target.result;
                   removeBtn.style.display = 'inline-block';
               }
               reader.readAsDataURL(file);
           }
       }

       // Profil resmini kaldır
       function removeProfileImage() {
           const previewImg = document.getElementById('previewImg');
           const fileInput = document.getElementById('profile_image');
           const removeBtn = document.getElementById('removeImageBtn');
           
           previewImg.src = '/static/img/default-avatar.png';
           fileInput.value = '';
           removeBtn.style.display = 'none';
       }

       // Kullanıcı durumu toggle
       document.addEventListener('DOMContentLoaded', function() {
           const isActiveCheckbox = document.getElementById('is_active');
           const statusLabel = document.getElementById('status_label');
           const statusInfo = document.getElementById('status_info');

           function updateStatus() {
               if (isActiveCheckbox && statusLabel && statusInfo) {
                   if (isActiveCheckbox.checked) {
                       statusLabel.textContent = {{ _('active')|tojson }};
                       statusLabel.classList.remove('text-muted');
                       statusLabel.classList.add('text-success');
                       statusInfo.innerHTML = `
                           <i class="bi bi-check-circle-fill text-success me-1"></i>
                           <small>{{ _('user_can_access') }}</small>
                       `;
                   } else {
                       statusLabel.textContent = {{ _('inactive')|tojson }};
                       statusLabel.classList.remove('text-success');
                       statusLabel.classList.add('text-muted');
                       statusInfo.innerHTML = `
                           <i class="bi bi-x-circle-fill text-muted me-1"></i>
                           <small>{{ _('user_cannot_access') }}</small>
                       `;
                   }
               }
           }

           if (isActiveCheckbox) {
               isActiveCheckbox.addEventListener('change', updateStatus);
               updateStatus(); // Sayfa yüklendiğinde durumu güncelle
           }
       });

       // Mobil şifre: göster/gizle
       function toggleMobilePasswordVisibility() {
           const input = document.getElementById('mobile_password');
           const eye = document.getElementById('mobile_pwd_eye');
           if (!input) return;
           if (input.type === 'password') {
               input.type = 'text';
               if (eye) { eye.classList.remove('bi-eye'); eye.classList.add('bi-eye-slash'); }
           } else {
               input.type = 'password';
               if (eye) { eye.classList.remove('bi-eye-slash'); eye.classList.add('bi-eye'); }
           }
       }

       // Mobil şifre: geçici şifre üret ve doldur
       function fillTempMobilePassword() {
           const input = document.getElementById('mobile_password');
           if (!input) return;
           const tmp = Math.random().toString(36).slice(-10);
           input.value = tmp;
       }

        // Sayfa yüklendiğinde
        document.addEventListener('DOMContentLoaded', function() {
            // Cihazları yükle
            loadDevices();
        });
    </script>
</body>
</html> 