@extends('layouts.admin')

@section('title', 'Kullanıcı Düzenle')
@section('page-title', 'Kullanıcı Düzenle: ' . $user->name)

@section('content')

<div class="max-w-lg mt-2">
    <form method="POST" action="{{ route('admin.kullanicilar.update', $user) }}" class="space-y-5">
        @csrf
        @method('PUT')

        <div class="bg-white rounded-xl shadow-sm border border-gray-100 p-6 space-y-4">
            <div>
                <label class="block text-sm font-medium text-gray-700 mb-1">Ad Soyad <span class="text-red-500">*</span></label>
                <input type="text" name="name" value="{{ old('name', $user->name) }}"
                       class="w-full border border-gray-300 rounded-lg px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-orange-400 @error('name') border-red-400 @enderror">
                @error('name')<p class="text-red-500 text-xs mt-1">{{ $message }}</p>@enderror
            </div>

            <div>
                <label class="block text-sm font-medium text-gray-700 mb-1">E-posta <span class="text-red-500">*</span></label>
                <input type="email" name="email" value="{{ old('email', $user->email) }}"
                       class="w-full border border-gray-300 rounded-lg px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-orange-400 @error('email') border-red-400 @enderror">
                @error('email')<p class="text-red-500 text-xs mt-1">{{ $message }}</p>@enderror
            </div>

            <div>
                <label class="block text-sm font-medium text-gray-700 mb-1">Yeni Şifre <span class="text-gray-400 font-normal">(boş bırakılırsa değişmez)</span></label>
                <div class="relative">
                    <input type="password" name="password" id="passwordField"
                           class="w-full border border-gray-300 rounded-lg px-3 py-2 pr-10 text-sm focus:outline-none focus:ring-2 focus:ring-orange-400 @error('password') border-red-400 @enderror">
                    <button type="button" id="togglePasswordBtn"
                            class="absolute right-3 top-1/2 -translate-y-1/2 text-gray-400 hover:text-gray-600">
                        <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 12a3 3 0 11-6 0 3 3 0 016 0z"/><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7-1.274 4.057-5.064 7-9.542 7-4.477 0-8.268-2.943-9.542-7z"/></svg>
                    </button>
                </div>
                {{-- Güvenlik Göstergesi (bilgi amaçlı) --}}
                <div id="editStrengthBar" class="hidden mt-2">
                    <div class="flex gap-1 mb-1">
                        <div id="editBar1" class="h-1.5 flex-1 rounded-full bg-gray-200 transition-colors"></div>
                        <div id="editBar2" class="h-1.5 flex-1 rounded-full bg-gray-200 transition-colors"></div>
                        <div id="editBar3" class="h-1.5 flex-1 rounded-full bg-gray-200 transition-colors"></div>
                    </div>
                    <p id="editStrengthLabel" class="text-xs text-gray-400"></p>
                </div>
                @error('password')<p class="text-red-500 text-xs mt-1">{{ $message }}</p>@enderror
            </div>

            <div>
                <label class="block text-sm font-medium text-gray-700 mb-1">Şifre Tekrar</label>
                <div class="relative">
                    <input type="password" name="password_confirmation" id="passwordConfirmField"
                           class="w-full border border-gray-300 rounded-lg px-3 py-2 pr-10 text-sm focus:outline-none focus:ring-2 focus:ring-orange-400">
                    <button type="button" id="togglePasswordConfirmBtn"
                            class="absolute right-3 top-1/2 -translate-y-1/2 text-gray-400 hover:text-gray-600">
                        <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 12a3 3 0 11-6 0 3 3 0 016 0z"/><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7-1.274 4.057-5.064 7-9.542 7-4.477 0-8.268-2.943-9.542-7z"/></svg>
                    </button>
                </div>
                <p id="editMatchMsg" class="hidden text-red-500 text-xs mt-1">Şifreler eşleşmiyor.</p>
                <p id="editMatchOk" class="hidden text-green-600 text-xs mt-1">Şifreler eşleşiyor.</p>
            </div>

            <div>
                <label class="block text-sm font-medium text-gray-700 mb-1">Rol <span class="text-red-500">*</span></label>
                <select name="role" id="roleSelect"
                        class="w-full border border-gray-300 rounded-lg px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-orange-400 @error('role') border-red-400 @enderror">
                    @foreach($roles as $role)
                    <option value="{{ $role->name }}" {{ old('role', $user->getRoleNames()->first()) == $role->name ? 'selected' : '' }}>{{ $role->name }}</option>
                    @endforeach
                </select>
                @error('role')<p class="text-red-500 text-xs mt-1">{{ $message }}</p>@enderror
            </div>

            {{-- Rol İzin Önizlemesi --}}
            <div id="rolePermissionsPanel" class="hidden">
                <p class="text-xs font-medium text-gray-500 mb-2">Bu rolün yetkileri:</p>
                <div id="rolePermissionsBadges" class="flex flex-wrap gap-1.5"></div>
            </div>
        </div>

        <div class="flex items-center gap-3">
            <button type="submit" class="bg-primary text-white px-6 py-2.5 rounded-lg text-sm font-medium hover:bg-orange-600 transition-colors">
                Değişiklikleri Kaydet
            </button>
            <a href="{{ route('admin.kullanicilar.index') }}" class="text-gray-500 hover:text-gray-700 text-sm">İptal</a>
        </div>
    </form>
</div>

<script nonce="{{ app('csp-nonce') }}">
// ─── Göz butonu — inline onclick yerine addEventListener (CSP uyumlu) ─────────
const eyeOpen  = '<svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 12a3 3 0 11-6 0 3 3 0 016 0z"/><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7-1.274 4.057-5.064 7-9.542 7-4.477 0-8.268-2.943-9.542-7z"/></svg>';
const eyeClosed = '<svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13.875 18.825A10.05 10.05 0 0112 19c-4.478 0-8.268-2.943-9.543-7a9.97 9.97 0 011.563-3.029m5.858.908a3 3 0 114.243 4.243M9.878 9.878l4.242 4.242M9.88 9.88l-3.29-3.29m7.532 7.532l3.29 3.29M3 3l3.59 3.59m0 0A9.953 9.953 0 0112 5c4.478 0 8.268 2.943 9.543 7a10.025 10.025 0 01-4.132 5.411m0 0L21 21"/></svg>';

function bindToggle(btnId, fieldId) {
    var btn = document.getElementById(btnId);
    var field = document.getElementById(fieldId);
    if (!btn || !field) return;
    btn.addEventListener('click', function () {
        var isPassword = field.type === 'password';
        field.type = isPassword ? 'text' : 'password';
        btn.innerHTML = isPassword ? eyeClosed : eyeOpen;
    });
}

document.addEventListener('DOMContentLoaded', function () {
    bindToggle('togglePasswordBtn', 'passwordField');
    bindToggle('togglePasswordConfirmBtn', 'passwordConfirmField');

    // Şifre güvenlik göstergesi
    var pwField = document.getElementById('passwordField');
    if (pwField) {
        pwField.addEventListener('input', function () {
            updateEditStrength(this.value);
            checkEditPasswordMatch();
        });
    }

    // Şifre tekrar eşleşme kontrolü
    var confField = document.getElementById('passwordConfirmField');
    if (confField) {
        confField.addEventListener('input', checkEditPasswordMatch);
    }

    // Rol izin paneli
    var sel = document.getElementById('roleSelect');
    if (sel && sel.value) updatePermissionPanel(sel.value);
});

const rolePermissions = @json($rolePermissions);

const permLabels = {
    'view job postings':       'İlanları Görüntüle',
    'create job postings':     'İlan Oluştur',
    'edit job postings':       'İlan Düzenle',
    'delete job postings':     'İlan Sil',
    'publish job postings':    'İlan Yayınla',
    'view applications':       'Başvuruları Görüntüle',
    'edit application status': 'Başvuru Durumu Değiştir',
    'add application notes':   'Başvuruya Not Ekle',
    'export applications':     'Başvuruları Dışa Aktar',
    'view interviews':         'Görüşmeleri Görüntüle',
    'manage interviews':       'Görüşmeleri Yönet',
    'manage departments':      'Departmanları Yönet',
    'manage general settings':          'Genel Ayarları Yönet',
    'manage google calendar settings':  'Google Calendar Ayarlarını Yönet',
    'manage virustotal settings':       'VirusTotal Ayarlarını Yönet',
    'manage system settings':           'Sistem Ayarlarını Yönet',
    'manage kvkk settings':             'KVKK Ayarlarını Yönet',
    'manage users':            'Kullanıcıları Yönet',
    'view logs':               'Logları Görüntüle',
};

function updatePermissionPanel(roleName) {
    var panel  = document.getElementById('rolePermissionsPanel');
    var badges = document.getElementById('rolePermissionsBadges');
    var perms  = rolePermissions[roleName] || [];

    if (!roleName || perms.length === 0) {
        panel.classList.add('hidden');
        return;
    }

    // XSS koruması: innerHTML yerine createElement kullan
    while (badges.firstChild) badges.removeChild(badges.firstChild);
    perms.forEach(function (p) {
        var span = document.createElement('span');
        span.className = 'text-xs bg-blue-50 text-blue-700 px-2 py-0.5 rounded-full border border-blue-100';
        span.textContent = permLabels[p] || p;
        badges.appendChild(span);
    });

    panel.classList.remove('hidden');
}

document.getElementById('roleSelect').addEventListener('change', function () {
    updatePermissionPanel(this.value);
});

// Çift DOMContentLoaded kaldırıldı — ilk DOMContentLoaded bloğunda (satır 107) zaten çağrılıyor

// ─── Şifre Eşleşme Kontrolü ──────────────────────────────────────────────────
function checkEditPasswordMatch() {
    var pwd  = document.getElementById('passwordField').value;
    var conf = document.getElementById('passwordConfirmField').value;
    var msg  = document.getElementById('editMatchMsg');
    var ok   = document.getElementById('editMatchOk');

    if (!conf) { msg.classList.add('hidden'); ok.classList.add('hidden'); return; }

    if (pwd !== conf) {
        msg.classList.remove('hidden');
        ok.classList.add('hidden');
    } else {
        msg.classList.add('hidden');
        ok.classList.remove('hidden');
    }
}

// ─── Şifre Güvenlik Göstergesi (bilgi amaçlı) ────────────────────────────────
function updateEditStrength(val) {
    var bar = document.getElementById('editStrengthBar');
    var label = document.getElementById('editStrengthLabel');
    var b1 = document.getElementById('editBar1');
    var b2 = document.getElementById('editBar2');
    var b3 = document.getElementById('editBar3');
    if (!val) { bar.classList.add('hidden'); return; }
    bar.classList.remove('hidden');
    var score = 0;
    if (val.length >= 8) score++;
    if (/[A-Z]/.test(val) && /[a-z]/.test(val)) score++;
    if (/[0-9]/.test(val)) score++;
    if (/[^A-Za-z0-9]/.test(val)) score++;
    var result;
    if (score <= 1) result = { score: 1, label: 'Zayıf — daha güçlü bir şifre kullanın', color: 'red' };
    else if (score <= 3) result = { score: 2, label: 'Orta — büyük/küçük harf, rakam ve özel karakter ekleyin', color: 'yellow' };
    else result = { score: 3, label: 'Güçlü', color: 'green' };
    var colors = { red: 'bg-red-400', yellow: 'bg-yellow-400', green: 'bg-green-500' };
    var c = colors[result.color] || 'bg-gray-200';
    b1.className = 'h-1.5 flex-1 rounded-full transition-colors ' + c;
    b2.className = 'h-1.5 flex-1 rounded-full transition-colors ' + (result.score >= 2 ? c : 'bg-gray-200');
    b3.className = 'h-1.5 flex-1 rounded-full transition-colors ' + (result.score >= 3 ? c : 'bg-gray-200');
    var textColors = { red: 'text-red-500', yellow: 'text-yellow-600', green: 'text-green-600' };
    label.className = 'text-xs ' + (textColors[result.color] || 'text-gray-400');
    label.textContent = result.label;
}
</script>

@endsection