$(document).ready(function() {
    // Initialize DataTables
    $('.datatable').DataTable({
        language: {
            url: '//cdn.datatables.net/plug-ins/1.13.4/i18n/id.json'
        }
    });

    // Load Notifications
    loadNotifications();

    // Auto refresh notifications every 30 seconds
    setInterval(loadNotifications, 30000);

    // Confirmation modal
    $('.btn-delete').click(function(e) {
        e.preventDefault();
        const url = $(this).attr('href');
        const message = $(this).data('message') || 'Apakah Anda yakin ingin menghapus data ini?';
        
        $('#confirmModal .modal-body').text(message);
        $('#confirmModal').modal('show');
        
        $('#confirmDelete').click(function() {
            window.location.href = url;
        });
    });

    // Show loading spinner on form submit
    $('form').submit(function() {
        $('.spinner-overlay').fadeIn();
    });
});

// Load notifications
function loadNotifications() {
    $.ajax({
        url: '../api/get_notifications.php',
        method: 'GET',
        dataType: 'json',
        success: function(data) {
            if (data.success) {
                updateNotificationMenu(data.notifications, data.unread_count);
            }
        }
    });
}

// Update notification menu
function updateNotificationMenu(notifications, unreadCount) {
    $('#notifCount').text(unreadCount);
    
    let html = '';
    if (notifications.length > 0) {
        notifications.forEach(function(notif) {
            html += `<div class="notif-item ${notif.status == 'belum_dibaca' ? 'unread' : ''}" onclick="markAsRead(${notif.id_notif})">`;
            html += `<p class="mb-1">${notif.pesan}</p>`;
            html += `<small class="text-muted">${notif.waktu}</small>`;
            html += `</div>`;
        });
    } else {
        html = '<li class="text-center py-2">Tidak ada notifikasi</li>';
    }
    
    $('#notifMenu').html(html);
}

// Mark notification as read
function markAsRead(id) {
    $.ajax({
        url: '../api/mark_notification_read.php',
        method: 'POST',
        data: { id: id },
        success: function() {
            loadNotifications();
        }
    });
}

// Format currency
function formatNumber(num) {
    return num.toString().replace(/(\d)(?=(\d{3})+(?!\d))/g, '$1.');
}

// Format date
function formatDate(date) {
    const d = new Date(date);
    return d.toLocaleDateString('id-ID', {
        day: 'numeric',
        month: 'long',
        year: 'numeric'
    });
}

// Validate form
function validateForm(formId) {
    let isValid = true;
    $(`#${formId} [required]`).each(function() {
        if (!$(this).val()) {
            $(this).addClass('is-invalid');
            isValid = false;
        } else {
            $(this).removeClass('is-invalid');
        }
    });
    return isValid;
}