@extends('layouts.dashboard')

@section('content')
<div class="max-w-4xl mx-auto space-y-6">
    <!-- Header -->
    <div class="mb-6">
        <h2 class="text-2xl font-bold text-slate-800">Keamanan Akun</h2>
        <p class="text-slate-500">Kelola password dan keamanan akun Anda.</p>
    </div>

    <!-- Alert Messages -->
    @if(session('success'))
    <div class="bg-emerald-50 text-emerald-600 px-4 py-3 rounded-lg flex items-center gap-3 border border-emerald-100">
        <i class="fa-solid fa-circle-check"></i>
        {{ session('success') }}
    </div>
    @endif

    @if($errors->any())
    <div class="bg-red-50 text-red-600 px-4 py-3 rounded-lg border border-red-100 mb-4">
        <ul class="list-disc list-inside text-sm">
            @foreach($errors->all() as $error)
                <li>{{ $error }}</li>
            @endforeach
        </ul>
    </div>
    @endif

    <div class="grid grid-cols-1 gap-6">

         <!-- 1. Ubah Password -->
         <div class="bg-white p-6 rounded-xl border border-slate-200 shadow-sm">
            <div class="flex items-center gap-3 mb-6 pb-4 border-b border-slate-100">
                <div class="w-10 h-10 rounded-full bg-orange-100 text-orange-600 flex items-center justify-center">
                    <i class="fa-solid fa-lock text-lg"></i>
                </div>
                <div>
                    <h3 class="font-bold text-slate-800">Ubah Password</h3>
                    <p class="text-xs text-slate-500">Pastikan menggunakan password yang kuat dan aman.</p>
                </div>
            </div>
    
            <form action="{{ route('profile.password') }}" method="POST">
                @csrf
                @method('PUT')
                <div class="space-y-4">
                    <div>
                        <label class="block text-sm font-medium text-slate-700 mb-1">Password Saat Ini</label>
                        <input type="password" name="current_password" class="w-full px-4 py-2 border border-slate-300 rounded-lg focus:ring-2 focus:ring-emerald-500 focus:border-emerald-500 transition-colors" required>
                    </div>
    
                    <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                        <div>
                            <label class="block text-sm font-medium text-slate-700 mb-1">Password Baru</label>
                            <input type="password" name="password" class="w-full px-4 py-2 border border-slate-300 rounded-lg focus:ring-2 focus:ring-emerald-500 focus:border-emerald-500 transition-colors" required>
                        </div>
                        <div>
                            <label class="block text-sm font-medium text-slate-700 mb-1">Konfirmasi Password</label>
                            <input type="password" name="password_confirmation" class="w-full px-4 py-2 border border-slate-300 rounded-lg focus:ring-2 focus:ring-emerald-500 focus:border-emerald-500 transition-colors" required>
                        </div>
                    </div>
    
                    <div class="pt-2">
                        <button type="submit" class="bg-emerald-600 hover:bg-emerald-700 text-white px-6 py-2 rounded-lg font-medium transition-colors text-sm">
                            Update Password
                        </button>
                    </div>
                </div>
            </form>
        </div>

        <!-- 2. Custom Login URL -->
        <div class="bg-white p-6 rounded-xl border border-slate-200 shadow-sm">
            <div class="flex items-center gap-3 mb-6 pb-4 border-b border-slate-100">
                <div class="w-10 h-10 rounded-full bg-indigo-100 text-indigo-600 flex items-center justify-center">
                    <i class="fa-solid fa-user-secret text-lg"></i>
                </div>
                <div>
                    <h3 class="font-bold text-slate-800">Halaman Login Rahasia</h3>
                    <p class="text-xs text-slate-500">Ubah URL akses login untuk mempersulit akses orang asing.</p>
                </div>
            </div>

            <form action="{{ route('security.slug') }}" method="POST" id="slugForm">
                @csrf
                @method('PATCH')
                <input type="hidden" name="security_password" id="slugPassword">
                <div class="space-y-4">
                    <div>
                        <label class="block text-sm font-medium text-slate-700 mb-1">Login Slug</label>
                        <div class="flex flex-col shadow-sm rounded-lg overflow-hidden group focus-within:ring-2 focus-within:ring-emerald-500">
                            <span class="inline-flex items-center px-4 py-2 bg-slate-50 border border-b-0 border-slate-300 text-slate-500 sm:text-sm overflow-hidden whitespace-nowrap text-ellipsis w-full">
                                {{ url('/login') }}/
                            </span>
                            <input type="text" name="login_slug" value="{{ auth()->user()->login_slug }}" placeholder="admin" class="flex-1 block w-full px-4 py-2 border border-slate-300 focus:outline-none focus:border-emerald-500 transition-colors sm:text-sm min-w-0" required pattern="[a-zA-Z0-9]+" title="Hanya huruf dan angka tanpa spasi">
                        </div>
                        <p class="mt-2 text-xs text-slate-500">
                            <i class="fa-solid fa-circle-info text-blue-500 mr-1"></i>
                            Hanya satu kata tanpa spasi. URL login baru Anda akan menjadi: <span class="font-mono bg-slate-100 px-1 py-0.5 rounded text-slate-700">{{ url('/login') }}/<span class="text-emerald-600 font-bold">[slug]</span></span>
                        </p>
                    </div>

                    <div class="pt-2">
                        <button type="button" onclick="openPasswordModal('slugForm')" class="bg-emerald-600 hover:bg-emerald-700 text-white px-6 py-2 rounded-lg font-medium transition-colors text-sm">
                            Simpan URL Login
                        </button>
                    </div>
                </div>
            </form>
        </div>

        <!-- 3. Security Question -->
        <div class="bg-white p-6 rounded-xl border border-slate-200 shadow-sm">
            <div class="flex items-center gap-3 mb-6 pb-4 border-b border-slate-100">
                <div class="w-10 h-10 rounded-full bg-blue-100 text-blue-600 flex items-center justify-center">
                    <i class="fa-solid fa-question-circle text-lg"></i>
                </div>
                <div>
                    <h3 class="font-bold text-slate-800">Pertanyaan Keamanan</h3>
                    <p class="text-xs text-slate-500">Lapisan keamanan tambahan saat login.</p>
                </div>
            </div>

            <form action="{{ route('security.question') }}" method="POST" id="questionForm">
                @csrf
                @method('PATCH')
                <input type="hidden" name="security_password" id="questionPassword">
                
                <div class="flex items-center justify-between mb-6 bg-slate-50 p-4 rounded-lg border border-slate-100">
                    <div class="flex gap-3">
                        <div class="flex-shrink-0 mt-0.5">
                            <i class="fa-solid fa-shield-halved text-emerald-500 text-base"></i>
                        </div>
                        <div>
                            <label class="text-sm font-medium text-slate-700 block cursor-pointer" for="secQCheckbox">Aktifkan Pertanyaan Keamanan</label>
                            <p class="text-xs text-slate-500 mt-0.5">Anda harus menjawab pertanyaan ini setelah memasukkan password.</p>
                        </div>
                    </div>
                    <label class="relative inline-flex items-center cursor-pointer">
                      <input type="checkbox" id="secQCheckbox" name="is_security_question_enabled" value="true" class="sr-only peer" onchange="toggleSecQ()" {{ auth()->user()->is_security_question_enabled ? 'checked' : '' }}>
                      <div class="w-11 h-6 bg-slate-200 peer-focus:outline-none peer-focus:ring-4 peer-focus:ring-blue-300 rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:border-gray-300 after:border after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-blue-600"></div>
                    </label>
                </div>

                <div id="secQInputs" class="space-y-4 {{ auth()->user()->is_security_question_enabled ? '' : 'hidden' }}">
                     <div>
                        <label class="block text-sm font-medium text-slate-700 mb-1">Pilih Pertanyaan</label>
                        <select name="security_question" class="w-full px-4 py-2 border border-slate-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500 transition-colors bg-white">
                             @php
                                $questions = [
                                    'Nama teman terbaik kamu',
                                    'Nama kota kamu',
                                    'Nama hewan kesayangan kamu',
                                    'Bulan lahir kamu',
                                    'Nama sekolah kamu',
                                    'Nama ketua RT kamu',
                                    'Kata Ajaib kamu'
                                ];
                                $current = auth()->user()->security_question;
                             @endphp
                             @foreach($questions as $q)
                                <option value="{{ $q }}" {{ $current == $q ? 'selected' : '' }}>{{ $q }}</option>
                             @endforeach
                        </select>
                     </div>
                     <div>
                        <label class="block text-sm font-medium text-slate-700 mb-1">Jawaban Anda</label>
                        <input type="text" name="security_answer" placeholder="Masukkan jawaban..." class="w-full px-4 py-2 border border-slate-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500 transition-colors">
                        <p class="text-[10px] text-slate-400 mt-1"><i class="fa-solid fa-check-double mr-1 text-emerald-500"></i> Jawaban tidak case-sensitive dan boleh menggunakan spasi.</p>
                     </div>
                </div>
                
                <div class="pt-4 border-t border-slate-100 mt-4">
                     <button type="button" onclick="openPasswordModal('questionForm')" class="bg-emerald-600 hover:bg-emerald-700 text-white px-6 py-2 rounded-lg font-medium transition-colors text-sm">
                        Simpan Pengaturan
                     </button>
                </div>
            </form>
            <script>
                function toggleSecQ() {
                    const chk = document.getElementById('secQCheckbox');
                    const inputs = document.getElementById('secQInputs');
                    if(chk.checked) {
                        inputs.classList.remove('hidden');
                    } else {
                        inputs.classList.add('hidden');
                    }
                }

                let targetFormId = null;

                function openPasswordModal(formId) {
                    targetFormId = formId;
                    document.getElementById('passwordConfirmModal').classList.remove('hidden');
                    document.getElementById('modalPasswordInput').value = '';
                    setTimeout(() => document.getElementById('modalPasswordInput').focus(), 100);
                }

                function closePasswordModal() {
                    document.getElementById('passwordConfirmModal').classList.add('hidden');
                    targetFormId = null;
                }

                function submitPasswordConfirm() {
                    const password = document.getElementById('modalPasswordInput').value;
                    if(!password) {
                        alert('Mohon masukkan password Anda.');
                        return;
                    }

                    if(targetFormId) {
                        const form = document.getElementById(targetFormId);
                        // Find hidden input inside the form
                        const hiddenInput = form.querySelector('input[name="security_password"]');
                        if(hiddenInput) {
                            hiddenInput.value = password;
                            form.submit();
                            closePasswordModal();
                        }
                    }
                }
            </script>

            <!-- Password Confirmation Modal -->
            <div id="passwordConfirmModal" class="fixed inset-0 z-[100] hidden" aria-labelledby="modal-title" role="dialog" aria-modal="true">
                <div class="flex items-end justify-center min-h-screen pt-4 px-4 pb-20 text-center sm:block sm:p-0">
                    <div class="fixed inset-0 bg-gray-500 bg-opacity-75 transition-opacity" aria-hidden="true" onclick="closePasswordModal()"></div>
                    <span class="hidden sm:inline-block sm:align-middle sm:h-screen" aria-hidden="true">&#8203;</span>
                    <div class="inline-block align-bottom bg-white rounded-lg text-left overflow-hidden shadow-xl transform transition-all sm:my-8 sm:align-middle sm:max-w-lg w-full">
                        <div class="bg-white px-4 pt-5 pb-4 sm:p-6 sm:pb-4">
                            <div class="sm:flex sm:items-start">
                                <div class="mx-auto flex-shrink-0 flex items-center justify-center h-12 w-12 rounded-full bg-orange-100 sm:mx-0 sm:h-10 sm:w-10">
                                    <i class="fa-solid fa-lock text-orange-600"></i>
                                </div>
                                <div class="mt-3 text-center sm:mt-0 sm:ml-4 sm:text-left w-full">
                                    <h3 class="text-lg leading-6 font-medium text-gray-900" id="modal-title">Konfirmasi Password</h3>
                                    <div class="mt-2 text-sm text-gray-500">
                                        <p>Untuk keamanan, silakan masukkan password Anda untuk konfirmasi perubahan ini.</p>
                                    </div>
                                    <div class="mt-4">
                                         <input type="password" id="modalPasswordInput" class="w-full px-4 py-2 border border-slate-300 rounded-lg focus:ring-2 focus:ring-emerald-500 focus:border-emerald-500 transition-colors" placeholder="Password Anda..." onkeyup="if(event.key === 'Enter') submitPasswordConfirm()">
                                    </div>
                                </div>
                            </div>
                        </div>
                        <div class="bg-gray-50 px-4 py-3 sm:px-6 sm:flex sm:flex-row-reverse">
                            <button type="button" onclick="submitPasswordConfirm()" class="w-full inline-flex justify-center rounded-md border border-transparent shadow-sm px-4 py-2 bg-slate-800 text-base font-medium text-white hover:bg-slate-900 focus:outline-none sm:ml-3 sm:w-auto sm:text-sm">Konfirmasi</button>
                            <button type="button" onclick="closePasswordModal()" class="mt-3 w-full inline-flex justify-center rounded-md border border-gray-300 shadow-sm px-4 py-2 bg-white text-base font-medium text-gray-700 hover:bg-gray-50 focus:outline-none sm:mt-0 sm:ml-3 sm:w-auto sm:text-sm">Batal</button>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- 4. Hard Reset Password -->
        <div class="bg-white p-6 rounded-xl border border-slate-200 shadow-sm">
            <div class="flex items-center gap-3 mb-6 pb-4 border-b border-slate-100">
                <div class="w-10 h-10 rounded-full bg-red-100 text-red-600 flex items-center justify-center">
                    <i class="fa-solid fa-radiation text-lg"></i>
                </div>
                <div>
                    <h3 class="font-bold text-slate-800">Hard Reset Password</h3>
                    <p class="text-xs text-slate-500">Link rahasia untuk mereset password tanpa login (Darurat).</p>
                </div>
            </div>

            <form action="{{ route('security.hard-reset') }}" method="POST" id="hardResetForm">
                @csrf
                @method('PATCH')
                <input type="hidden" name="security_password" id="hardResetPassword">
                
                <div class="flex items-center justify-between mb-6 bg-slate-50 p-4 rounded-lg border border-slate-100">
                    <div class="flex gap-3">
                        <div class="flex-shrink-0 mt-0.5">
                            <i class="fa-solid fa-triangle-exclamation text-red-500 text-base"></i>
                        </div>
                        <div>
                            <label class="text-sm font-medium text-slate-700 block cursor-pointer" for="hardResetCheckbox">Aktifkan Hard Reset</label>
                            <p class="text-xs text-slate-500 mt-0.5">Memungkinkan reset password lewat URL rahasia tanpa password lama.</p>
                        </div>
                    </div>
                    <label class="relative inline-flex items-center cursor-pointer">
                      <input type="checkbox" id="hardResetCheckbox" name="hard_reset_enabled" value="true" class="sr-only peer" onchange="toggleHardReset()" {{ auth()->user()->hard_reset_enabled ? 'checked' : '' }}>
                      <div class="w-11 h-6 bg-slate-200 peer-focus:outline-none peer-focus:ring-4 peer-focus:ring-red-300 rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:border-gray-300 after:border after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-red-600"></div>
                    </label>
                </div>

                <div id="hardResetInputs" class="space-y-4 {{ auth()->user()->hard_reset_enabled ? '' : 'hidden' }}">
                     <div>
                        <label class="block text-sm font-medium text-slate-700 mb-1">Kode Rahasia (URL)</label>
                        <div class="flex flex-col shadow-sm rounded-lg overflow-hidden group focus-within:ring-2 focus-within:ring-red-500 relative">
                            <span class="inline-flex items-center px-4 py-2 bg-slate-50 border border-b-0 border-slate-300 text-slate-500 sm:text-sm overflow-hidden whitespace-nowrap text-ellipsis w-full">
                                {{ url('/') }}/
                            </span>
                            <div class="flex w-full">
                                <input type="password" id="hardResetInput" name="hard_reset_code" value="{{ auth()->user()->hard_reset_code }}" placeholder="x8s7_s@!a" class="flex-1 block w-full px-4 py-2 border border-slate-300 border-r-0 focus:outline-none focus:border-red-500 transition-colors sm:text-sm min-w-0" pattern="(?=.*[a-zA-Z])(?=.*\d)(?=.*[\W_]).{10,}" title="Minimal 10 karakter, harus ada huruf, angka, dan simbol">
                                <button type="button" onclick="toggleSecretVisibility()" class="px-3 bg-white border border-l-0 border-slate-300 text-slate-400 hover:text-slate-600 focus:outline-none">
                                    <i class="fa-solid fa-eye" id="hardResetEyeIcon"></i>
                                </button>
                            </div>
                        </div>
                        
                        <div class="flex flex-wrap gap-2 mt-2">
                             @if(auth()->user()->hard_reset_code)
                             <button type="button" onclick="copySecretUrl()" class="text-xs bg-slate-100 hover:bg-slate-200 text-slate-600 px-3 py-1.5 rounded-md transition-colors flex items-center gap-1.5">
                                 <i class="fa-regular fa-copy"></i> Salin Link
                             </button>
                             <button type="button" onclick="downloadSecret()" class="text-xs bg-slate-100 hover:bg-slate-200 text-slate-600 px-3 py-1.5 rounded-md transition-colors flex items-center gap-1.5">
                                 <i class="fa-solid fa-download"></i> Simpan (txt)
                             </button>
                             @endif
                        </div>

                        <p class="mt-2 text-xs text-slate-500">
                            <i class="fa-solid fa-circle-info text-red-500 mr-1"></i>
                            Harus unik, minimal 10 karakter, gabungan huruf, angka, dan simbol.
                        </p>
                     </div>
                </div>
                
                <div class="pt-4 border-t border-slate-100 mt-4">
                     <button type="button" onclick="openPasswordModal('hardResetForm')" class="bg-red-600 hover:bg-red-700 text-white px-6 py-2 rounded-lg font-medium transition-colors text-sm">
                        Simpan Pengaturan
                     </button>
                </div>
            </form>
            <script>
                function toggleHardReset() {
                    const chk = document.getElementById('hardResetCheckbox');
                    const inputs = document.getElementById('hardResetInputs');
                    if(chk.checked) {
                        inputs.classList.remove('hidden');
                    } else {
                        inputs.classList.add('hidden');
                    }
                }

                function toggleSecretVisibility() {
                    const input = document.getElementById('hardResetInput');
                    const icon = document.getElementById('hardResetEyeIcon');
                    if (input.type === 'password') {
                        input.type = 'text';
                        icon.classList.remove('fa-eye');
                        icon.classList.add('fa-eye-slash');
                    } else {
                        input.type = 'password';
                        icon.classList.remove('fa-eye-slash');
                        icon.classList.add('fa-eye');
                    }
                }

                function copySecretUrl() {
                    const code = document.getElementById('hardResetInput').value;
                    if(!code) return;
                    const url = "{{ url('/') }}/" + code;
                    
                    if(navigator.clipboard && navigator.clipboard.writeText) {
                         navigator.clipboard.writeText(url).then(() => {
                             // Assuming showToast is globally available from layout
                             if(typeof showToast === 'function') showToast('Link Hard Reset disalin!');
                             else alert('Copied!');
                         });
                    } else {
                        alert('URL: ' + url);
                    }
                }

                function downloadSecret() {
                    const code = document.getElementById('hardResetInput').value;
                    if(!code) return;
                    const url = "{{ url('/') }}/" + code;
                    const content = `SelinKu - Hard Reset URL\n========================\n\nURL ini sangat rahasia. Gunakan untuk mereset password jika Anda lupa password admin.\n\nURL: ${url}\n\nSimpan file ini di tempat aman!\n\nDibuat pada: {{ now()->format('d M Y H:i') }}`;
                    
                    const blob = new Blob([content], { type: 'text/plain' });
                    const a = document.createElement('a');
                    a.href = URL.createObjectURL(blob);
                    a.download = 'selinku-secret-reset-key.txt';
                    document.body.appendChild(a);
                    a.click();
                    document.body.removeChild(a);
                }
            </script>
        </div>

    </div>
</div>
@endsection
