<!DOCTYPE html>
<html lang="{{ current_language }}">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>{{ _('edit_device') }} - iAccess Terminal</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
    <style>
        :root {
            --primary-color: #667eea;
            --secondary-color: #764ba2;
            --success-color: #28a745;
            --warning-color: #ffc107;
            --danger-color: #dc3545;
            --info-color: #17a2b8;
            --dark-color: #343a40;
            --light-color: #f8f9fa;
        }

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

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

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

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

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

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

        .device-form-card {
            background: rgba(255, 255, 255, 0.95);
            border-radius: 20px;
            box-shadow: 0 15px 35px rgba(0, 0, 0, 0.1);
            backdrop-filter: blur(10px);
            border: 1px solid rgba(255, 255, 255, 0.2);
            max-width: 600px;
            margin: 0 auto;
        }

        .form-header {
            background: linear-gradient(135deg, var(--primary-color), var(--secondary-color));
            color: white;
            padding: 30px;
            border-radius: 20px 20px 0 0;
            text-align: center;
        }

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

        .form-header p {
            margin: 10px 0 0 0;
            opacity: 0.9;
            font-size: 1rem;
        }

        .form-body {
            padding: 40px;
        }

        .form-group {
            margin-bottom: 25px;
        }

        .form-label {
            font-weight: 600;
            color: var(--dark-color);
            margin-bottom: 8px;
            display: flex;
            align-items: center;
        }

        .form-label i {
            margin-right: 8px;
            color: var(--primary-color);
            width: 20px;
        }

        .form-control, .form-select {
            border-radius: 12px;
            border: 2px solid #e9ecef;
            padding: 15px 20px;
            font-size: 1rem;
            transition: all 0.3s ease;
            background: rgba(255, 255, 255, 0.9);
        }

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

        .form-control:disabled {
            background: #f8f9fa;
            color: #6c757d;
            cursor: not-allowed;
        }

        .btn-modern {
            border-radius: 8px;  /* Reduced from 12px */
            padding: 10px 20px;  /* Reduced from 15px 30px */
            font-weight: 600;
            font-size: 0.9rem;  /* Reduced from 1rem */
            transition: all 0.3s ease;
            border: none;
            text-transform: uppercase;
            letter-spacing: 0.5px;
        }

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

        .btn-primary-modern:hover {
            transform: translateY(-2px);
            box-shadow: 0 8px 25px rgba(102, 126, 234, 0.4);
            color: white;
        }

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

        .btn-secondary-modern:hover {
            transform: translateY(-2px);
            box-shadow: 0 8px 25px rgba(108, 117, 125, 0.4);
            color: white;
        }

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

        .btn-danger-modern:hover {
            transform: translateY(-2px);
            box-shadow: 0 8px 25px rgba(220, 53, 69, 0.4);
            color: white;
        }

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

        .device-info-card h6 {
            color: var(--primary-color);
            font-weight: 600;
            margin-bottom: 15px;
        }

        .info-item {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 8px 0;
            border-bottom: 1px solid rgba(102, 126, 234, 0.1);
        }

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

        .info-label {
            color: var(--dark-color);
            font-weight: 500;
        }

        .info-value {
            color: var(--primary-color);
            font-weight: 600;
        }

        .alert {
            border-radius: 12px;
            border: none;
            padding: 15px 20px;
        }

        @media (max-width: 768px) {
            .main-container {
                margin-top: 60px;
                padding: 10px;
            }
            
            .form-body {
                padding: 30px 20px;
            }
            
            .form-header {
                padding: 25px 20px;
            }
            
            .form-header h2 {
                font-size: 1.5rem;
            }
        }
    </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" href="{{ url_for('users') }}">
                            <i class="fas fa-users me-1"></i>{{ _('users_title') }}
                        </a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="{{ url_for('access_logs') }}">
                            <i class="fas fa-clipboard-list me-1"></i>{{ _('access_logs_title') }}
                        </a>
                    </li>
                </ul>
                
                <ul class="navbar-nav">
                    <li class="nav-item dropdown">
                        <a class="nav-link dropdown-toggle d-flex align-items-center" href="#" id="userDropdown" role="button" data-bs-toggle="dropdown">
                            {% if user and user.profile_image %}
                                {% if user.profile_image.startswith('@') %}
                                  {% set imgfile = user.profile_image[1:] %}
                                  <img src="{{ url_for('static', filename='uploads/' + imgfile) }}" 
                                {% else %}
                                  <img src="{{ url_for('static', filename='uploads/' + user.profile_image) }}" 
                                {% endif %}
                                      alt="{{ _('profile_image') }}" class="rounded-circle me-2" width="32" height="32" style="object-fit: cover;">
                            {% else %}
                                <img src="{{ url_for('static', filename='img/default-avatar.png') }}" 
                                    alt="{{ _('profile_image') }}" class="rounded-circle me-2" width="32" height="32" style="object-fit: cover;">
                            {% endif %}
                            <div class="d-flex flex-column">
                                <span class="fw-bold">{{ user_name }}</span>
                                {% if user and user.company %}
                                    <small class="text-muted">{{ user.company }}</small>
                                {% endif %}
                            </div>
                        </a>
                        <ul class="dropdown-menu dropdown-menu-end">
                            <li><a class="dropdown-item" href="{{ url_for('profile') }}"><i class="fas fa-user me-2"></i>{{ _('profile') }}</a></li>
                            <li><a class="dropdown-item" href="#"><i class="fas fa-cog me-2"></i>{{ _('settings') }}</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>
                    <li class="nav-item dropdown">
                        <a class="nav-link dropdown-toggle" href="#" id="langDropdown" role="button" data-bs-toggle="dropdown">
                            <i class="fas fa-globe me-1"></i>{{ 'EN' if session.get('dil') == 'en' else 'TR' }}
                        </a>
                        <ul class="dropdown-menu dropdown-menu-end">
                            <li><a class="dropdown-item" href="?lang=tr"><i class="flag-icon flag-icon-tr me-2"></i>Türkçe</a></li>
                            <li><a class="dropdown-item" href="?lang=en"><i class="flag-icon flag-icon-us me-2"></i>English</a></li>
                        </ul>
                    </li>
                </ul>
            </div>
        </div>
    </nav>

    <!-- Main Content -->
    <div class="main-container">
        <div class="container">
            <div class="device-form-card">
                <div class="form-header">
                    <h2><i class="fas fa-edit me-2"></i>{{ _('device_edit_title') }}</h2>
                    <p>{{ _('device_edit_subtitle') }}</p>
                </div>
                
                <div class="form-body">
                    {% with messages = get_flashed_messages(with_categories=true) %}
                        {% if messages %}
                            {% for category, message in messages %}
                                <div class="alert alert-{{ 'danger' if category == 'error' else 'success' }} alert-dismissible fade show" role="alert">
                                    <i class="fas fa-{{ '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 %}

                    <!-- Device Info Card -->
                    <div class="device-info-card">
                        <h6><i class="fas fa-info-circle me-2"></i>{{ _('device_info') }}</h6>
                        <div class="info-item">
                            <span class="info-label">{{ _('device_id_label') }}:</span>
                            <span class="info-value">{{ device.serial_number }}</span>
                        </div>
                        <div class="info-item">
                            <span class="info-label">{{ _('connection_status') }}:</span>
                            <span class="info-value" id="connectionStatus">
                                {% if is_connected %}
                                <i class="fas fa-circle text-success me-1"></i>{{ _('connected') }}
                                {% else %}
                                <i class="fas fa-circle text-danger me-1"></i>{{ _('disconnected') }}
                                {% endif %}
                            </span>
                        </div>
                    </div>

                    <form method="POST" id="editForm">
                        <div class="form-group">
                            <label for="device_name" class="form-label">
                                <i class="fas fa-microchip"></i>{{ _('device_name_label') }}
                            </label>
                            <input type="text" 
                                   class="form-control" 
                                   id="device_name" 
                                   name="device_name" 
                                   value="{{ device.device_name }}" 
                                   placeholder="{{ _('device_name_placeholder') }}"
                                   required>
                        </div>

                        <div class="form-group">
                            <label for="device_type" class="form-label">
                                <i class="fas fa-network-wired"></i>{{ _('device_type_label') }}
                            </label>
                            <select class="form-select" id="device_type" name="device_type" required>
                                <option value="client" {% if device.device_type == 'client' %}selected{% endif %}>{{ _('device_tcp_client') }}</option>
                                <option value="server" {% if device.device_type == 'server' %}selected{% endif %}>{{ _('device_tcp_server') }}</option>
                            </select>
                        </div>

                        <div class="form-group">
                            <label for="ip_address" class="form-label">
                                <i class="fas fa-globe"></i>{{ _('device_ip_label') }}
                            </label>
                            <input type="text" 
                                   class="form-control" 
                                   id="ip_address" 
                                   name="ip_address" 
                                   value="{{ device.ip_address }}" 
                                   placeholder="{{ _('device_ip_placeholder') }}"
                                   {% if device.device_type == 'server' %}readonly disabled{% endif %}
                                   required>
                            {% if device.device_type == 'server' %}
                            <small class="text-muted mt-2 d-block">
                                <i class="fas fa-info-circle me-1"></i>{{ _('server_ip_readonly') }}
                            </small>
                            {% endif %}
                        </div>

                        <div class="form-group">
                            <label for="serial_number" class="form-label">
                                <i class="fas fa-barcode"></i>{{ _('device_serial_label') }}
                            </label>
                            <input type="text" 
                                   class="form-control" 
                                   id="serial_number" 
                                   name="serial_number" 
                                   value="{{ device.serial_number }}" 
                                   readonly 
                                   disabled>
                            <small class="text-muted mt-2 d-block">
                                <i class="fas fa-info-circle me-1"></i>{{ _('serial_number_readonly') }}
                            </small>
                        </div>

                        <div class="d-grid gap-3 mt-4">
                            <button type="submit" class="btn btn-primary-modern btn-modern" id="saveBtn">
                                <i class="fas fa-save me-2"></i>{{ _('update') }}
                            </button>
                            <button type="button" class="btn btn-danger-modern btn-modern" id="deleteBtn" onclick="confirmDelete()">
                                <i class="fas fa-trash me-2"></i>{{ _('delete') }}
                            </button>
                            <a href="{{ url_for('devices') }}" class="btn btn-secondary-modern btn-modern">
                                <i class="fas fa-arrow-left me-2"></i>{{ _('back_to_devices') }}
                            </a>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>
    
    <script>
        // Form validation and submission
        document.getElementById('editForm').addEventListener('submit', function(e) {
            e.preventDefault();
            
            const saveBtn = document.getElementById('saveBtn');
            const originalText = saveBtn.innerHTML;
            
            // Show loading state
            saveBtn.innerHTML = '<i class="fas fa-spinner fa-spin me-2"></i>{{ _("saving") }}...';
            saveBtn.disabled = true;
            
            // Submit form after showing loading state
            setTimeout(() => {
                this.submit();
            }, 100);
        });

        // Delete confirmation
        function confirmDelete() {
            if (confirm('{{ _("confirm_delete_device") }}')) {
                const deleteBtn = document.getElementById('deleteBtn');
                deleteBtn.innerHTML = '<i class="fas fa-spinner fa-spin me-2"></i>{{ _("deleting") }}...';
                deleteBtn.disabled = true;
                
                // Redirect to delete route
                window.location.href = '{{ url_for("delete_user_device", device_id=device.serial_number) }}';
            }
        }

        // Real-time validation
        document.getElementById('device_name').addEventListener('input', function() {
            if (this.value.length < 2) {
                this.style.borderColor = 'var(--danger-color)';
                this.style.boxShadow = '0 0 0 0.2rem rgba(220, 53, 69, 0.25)';
            } else {
                this.style.borderColor = '#e9ecef';
                this.style.boxShadow = 'none';
            }
        });

        document.getElementById('ip_address').addEventListener('input', function() {
            const ipRegex = /^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/;
            if (!ipRegex.test(this.value) && this.value !== '') {
                this.style.borderColor = 'var(--danger-color)';
                this.style.boxShadow = '0 0 0 0.2rem rgba(220, 53, 69, 0.25)';
            } else {
                this.style.borderColor = '#e9ecef';
                this.style.boxShadow = 'none';
            }
        });

        // Handle device type change
        document.getElementById('device_type').addEventListener('change', function() {
            const ipInput = document.getElementById('ip_address');
            const ipHelpText = ipInput.nextElementSibling;
            
            if (this.value === 'server') {
                ipInput.readOnly = true;
                ipInput.disabled = true;
                
                // Add help text if it doesn't exist
                if (!ipHelpText || !ipHelpText.classList.contains('text-muted')) {
                    const helpText = document.createElement('small');
                    helpText.className = 'text-muted mt-2 d-block';
                    helpText.innerHTML = '<i class="fas fa-info-circle me-1"></i>{{ _("server_ip_readonly") }}';
                    ipInput.parentNode.insertBefore(helpText, ipInput.nextSibling);
                }
            } else {
                ipInput.readOnly = false;
                ipInput.disabled = false;
                
                // Remove help text if it exists
                if (ipHelpText && ipHelpText.classList.contains('text-muted')) {
                    ipHelpText.remove();
                }
            }
        });

        // Auto-save draft
        let autoSaveTimer;
        const formInputs = document.querySelectorAll('#editForm input, #editForm select');
        
        formInputs.forEach(input => {
            input.addEventListener('input', function() {
                clearTimeout(autoSaveTimer);
                autoSaveTimer = setTimeout(() => {
                    // Save form data to localStorage as draft
                    const formData = new FormData(document.getElementById('editForm'));
                    const draft = {};
                    for (let [key, value] of formData.entries()) {
                        draft[key] = value;
                    }
                    localStorage.setItem('deviceEditDraft', JSON.stringify(draft));
                }, 1000);
            });
        });

        // Load draft on page load
        window.addEventListener('load', function() {
            const draft = localStorage.getItem('deviceEditDraft');
            if (draft) {
                const draftData = JSON.parse(draft);
                Object.keys(draftData).forEach(key => {
                    const input = document.getElementById(key);
                    if (input && !input.readOnly) {
                        input.value = draftData[key];
                    }
                });
            }
        });

        // Clear draft on successful save
        document.getElementById('editForm').addEventListener('submit', function() {
            localStorage.removeItem('deviceEditDraft');
        });

        // Real-time device connection status check
        function updateDeviceStatus() {
            const deviceId = '{{ device.serial_number }}';
            const statusElement = document.getElementById('connectionStatus');
            
            fetch(`/api/device/status/${deviceId}`)
                .then(response => response.json())
                .then(data => {
                    if (data.connected) {
                        statusElement.innerHTML = '<i class="fas fa-circle text-success me-2"></i>{{ _("connected") }}';
                        statusElement.className = 'badge bg-success';
                    } else {
                        statusElement.innerHTML = '<i class="fas fa-circle text-danger me-2"></i>{{ _("disconnected") }}';
                        statusElement.className = 'badge bg-danger';
                    }
                })
                .catch(error => {
                    console.error('Cihaz durumu kontrol hatası:', error);
                    statusElement.innerHTML = '<i class="fas fa-circle text-warning me-2"></i>{{ _("unknown") }}';
                    statusElement.className = 'badge bg-warning';
                });
        }

        // Update status every 5 seconds
        setInterval(updateDeviceStatus, 5000);
        
        // Initial status check
        updateDeviceStatus();
    </script>
</body>
</html> 