// Main JavaScript for DigiMobiz

$(document).ready(function() {
    // Sidebar toggle for mobile
    $('#sidebarToggle').click(function(e) {
        e.preventDefault();
        $('.sidebar').toggleClass('active');
    });

    // Confirm delete
    $(document).on('click', '.btn-delete', function(e) {
        if (!confirm('Are you sure you want to delete this item? This action cannot be undone.')) {
            e.preventDefault();
        }
    });

    // Confirm action
    $(document).on('click', '[data-confirm]', function(e) {
        var msg = $(this).data('confirm') || 'Are you sure?';
        if (!confirm(msg)) {
            e.preventDefault();
        }
    });

    // Tooltips
    var tooltipTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="tooltip"]'));
    tooltipTriggerList.map(function(el) { return new bootstrap.Tooltip(el); });

    // Auto calculate totals
    $(document).on('input', '.calc-qty, .calc-price', function() {
        var row = $(this).closest('tr');
        var qty = parseFloat(row.find('.calc-qty').val()) || 0;
        var price = parseFloat(row.find('.calc-price').val()) || 0;
        var total = qty * price;
        row.find('.calc-total').val(total.toFixed(2));
        calculateGrandTotal();
    });

    // Calculate discount
    $(document).on('input', '#discountValue, #discountType, #subtotalAmount', function() {
        calculateInvoiceTotals();
    });

    // Calculate tax
    $(document).on('input', '#taxValue, #taxType', function() {
        calculateInvoiceTotals();
    });

    // Print invoice
    $(document).on('click', '.btn-print', function() {
        window.print();
    });

    // Select2 for searchable selects
    if ($.fn.select2) {
        $('.select2').select2({
            theme: 'bootstrap-5',
            width: '100%'
        });
    }

    // Load notifications
    loadNotifications();
});

// Calculate grand total for purchase/order tables
function calculateGrandTotal() {
    var total = 0;
    $('.calc-total').each(function() {
        total += parseFloat($(this).val()) || 0;
    });
    $('#grandTotal').val(total.toFixed(2));
    $('#grandTotalDisplay').text(total.toFixed(2));
}

// Calculate invoice totals with discount and tax
function calculateInvoiceTotals() {
    var subtotal = parseFloat($('#subtotalAmount').val()) || 0;
    var discountType = $('#discountType').val();
    var discountValue = parseFloat($('#discountValue').val()) || 0;
    var taxType = $('#taxType').val();
    var taxValue = parseFloat($('#taxValue').val()) || 0;
    var discountAmount = 0;
    var taxAmount = 0;

    if (discountType === 'Percentage') {
        discountAmount = (subtotal * discountValue) / 100;
    } else {
        discountAmount = discountValue;
    }
    if (discountAmount > subtotal) discountAmount = subtotal;

    var afterDiscount = subtotal - discountAmount;

    if (taxType === 'Percentage') {
        taxAmount = (afterDiscount * taxValue) / 100;
    } else {
        taxAmount = taxValue;
    }

    var total = afterDiscount + taxAmount;

    $('#discountAmount').val(discountAmount.toFixed(2));
    $('#taxAmount').val(taxAmount.toFixed(2));
    $('#totalAmount').val(total.toFixed(2));
    $('#totalAmountDisplay').text(total.toFixed(2));
}

// Load notifications via AJAX
function loadNotifications() {
    $.get('/DigiMobiz/ajax/notifications.php', function(data) {
        if (data.count > 0) {
            $('#notificationCount').text(data.count);
            var html = '';
            $.each(data.notifications, function(i, n) {
                html += '<a class="dropdown-item" href="' + n.link + '"><small>' + n.message + '</small><br><span class="text-muted" style="font-size:11px;">' + n.time + '</span></a>';
            });
            $('#notificationList').html(html);
        }
    }, 'json').fail(function() {});
}


