
<?php $__env->startSection('title', 'Sebaran Rusun'); ?>

<?php $__env->startSection('styles'); ?>
    <style>
        body {
            background: #f4f4f4;
        }

        .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-nav {
            flex: 1;
            padding: 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;
        }

        .main {
            flex: 1;
            display: flex;
            flex-direction: column;
            background: #f4f4f4;
            transition: background-color 0.3s ease;
        }

        .dark .main {
            background: #1a202c;
        }

        .main-header {
            background: #fff;
            padding: 24px 32px 16px 32px;
            display: flex;
            align-items: center;
            justify-content: space-between;
            border-bottom: 1px solid #e5e7eb;
            transition: background-color 0.3s ease, border-color 0.3s ease;
        }
        
        /* 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 .header-actions {
            display: flex;
            align-items: center;
            gap: 16px;
        }

        .main-header .header-actions button {
            background: #d72660;
            color: #fff;
            border: none;
            border-radius: 8px;
            padding: 8px 18px;
            font-weight: 600;
            font-size: 1rem;
            cursor: pointer;
        }

        .main-header .header-actions button:hover {
            background: #b61f50;
        }

        .main-header .header-actions i {
            font-size: 1.3rem;
            color: #535963;
            background: #f4f4f4;
            border-radius: 50%;
            padding: 6px;
            margin-right: 2px;
            cursor: pointer;
        }

        .dark .main-header {
            background: #2d3748;
            border-color: #4a5568;
        }

        .title {
            font-size: 1.4rem;
            font-weight: 700;
            color: #222;
            transition: color 0.3s ease;
        }

        .dark .title {
            color: #f7fafc;
        }

        .subtitle {
            color: #6b7280;
            font-size: 1.05rem;
            margin-top: 2px;
            transition: color 0.3s ease;
        }

        .dark .subtitle {
            color: #cbd5e0;
        }

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

        .search-container {
            position: relative;
            margin-bottom: 1.5rem;
        }

        .search-input {
            width: 100%;
            padding: 12px 48px 12px 16px;
            border-radius: 8px;
            border: 2px solid #e5e7eb;
            background: #fff;
            color: #333;
            font-size: 1rem;
            transition: border-color 0.3s ease, background-color 0.3s ease, color 0.3s ease;
        }

        .dark .search-input {
            background: #1a202c;
            border-color: #4a5568;
            color: #e2e8f0;
        }

        .search-input:focus {
            border-color: #22c1b6;
            outline: none;
            box-shadow: 0 0 0 3px rgba(34, 193, 182, 0.1);
        }

        .search-icon {
            position: absolute;
            right: 16px;
            top: 50%;
            transform: translateY(-50%);
            color: #9ca3af;
            pointer-events: none;
            transition: color 0.3s ease;
        }

        .dark .search-icon {
            color: #718096;
        }

        .search-clear {
            position: absolute;
            right: 16px;
            top: 50%;
            transform: translateY(-50%);
            background: #ef4444;
            color: #fff;
            border: none;
            border-radius: 50%;
            width: 24px;
            height: 24px;
            display: none;
            align-items: center;
            justify-content: center;
            cursor: pointer;
            font-size: 0.8rem;
            transition: background 0.2s;
        }

        .search-clear:hover {
            background: #dc2626;
        }

        .search-clear.show {
            display: flex;
        }

        .search-stats {
            margin-top: 8px;
            color: #6b7280;
            font-size: 0.9rem;
            transition: color 0.3s ease;
        }

        .dark .search-stats {
            color: #a0aec0;
        }

        .btn-primary {
            background: linear-gradient(135deg, #667eea 0%, #22c1b6 100%);
            color: #fff;
            border: none;
            border-radius: 8px;
            padding: 10px 28px;
            font-weight: 600;
            font-size: 1rem;
            cursor: pointer;
            transition: all 0.2s;
        }

        .btn-primary:hover {
            background: #1da89c;
            transform: translateY(-1px);
            box-shadow: 0 4px 12px rgba(34, 193, 182, 0.3);
        }

        .btn-secondary {
            background: #6b7280;
            color: #fff;
            border: none;
            border-radius: 8px;
            padding: 8px 22px;
            font-weight: 600;
            font-size: 1rem;
            cursor: pointer;
            transition: background 0.2s;
            margin-right: 12px;
        }

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

        .main-content {
            padding: 32px;
            transition: background-color 0.3s ease;
        }

        .content-section {
            background: #fff;
            border-radius: 12px;
            box-shadow: 0 2px 12px rgba(0, 0, 0, 0.04);
            padding: 32px;
            margin-top: 2rem;
            transition: background-color 0.3s ease, box-shadow 0.3s ease;
        }

        .dark .content-section {
            background: #2d3748;
            box-shadow: 0 2px 12px rgba(0, 0, 0, 0.3);
        }

        .section-title {
            font-size: 1.3rem;
            font-weight: 700;
            color: #23272b;
            margin-bottom: 1.5rem;
            transition: color 0.3s ease;
        }

        .dark .section-title {
            color: #f7fafc;
        }

        /* New: section header to align title and actions on one row */
        .section-header {
            display: flex;
            align-items: center;
            justify-content: space-between;
            gap: 12px;
            margin-bottom: 1rem; /* slightly less than .section-title bottom to keep spacing */
        }

        .alert {
            padding: 12px 20px;
            border-radius: 8px;
            margin-bottom: 1rem;
            font-weight: 600;
            animation: alertSlideIn 0.3s ease;
        }

        @keyframes alertSlideIn {
            from {
                opacity: 0;
                transform: translateY(-10px);
            }

            to {
                opacity: 1;
                transform: translateY(0);
            }
        }

        .alert-success {
            background: #d1fae5;
            color: #065f46;
            border-left: 4px solid #22c1b6;
        }

        .alert-error {
            background: #fee2e2;
            color: #991b1b;
            border-left: 4px solid #ef4444;
        }

        .data-table {
            width: 100%;
            border-collapse: collapse;
            margin-top: 1rem;
        }

        .data-table thead th {
            background: #f9fafb;
            padding: 12px;
            text-align: left;
            font-weight: 600;
            color: #374151;
            border-bottom: 2px solid #e5e7eb;
            transition: background-color 0.3s ease, color 0.3s ease;
        }

        .dark .data-table thead th {
            background: #1a202c;
            color: #e2e8f0;
            border-bottom-color: #4a5568;
        }

        .data-table tbody td {
            padding: 12px;
            border-bottom: 1px solid #e5e7eb;
            color: #6b7280;
            transition: color 0.3s ease, border-color 0.3s ease;
        }

        .dark .data-table tbody td {
            color: #cbd5e0;
            border-bottom-color: #4a5568;
        }

        .data-table tbody tr {
            transition: background-color 0.2s;
        }

        .data-table tbody tr:hover {
            background: #f9fafb;
        }

        .dark .data-table tbody tr:hover {
            background: #374151;
        }

        .badge {
            display: inline-block;
            padding: 4px 12px;
            border-radius: 12px;
            font-size: 0.85rem;
            font-weight: 600;
        }

        .badge-success {
            background: #d1fae5;
            color: #065f46;
        }

        .badge-warning {
            background: #fef3c7;
            color: #92400e;
        }

        .badge-info {
            background: #dbeafe;
            color: #1e40af;
        }

        .btn-sm {
            padding: 6px 16px;
            font-size: 0.9rem;
            border-radius: 6px;
            cursor: pointer;
            transition: all 0.2s;
            border: none;
        }

        .btn-edit {
            background: #3b82f6;
            color: #fff;
            margin-right: 8px;
        }

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

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

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

        .loading {
            display: none;
            text-align: center;
            padding: 2rem;
            color: #6b7280;
        }

        .loading.show {
            display: block;
        }

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

        .modal.show {
            display: block;
        }

        .modal-content {
            background-color: #fff;
            margin: 5% auto;
            padding: 0;
            border-radius: 12px;
            width: 90%;
            max-width: 800px;
            box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);
            transition: background-color 0.3s ease;
        }

        .dark .modal-content {
            background-color: #2d3748;
        }

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

        .dark .modal-header {
            border-bottom-color: #4a5568;
        }

        .modal-header h3 {
            margin: 0;
            font-size: 1.3rem;
            font-weight: 700;
            color: #1f2937;
            transition: color 0.3s ease;
        }

        .dark .modal-header h3 {
            color: #f7fafc;
        }

        .close {
            color: #9ca3af;
            font-size: 28px;
            font-weight: bold;
            cursor: pointer;
            transition: color 0.2s;
        }

        .close:hover {
            color: #374151;
        }

        .dark .close:hover {
            color: #e2e8f0;
        }

        .modal-body {
            padding: 24px;
        }

        .form-grid {
            display: grid;
            grid-template-columns: repeat(2, 1fr);
            gap: 20px;
        }

        .form-grid-full {
            grid-column: 1 / -1;
        }

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

        .form-group label {
            font-weight: 600;
            margin-bottom: 8px;
            display: block;
            color: #374151;
            transition: color 0.3s ease;
        }

        .dark .form-group label {
            color: #e2e8f0;
        }

        .form-group input,
        .form-group select,
        .form-group textarea {
            width: 100%;
            padding: 12px 16px;
            border-radius: 8px;
            border: 2px solid #e5e7eb;
            background: #fff;
            color: #333;
            font-size: 1rem;
            margin-top: 4px;
            box-sizing: border-box;
            transition: border-color 0.3s ease, background-color 0.3s ease, color 0.3s ease;
        }

        .dark .form-group input,
        .dark .form-group select,
        .dark .form-group textarea {
            background: #1a202c;
            border-color: #4a5568;
            color: #e2e8f0;
        }

        .form-group input:focus,
        .form-group select:focus,
        .form-group textarea:focus {
            border-color: #22c1b6;
            outline: none;
            box-shadow: 0 0 0 3px rgba(34, 193, 182, 0.1);
        }

        .form-group textarea {
            resize: vertical;
            min-height: 100px;
        }

        .form-group small {
            color: #6b7280;
            font-size: 0.9rem;
            margin-top: 4px;
            display: block;
            transition: color 0.3s ease;
        }

        .dark .form-group small {
            color: #a0aec0;
        }

        .modal-footer {
            padding: 20px 24px;
            border-top: 1px solid #e5e7eb;
            display: flex;
            justify-content: flex-end;
            gap: 12px;
            transition: border-color 0.3s ease;
        }

        .dark .modal-footer {
            border-top-color: #4a5568;
        }

        .image-preview {
            margin-top: 12px;
            text-align: center;
        }

        .image-preview img {
            max-width: 200px;
            max-height: 200px;
            border-radius: 8px;
            box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
            object-fit: cover;
        }

        .rusun-photo {
            width: 80px;
            height: 60px;
            object-fit: cover;
            border-radius: 6px;
        }

        /* Smooth transitions */
        * {
            transition-property: background-color, color, border-color, box-shadow;
            transition-duration: 0.3s;
            transition-timing-function: ease;
        }
    </style>
<?php $__env->stopSection(); ?>

<?php $__env->startSection('content'); ?>
    <div class="admin-dashboard">
        <?php echo $__env->make('admin.components.sidebar', array_diff_key(get_defined_vars(), ['__data' => 1, '__path' => 1]))->render(); ?>

        <main class="main">
            <div class="main-header">
                <div>
                    <div class="title">Sebaran Rusun</div>
                    <div class="subtitle">Kelola data rusun dan lokasi penyebaran</div>
                </div>
                <div class="header-actions">
                    <a href="feedback"><i class="fas fa-bell"></i></a>
                    <a href="pengaturan-situs"><i class="fas fa-cog"></i></a>
                    <form method="POST" action="<?php echo e(route('logout')); ?>" style="display:inline;">
                        <?php echo csrf_field(); ?>
                        <button type="submit">Keluar</button>
                    </form>
                </div>
            </div>

            <div class="main-content">
                <div id="alert-container"></div>

                <div class="content-section">
                    <div class="section-header">
                        <div class="section-title">Data Rusun</div>
                        <div class="header-actions">
                            <button class="btn-primary" onclick="showAddModal()">
                                <i class="fas fa-plus"></i> Tambah Rusun
                            </button>
                        </div>
                    </div>

                    <!-- Search Bar -->
                    <div class="search-container">
                        <input type="text" id="searchInput" class="search-input"
                            placeholder="Cari berdasarkan nama, alamat, tipe, atau kontraktor..." onkeyup="searchRusun()">
                        <i class="fas fa-search search-icon" id="searchIcon"></i>
                        <button class="search-clear" id="searchClear" onclick="clearSearch()">
                            <i class="fas fa-times"></i>
                        </button>
                    </div>

                    <div class="search-stats" id="searchStats"></div>

                    <div class="loading" id="loading">
                        <i class="fas fa-spinner fa-spin" style="font-size: 2rem;"></i>
                        <p>Memuat data...</p>
                    </div>

                    <div id="tableContainer"></div>
                </div>
            </div>
        </main>
    </div>

    <!-- Modal Form -->
    <div id="rusunModal" class="modal">
        <div class="modal-content">
            <div class="modal-header">
                <h3 id="modalTitle">Tambah Rusun</h3>
                <span class="close" onclick="closeModal()">&times;</span>
            </div>
            <form id="rusunForm" enctype="multipart/form-data">
                <div class="modal-body">
                    <input type="hidden" id="rusun_id">

                    <div class="form-grid">
                        <div class="form-group">
                            <label for="name">Nama Rusun *</label>
                            <input type="text" id="name" required>
                        </div>

                        <div class="form-group">
                            <label for="type">Tipe</label>
                            <input type="text" id="type" placeholder="e.g. Tower, Blok">
                        </div>
                    </div>

                    <div class="form-group form-grid-full">
                        <label for="address">Alamat *</label>
                        <textarea id="address" required></textarea>
                    </div>

                    <div class="form-grid">
                        <div class="form-group">
                            <label for="unit">Jumlah Unit</label>
                            <input type="number" id="unit" min="0">
                        </div>

                        <div class="form-group">
                            <label for="tower">Jumlah Tower</label>
                            <input type="number" id="tower" min="0">
                        </div>

                        <div class="form-group">
                            <label for="floor">Jumlah Lantai</label>
                            <input type="number" id="floor" min="0">
                        </div>

                        <div class="form-group">
                            <label for="occupied">Unit Terisi</label>
                            <input type="number" id="occupied" min="0">
                        </div>
                    </div>

                    <div class="form-grid">
                        <div class="form-group">
                            <label for="user">Pengguna</label>
                            <input type="text" id="user" placeholder="e.g. Umum, ASN">
                        </div>

                        <div class="form-group">
                            <label for="development_year">Tahun Pembangunan</label>
                            <input type="number" id="development_year" min="1900" max="2100">
                        </div>

                        <div class="form-group">
                            <label for="handover_status">Status Serah Terima</label>
                            <select id="handover_status">
                                <option value="">Pilih Status</option>
                                <option value="true">Sudah</option>
                                <option value="false">Belum</option>
                            </select>
                        </div>

                        <div class="form-group">
                            <label for="handover_year">Tahun Serah Terima</label>
                            <input type="number" id="handover_year" min="1900" max="2100">
                        </div>
                    </div>

                    <div class="form-group form-grid-full">
                        <label for="contractor">Kontraktor</label>
                        <input type="text" id="contractor">
                    </div>

                    <div class="form-grid">
                        <div class="form-group">
                            <label for="latitude">Latitude</label>
                            <input type="text" id="latitude" step="any" placeholder="e.g. -7.797068">
                            <small>Koordinat latitude lokasi</small>
                        </div>

                        <div class="form-group">
                            <label for="longitude">Longitude</label>
                            <input type="text" id="longitude" step="any" placeholder="e.g. 110.370529">
                            <small>Koordinat longitude lokasi</small>
                        </div>
                    </div>

                    <div class="form-group form-grid-full">
                        <label for="photo_url">URL Foto Rusun</label>
                        <input type="url" id="photo_url" placeholder="https://example.com/foto-rusun.jpg">
                        <small>Masukkan URL foto rusun (format: https://...)</small>
                        <div class="image-preview" id="photoPreview" style="display: none;">
                            <img id="previewImage" src="" alt="Preview">
                        </div>
                    </div>

                    <div class="form-group form-grid-full">
                        <label>Region</label>
                        <div style="padding: 10px; background: #f3f4f6; border-radius: 6px; color: #6b7280;">
                            <i class="fas fa-map-marker-alt"></i> <span id="regionDisplay">Loading...</span>
                        </div>
                        <small>Region akan otomatis ditambahkan berdasarkan akun Anda</small>
                    </div>
                </div>

                <div class="modal-footer">
                    <button type="button" class="btn-secondary" onclick="closeModal()">Batal</button>
                    <button type="submit" class="btn-primary">
                        <i class="fas fa-save"></i> Simpan
                    </button>
                </div>
            </form>
        </div>
    </div>

    <script>
        const baseUrl = '<?php echo e(env('BASE_URL')); ?>';
        let rusunData = [];
        let filteredData = [];
        let userSiteRegion = ''; // Store site region from user session

        function getAuthToken() {
            return '<?php echo e(session('auth.token')); ?>';
        }

        function getUserSiteId() {
            <?php
                $user = session('auth.user');
                $siteId = $user['site_id'] ?? null;
                // Debug: Log user data
                \Log::info('User session data:', ['user' => $user, 'site_id' => $siteId]);
            ?>
            console.log('User session:', <?php echo json_encode($user, 15, 512) ?>);
            console.log('Site ID from session:', <?php echo e($siteId ?? 'null'); ?>);
            return <?php echo e($siteId ?? 'null'); ?>;
        }

        function showAlert(message, type = 'success') {
            const alertContainer = document.getElementById('alert-container');
            const alertClass = type === 'success' ? 'alert-success' : 'alert-error';
            alertContainer.innerHTML = `<div class="alert ${alertClass}">${message}</div>`;
            setTimeout(() => {
                alertContainer.innerHTML = '';
            }, 5000);
        }

        // Fetch site data to get region name
        async function fetchUserSiteRegion() {
            const siteId = getUserSiteId();
            console.log('Getting site ID from session:', siteId);

            if (!siteId) {
                console.error('Site ID not found in session');
                const regionDisplay = document.getElementById('regionDisplay');
                if (regionDisplay) {
                    regionDisplay.textContent = 'Site ID tidak ditemukan';
                    regionDisplay.style.color = '#ef4444';
                }
                return;
            }

            console.log('Fetching site data for site_id:', siteId);

            try {
                // Try to fetch site data from public sites API
                const response = await fetch(`${baseUrl}/api/public/sites`, {
                    headers: {
                        'Content-Type': 'application/json'
                    }
                });

                if (!response.ok) {
                    throw new Error('Gagal memuat data site');
                }

                const sitesData = await response.json();
                console.log('Sites data:', sitesData);

                // Find site by site_id
                let siteInfo = null;

                // Check if sitesData is array or object
                if (Array.isArray(sitesData)) {
                    siteInfo = sitesData.find(site => site.id === siteId);
                } else if (sitesData.site && sitesData.site.id === siteId) {
                    siteInfo = sitesData.site;
                } else if (sitesData.id === siteId) {
                    siteInfo = sitesData;
                }

                console.log('Found site info:', siteInfo);

                if (!siteInfo || !siteInfo.name) {
                    throw new Error('Site tidak ditemukan atau name tidak tersedia');
                }

                // Store the site name as region (convert to lowercase and replace spaces with dash)
                userSiteRegion = (siteInfo.name || '').toLowerCase().replace(/\s+/g, '-');
                console.log('User site region:', userSiteRegion);

                // Update region display in form
                const regionDisplay = document.getElementById('regionDisplay');
                if (regionDisplay) {
                    regionDisplay.textContent = siteInfo.name.toUpperCase();
                    regionDisplay.style.color = '#059669';
                    regionDisplay.style.fontWeight = '600';
                }

            } catch (error) {
                console.error('Error fetching site data:', error);
                const regionDisplay = document.getElementById('regionDisplay');
                if (regionDisplay) {
                    regionDisplay.textContent = 'Gagal memuat: ' + error.message;
                    regionDisplay.style.color = '#ef4444';
                }
                showAlert('Gagal memuat data region: ' + error.message, 'error');
            }
        }

        // Search functionality
        function searchRusun() {
            const searchInput = document.getElementById('searchInput');
            const searchTerm = searchInput.value.toLowerCase().trim();
            const searchClear = document.getElementById('searchClear');
            const searchIcon = document.getElementById('searchIcon');
            const searchStats = document.getElementById('searchStats');

            // Toggle clear button
            if (searchTerm) {
                searchClear.classList.add('show');
                searchIcon.style.display = 'none';
            } else {
                searchClear.classList.remove('show');
                searchIcon.style.display = 'block';
            }

            // Filter data
            if (!searchTerm) {
                filteredData = rusunData;
                searchStats.textContent = '';
            } else {
                filteredData = rusunData.filter(rusun => {
                    return (
                        (rusun.name && rusun.name.toLowerCase().includes(searchTerm)) ||
                        (rusun.address && rusun.address.toLowerCase().includes(searchTerm)) ||
                        (rusun.type && rusun.type.toLowerCase().includes(searchTerm)) ||
                        (rusun.contractor && rusun.contractor.toLowerCase().includes(searchTerm)) ||
                        (rusun.user && rusun.user.toLowerCase().includes(searchTerm))
                    );
                });

                const resultText = filteredData.length === 1 ? 'hasil' : 'hasil';
                searchStats.textContent = `Ditemukan ${filteredData.length} ${resultText} dari ${rusunData.length} data`;
            }

            // Display filtered results
            displayRusunTable(filteredData);
        }

        // Clear search
        function clearSearch() {
            const searchInput = document.getElementById('searchInput');
            searchInput.value = '';
            searchRusun();
            searchInput.focus();
        }

        // Load all rusun data
        async function loadRusunData() {
            const loading = document.getElementById('loading');
            const tableContainer = document.getElementById('tableContainer');

            try {
                loading.classList.add('show');
                tableContainer.innerHTML = '';

                const response = await fetch(`${baseUrl}/api/admin/flat`, {
                    headers: {
                        'Authorization': `Bearer ${getAuthToken()}`,
                        'Content-Type': 'application/json'
                    }
                });

                if (!response.ok) {
                    throw new Error('Gagal memuat data rusun');
                }

                const data = await response.json();
                rusunData = data;
                filteredData = data;

                loading.classList.remove('show');
                displayRusunTable(data);

                // Update search stats
                const searchStats = document.getElementById('searchStats');
                searchStats.textContent = `Menampilkan ${data.length} data rusun`;

            } catch (error) {
                console.error('Error:', error);
                loading.classList.remove('show');
                showAlert('Gagal memuat data rusun: ' + error.message, 'error');
            }
        }

        // Display rusun table
        function displayRusunTable(data) {
            const tableContainer = document.getElementById('tableContainer');

            if (!data || data.length === 0) {
                const searchInput = document.getElementById('searchInput');
                const isSearching = searchInput && searchInput.value.trim() !== '';

                if (isSearching) {
                    tableContainer.innerHTML = `
                <div style="text-align: center; padding: 3rem;">
                    <i class="fas fa-search" style="font-size: 3rem; color: #9ca3af; margin-bottom: 1rem;"></i>
                    <p style="color: #6b7280; font-size: 1.1rem; font-weight: 600;">Tidak ada data yang ditemukan</p>
                    <p style="color: #9ca3af; font-size: 0.95rem;">Coba kata kunci pencarian yang berbeda</p>
                </div>
            `;
                } else {
                    tableContainer.innerHTML = `
                <div style="text-align: center; padding: 3rem;">
                    <i class="fas fa-building" style="font-size: 3rem; color: #9ca3af; margin-bottom: 1rem;"></i>
                    <p style="color: #6b7280; font-size: 1.1rem; font-weight: 600;">Belum ada data rusun</p>
                    <p style="color: #9ca3af; font-size: 0.95rem;">Klik tombol "Tambah Rusun" untuk menambahkan data</p>
                </div>
            `;
                }
                return;
            }

            let tableHtml = `
        <table class="data-table">
            <thead>
                <tr>
                    <th>Foto</th>
                    <th>Nama</th>
                    <th>Alamat</th>
                    <th>Unit/Tower/Lantai</th>
                    <th>Terisi</th>
                    <th>Tahun</th>
                    <th>Status</th>
                    <th>Aksi</th>
                </tr>
            </thead>
            <tbody>
    `;

            data.forEach(rusun => {
                const photoUrl = rusun.photo_url ? rusun.photo_url : '';
                const handoverStatus = rusun.handover_status ?
                    '<span class="badge badge-success">Sudah Diserahkan</span>' :
                    '<span class="badge badge-warning">Belum Diserahkan</span>';

                // Get search term for highlighting
                const searchInput = document.getElementById('searchInput');
                const searchTerm = searchInput ? searchInput.value.trim() : '';

                // Highlight search terms
                const nameDisplay = highlightSearchTerm(rusun.name, searchTerm);
                const typeDisplay = highlightSearchTerm(rusun.type, searchTerm);
                const addressDisplay = highlightSearchTerm(rusun.address, searchTerm);

                // Create photo display with error handling
                let photoDisplay = '<span class="badge badge-info">No Photo</span>';
                if (photoUrl) {
                    photoDisplay = `<img src="${photoUrl}" alt="Foto ${rusun.name}" class="rusun-photo" onerror="this.style.display='none'; this.nextElementSibling.style.display='inline-block';">
                            <span class="badge badge-warning" style="display:none;">Error Load</span>`;
                }

                tableHtml += `
            <tr>
                <td>
                    ${photoDisplay}
                </td>
                <td><strong>${nameDisplay || '-'}</strong><br><small>${typeDisplay || '-'}</small></td>
                <td>${addressDisplay || '-'}</td>
                <td>${rusun.unit || 0} / ${rusun.tower || 0} / ${rusun.floor || 0}</td>
                <td><span class="badge badge-info">${rusun.occupied || 0} unit</span></td>
                <td>${rusun.development_year || '-'}</td>
                <td>${handoverStatus}</td>
                <td>
                    <button class="btn-sm btn-edit" onclick="editRusun(${rusun.id})">
                        <i class="fas fa-edit"></i> Edit
                    </button>
                    <button class="btn-sm btn-delete" onclick="deleteRusun(${rusun.id})">
                        <i class="fas fa-trash"></i> Hapus
                    </button>
                </td>
            </tr>
        `;
            });

            tableHtml += `
            </tbody>
        </table>
    `;

            tableContainer.innerHTML = tableHtml;
        }

        // Show add modal
        function showAddModal() {
            document.getElementById('modalTitle').textContent = 'Tambah Rusun';
            document.getElementById('rusunForm').reset();
            document.getElementById('rusun_id').value = '';
            document.getElementById('photoPreview').style.display = 'none';
            document.getElementById('rusunModal').classList.add('show');
        }

        // Highlight search term in text
        function highlightSearchTerm(text, searchTerm) {
            if (!text || !searchTerm) return text || '-';

            const regex = new RegExp(`(${searchTerm})`, 'gi');
            return text.replace(regex,
                '<mark style="background: #fef3c7; padding: 2px 4px; border-radius: 3px;">$1</mark>');
        }

        // Edit rusun
        function editRusun(id) {
            const rusun = rusunData.find(r => r.id === id);
            if (!rusun) return;

            document.getElementById('modalTitle').textContent = 'Edit Rusun';
            document.getElementById('rusun_id').value = rusun.id;
            document.getElementById('name').value = rusun.name || '';
            document.getElementById('address').value = rusun.address || '';
            document.getElementById('unit').value = rusun.unit || '';
            document.getElementById('tower').value = rusun.tower || '';
            document.getElementById('type').value = rusun.type || '';
            document.getElementById('floor').value = rusun.floor || '';
            document.getElementById('occupied').value = rusun.occupied || '';
            document.getElementById('user').value = rusun.user || '';
            document.getElementById('development_year').value = rusun.development_year || '';
            document.getElementById('handover_status').value = rusun.handover_status !== null ? rusun.handover_status
                .toString() : '';
            document.getElementById('handover_year').value = rusun.handover_year || '';
            document.getElementById('contractor').value = rusun.contractor || '';
            document.getElementById('latitude').value = rusun.latitude || '';
            document.getElementById('longitude').value = rusun.longitude || '';
            document.getElementById('photo_url').value = rusun.photo_url || '';

            if (rusun.photo_url) {
                document.getElementById('previewImage').src = rusun.photo_url;
                document.getElementById('photoPreview').style.display = 'block';
            } else {
                document.getElementById('photoPreview').style.display = 'none';
            }

            document.getElementById('rusunModal').classList.add('show');
        }

        // Close modal
        function closeModal() {
            document.getElementById('rusunModal').classList.remove('show');
        }

        // Preview image from URL
        document.getElementById('photo_url').addEventListener('input', function(e) {
            const url = e.target.value.trim();
            const photoPreview = document.getElementById('photoPreview');
            const previewImage = document.getElementById('previewImage');

            if (url && isValidUrl(url)) {
                // Check if it's likely a direct image URL
                if (!isImageUrl(url)) {
                    const helpMsg = getUrlHelpMessage(url);
                    showAlert(helpMsg, 'error');
                    photoPreview.style.display = 'none';
                    return;
                }

                previewImage.src = url;
                photoPreview.style.display = 'block';

                // Handle image load error
                previewImage.onerror = function() {
                    photoPreview.style.display = 'none';
                    const helpMsg = getUrlHelpMessage(url);
                    showAlert(helpMsg, 'error');
                };
            } else {
                photoPreview.style.display = 'none';
            }
        });

        // Validate URL format
        function isValidUrl(string) {
            try {
                const url = new URL(string);
                return url.protocol === 'http:' || url.protocol === 'https:';
            } catch (_) {
                return false;
            }
        }

        // Check if URL is a direct image link
        function isImageUrl(url) {
            // Check if URL ends with image extension
            const imageExtensions = ['.jpg', '.jpeg', '.png', '.gif', '.webp', '.bmp', '.svg'];
            const urlLower = url.toLowerCase();
            return imageExtensions.some(ext => urlLower.includes(ext));
        }

        // Get helpful message for common URL issues
        function getUrlHelpMessage(url) {
            if (url.includes('unsplash.com/') && !url.includes('images.unsplash.com')) {
                return 'URL Unsplash tidak valid! Gunakan link langsung gambar dari images.unsplash.com (Klik kanan foto → Copy image address)';
            }
            if (!isImageUrl(url)) {
                return 'URL harus mengarah langsung ke file gambar (.jpg, .png, .webp, dll)';
            }
            return 'URL foto tidak dapat dimuat. Pastikan link dapat diakses publik.';
        }

        // Handle form submission
        document.getElementById('rusunForm').addEventListener('submit', async function(e) {
            e.preventDefault();

            const rusunId = document.getElementById('rusun_id').value;
            const isEdit = rusunId !== '';

            // Show loading state
            const submitBtn = this.querySelector('button[type="submit"]');
            const originalBtnText = submitBtn.innerHTML;
            submitBtn.disabled = true;
            submitBtn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Menyimpan...';

            try {
                // Prepare form data
                const formData = {
                    name: document.getElementById('name').value.trim(),
                    address: document.getElementById('address').value.trim(),
                    unit: document.getElementById('unit').value ? parseInt(document.getElementById('unit')
                        .value) : null,
                    tower: document.getElementById('tower').value ? parseInt(document.getElementById(
                        'tower').value) : null,
                    type: document.getElementById('type').value.trim() || null,
                    floor: document.getElementById('floor').value ? parseInt(document.getElementById(
                        'floor').value) : null,
                    occupied: document.getElementById('occupied').value ? parseInt(document.getElementById(
                        'occupied').value) : null,
                    user: document.getElementById('user').value.trim() || null,
                    development_year: document.getElementById('development_year').value ? parseInt(document
                        .getElementById('development_year').value) : null,
                    handover_status: document.getElementById('handover_status').value !== '' ? document
                        .getElementById('handover_status').value === 'true' : null,
                    handover_year: document.getElementById('handover_year').value ? parseInt(document
                        .getElementById('handover_year').value) : null,
                    contractor: document.getElementById('contractor').value.trim() || null,
                    latitude: document.getElementById('latitude').value ? parseFloat(document
                        .getElementById('latitude').value) : null,
                    longitude: document.getElementById('longitude').value ? parseFloat(document
                        .getElementById('longitude').value) : null,
                    photo_url: document.getElementById('photo_url').value.trim() || null,
                    region: userSiteRegion || null, // Automatically add region from user session
                };

                // Validate region
                if (!formData.region) {
                    throw new Error('Region tidak ditemukan. Pastikan Anda sudah login dengan benar.');
                }

                // Validate photo URL if provided
                if (formData.photo_url) {
                    if (!isValidUrl(formData.photo_url)) {
                        throw new Error('URL foto tidak valid. Gunakan format: https://...');
                    }
                    if (!isImageUrl(formData.photo_url)) {
                        throw new Error(getUrlHelpMessage(formData.photo_url));
                    }
                }

                // Submit form data
                const url = isEdit ? `${baseUrl}/api/admin/flat/${rusunId}` : `${baseUrl}/api/admin/flat`;
                const method = isEdit ? 'PUT' : 'POST';

                const response = await fetch(url, {
                    method: method,
                    headers: {
                        'Authorization': `Bearer ${getAuthToken()}`,
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify(formData)
                });

                if (!response.ok) {
                    const error = await response.text();
                    throw new Error(error || 'Gagal menyimpan data');
                }

                showAlert(isEdit ? 'Data rusun berhasil diperbarui!' : 'Rusun berhasil ditambahkan!',
                    'success');
                closeModal();
                loadRusunData();

            } catch (error) {
                console.error('Error:', error);
                showAlert('Gagal menyimpan data: ' + error.message, 'error');
            } finally {
                // Restore button state
                submitBtn.disabled = false;
                submitBtn.innerHTML = originalBtnText;
            }
        });

        // Delete rusun
        async function deleteRusun(id) {
            if (!confirm('Apakah Anda yakin ingin menghapus data rusun ini?')) {
                return;
            }

            try {
                const response = await fetch(`${baseUrl}/api/admin/flat/${id}`, {
                    method: 'DELETE',
                    headers: {
                        'Authorization': `Bearer ${getAuthToken()}`,
                        'Content-Type': 'application/json'
                    }
                });

                if (!response.ok) {
                    throw new Error('Gagal menghapus data');
                }

                showAlert('Data rusun berhasil dihapus!', 'success');
                loadRusunData();

            } catch (error) {
                console.error('Error:', error);
                showAlert('Gagal menghapus data: ' + error.message, 'error');
            }
        }

        // Initialize
        document.addEventListener('DOMContentLoaded', async function() {
            // Fetch user site region first
            await fetchUserSiteRegion();
            // Then load rusun data
            loadRusunData();
        });

        // Close modal when clicking outside
        window.onclick = function(event) {
            const modal = document.getElementById('rusunModal');
            if (event.target === modal) {
                closeModal();
            }
        };
    </script>
<?php $__env->stopSection(); ?>

<?php echo $__env->make('layouts.layoutadmin', array_diff_key(get_defined_vars(), ['__data' => 1, '__path' => 1]))->render(); ?><?php /**PATH D:\laravel\krs-jawa3-template\krs-jawa3-web-template\resources\views/admin/sebaranrusunAdmin.blade.php ENDPATH**/ ?>