@extends('layouts.admin')

@section('title', 'Yeni Kullanıcı')
@section('page-title', 'Yeni Kullanıcı Oluştur')

@section('content')

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

        <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') }}"
                       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') }}"
                       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">Şifre <span class="text-red-500">*</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 eye-icon" 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 --}}
                <div id="strengthBar" class="hidden mt-2">
                    <div class="flex gap-1 mb-1">
                        <div id="bar1" class="h-1.5 flex-1 rounded-full bg-gray-200 transition-colors"></div>
                        <div id="bar2" class="h-1.5 flex-1 rounded-full bg-gray-200 transition-colors"></div>
                        <div id="bar3" class="h-1.5 flex-1 rounded-full bg-gray-200 transition-colors"></div>
                    </div>
                    <p id="strengthLabel" 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 <span class="text-red-500">*</span></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 eye-icon" 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="createMatchMsg" class="hidden text-red-500 text-xs mt-1">Şifreler eşleşmiyor.</p>
                <p id="createMatchOk" 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">
                    <option value="">Seçiniz</option>
                    @foreach($roles as $role)
                    <option value="{{ $role->name }}" {{ old('role') == $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">
                Kullanıcı Oluştur
            </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') }}">
(function () {
    var 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>';
    var 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;
        });
    }

    var rolePermissions = @json($rolePermissions);

    var 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 site settings':    'Site 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');
    }

    // ─── Şifre Güvenlik Göstergesi ────────────────────────────────────────────
    function checkPasswordStrength(val) {
        if (!val) return { score: 0, label: '', color: '' };
        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++;
        if (score <= 1) return { score: 1, label: 'Zayıf — daha güçlü bir şifre kullanın', color: 'red' };
        if (score <= 3) return { score: 2, label: 'Orta — büyük/küçük harf, rakam ve özel karakter ekleyin', color: 'yellow' };
        return { score: 3, label: 'Güçlü', color: 'green' };
    }

    function updateStrength(val) {
        var bar   = document.getElementById('strengthBar');
        var label = document.getElementById('strengthLabel');
        var b1    = document.getElementById('bar1');
        var b2    = document.getElementById('bar2');
        var b3    = document.getElementById('bar3');
        if (!val) { bar.classList.add('hidden'); return; }
        bar.classList.remove('hidden');
        var result = checkPasswordStrength(val);
        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;
    }

    // ─── Şifre Eşleşme Kontrolü ──────────────────────────────────────────────
    function checkPasswordMatch() {
        var pwd  = document.getElementById('passwordField').value;
        var conf = document.getElementById('passwordConfirmField').value;
        var msg  = document.getElementById('createMatchMsg');
        var ok   = document.getElementById('createMatchOk');
        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');
        }
    }

    document.addEventListener('DOMContentLoaded', function () {
        // Göz butonları
        bindToggle('togglePasswordBtn', 'passwordField');
        bindToggle('togglePasswordConfirmBtn', 'passwordConfirmField');

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

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

        // Rol izin paneli
        var sel = document.getElementById('roleSelect');
        if (sel) {
            sel.addEventListener('change', function () {
                updatePermissionPanel(this.value);
            });
            // Sayfa yüklendiğinde eski değer varsa göster (validation hatası sonrası)
            if (sel.value) updatePermissionPanel(sel.value);
        }
    });
})();
</script>

@endsection