@extends('layouts.layoutadmin')

@section('title', 'Pengaturan Navbar')

@section('styles')
    <style>
        .admin-dashboard {
            display: flex;
            min-height: 100vh;
            background: #f4f4f4;
        }

        .sidebar {
            width: 260px;
            background: #23272b;
            color: #fff;
            display: flex;
            flex-direction: column;
            padding: 24px 0 0 0;
            border-right: 1px solid #e5e7eb;
        }

        .sidebar .sidebar-header {
            display: flex;
            align-items: center;
            gap: 12px;
            padding: 0 24px 24px 24px;
            font-size: 1.1rem;
            font-weight: 700;
        }

        .sidebar .sidebar-header i {
            font-size: 1.6rem;
            color: #22c1b6;
        }

        .sidebar .sidebar-header span {
            font-size: 1.1rem;
            font-weight: 700;
            color: #fff;
        }

        .sidebar-nav {
            flex: 1;
            padding: 0 0 0 0;
        }

        .sidebar-nav ul {
            list-style: none;
            padding: 0;
            margin: 0;
        }

        .sidebar-nav li {
            margin-bottom: 4px;
        }

        .sidebar-nav a {
            display: flex;
            align-items: center;
            gap: 10px;
            padding: 10px 28px;
            color: #bfc5c9;
            text-decoration: none;
            border-radius: 8px 0 0 8px;
            font-size: 1rem;
            transition: background 0.2s, color 0.2s;
        }

        .sidebar-nav a.active,
        .sidebar-nav a:hover {
            background: #22c1b6;
            color: #fff;
        }

        .sidebar-footer {
            padding: 18px 24px;
            border-top: 1px solid #333;
            background: #23272b;
            display: flex;
            align-items: center;
            gap: 12px;
            font-size: 0.98rem;
        }

        .sidebar-footer .avatar {
            width: 36px;
            height: 36px;
            border-radius: 50%;
            background: #444;
            display: flex;
            align-items: center;
            justify-content: center;
            color: #fff;
            font-size: 1.2rem;
            font-weight: 700;
        }

        .sidebar-footer .user-info {
            display: flex;
            flex-direction: column;
            gap: 2px;
        }

        .sidebar-footer .user-info span {
            color: #fff;
            font-weight: 600;
            font-size: 1rem;
        }

        .sidebar-footer .user-info small {
            color: #bfc5c9;
            font-size: 0.95rem;
        }

        .main {
            flex: 1;
            display: flex;
            flex-direction: column;
        }

        .main-header {
            background: #fff;
            padding: 24px;
            border-bottom: 1px solid #e5e7eb;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        
        /* Keep admin header/navbar white regardless of site dark/light mode */
        body.dark-mode .admin-dashboard .main-header,
        .admin-dashboard .main-header {
            background: #ffffff !important;
            color: #222 !important;
            border-bottom: 1px solid #e5e7eb !important;
        }

        /* Ensure header child elements keep their intended colors in dark mode */
        body.dark-mode .admin-dashboard .main-header .title,
        body.dark-mode .admin-dashboard .main-header .subtitle,
        body.dark-mode .admin-dashboard .main-header .header-actions,
        body.dark-mode .admin-dashboard .main-header .header-actions * {
            color: inherit !important;
            background: transparent !important;
        }

        .main-header .title {
            font-size: 24px;
            font-weight: 600;
            color: #111827;
        }

        .main-header .subtitle {
            font-size: 14px;
            color: #6b7280;
            margin-top: 4px;
        }

        .header-actions {
            display: flex;
            gap: 16px;
            align-items: center;
        }

        .header-actions i {
            font-size: 18px;
            color: #6b7280;
            cursor: pointer;
        }

        .header-actions button {
            background: #ef4444;
            color: #fff;
            border: none;
            padding: 8px 16px;
            border-radius: 6px;
            cursor: pointer;
        }

        .main-content {
            flex: 1;
            padding: 24px;
        }

        .card {
            background: #fff;
            border-radius: 8px;
            box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
            overflow: hidden;
        }

        .card-header {
            padding: 20px 24px;
            border-bottom: 1px solid #e5e7eb;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        .card-header h3 {
            margin: 0;
            font-size: 18px;
            font-weight: 600;
        }

        .card-body {
            padding: 24px;
        }

        .table-responsive {
            overflow-x: auto;
        }

        .table {
            width: 100%;
            border-collapse: collapse;
        }

        .table th,
        .table td {
            padding: 12px;
            text-align: left;
            border-bottom: 1px solid #e5e7eb;
        }

        .table th {
            background: #f9fafb;
            font-weight: 600;
            font-size: 14px;
            color: #374151;
        }

        .table td {
            font-size: 14px;
            color: #6b7280;
        }

        .table code {
            background: #f3f4f6;
            padding: 2px 6px;
            border-radius: 4px;
            font-size: 13px;
            color: #1f2937;
        }

        .btn {
            padding: 8px 16px;
            border: none;
            border-radius: 6px;
            cursor: pointer;
            font-size: 14px;
            font-weight: 500;
            display: inline-flex;
            align-items: center;
            gap: 6px;
        }

        .btn-primary {
            background: #3b82f6;
            color: #fff;
        }

        .btn-primary:hover {
            background: #2563eb;
        }

        .btn-sm {
            padding: 6px 12px;
            font-size: 13px;
        }

        .btn-warning {
            background: #f59e0b;
            color: #fff;
        }

        .btn-warning:hover {
            background: #d97706;
        }

        .btn-danger {
            background: #ef4444;
            color: #fff;
        }

        .btn-danger:hover {
            background: #dc2626;
        }

        .btn-secondary {
            background: #6b7280;
            color: #fff;
        }

        .btn-secondary:hover {
            background: #4b5563;
        }

        .badge {
            padding: 4px 8px;
            border-radius: 4px;
            font-size: 12px;
            font-weight: 500;
        }

        .badge-success {
            background: #10b981;
            color: white;
        }

        .badge-secondary {
            background: #6b7280;
            color: white;
        }

        .alert {
            padding: 12px 16px;
            border-radius: 6px;
            margin-bottom: 20px;
        }

        .alert-success {
            background: #d1fae5;
            color: #065f46;
            border: 1px solid #10b981;
        }

        .alert-danger {
            background: #fee2e2;
            color: #991b1b;
            border: 1px solid #ef4444;
        }

        .modal {
            display: none;
            position: fixed;
            z-index: 1000;
            left: 0;
            top: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0, 0, 0, 0.5);
        }

        .modal-content {
            background-color: #fff;
            margin: 5% auto;
            padding: 0;
            border-radius: 8px;
            width: 90%;
            max-width: 600px;
            box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
        }

        .modal-header {
            padding: 20px;
            border-bottom: 1px solid #e5e7eb;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        .modal-header h3 {
            margin: 0;
        }

        .modal-body {
            padding: 20px;
        }

        .modal-footer {
            padding: 15px 20px;
            border-top: 1px solid #e5e7eb;
            display: flex;
            justify-content: flex-end;
            gap: 10px;
        }

        .close {
            color: #aaa;
            font-size: 28px;
            font-weight: bold;
            cursor: pointer;
        }

        .close:hover {
            color: #000;
        }

        .text-danger {
            color: #ef4444;
        }

        .form-text {
            font-size: 12px;
            color: #6b7280;
        }

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

        .form-group label {
            display: block;
            margin-bottom: 8px;
            font-weight: 500;
            color: #374151;
        }

        .form-control {
            width: 100%;
            padding: 10px 12px;
            border: 1px solid #d1d5db;
            border-radius: 6px;
            font-size: 14px;
            transition: border-color 0.2s;
        }

        .form-control:focus {
            outline: none;
            border-color: #3b82f6;
            box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.1);
        }

        .form-control[readonly] {
            background-color: #f3f4f6;
            cursor: not-allowed;
        }

        select.form-control {
            cursor: pointer;
        }
    </style>
@endsection

@section('content')
    <div class="admin-dashboard">
        @include('admin.components.sidebar')

        <main class="main">
            <div class="main-header">
                <div>
                    <div class="title">Pengaturan Navbar</div>
                    <div class="subtitle">Kelola menu navigasi Profil Kawasan Kumuh</div>
                </div>
                <div class="header-actions">
                    <i class="fas fa-bell"></i>
                    <i class="fas fa-cog"></i>
                    <form method="POST" action="{{ route('logout') }}" style="display:inline;">
                        @csrf
                        <button type="submit">Keluar</button>
                    </form>
                </div>
            </div>

            <div class="main-content">
                <div class="alert alert-success" id="successAlert" style="display: none;"></div>
                <div class="alert alert-danger" id="errorAlert" style="display: none;"></div>

                <div class="card">
                    <div class="card-header">
                        <h3>Daftar Menu Navbar</h3>
                        <button class="btn btn-primary" onclick="showAddModal()">
                            <i class="fas fa-plus"></i> Tambah Menu
                        </button>
                    </div>
                    <div class="card-body">
                        <div class="table-responsive">
                            <table class="table">
                                <thead>
                                    <tr>
                                        <th>Key Menu</th>
                                        <th>Label</th>
                                        <th>URL</th>
                                        <th>Order</th>
                                        <th>Status</th>
                                        <th>Aksi</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    @foreach ($menus as $key => $menu)
                                        <tr>
                                            <td><code>{{ $key }}</code></td>
                                            <td>{{ $menu['label'] }}</td>
                                            <td>{{ $menu['url'] ?? '#' }}</td>
                                            <td>{{ $menu['order'] ?? 0 }}</td>
                                            <td>
                                                @if ($menu['is_active'])
                                                    <span class="badge badge-success">Aktif</span>
                                                @else
                                                    <span class="badge badge-secondary">Nonaktif</span>
                                                @endif
                                            </td>
                                            <td>
                                                <button class="btn btn-sm btn-warning"
                                                    onclick="editMenu('{{ $key }}', '{{ addslashes($menu['label']) }}', '{{ addslashes($menu['url'] ?? '#') }}', {{ $menu['is_active'] ? 'true' : 'false' }}, null, {{ $menu['order'] ?? 0 }})">
                                                    <i class="fas fa-edit"></i>
                                                </button>
                                                <button class="btn btn-sm btn-danger"
                                                    onclick="deleteMenu('{{ $key }}')">
                                                    <i class="fas fa-trash"></i>
                                                </button>
                                            </td>
                                        </tr>
                                    @endforeach
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Add Modal -->
            <div class="modal" id="addModal">
                <div class="modal-content">
                    <div class="modal-header">
                        <h3>Tambah Menu Baru</h3>
                        <span class="close" onclick="closeAddModal()">&times;</span>
                    </div>
                    <div class="modal-body">
                        <form id="addForm" onsubmit="submitAdd(event)">
                            <div class="form-group">
                                <label>Key Menu <span class="text-danger">*</span></label>
                                <input type="text" name="menu_key" class="form-control" required
                                    placeholder="contoh: profil_kumuh_baru">
                                <small class="form-text">Gunakan format: huruf_kecil_tanpa_spasi</small>
                            </div>
                            <div class="form-group">
                                <label>Label Menu <span class="text-danger">*</span></label>
                                <input type="text" name="label" class="form-control" required
                                    placeholder="Nama menu yang ditampilkan">
                            </div>
                            <div class="form-group">
                                <label>Order / Urutan</label>
                                <input type="number" name="order" class="form-control" value="0" min="0">
                                <small class="form-text">Urutan tampilan menu (0 = pertama)</small>
                            </div>
                            <div class="form-group">
                                <label>URL</label>
                                <input type="text" name="url" class="form-control" placeholder="https://example.com">
                            </div>
                            <div class="form-group">
                                <label>
                                    <input type="checkbox" name="is_active" checked> Aktif
                                </label>
                            </div>
                            <div class="modal-footer">
                                <button type="button" class="btn btn-secondary" onclick="closeAddModal()">Batal</button>
                                <button type="submit" class="btn btn-primary">Simpan</button>
                            </div>
                        </form>
                    </div>
                </div>
            </div>

            <!-- Edit Modal -->
            <div class="modal" id="editModal">
                <div class="modal-content">
                    <div class="modal-header">
                        <h3>Edit Menu</h3>
                        <span class="close" onclick="closeEditModal()">&times;</span>
                    </div>
                    <div class="modal-body">
                        <form id="editForm" onsubmit="submitEdit(event)">
                            <input type="hidden" name="menu_key" id="edit_menu_key">
                            <div class="form-group">
                                <label>Key Menu</label>
                                <input type="text" class="form-control" id="edit_menu_key_display" readonly>
                            </div>
                            <div class="form-group">
                                <label>Label Menu <span class="text-danger">*</span></label>
                                <input type="text" name="label" id="edit_label" class="form-control" required>
                            </div>
                            <div class="form-group">
                                <label>Order / Urutan</label>
                                <input type="number" name="order" id="edit_order" class="form-control"
                                    value="0" min="0">
                                <small class="form-text">Urutan tampilan menu (0 = pertama)</small>
                            </div>
                            <div class="form-group">
                                <label>URL</label>
                                <input type="text" name="url" id="edit_url" class="form-control">
                            </div>
                            <div class="form-group">
                                <label>
                                    <input type="checkbox" name="is_active" id="edit_is_active"> Aktif
                                </label>
                            </div>
                            <div class="modal-footer">
                                <button type="button" class="btn btn-secondary"
                                    onclick="closeEditModal()">Batal</button>
                                <button type="submit" class="btn btn-primary">Update</button>
                            </div>
                        </form>
                    </div>
                </div>
            </div>

            <script>
                // Get CSRF token from Laravel
                const csrfToken = '{{ csrf_token() }}';

                function showAddModal() {
                    document.getElementById('addModal').style.display = 'block';
                }

                function closeAddModal() {
                    document.getElementById('addModal').style.display = 'none';
                    document.getElementById('addForm').reset();
                }

                function showEditModal() {
                    document.getElementById('editModal').style.display = 'block';
                }

                function closeEditModal() {
                    document.getElementById('editModal').style.display = 'none';
                    document.getElementById('editForm').reset();
                }

                function editMenu(key, label, url, isActive, parentKey, order) {
                    document.getElementById('edit_menu_key').value = key;
                    document.getElementById('edit_menu_key_display').value = key;
                    document.getElementById('edit_label').value = label;
                    document.getElementById('edit_url').value = url;
                    document.getElementById('edit_is_active').checked = isActive;
                    document.getElementById('edit_order').value = order || 0;
                    showEditModal();
                }

                async function submitAdd(event) {
                    event.preventDefault();
                    const form = event.target;
                    const formData = new FormData(form);

                    const data = {
                        menu_key: formData.get('menu_key'),
                        label: formData.get('label'),
                        url: formData.get('url') || '#',
                        parent_key: null,
                        order: parseInt(formData.get('order')) || 0,
                        is_active: formData.get('is_active') ? true : false
                    };

                    try {
                        const token = sessionStorage.getItem('authToken');
                        const response = await fetch('/admin/pengaturan-navbar/add', {
                            method: 'POST',
                            headers: {
                                'Content-Type': 'application/json',
                                'Authorization': `Bearer ${token}`,
                                'X-CSRF-TOKEN': csrfToken
                            },
                            body: JSON.stringify(data)
                        });

                        // Check if response is JSON
                        const contentType = response.headers.get('content-type');
                        if (!contentType || !contentType.includes('application/json')) {
                            const text = await response.text();
                            console.error('Non-JSON response:', text);
                            throw new Error('Server tidak mengembalikan JSON. Mungkin ada error di server.');
                        }

                        const result = await response.json();

                        if (result.success) {
                            showAlert('success', result.message);
                            closeAddModal();
                            setTimeout(() => location.reload(), 1000);
                        } else {
                            showAlert('error', result.message || 'Gagal menambahkan menu');
                        }
                    } catch (error) {
                        console.error('Error details:', error);
                        showAlert('error', 'Terjadi kesalahan: ' + error.message);
                    }
                }

                async function submitEdit(event) {
                    event.preventDefault();
                    const form = event.target;
                    const formData = new FormData(form);

                    // Get all current menus
                    const menus = @json($menus);
                    const menuKey = formData.get('menu_key');

                    // Update the specific menu
                    menus[menuKey] = {
                        label: formData.get('label'),
                        url: formData.get('url') || '#',
                        parent_key: null,
                        order: parseInt(formData.get('order')) || 0,
                        is_active: formData.get('is_active') ? true : false
                    };

                    try {
                        const token = sessionStorage.getItem('authToken');
                        const response = await fetch('/admin/pengaturan-navbar/update', {
                            method: 'POST',
                            headers: {
                                'Content-Type': 'application/json',
                                'Authorization': `Bearer ${token}`,
                                'X-CSRF-TOKEN': csrfToken
                            },
                            body: JSON.stringify({
                                menus: menus
                            })
                        });

                        // Check if response is JSON
                        const contentType = response.headers.get('content-type');
                        if (!contentType || !contentType.includes('application/json')) {
                            const text = await response.text();
                            console.error('Non-JSON response:', text);
                            throw new Error('Server tidak mengembalikan JSON. Mungkin ada error di server.');
                        }

                        const result = await response.json();

                        if (result.success) {
                            showAlert('success', result.message);
                            closeEditModal();
                            setTimeout(() => location.reload(), 1000);
                        } else {
                            showAlert('error', result.message || 'Gagal mengupdate menu');
                        }
                    } catch (error) {
                        console.error('Error details:', error);
                        showAlert('error', 'Terjadi kesalahan: ' + error.message);
                    }
                }

                async function deleteMenu(menuKey) {
                    if (!confirm('Apakah Anda yakin ingin menghapus menu ini?')) {
                        return;
                    }

                    try {
                        const token = sessionStorage.getItem('authToken');
                        const response = await fetch(`/admin/pengaturan-navbar/delete/${menuKey}`, {
                            method: 'DELETE',
                            headers: {
                                'Authorization': `Bearer ${token}`,
                                'X-CSRF-TOKEN': csrfToken
                            }
                        });

                        // Check if response is JSON
                        const contentType = response.headers.get('content-type');
                        if (!contentType || !contentType.includes('application/json')) {
                            const text = await response.text();
                            console.error('Non-JSON response:', text);
                            throw new Error('Server tidak mengembalikan JSON. Mungkin ada error di server.');
                        }

                        const result = await response.json();

                        if (result.success) {
                            showAlert('success', result.message);
                            setTimeout(() => location.reload(), 1000);
                        } else {
                            showAlert('error', result.message || 'Gagal menghapus menu');
                        }
                    } catch (error) {
                        console.error('Error details:', error);
                        showAlert('error', 'Terjadi kesalahan: ' + error.message);
                    }
                }

                function showAlert(type, message) {
                    const alertId = type === 'success' ? 'successAlert' : 'errorAlert';
                    const alert = document.getElementById(alertId);
                    alert.textContent = message;
                    alert.style.display = 'block';
                    setTimeout(() => {
                        alert.style.display = 'none';
                    }, 5000);
                }

                // Close modal when clicking outside
                window.onclick = function(event) {
                    const addModal = document.getElementById('addModal');
                    const editModal = document.getElementById('editModal');
                    if (event.target == addModal) {
                        closeAddModal();
                    }
                    if (event.target == editModal) {
                        closeEditModal();
                    }
                }
            </script>
        </main>
    </div>
@endsection
