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

        .settings-card {
            background: rgba(255, 255, 255, 0.95);
            border-radius: 10px;
            box-shadow: 0 7px 17px rgba(0, 0, 0, 0.1);
            backdrop-filter: blur(10px);
            border: 1px solid rgba(255, 255, 255, 0.2);
            margin-bottom: 10px;
        }

        .card-header-modern {
            background: linear-gradient(135deg, var(--primary-color), var(--secondary-color));
            color: white;
            padding: 12px 15px;
            border-radius: 10px 10px 0 0;
            border: none;
        }

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

        .device-info-details {
            margin-top: 12px;
            padding-top: 8px;
            border-top: 1px solid rgba(255, 255, 255, 0.2);
        }

        .device-info-details p {
            margin: 0;
            font-size: 1rem;
            color: rgba(255, 255, 255, 0.9);
            line-height: 1.4;
        }

        .device-info-details strong {
            color: white;
            font-weight: 600;
        }

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

        .settings-section {
            margin-bottom: 15px;
            padding: 10px;
            border: 1px solid #e9ecef;
            border-radius: 7px;
            background: #f8f9fa;
        }

        .settings-section h4 {
            color: var(--primary-color);
            font-weight: 600;
            margin-bottom: 10px;
            display: flex;
            align-items: center;
        }

        .settings-section h4 i {
            margin-right: 8px;
            font-size: 1.2rem;
        }

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

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

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

        .form-control {
            border: 1px solid #e9ecef;
            border-radius: 5px;
            padding: 10px 12px;
            font-size: 0.8rem;
            transition: all 0.3s ease;
        }

        textarea.form-control {
            min-height: 55px;
            resize: vertical;
        }

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

        .btn-modern {
            border-radius: 5px;
            padding: 6px 12px;
            font-weight: 600;
            transition: all 0.3s ease;
            border: none;
            text-transform: uppercase;
            letter-spacing: 0.25px;
        }

        .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 5px 15px rgba(102, 126, 234, 0.4);
        }

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

        .btn-warning-modern {
            background: linear-gradient(135deg, #007bff, #0056b3);
            color: white;
        }

        .btn-danger-modern {
            background: linear-gradient(135deg, #007bff, #0056b3);
            color: white;
        }

        .btn-info-modern {
            background: linear-gradient(135deg, #007bff, #0056b3);
            color: white;
        }

        .btn-secondary-modern {
            background: linear-gradient(135deg, #007bff, #0056b3);
            color: white;
        }

        .switch-container {
            display: flex;
            align-items: center;
            justify-content: space-between;
            padding: 7px;
            background: white;
            border-radius: 5px;
            border: 1px solid #e9ecef;
        }

        .switch-label {
            font-weight: 600;
            color: var(--dark-color);
            margin: 0;
            font-size: 0.5rem;
        }

        .form-switch {
            padding-left: 2.5em;
        }

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

        .alert-modern {
            border-radius: 5px;
            border: none;
            padding: 10px 12px;
            margin-bottom: 10px;
            font-size: 0.55rem;
            font-weight: 500;
            box-shadow: 0 2px 7px rgba(0, 0, 0, 0.2);
            animation: slideIn 0.5s ease-out;
        }

        @keyframes slideIn {
            from {
                transform: translateX(100%);
                opacity: 0;
            }
            to {
                transform: translateX(0);
                opacity: 1;
            }
        }

        #alertContainer {
            position: fixed !important;
            z-index: 99999 !important;
            max-width: 400px !important;
            min-width: 250px !important;
            background: transparent !important;
            pointer-events: none !important;
        }

        .alert-success-modern {
            background: #28a745 !important;
            color: white !important;
            border: none !important;
            padding: 6px 10px !important;
            margin: 2px !important;
            border-radius: 4px !important;
            font-size: 7px !important;
            font-weight: 500 !important;
            box-shadow: 0 2px 6px rgba(0,0,0,0.3) !important;
        }

        .alert-danger-modern {
            background: #dc3545 !important;
            color: white !important;
            border: none !important;
            padding: 6px 10px !important;
            margin: 2px !important;
            border-radius: 8px !important;
            font-size: 14px !important;
            font-weight: 500 !important;
            box-shadow: 0 4px 12px rgba(0,0,0,0.3) !important;
        }



        @media (max-width: 768px) {
            .main-container {
                margin-top: 30px;
                padding: 5px;
            }
            
            .card-header-modern {
                padding: 10px;
            }
            
            .card-body-modern {
                padding: 10px;
            }
            
            .settings-section {
                padding: 7px;
            }
        }
    </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><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">
            <!-- Device Info Card -->
            <div class="settings-card">
                <div class="card-header-modern">
                    <h3><i class="fas fa-cog me-2"></i>{{ _('device_settings') }} - {{ device_info.device_name }}</h3>
                    <div class="device-info-details">
                        <p class="mb-1"><strong>{{ _('device_id') }}:</strong> {{ device_info.device_id }}</p>
                        <p class="mb-0"><strong>{{ _('ip_address_label') }}:</strong> {{ device_info.ip_address }}</p>
                    </div>
                </div>
                
                <div class="card-body-modern">


                    <!-- Alert Messages -->
                    <div id="alertContainer"></div>

                    <!-- Network Settings -->
                    <div class="settings-section">
                        <h4><i class="fas fa-network-wired"></i>{{ _('network_settings') }}</h4>
                        <p class="text-muted small">{{ _('network_settings_help') }}</p>
                        
                        <div class="row">
                            <!-- WiFi Static IP -->
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label class="form-label"><i class="fas fa-wifi"></i>{{ _('wifi_static_ip') }}</label>
                                    <small class="text-muted d-block mb-1">{{ _('wifi_static_ip_help') }}</small>
                                    <div class="row">
                                        <div class="col-md-6">
                                            <input type="text" class="form-control" id="wifiIp" placeholder="{{ _('ip_address_label') }}" value="192.168.1.100">
                                        </div>
                                        <div class="col-md-6">
                                            <input type="text" class="form-control" id="wifiNetmask" placeholder="{{ _('subnet_mask') }}" value="255.255.255.0">
                                        </div>
                                    </div>
                                    <div class="row mt-1">
                                        <div class="col-md-6">
                                            <input type="text" class="form-control" id="wifiGateway" placeholder="{{ _('gateway') }}" value="192.168.1.1">
                                        </div>
                                        <div class="col-md-6">
                                            <input type="text" class="form-control" id="wifiDns" placeholder="DNS" value="8.8.8.8">
                                        </div>
                                    </div>
                                    <div class="mt-1">
                                        <div class="form-check form-switch">
                                            <input class="form-check-input" type="checkbox" id="wifiActive">
                                            <label class="form-check-label" for="wifiActive">{{ _('wifi_static_ip_active') }}</label>
                                        </div>
                                    </div>
                                    <button class="btn btn-primary-modern btn-modern mt-1" id="wifiStaticBtn" onclick="setWifiStaticIP()">{{ _('save') }}</button>
                                </div>
                            </div>

                            <!-- Ethernet Static IP -->
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label class="form-label"><i class="fas fa-ethernet"></i>{{ _('ethernet_static_ip') }}</label>
                                    <small class="text-muted d-block mb-1">{{ _('ethernet_static_ip_help') }}</small>
                                    <div class="row">
                                        <div class="col-md-6">
                                            <input type="text" class="form-control" id="ethIp" placeholder="{{ _('ip_address_label') }}" value="192.168.1.100">
                                        </div>
                                        <div class="col-md-6">
                                            <input type="text" class="form-control" id="ethNetmask" placeholder="{{ _('subnet_mask') }}" value="255.255.255.0">
                                        </div>
                                    </div>
                                    <div class="row mt-1">
                                        <div class="col-md-6">
                                            <input type="text" class="form-control" id="ethGateway" placeholder="{{ _('gateway') }}" value="192.168.1.1">
                                        </div>
                                        <div class="col-md-6">
                                            <input type="text" class="form-control" id="ethDns" placeholder="DNS" value="8.8.8.8">
                                        </div>
                                    </div>
                                    <div class="mt-1">
                                        <div class="form-check form-switch">
                                            <input class="form-check-input" type="checkbox" id="ethActive">
                                            <label class="form-check-label" for="ethActive">{{ _('ethernet_static_ip_active') }}</label>
                                        </div>
                                    </div>
                                    <button class="btn btn-primary-modern btn-modern mt-1" id="ethStaticBtn" onclick="setEthStaticIP()">{{ _('save') }}</button>
                                </div>
                            </div>
                        </div>

                        <div class="row">
                            <!-- Remote Target -->
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label class="form-label"><i class="fas fa-server"></i>{{ _('remote_target') }}</label>
                                    <small class="text-muted d-block mb-1">{{ _('remote_target_help') }}</small>
                                    <input type="text" class="form-control" id="remoteTarget" placeholder="192.168.1.107:5002">
                                    <button class="btn btn-primary-modern btn-modern mt-1" id="remoteTargetBtn" onclick="setRemoteTarget()">{{ _('save') }}</button>
                                </div>
                            </div>

                            <!-- WiFi SSID/Password -->
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label class="form-label"><i class="fas fa-wifi"></i>{{ _('wifi_connection') }}</label>
                                    <small class="text-muted d-block mb-1">{{ _('wifi_connection_help') }}</small>
                                    <input type="text" class="form-control" id="wifiSSID" placeholder="SSID" autocomplete="off">
                                    <input type="password" class="form-control mt-1" id="wifiPassword" placeholder="{{ _('wifi_password') }}" autocomplete="off">
                                    <button class="btn btn-primary-modern btn-modern mt-1" id="wifiConfigBtn" onclick="setWifiConfig()">{{ _('save') }}</button>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Hardware Settings -->
                    <div class="settings-section">
                        <h4><i class="fas fa-microchip"></i>{{ _('hardware_settings') }}</h4>
                        <p class="text-muted small">{{ _('hardware_settings_help') }}</p>
                        
                        <div class="row">
                            <!-- Relay 1 -->
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label class="form-label"><i class="fas fa-toggle-on"></i>{{ _('relay1_settings') }}</label>
                                    <small class="text-muted d-block mb-1">{{ _('relay1_settings_help') }}</small>
                                    <div class="row">
                                        <div class="col-md-6">
                                            <select class="form-control" id="relay1Mode">
                                                <option value="0">{{ _('off') }}</option>
                                                <option value="1">{{ _('trigger') }}</option>
                                            </select>
                                        </div>
                                        <div class="col-md-6">
                                            <input type="number" class="form-control" id="relay1Timeout" placeholder="{{ _('duration_ms') }}" value="1500" min="100" max="10000">
                                        </div>
                                    </div>
                                    <button class="btn btn-primary-modern btn-modern mt-1" id="relay1Btn" onclick="setRelay1()">{{ _('save') }}</button>
                                </div>
                            </div>

                            <!-- Relay 2 -->
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label class="form-label"><i class="fas fa-toggle-on"></i>{{ _('relay2_settings') }}</label>
                                    <small class="text-muted d-block mb-1">{{ _('relay2_settings_help') }}</small>
                                    <div class="row">
                                        <div class="col-md-6">
                                            <select class="form-control" id="relay2Mode">
                                                <option value="0">{{ _('off') }}</option>
                                                <option value="1">{{ _('trigger') }}</option>
                                            </select>
                                        </div>
                                        <div class="col-md-6">
                                            <input type="number" class="form-control" id="relay2Timeout" placeholder="{{ _('duration_ms') }}" value="1500" min="100" max="10000">
                                        </div>
                                    </div>
                                    <button class="btn btn-primary-modern btn-modern mt-1" id="relay2Btn" onclick="setRelay2()">{{ _('save') }}</button>
                                </div>
                            </div>
                        </div>

                        <div class="row">
                            <!-- Input 1 -->
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label class="form-label"><i class="fas fa-sign-in-alt"></i>{{ _('input1_settings') }}</label>
                                    <small class="text-muted d-block mb-1">{{ _('input1_settings_help') }}</small>
                                    <div class="row">
                                        <div class="col-md-4">
                                            <select class="form-control" id="input1Mode">
                                                <option value="0">{{ _('off') }}</option>
                                                <option value="1">{{ _('input_mode') }}</option>
                                                <option value="2">{{ _('alarm') }}</option>
                                            </select>
                                        </div>
                                        <div class="col-md-4">
                                            <select class="form-control" id="input1Polarity">
                                                <option value="0">{{ _('normal') }}</option>
                                                <option value="1">{{ _('reverse') }}</option>
                                            </select>
                                        </div>
                                        <div class="col-md-4">
                                            <input type="number" class="form-control" id="input1Counter" placeholder="{{ _('counter_ms') }}" value="500" min="100" max="2000">
                                        </div>
                                    </div>
                                    <button class="btn btn-primary-modern btn-modern mt-1" id="input1Btn" onclick="setInput1()">
                                        {{ _('save') }}
                                    </button>
                                </div>
                            </div>

                            <!-- Input 2 -->
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label class="form-label"><i class="fas fa-sign-in-alt"></i>{{ _('input2_settings') }}</label>
                                    <small class="text-muted d-block mb-1">{{ _('input2_settings_help') }}</small>
                                    <div class="row">
                                        <div class="col-md-4">
                                            <select class="form-control" id="input2Mode">
                                                <option value="0">{{ _('off') }}</option>
                                                <option value="1">{{ _('input_mode') }}</option>
                                                <option value="2">{{ _('alarm') }}</option>
                                            </select>
                                        </div>
                                        <div class="col-md-4">
                                            <select class="form-control" id="input2Polarity">
                                                <option value="0">{{ _('normal') }}</option>
                                                <option value="1">{{ _('reverse') }}</option>
                                            </select>
                                        </div>
                                        <div class="col-md-4">
                                            <input type="number" class="form-control" id="input2Counter" placeholder="{{ _('counter_ms') }}" value="500" min="100" max="2000">
                                        </div>
                                    </div>
                                    <button class="btn btn-primary-modern btn-modern mt-1" id="input2Btn" onclick="setInput2()">
                                        {{ _('save') }}
                                    </button>
                                </div>
                            </div>
                        </div>

                        <div class="row">
                            <!-- RS485 Baudrate -->
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label class="form-label"><i class="fas fa-exchange-alt"></i>{{ _('rs485_baudrate') }}</label>
                                    <small class="text-muted d-block mb-1">{{ _('rs485_baudrate_help') }}</small>
                                    <select class="form-control" id="rs485Baud">
                                        <option value="9600">9600</option>
                                        <option value="19200">19200</option>
                                        <option value="38400">38400</option>
                                        <option value="57600">57600</option>
                                        <option value="115200" selected>115200</option>
                                    </select>
                                    <button class="btn btn-primary-modern btn-modern mt-1" id="rs485BaudBtn" onclick="setRS485Baud()">
                                        {{ _('save') }}
                                    </button>
                                </div>
                            </div>

                            <!-- LED Brightness -->
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label class="form-label"><i class="fas fa-lightbulb"></i>{{ _('led_brightness') }}</label>
                                    <small class="text-muted d-block mb-1">{{ _('led_brightness_help') }}</small>
                                    <input type="range" class="form-control" id="ledBrightness" min="0" max="100" value="30">
                                    <div class="d-flex justify-content-between">
                                        <small>0%</small>
                                        <small id="ledValue">30%</small>
                                        <small>100%</small>
                                    </div>
                                    <button class="btn btn-primary-modern btn-modern mt-1" id="backlightBtn" onclick="setBacklight()">
                                        {{ _('save') }}
                                    </button>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- System Settings -->
                    <div class="settings-section">
                        <h4><i class="fas fa-cogs"></i>{{ _('system_settings') }}</h4>
                        <p class="text-muted small">{{ _('system_settings_help') }}</p>
                        
                        <div class="row">

                            <!-- Terminal Mode -->
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label class="form-label"><i class="fas fa-terminal me-1"></i>{{ _('terminal_mode') }}</label>
                                    <small class="text-muted d-block mb-1">{{ _('terminal_mode_help') }}</small>
                                    <div class="form-check form-switch">
                                        <input class="form-check-input" type="checkbox" id="terminalMode">
                                        <label class="form-check-label" for="terminalMode">{{ _('active') }}</label>
                                    </div>
                                </div>
                                <button class="btn btn-primary-modern btn-modern mt-1" id="terminalModeBtn" onclick="setTerminalMode()">{{ _('save') }}</button>
                            </div>
                        </div>

                        <div class="row">

                            <!-- Access Rate Limit -->
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label class="form-label"><i class="fas fa-tachometer-alt"></i>{{ _('access_rate_limit') }}</label>
                                    <small class="text-muted d-block mb-1">{{ _('access_rate_limit_help') }}</small>
                                    <input type="number" class="form-control" id="accessRate" placeholder="{{ _('access_rate_limit_placeholder') }}" value="2" min="1" max="10">
                                    <button class="btn btn-primary-modern btn-modern mt-1" id="accessRateBtn" onclick="setAccessRate()">{{ _('save') }}</button>
                                </div>
                            </div>
                        </div>

                        <div class="row">
                            <!-- Master Card UUID -->
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label class="form-label"><i class="fas fa-id-card"></i>{{ _('master_card_uuid') }}</label>
                                    <small class="text-muted d-block mb-1">{{ _('master_card_uuid_help') }}</small>
                                    <input type="text" class="form-control" id="masterCardUUID" placeholder="{{ _('master_card_uuid_placeholder') }}" autocomplete="off">
                                    <div class="d-flex gap-1 mt-1">
                                        <button class="btn btn-primary-modern btn-modern" id="masterCardBtn" onclick="setMasterCard()">{{ _('save') }}</button>
                                        <button class="btn btn-danger-modern btn-modern" id="clearMasterCardBtn" onclick="clearMasterCard()">{{ _('delete') }}</button>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>



                    <!-- RFID Card Management -->
                    <div class="settings-section">
                        <h4><i class="fas fa-credit-card"></i>{{ _('rfid_management') }}</h4>
                        <p class="text-muted small">{{ _('rfid_management_help') }}</p>
                        
                        <div class="row">
                            <!-- Add Cards -->
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label class="form-label"><i class="fas fa-plus"></i>{{ _('add_cards') }}</label>
                                    <small class="text-muted d-block mb-1">{{ _('add_cards_help') }}</small>
                                    <textarea class="form-control" id="addCards" placeholder="{{ _('add_cards_placeholder') }}" rows="2"></textarea>
                                    <button class="btn btn-primary-modern btn-modern mt-1" id="addCardsBtn" onclick="addCards()">{{ _('save') }}</button>
                                </div>
                            </div>

                            <!-- Delete Cards -->
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label class="form-label"><i class="fas fa-minus"></i>{{ _('delete_cards') }}</label>
                                    <small class="text-muted d-block mb-1">{{ _('delete_cards_help') }}</small>
                                    <textarea class="form-control" id="deleteCards" placeholder="{{ _('delete_cards_placeholder') }}" rows="2"></textarea>
                                    <button class="btn btn-primary-modern btn-modern mt-1" id="deleteCardsBtn" onclick="deleteCards()">{{ _('save') }}</button>
                                </div>
                            </div>
                        </div>

                        <div class="row">
                            
                        </div>
                    </div>

                    <!-- Firmware Management -->
                    <div class="settings-section">
                        <h4><i class="fas fa-microchip"></i>{{ _('firmware_management') }}</h4>
                        <p class="text-muted small">{{ _('firmware_management_help') }}</p>
                        
                        <div class="row">
                            <div class="col-md-6">
                                <button class="btn btn-primary-modern btn-modern w-100 mb-2" onclick="updateFirmware()">
                                    <i class="fas fa-download me-1"></i>{{ _('update_firmware') }}
                                </button>
                            </div>
                            <div class="col-md-6">
                                <button class="btn btn-success-modern btn-modern w-100 mb-2" onclick="validateFirmware()">
                                    <i class="fas fa-check-circle me-1"></i>{{ _('validate_firmware') }}
                                </button>
                            </div>
                        </div>
                    </div>
                </div>

                    <!-- Maintenance -->
                    <div class="settings-section">
                        <h4><i class="fas fa-tools"></i>{{ _('maintenance') }}</h4>
                        <p class="text-muted small">{{ _('maintenance_help') }}</p>
                        
                        <div class="row">
                            
                            <div class="col-md-6">
                                <button class="btn btn-warning-modern btn-modern w-100 mb-2" onclick="clearInputAlarms()"><i class="fas fa-bell-slash me-1"></i>{{ _('clear_input_alarms') }}</button>
                            </div>
                            <div class="col-md-6">
                                <button class="btn btn-secondary-modern btn-modern w-100 mb-2" onclick="clearLogs()"><i class="fas fa-trash me-1"></i>{{ _('clear_logs') }}</button>
                            </div>
                            <div class="col-md-6">
                                <button class="btn btn-info-modern btn-modern w-100 mb-2" onclick="doBackup()"><i class="fas fa-download me-1"></i>{{ _('backup') }}</button>
                            </div>
                            <div class="col-md-6">
                                <button class="btn btn-warning-modern btn-modern w-100 mb-2" onclick="formatFS()"><i class="fas fa-eraser me-1"></i>{{ _('format_filesystem') }}</button>
                            </div>
                            <div class="col-md-6">
                                <button class="btn btn-danger-modern btn-modern w-100 mb-2" onclick="restartDevice()"><i class="fas fa-redo me-1"></i>{{ _('restart_device') }}</button>
                            </div>
                            <div class="col-md-6">
                                <button class="btn btn-danger-modern btn-modern w-100 mb-2" onclick="setFactorySettings()"><i class="fas fa-undo me-1"></i>{{ _('factory_reset') }}</button>
                            </div>
                        </div>
                    </div>

                    <!-- Back Button -->
                    <div class="text-center mt-4">
                        <a href="{{ url_for('devices') }}" class="btn btn-secondary-modern btn-modern"><i class="fas fa-arrow-left me-1"></i>{{ _('back_to_devices') }}</a>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        const deviceId = '{{ device_info.device_id }}';
        let isLoadingSettings = false;
        
        // Sayfa yüklendiğinde cihaz bilgilerini al ve form alanlarını doldur
        document.addEventListener('DOMContentLoaded', function() {
            // Cihaz bilgilerini al
            loadDeviceSettings();
            
            // Sadece güvenlik gerektiren alanları temizle
            document.getElementById('addCards').value = '';
            document.getElementById('deleteCards').value = '';
        });



                // Cihaz ayarlarını yükle
        async function loadDeviceSettings() {
            if (isLoadingSettings) return;
            isLoadingSettings = true;
            
            try {
                // Sadece veritabanından son getdeviceinfo verisini al
                const response = await fetch(`/api/deviceinfo/${deviceId}`);
                const data = await response.json();
                if (data.success && data.info) {
                let deviceInfo = {};
                if (data.info.device_data) {
                    deviceInfo = data.info.device_data;
                    if (typeof deviceInfo === 'string') {
                        try { deviceInfo = JSON.parse(deviceInfo); } catch (_) { deviceInfo = {}; }
                    }
                }
                
                /* json_logs kullanımı kaldırıldı; deviceInfo yalnızca API'nin cache'den döndürdüğü veriden doldurulur */
                
                
                // Ethernet Static IP ayarlarını doldur
                if (deviceInfo.ethstatic && Array.isArray(deviceInfo.ethstatic) && deviceInfo.ethstatic.length >= 4) {
                    document.getElementById('ethIp').value = deviceInfo.ethstatic[0] || '';
                    document.getElementById('ethNetmask').value = deviceInfo.ethstatic[1] || '';
                    document.getElementById('ethGateway').value = deviceInfo.ethstatic[2] || '';
                    document.getElementById('ethDns').value = deviceInfo.ethstatic[3] || '';
                    document.getElementById('ethActive').checked = true;
                } else {
                    document.getElementById('ethActive').checked = false;
                }
                
                
                // WiFi Static IP ayarlarını doldur
                if (deviceInfo.wifistatic && Array.isArray(deviceInfo.wifistatic) && deviceInfo.wifistatic.length >= 4) {
                    document.getElementById('wifiIp').value = deviceInfo.wifistatic[0] || '';
                    document.getElementById('wifiNetmask').value = deviceInfo.wifistatic[1] || '';
                    document.getElementById('wifiGateway').value = deviceInfo.wifistatic[2] || '';
                    document.getElementById('wifiDns').value = deviceInfo.wifistatic[3] || '';
                    document.getElementById('wifiActive').checked = true;
                } else {
                    document.getElementById('wifiActive').checked = false;
                }
                
                // Diğer ayarları da doldur
                if (deviceInfo.remotetarget) {
                    document.getElementById('remoteTarget').value = deviceInfo.remotetarget;
                } else {
                }
                
                if (deviceInfo.ledBrightness !== undefined) {
                    // 25-255 aralığını 0-100 aralığına çevir
                    const brightnessPercent = Math.round(((deviceInfo.ledBrightness - 25) / (255 - 25)) * 100);
                    const clampedValue = Math.max(0, Math.min(100, brightnessPercent));
                    document.getElementById('ledBrightness').value = clampedValue;
                    document.getElementById('ledValue').textContent = clampedValue + '%';
                }
                
                if (deviceInfo.rs485Baudrate) {
                    document.getElementById('rs485Baud').value = deviceInfo.rs485Baudrate;
                }
                
                if (deviceInfo.ratelimit !== undefined) {
                    document.getElementById('accessRate').value = deviceInfo.ratelimit;
                }
                
                if (deviceInfo.mastercarduuid !== undefined && deviceInfo.mastercarduuid !== null) {
                    let mc = deviceInfo.mastercarduuid;
                    if (typeof mc === 'string') {
                        mc = parseInt(mc, 10);
                    }
                    if (!Number.isNaN(mc) && mc !== 0xFFFFFFFF) {
                        document.getElementById('masterCardUUID').value = '0x' + mc.toString(16).toUpperCase();
                    }
                } else {
                }
                
                // Relay ayarlarını doldur (array format: [mode, timeout])
                if (deviceInfo.relay1 && Array.isArray(deviceInfo.relay1) && deviceInfo.relay1.length >= 2) {
                    document.getElementById('relay1Mode').value = deviceInfo.relay1[0] || 0;
                    document.getElementById('relay1Timeout').value = deviceInfo.relay1[1] || 1500;
                }
                
                if (deviceInfo.relay2 && Array.isArray(deviceInfo.relay2) && deviceInfo.relay2.length >= 2) {
                    document.getElementById('relay2Mode').value = deviceInfo.relay2[0] || 0;
                    document.getElementById('relay2Timeout').value = deviceInfo.relay2[1] || 1500;
                }
                
                // Input ayarlarını doldur (array format: [mode, polarity, counter])
                if (deviceInfo.input1 && Array.isArray(deviceInfo.input1) && deviceInfo.input1.length >= 3) {
                    document.getElementById('input1Mode').value = deviceInfo.input1[0] || 0;
                    document.getElementById('input1Polarity').value = deviceInfo.input1[1] || 0;
                    document.getElementById('input1Counter').value = deviceInfo.input1[2] || 500;
                }
                
                if (deviceInfo.input2 && Array.isArray(deviceInfo.input2) && deviceInfo.input2.length >= 3) {
                    document.getElementById('input2Mode').value = deviceInfo.input2[0] || 0;
                    document.getElementById('input2Polarity').value = deviceInfo.input2[1] || 0;
                    document.getElementById('input2Counter').value = deviceInfo.input2[2] || 500;
                }
                
                // WiFi SSID ve şifre
                document.getElementById('wifiSSID').value = deviceInfo.wifissid || '';
                document.getElementById('wifiPassword').value = deviceInfo.wifipasswd || '';
                
                
                // Switch durumlarını doldur
                if (deviceInfo.isTerminal !== undefined) {
                    document.getElementById('terminalMode').checked = deviceInfo.isTerminal;
                }
                
                }

            } catch (error) {
                console.error('Cihaz ayarları yüklenirken hata:', error);
            } finally {
                isLoadingSettings = false;
            }
        }
        
        // LED Brightness slider
        document.getElementById('ledBrightness').addEventListener('input', function() {
            document.getElementById('ledValue').textContent = this.value + '%';
        });





        // Buton rengini değiştir
        function changeButtonColor(buttonId, isSuccess) {
            const button = document.getElementById(buttonId);
            
            if (button) {
                if (isSuccess) {
                    button.classList.add('btn-success');
                    button.classList.remove('btn-warning-modern', 'btn-primary-modern', 'btn-info-modern', 'btn-secondary-modern');
                    
                    setTimeout(() => {
                        if (buttonId.includes('wifi') || buttonId.includes('eth') || buttonId.includes('terminal')) {
                            button.classList.add('btn-primary-modern');
                        } else if (buttonId.includes('remote') || buttonId.includes('input')) {
                            button.classList.add('btn-info-modern');
                        } else if (buttonId.includes('relay') || buttonId.includes('backlight')) {
                            button.classList.add('btn-warning-modern');
                        } else {
                            button.classList.add('btn-secondary-modern');
                        }
                        button.classList.remove('btn-success');
                    }, 1000);
                } else {
                    button.classList.add('btn-danger');
                    button.classList.remove('btn-warning-modern', 'btn-primary-modern', 'btn-info-modern', 'btn-secondary-modern');
                    
                    setTimeout(() => {
                        if (buttonId.includes('wifi') || buttonId.includes('eth') || buttonId.includes('terminal')) {
                            button.classList.add('btn-primary-modern');
                        } else if (buttonId.includes('remote') || buttonId.includes('input')) {
                            button.classList.add('btn-info-modern');
                        } else if (buttonId.includes('relay') || buttonId.includes('backlight')) {
                            button.classList.add('btn-warning-modern');
                        } else {
                            button.classList.add('btn-secondary-modern');
                        }
                        button.classList.remove('btn-danger');
                    }, 1000);
                }
            }
        }

        // Send command to device
        async function sendCommand(command, data = {}, buttonId = null) {
            
            try {
                const response = await fetch(`/api/device_command/${deviceId}`, {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({ command: command, data: data })
                });
                
                const result = await response.json();
                
                if (result.success) {
                    let isSuccess = true;
                    if (result.message.includes('setfail') || result.message.includes('savefailed') || result.message.includes('uygulanamadı') || result.message.includes('kaydedilemedi')) {
                        isSuccess = false;
                    } else if (result.message.includes('setok') || result.message.includes('saveok') || result.message.includes('başarıyla')) {
                        isSuccess = true;
                    }
                    
                    if (buttonId) {
                        changeButtonColor(buttonId, isSuccess);
                    }
                    // Komut başarılıysa kısa gecikme ile ayarları yenile
                    setTimeout(() => { loadDeviceSettings(); }, 800);
                } else {
                    if (buttonId) {
                        changeButtonColor(buttonId, false);
                    }
                }
                
            } catch (error) {
                // Hata durumunda butonu kırmızı yap
                if (buttonId) {
                    changeButtonColor(buttonId, false);
                }
            }
        }

        // Raw command function for firmware operations
        async function sendRawCommand(command) {
            try {
                const response = await fetch(`/api/device_command/${deviceId}`, {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({ command: command, data: {} })
                });
                
                const result = await response.json();
                
                if (result.success) {
                    let isSuccess = true;
                    if (result.message && (result.message.includes('setfail') || result.message.toLowerCase().includes('fail'))) {
                        isSuccess = false;
                        alert('{{ _("operation_failed") }}: ' + result.message);
                    } else if (result.message && (result.message.includes('setok') || result.message.toLowerCase().includes('ok'))) {
                        isSuccess = true;
                        alert('{{ _("operation_successful") }}: ' + result.message);
                    } else {
                        alert('{{ _("command_sent") }}: ' + result.message);
                    }
                } else {
                    alert('{{ _("communication_error") }}: ' + (result.message || 'Unknown error'));
                }
                
            } catch (error) {
                alert('{{ _("network_error") }}: ' + error.message);
            }
        }

        // Network Settings Functions
        function setWifiStaticIP() {
            const data = {
                ip: document.getElementById('wifiIp').value,
                netmask: document.getElementById('wifiNetmask').value,
                gateway: document.getElementById('wifiGateway').value,
                dns: document.getElementById('wifiDns').value,
                active: document.getElementById('wifiActive').checked
            };
            sendCommand('setstaticwifi', data, 'wifiStaticBtn');
        }

        function setEthStaticIP() {
            const data = {
                ip: document.getElementById('ethIp').value,
                netmask: document.getElementById('ethNetmask').value,
                gateway: document.getElementById('ethGateway').value,
                dns: document.getElementById('ethDns').value,
                active: document.getElementById('ethActive').checked
            };
            sendCommand('setstaticeth', data, 'ethStaticBtn');
        }

        function setRemoteTarget() {
            const data = document.getElementById('remoteTarget').value;
            sendCommand('setremotetarget', data, 'remoteTargetBtn');
        }

        // Hardware Settings Functions
        function setRelay1() {
            const data = {
                mode: parseInt(document.getElementById('relay1Mode').value),
                timeout: parseInt(document.getElementById('relay1Timeout').value)
            };
            sendCommand('setrelay1', data, 'relay1Btn');
        }

        function setRelay2() {
            const data = {
                mode: parseInt(document.getElementById('relay2Mode').value),
                timeout: parseInt(document.getElementById('relay2Timeout').value)
            };
            sendCommand('setrelay2', data, 'relay2Btn');
        }

        function setInput1() {
            const data = {
                mode: parseInt(document.getElementById('input1Mode').value),
                polarity: parseInt(document.getElementById('input1Polarity').value),
                detectcounter: parseInt(document.getElementById('input1Counter').value)
            };
            sendCommand('setinput1', data, 'input1Btn');
        }

        function setInput2() {
            const data = {
                mode: parseInt(document.getElementById('input2Mode').value),
                polarity: parseInt(document.getElementById('input2Polarity').value),
                detectcounter: parseInt(document.getElementById('input2Counter').value)
            };
            sendCommand('setinput2', data, 'input2Btn');
        }

        function setRS485Baud() {
            const data = parseInt(document.getElementById('rs485Baud').value);
            sendCommand('setrs485baud', data, 'rs485BaudBtn');
        }

        function setBacklight() {
            const percentValue = parseInt(document.getElementById('ledBrightness').value);
            // 0-100 aralığını 25-255 aralığına çevir
            const data = Math.round(25 + (percentValue / 100) * (255 - 25));
            sendCommand('setbacklight', data, 'backlightBtn');
        }

        // System Settings Functions
        function setTerminalMode() {
            const data = document.getElementById('terminalMode').checked;
            sendCommand('setterminalmode', data, 'terminalModeBtn');
        }


        function setAccessRate() {
            const data = parseInt(document.getElementById('accessRate').value);
            sendCommand('setaccessrate', data, 'accessRateBtn');
        }

        function setMasterCard() {
            const uuid = document.getElementById('masterCardUUID').value;
            const data = uuid === '' ? 0xFFFFFFFF : parseInt(uuid, 10);
            sendCommand('setmastercarduuid', data, 'masterCardBtn');
        }

        function clearMasterCard() {
            const data = 0xFFFFFFFF; // uint32 max değeri
            sendCommand('setmastercarduuid', data, 'clearMasterCardBtn');
        }

        // WiFi Settings Functions
        function setWifiConfig() {
            const ssid = document.getElementById('wifiSSID').value;
            const password = document.getElementById('wifiPassword').value;
            
            // SSID ve şifreyi aynı anda gönder
            const data = {
                setwifissid: ssid,
                setwifipassword: password
            };
            sendCommand('setwifissid', data, 'wifiConfigBtn');
        }

        // Firmware Management Functions
        function updateFirmware() {
            if (confirm('{{ _("confirm_firmware_update") }}')) {
                sendRawCommand('setsoftwareupdate');
            }
        }

        function validateFirmware() {
            if (confirm('{{ _("confirm_firmware_validate") }}')) {
                sendRawCommand('setvalidapp');
            }
        }

        // RFID Card Management Functions
        function addCards() {
            const cardsText = document.getElementById('addCards').value;
            if (!cardsText.trim()) {
                alert('Lütfen kart UUID\'leri girin!');
                return;
            }
            
            const cards = cardsText.split('\n').filter(card => card.trim() !== '');
            sendCommand('addcards', cards, 'addCardsBtn');
        }

        function deleteCards() {
            const cardsText = document.getElementById('deleteCards').value;
            if (!cardsText.trim()) {
                alert('Lütfen silinecek kart UUID\'leri girin!');
                return;
            }
            
            const cards = cardsText.split('\n').filter(card => card.trim() !== '');
            sendCommand('deletecards', cards, 'deleteCardsBtn');
        }

        function getCards() {
            sendCommand('getcards', {}, 'getCardsBtn');
        }

        function updateCards() {
            sendCommand('updatecards', {}, 'updateCardsBtn');
        }

        function formatCards() {
            if (confirm('Tüm RFID kartları silinecek. Bu işlem geri alınamaz! Devam etmek istiyor musunuz?')) {
                sendCommand('formatcards', {}, 'formatCardsBtn');
            }
        }

        // Maintenance Functions
        function getDeviceInfo() {
            sendCommand('getdeviceinfo');
        }

        function clearInputAlarms() {
            sendCommand('clearinputs');
        }

        function clearLogs() {
            sendCommand('clearlog');
        }

        function doBackup() {
            sendCommand('dobackup');
        }

        function formatFS() {
            if (confirm('Dosya sistemi formatlanacak. Bu işlem geri alınamaz! Devam etmek istiyor musunuz?')) {
                sendCommand('formatfs');
            }
        }

        function restartDevice() {
            if (confirm('Cihaz yeniden başlatılacak. Devam etmek istiyor musunuz?')) {
                sendCommand('restart');
            }
        }

        function setFactorySettings() {
            if (confirm('Cihaz fabrika ayarlarına döndürülecek. Tüm veriler silinecek! Devam etmek istiyor musunuz?')) {
                sendCommand('setfactorysettings');
            }
        }
    </script>
</body>
</html> 