
<?php $__env->startSection('title', 'Manajemen Laporan Bug - Admin'); ?>

<?php $__env->startSection('content'); ?>
<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 .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;
        background: #f4f4f4;
    }

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

    /* 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: 1.4rem;
        font-weight: 700;
        color: #222;
    }

    .main-header .subtitle {
        color: #6b7280;
        font-size: 1.05rem;
        margin-top: 2px;
    }

    .main-content {
        flex: 1;
        padding: 32px;
        overflow-y: auto;
    }

    .bg-gradient-primary {
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    }
    
    .bg-gradient-success {
        background: linear-gradient(135deg, #43e97b 0%, #38f9d7 100%);
    }
    
    .bg-gradient-info {
        background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
    }
    
    .bg-gradient-warning {
        background: linear-gradient(135deg, #fa709a 0%, #fee140 100%);
    }
    
    .table-hover tbody tr:hover {
        background-color: rgba(102, 126, 234, 0.05);
        cursor: pointer;
    }
    
    .btn-action {
        width: 32px;
        height: 32px;
        padding: 0;
        display: inline-flex;
        align-items: center;
        justify-content: center;
        border-radius: 8px;
        transition: all 0.3s ease;
    }
    
    .btn-action:hover {
        transform: translateY(-2px);
        box-shadow: 0 4px 8px rgba(0,0,0,0.15);
    }
    
    .badge-date {
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        color: white;
        padding: 0.5rem 1rem;
        border-radius: 20px;
        font-weight: 500;
    }
    
    .card {
        transition: all 0.3s ease;
    }
    
    .card:hover {
        transform: translateY(-5px);
    }
    
    .input-group-text {
        border-right: 0;
    }
    
    .form-control:focus {
        border-color: #667eea;
        box-shadow: 0 0 0 0.2rem rgba(102, 126, 234, 0.25);
    }
    
    .page-link {
        color: #667eea;
    }
    
    .page-link:hover {
        color: #764ba2;
        background-color: rgba(102, 126, 234, 0.1);
    }
    
    .page-item.active .page-link {
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        border-color: #667eea;
    }

    .truncate-text {
        display: -webkit-box;
        -webkit-line-clamp: 3;
        -webkit-box-orient: vertical;
        overflow: hidden;
        text-overflow: ellipsis;
    }
</style>

<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">
                    <i class="fas fa-bug me-2"></i>Manajemen Laporan Bug
                </div>
                <div class="subtitle">Kelola laporan bug dari pengguna</div>
            </div>
            <div class="header-actions">
                <button class="btn btn-light btn-sm" onclick="refreshData()">
                    <i class="fas fa-sync-alt me-1"></i>Refresh
                </button>
                <button class="btn btn-info btn-sm" onclick="exportData()">
                    <i class="fas fa-download me-1"></i>Export
                </button>
            </div>
        </div>
        <div class="main-content">
            <div class="container-fluid">
                <div class="row">
                    <div class="col-12">
                        <div class="card shadow-lg border-0 rounded-3">
                            <div class="card-header bg-gradient-primary text-white d-flex justify-content-between align-items-center py-3">
                                <div>
                                    <h5 class="mb-0">
                                        <i class="fas fa-bug me-2"></i>Daftar Laporan Bug
                                    </h5>
                                </div>
                            </div>

                            <div class="card-body p-4">
                                <!-- Stats Cards -->
                                <div class="row mb-4">
                                    <div class="col-md-4 mb-3">
                                        <div class="card bg-gradient-primary text-white border-0">
                                            <div class="card-body">
                                                <div class="d-flex justify-content-between align-items-center">
                                                    <div>
                                                        <h6 class="text-white-50 mb-2">Total Laporan</h6>
                                                        <h2 class="mb-0" id="totalBugs">0</h2>
                                                    </div>
                                                    <div class="display-4 opacity-50">
                                                        <i class="fas fa-bug"></i>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                    <div class="col-md-4 mb-3">
                                        <div class="card bg-gradient-success text-white border-0">
                                            <div class="card-body">
                                                <div class="d-flex justify-content-between align-items-center">
                                                    <div>
                                                        <h6 class="text-white-50 mb-2">Hari Ini</h6>
                                                        <h2 class="mb-0" id="todayBugs">0</h2>
                                                    </div>
                                                    <div class="display-4 opacity-50">
                                                        <i class="fas fa-calendar-day"></i>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                    <div class="col-md-4 mb-3">
                                        <div class="card bg-gradient-info text-white border-0">
                                            <div class="card-body">
                                                <div class="d-flex justify-content-between align-items-center">
                                                    <div>
                                                        <h6 class="text-white-50 mb-2">Bulan Ini</h6>
                                                        <h2 class="mb-0" id="monthBugs">0</h2>
                                                    </div>
                                                    <div class="display-4 opacity-50">
                                                        <i class="fas fa-calendar-alt"></i>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </div>

                                <!-- Search and Filter -->
                                <div class="row mb-4">
                                    <div class="col-md-6 mb-3">
                                        <div class="input-group">
                                            <span class="input-group-text bg-white">
                                                <i class="fas fa-search"></i>
                                            </span>
                                            <input type="text" class="form-control border-start-0" id="searchInput" placeholder="Cari laporan bug...">
                                        </div>
                                    </div>
                                    <div class="col-md-3 mb-3">
                                        <select class="form-select" id="sortBy">
                                            <option value="createdAt-desc">Terbaru</option>
                                            <option value="createdAt-asc">Terlama</option>
                                        </select>
                                    </div>
                                    <div class="col-md-3 mb-3">
                                        <select class="form-select" id="itemsPerPage">
                                            <option value="10">10 per halaman</option>
                                            <option value="25">25 per halaman</option>
                                            <option value="50">50 per halaman</option>
                                            <option value="100">100 per halaman</option>
                                        </select>
                                    </div>
                                </div>

                                <!-- Loading State -->
                                <div id="loadingState" class="text-center py-5 d-none">
                                    <div class="spinner-border text-danger" role="status">
                                        <span class="visually-hidden">Loading...</span>
                                    </div>
                                    <p class="mt-3 text-muted">Memuat data...</p>
                                </div>

                                <!-- Empty State -->
                                <div id="emptyState" class="text-center py-5 d-none">
                                    <i class="fas fa-inbox fa-4x text-muted mb-3"></i>
                                    <p class="text-muted">Belum ada laporan bug</p>
                                </div>

                                <!-- Bug Reports Table -->
                                <div id="tableContainer" class="table-responsive">
                                    <table class="table table-hover align-middle">
                                        <thead class="table-light">
                                            <tr>
                                                <th width="5%">No</th>
                                                <th width="60%">Laporan</th>
                                                <th width="20%">Tanggal</th>
                                                <th width="15%" class="text-center">Aksi</th>
                                            </tr>
                                        </thead>
                                        <tbody id="bugTableBody">
                                            <!-- Data will be inserted here -->
                                        </tbody>
                                    </table>
                                </div>

                                <!-- Pagination -->
                                <div id="paginationContainer" class="d-flex justify-content-between align-items-center mt-4 d-none">
                                    <div>
                                        <small class="text-muted" id="paginationInfo"></small>
                                    </div>
                                    <nav>
                                        <ul class="pagination mb-0" id="paginationList">
                                            <!-- Pagination will be inserted here -->
                                        </ul>
                                    </nav>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <!-- View Detail Modal -->
            <div class="modal fade" id="viewModal" tabindex="-1">
                <div class="modal-dialog modal-lg">
                    <div class="modal-content">
                        <div class="modal-header bg-gradient-primary text-white">
                            <h5 class="modal-title">
                                <i class="fas fa-eye me-2"></i>Detail Laporan Bug
                            </h5>
                            <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
                        </div>
                        <div class="modal-body">
                            <div class="row">
                                <div class="col-12 mb-3">
                                    <label class="fw-bold text-muted small">Laporan Bug:</label>
                                    <div class="p-3 bg-light rounded">
                                        <p class="mb-0" id="viewReport" style="white-space: pre-wrap;"></p>
                                    </div>
                                </div>
                                <div class="col-md-6 mb-3">
                                    <label class="fw-bold text-muted small">Dibuat Pada:</label>
                                    <p id="viewCreatedAt"></p>
                                </div>
                                <div class="col-md-6 mb-3">
                                    <label class="fw-bold text-muted small">Terakhir Diupdate:</label>
                                    <p id="viewUpdatedAt"></p>
                                </div>
                            </div>
                        </div>
                        <div class="modal-footer">
                            <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">
                                <i class="fas fa-times me-1"></i>Tutup
                            </button>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Edit Modal -->
            <div class="modal fade" id="editModal" tabindex="-1">
                <div class="modal-dialog modal-lg">
                    <div class="modal-content">
                        <div class="modal-header bg-gradient-warning text-white">
                            <h5 class="modal-title">
                                <i class="fas fa-edit me-2"></i>Edit Laporan Bug
                            </h5>
                            <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
                        </div>
                        <form id="editForm">
                            <div class="modal-body">
                                <input type="hidden" id="editId">
                                <div class="mb-3">
                                    <label for="editReport" class="form-label">Laporan Bug <span class="text-danger">*</span></label>
                                    <textarea class="form-control" id="editReport" name="report" rows="8" required></textarea>
                                </div>
                            </div>
                            <div class="modal-footer">
                                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">
                                    <i class="fas fa-times me-1"></i>Batal
                                </button>
                                <button type="submit" class="btn btn-warning text-white">
                                    <i class="fas fa-save me-1"></i>Simpan Perubahan
                                </button>
                            </div>
                        </form>
                    </div>
                </div>
            </div>
        </div>
    </main>
</div>

<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>

<script>
let bugData = [];
let filteredData = [];
let currentPage = 1;
let itemsPerPage = 10;
const API_BASE_URL = '<?php echo e(env('BASE_URL')); ?>/api/admin/bug-report';

// Get auth token
function getAuthToken() {
    let token = localStorage.getItem('accessToken') || 
                localStorage.getItem('token') || 
                sessionStorage.getItem('token') ||
                sessionStorage.getItem('accessToken');
    return token;
}

// Initialize
document.addEventListener('DOMContentLoaded', function() {
    console.log('Bug Report page loaded');
    loadBugData();
    setupEventListeners();
});

// Setup event listeners
function setupEventListeners() {
    document.getElementById('searchInput').addEventListener('input', debounce(handleSearch, 300));
    document.getElementById('sortBy').addEventListener('change', handleSort);
    document.getElementById('itemsPerPage').addEventListener('change', handleItemsPerPageChange);
    document.getElementById('editForm').addEventListener('submit', handleEditSubmit);
}

// Load bug data
async function loadBugData() {
    showLoading();
    
    try {
        const token = getAuthToken();
        
        if (!token) {
            hideLoading();
            showError('Token tidak ditemukan. Silakan login ulang.');
            setTimeout(() => {
                window.location.href = '/login';
            }, 2000);
            return;
        }
        
        const response = await fetch(API_BASE_URL, {
            headers: {
                'Authorization': `Bearer ${token}`,
                'Content-Type': 'application/json'
            }
        });

        if (!response.ok) {
            if (response.status === 401) {
                hideLoading();
                showError('Sesi Anda telah berakhir. Silakan login ulang.');
                setTimeout(() => {
                    window.location.href = '/login';
                }, 2000);
                return;
            }
            throw new Error('Failed to fetch bug reports');
        }

        const result = await response.json();
        console.log('API Response:', result);
        
        if (Array.isArray(result)) {
            bugData = result;
        } else if (result.data && Array.isArray(result.data)) {
            bugData = result.data;
        } else {
            bugData = [];
        }
        
        console.log('Bug Data:', bugData);
        filteredData = [...bugData];
        
        updateStats();
        renderTable();
        hideLoading();
        
        if (bugData.length === 0) {
            showEmptyState();
        }
    } catch (error) {
        console.error('Error loading bug reports:', error);
        hideLoading();
        showError('Gagal memuat data laporan bug. Silakan refresh halaman.');
    }
}

// Update statistics
function updateStats() {
    const total = bugData.length;
    const today = new Date().toDateString();
    const thisMonth = new Date().getMonth();
    const thisYear = new Date().getFullYear();
    
    const todayCount = bugData.filter(bug => {
        const bugDate = new Date(bug.createdAt);
        return bugDate.toDateString() === today;
    }).length;
    
    const monthCount = bugData.filter(bug => {
        const bugDate = new Date(bug.createdAt);
        return bugDate.getMonth() === thisMonth && bugDate.getFullYear() === thisYear;
    }).length;
    
    document.getElementById('totalBugs').textContent = total;
    document.getElementById('todayBugs').textContent = todayCount;
    document.getElementById('monthBugs').textContent = monthCount;
}

// Render table
function renderTable() {
    const tbody = document.getElementById('bugTableBody');
    tbody.innerHTML = '';
    
    const startIndex = (currentPage - 1) * itemsPerPage;
    const endIndex = startIndex + itemsPerPage;
    const paginatedData = filteredData.slice(startIndex, endIndex);
    
    if (paginatedData.length === 0 && filteredData.length > 0) {
        currentPage = 1;
        renderTable();
        return;
    }
    
    paginatedData.forEach((bug, index) => {
        const row = document.createElement('tr');
        row.innerHTML = `
            <td>${startIndex + index + 1}</td>
            <td>
                <div class="truncate-text" title="${escapeHtml(bug.report)}">
                    ${escapeHtml(bug.report)}
                </div>
            </td>
            <td>
                <span class="badge badge-date">
                    <i class="far fa-calendar me-1"></i>
                    ${formatDate(bug.createdAt)}
                </span>
            </td>
            <td class="text-center">
                <div class="btn-group" role="group">
                    <button class="btn btn-info btn-sm btn-action" onclick="viewBug(${bug.id})" title="Lihat Detail">
                        <i class="fas fa-eye"></i>
                    </button>
                    <button class="btn btn-warning btn-sm btn-action" onclick="editBug(${bug.id})" title="Edit">
                        <i class="fas fa-edit"></i>
                    </button>
                    <button class="btn btn-danger btn-sm btn-action" onclick="deleteBug(${bug.id})" title="Hapus">
                        <i class="fas fa-trash"></i>
                    </button>
                </div>
            </td>
        `;
        tbody.appendChild(row);
    });
    
    renderPagination();
}

// Render pagination
function renderPagination() {
    const totalPages = Math.ceil(filteredData.length / itemsPerPage);
    const paginationList = document.getElementById('paginationList');
    const paginationInfo = document.getElementById('paginationInfo');
    const paginationContainer = document.getElementById('paginationContainer');
    
    if (totalPages <= 1) {
        paginationContainer.classList.add('d-none');
        return;
    }
    
    paginationContainer.classList.remove('d-none');
    
    const startIndex = (currentPage - 1) * itemsPerPage + 1;
    const endIndex = Math.min(currentPage * itemsPerPage, filteredData.length);
    paginationInfo.textContent = `Menampilkan ${startIndex}-${endIndex} dari ${filteredData.length} data`;
    
    paginationList.innerHTML = '';
    
    // Previous button
    const prevLi = document.createElement('li');
    prevLi.className = `page-item ${currentPage === 1 ? 'disabled' : ''}`;
    prevLi.innerHTML = `<a class="page-link" href="#" onclick="changePage(${currentPage - 1}); return false;">
        <i class="fas fa-chevron-left"></i>
    </a>`;
    paginationList.appendChild(prevLi);
    
    // Page numbers
    let startPage = Math.max(1, currentPage - 2);
    let endPage = Math.min(totalPages, currentPage + 2);
    
    if (startPage > 1) {
        const li = document.createElement('li');
        li.className = 'page-item';
        li.innerHTML = `<a class="page-link" href="#" onclick="changePage(1); return false;">1</a>`;
        paginationList.appendChild(li);
        
        if (startPage > 2) {
            const dots = document.createElement('li');
            dots.className = 'page-item disabled';
            dots.innerHTML = `<span class="page-link">...</span>`;
            paginationList.appendChild(dots);
        }
    }
    
    for (let i = startPage; i <= endPage; i++) {
        const li = document.createElement('li');
        li.className = `page-item ${i === currentPage ? 'active' : ''}`;
        li.innerHTML = `<a class="page-link" href="#" onclick="changePage(${i}); return false;">${i}</a>`;
        paginationList.appendChild(li);
    }
    
    if (endPage < totalPages) {
        if (endPage < totalPages - 1) {
            const dots = document.createElement('li');
            dots.className = 'page-item disabled';
            dots.innerHTML = `<span class="page-link">...</span>`;
            paginationList.appendChild(dots);
        }
        
        const li = document.createElement('li');
        li.className = 'page-item';
        li.innerHTML = `<a class="page-link" href="#" onclick="changePage(${totalPages}); return false;">${totalPages}</a>`;
        paginationList.appendChild(li);
    }
    
    // Next button
    const nextLi = document.createElement('li');
    nextLi.className = `page-item ${currentPage === totalPages ? 'disabled' : ''}`;
    nextLi.innerHTML = `<a class="page-link" href="#" onclick="changePage(${currentPage + 1}); return false;">
        <i class="fas fa-chevron-right"></i>
    </a>`;
    paginationList.appendChild(nextLi);
}

// Change page
function changePage(page) {
    const totalPages = Math.ceil(filteredData.length / itemsPerPage);
    if (page < 1 || page > totalPages) return;
    currentPage = page;
    renderTable();
}

// Handle search
function handleSearch(e) {
    const searchTerm = e.target.value.toLowerCase();
    filteredData = bugData.filter(bug => 
        bug.report.toLowerCase().includes(searchTerm)
    );
    currentPage = 1;
    renderTable();
}

// Handle sort
function handleSort(e) {
    const [field, order] = e.target.value.split('-');
    
    filteredData.sort((a, b) => {
        let aValue = a[field];
        let bValue = b[field];
        
        if (field === 'createdAt') {
            aValue = new Date(aValue);
            bValue = new Date(bValue);
        }
        
        if (order === 'asc') {
            return aValue > bValue ? 1 : -1;
        } else {
            return aValue < bValue ? 1 : -1;
        }
    });
    
    renderTable();
}

// Handle items per page change
function handleItemsPerPageChange(e) {
    itemsPerPage = parseInt(e.target.value);
    currentPage = 1;
    renderTable();
}

// View bug
async function viewBug(id) {
    try {
        const token = getAuthToken();
        const response = await fetch(`${API_BASE_URL}/${id}`, {
            headers: {
                'Authorization': `Bearer ${token}`,
                'Content-Type': 'application/json'
            }
        });

        if (!response.ok) throw new Error('Failed to fetch bug report');

        const result = await response.json();
        const bug = result.data || result;
        
        document.getElementById('viewReport').textContent = bug.report;
        document.getElementById('viewCreatedAt').textContent = formatDateTime(bug.createdAt);
        document.getElementById('viewUpdatedAt').textContent = formatDateTime(bug.updatedAt);
        
        const modal = new bootstrap.Modal(document.getElementById('viewModal'));
        modal.show();
    } catch (error) {
        console.error('Error viewing bug report:', error);
        showError('Gagal memuat detail laporan bug');
    }
}

// Edit bug
async function editBug(id) {
    try {
        const token = getAuthToken();
        const response = await fetch(`${API_BASE_URL}/${id}`, {
            headers: {
                'Authorization': `Bearer ${token}`,
                'Content-Type': 'application/json'
            }
        });

        if (!response.ok) throw new Error('Failed to fetch bug report');

        const result = await response.json();
        const bug = result.data || result;
        
        document.getElementById('editId').value = bug.id;
        document.getElementById('editReport').value = bug.report;
        
        const modal = new bootstrap.Modal(document.getElementById('editModal'));
        modal.show();
    } catch (error) {
        console.error('Error loading bug report for edit:', error);
        showError('Gagal memuat data laporan bug');
    }
}

// Handle edit submit
async function handleEditSubmit(e) {
    e.preventDefault();
    
    const id = document.getElementById('editId').value;
    const data = {
        report: document.getElementById('editReport').value
    };
    
    try {
        const token = getAuthToken();
        const response = await fetch(`${API_BASE_URL}/${id}`, {
            method: 'PUT',
            headers: {
                'Authorization': `Bearer ${token}`,
                'Content-Type': 'application/json'
            },
            body: JSON.stringify(data)
        });

        if (!response.ok) throw new Error('Failed to update bug report');

        const modal = bootstrap.Modal.getInstance(document.getElementById('editModal'));
        modal.hide();
        
        showSuccess('Laporan bug berhasil diperbarui');
        loadBugData();
    } catch (error) {
        console.error('Error updating bug report:', error);
        showError('Gagal memperbarui laporan bug');
    }
}

// Delete bug
async function deleteBug(id) {
    const result = await Swal.fire({
        title: 'Konfirmasi Hapus',
        text: 'Apakah Anda yakin ingin menghapus laporan bug ini?',
        icon: 'warning',
        showCancelButton: true,
        confirmButtonColor: '#d33',
        cancelButtonColor: '#3085d6',
        confirmButtonText: 'Ya, Hapus!',
        cancelButtonText: 'Batal'
    });
    
    if (result.isConfirmed) {
        try {
            const token = getAuthToken();
            const response = await fetch(`${API_BASE_URL}/${id}`, {
                method: 'DELETE',
                headers: {
                    'Authorization': `Bearer ${token}`,
                    'Content-Type': 'application/json'
                }
            });

            if (!response.ok) throw new Error('Failed to delete bug report');

            showSuccess('Laporan bug berhasil dihapus');
            loadBugData();
        } catch (error) {
            console.error('Error deleting bug report:', error);
            showError('Gagal menghapus laporan bug');
        }
    }
}

// Refresh data
function refreshData() {
    loadBugData();
    showSuccess('Data berhasil direfresh');
}

// Export data
function exportData() {
    const csvContent = generateCSV(bugData);
    const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' });
    const link = document.createElement('a');
    const url = URL.createObjectURL(blob);
    
    link.setAttribute('href', url);
    link.setAttribute('download', `bug_reports_export_${new Date().toISOString().split('T')[0]}.csv`);
    link.style.visibility = 'hidden';
    
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    
    showSuccess('Data berhasil diexport');
}

// Generate CSV
function generateCSV(data) {
    const headers = ['No', 'Laporan Bug', 'Tanggal Dibuat'];
    const rows = data.map((item, index) => [
        index + 1,
        item.report.replace(/\n/g, ' ').replace(/"/g, '""'),
        formatDateTime(item.createdAt)
    ]);
    
    const csvRows = [
        headers.join(','),
        ...rows.map(row => row.map(cell => `"${cell}"`).join(','))
    ];
    
    return csvRows.join('\n');
}

// Utility functions
function showLoading() {
    document.getElementById('loadingState').classList.remove('d-none');
    document.getElementById('tableContainer').classList.add('d-none');
    document.getElementById('emptyState').classList.add('d-none');
}

function hideLoading() {
    document.getElementById('loadingState').classList.add('d-none');
    document.getElementById('tableContainer').classList.remove('d-none');
}

function showEmptyState() {
    document.getElementById('emptyState').classList.remove('d-none');
    document.getElementById('tableContainer').classList.add('d-none');
}

function showSuccess(message) {
    Swal.fire({
        icon: 'success',
        title: 'Berhasil!',
        text: message,
        timer: 2000,
        showConfirmButton: false
    });
}

function showError(message) {
    Swal.fire({
        icon: 'error',
        title: 'Oops...',
        text: message
    });
}

function formatDate(dateString) {
    const options = { year: 'numeric', month: 'short', day: 'numeric' };
    return new Date(dateString).toLocaleDateString('id-ID', options);
}

function formatDateTime(dateString) {
    const options = { 
        year: 'numeric', 
        month: 'long', 
        day: 'numeric',
        hour: '2-digit',
        minute: '2-digit'
    };
    return new Date(dateString).toLocaleDateString('id-ID', options);
}

function escapeHtml(text) {
    const map = {
        '&': '&amp;',
        '<': '&lt;',
        '>': '&gt;',
        '"': '&quot;',
        "'": '&#039;'
    };
    return text.replace(/[&<>"']/g, m => map[m]);
}

function debounce(func, wait) {
    let timeout;
    return function executedFunction(...args) {
        const later = () => {
            clearTimeout(timeout);
            func(...args);
        };
        clearTimeout(timeout);
        timeout = setTimeout(later, wait);
    };
}
</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/laporanbugAdmin.blade.php ENDPATH**/ ?>