$(document).ready(function () {

    
  // ✅ Reusable confirmation modal
  function showConfirm(message, callback) {
    $("#psmConfirmMessage").text(message);
    $("#psmConfirmModal").fadeIn(150);
    $("#psmConfirmYes").off("click").on("click", function() {
      $("#psmConfirmModal").fadeOut(150);
      callback(true);
    });
    $("#psmConfirmNo").off("click").on("click", function() {
      $("#psmConfirmModal").fadeOut(150);
      callback(false);
    });
  }

  // ✅ Auto-remove messages
  function showMessage(type, msg) {
    $(".messages").html(`<div class="alert alert-${type}">${msg}</div>`);
    setTimeout(() => $(".messages .alert").fadeOut(500, function(){ $(this).remove(); }), 5000);
  }

  // ===================================================================
  // 🚀 PRODUCT MANAGEMENT (Table: #productlist)
  // ===================================================================

  if ($("#productlist").length) {
    loadProducts();

    // ✅ Add or Update Product
    $("#psmProductForm").on("submit", function(e) {
        e.preventDefault();
        
        // Set default value for hidden qty field
        $("#psm_product_qty").val("1");
        
        // Get all selected companies
        var selectedCompanies = [];
        $('input[name="cname[]"]:checked').each(function() {
            selectedCompanies.push($(this).val());
        });
        
        // Get all selected tags
        var selectedTags = [];
        $('input[name="tname[]"]:checked').each(function() {
            selectedTags.push($(this).val());
        });
        
        
        // Create FormData
        var formData = new FormData();
        formData.append('action', 'save_product');
        formData.append('id', $("#psm_product_id").val());
        formData.append('name', $("#psm_product_name").val());
        formData.append('stance', $("#psm_stance").val());
        formData.append('unit', $("#psm_product_unit").val());
        formData.append('qty', $("#psm_product_qty").val());
        formData.append('price', $("#psm_product_price").val());
        formData.append('sale_price', $("#psm_product_sale_price").val());
        formData.append('status', $("#psm_product_status").val());
        
        // Append each selected company - this is KEY for multiple insertions
        selectedCompanies.forEach(function(company) {
            formData.append('cname[]', company);
        });
        
        // Append each selected tag - this is KEY for multiple insertions
        selectedTags.forEach(function(tag) {
            formData.append('tname[]', tag);
        });
        
     
        
        $.ajax({
            url: "functions.php",
            type: "POST",
            dataType: "json",
            data: formData,
            processData: false,
            contentType: false,
            success: function(resp) {
                
                showMessage(resp.status, resp.message);
                if (resp.status === "success") {
                    $("#addProductModal").modal("hide");
                    $("#psmProductForm")[0].reset();
                    $('input[name="cname[]"]').prop('checked', false);
                    $('input[name="tname[]"]').prop('checked', false);
                    loadProducts();
                   
                }
            },

        });
    });

    // ✅ Load Products Function
    function loadProducts() {
        $.ajax({
            url: "functions.php",
            type: "POST",
            data: { action: "get_all_products" },
            dataType: "json",
            success: function(resp) {
                if (resp.status === "success") {
                    const rows = resp.data.map(p => `
                        <tr data-row="product"
                            data-id="${p.id}"
                            data-name="${p.name || ''}"
                            data-unit="${p.unit || ''}"
                            data-price="${p.price || ''}"
                            data-sale="${p.sale_price || ''}"
                            data-status="${p.status || ''}"
                            data-ctype="${p.ctype || ''}">
                            <td><input type="checkbox" id="${p.id}" class="psmProductCheckbox"></td>
                            <td>${p.id}</td>
                            <td><label for="${p.id}">${p.name}</label></td>
                            <td>${p.unit || ''}</td>
                            <td>${p.price || ''} Tk / ${p.sale_price || ''} Tk</td>
                            <td>${p.status || ''}</td>
                            <td>
                                <button class="btn btn-sm btn-info psmEditProduct" title="Edit">
                                    <i class="fa fa-edit"></i>
                                </button>
                                <button class="btn btn-sm btn-danger psmDeleteProduct" title="Delete">
                                    <i class="fa fa-trash"></i>
                                </button>
                            </td>
                        </tr>
                    `).join('');

                    $("#productlist tbody").html(rows);

                    if ($("#productlist thead tr th").first().find("#psmProductSelectAll").length === 0) {
                        $("#productlist thead tr").prepend('<th><input type="checkbox" id="psmProductSelectAll"></th>');
                    }
                }
            }
        });
    }

    $('#psmProductSearch').on('input change', function () {
        const keyword = $('#psmProductSearch').val().toLowerCase();
    
        $('tbody tr[data-row="product"]').each(function () {
            const rowText = $(this).text().toLowerCase();
    
            const matchesSearch = rowText.indexOf(keyword) !== -1;
    
            $(this).toggle(matchesSearch);
        });
    });

    // ✅ Delete Single Product
    $(document).on("click", ".psmDeleteProduct", function() {
        const tr = $(this).closest("tr");
        const id = tr.data("id");
       
        $.ajax({
            url: "functions.php",
            type: "POST",
            dataType: "json",
            data: { action: "delete_product", id: id },
            success: function(response) {
                showMessage(response.status, response.message);
                if (response.status === "success") {
                    tr.remove();
                    $("#psmProductSelectAll").prop("checked", false);
                }
            }
        });
        
    });

    // ✅ Bulk Delete Products
    $("#psmBulkDelete").on("click", function() {
        const ids = $("#productlist .psmProductCheckbox:checked").map(function() {
            return $(this).closest("tr").data("id");
        }).get();

        if (ids.length === 0) {
            showMessage("error", "Please select at least one product to delete.");
            return;
        }

        $.ajax({
            url: "functions.php",
            type: "POST",
            dataType: "json",
            data: { 
                action: "bulk_delete_product", 
                ids: ids 
            },
            traditional: true,
            success: function(response) {
                showMessage(response.status, response.message);
                if (response.status === "success") {
                    ids.forEach(id => $(`#productlist tr[data-id="${id}"]`).remove());
                    $("#psmProductSelectAll").prop("checked", false);
                }
            }
        });
           
    });

    // ✅ Load Product Companies and Tags for Editing
    function loadProductCompaniesAndTags(productId) {

        $.ajax({
            url: "functions.php",
            type: "POST",
            data: { 
                action: "get_product_companies_tags",
                product_id: productId 
            },
            dataType: "json",
            success: function(response) {

                if (response.status === "success") {
                    // Uncheck all first
                    $('input[name="cname[]"]').prop('checked', false);
                    $('input[name="tname[]"]').prop('checked', false);
                    
                    // ✅ Check the companies
                    if (Array.isArray(response.companies)) {
                        response.companies.forEach(function(cid) {
                            $('input[name="cname[]"][value="' + cid + '"]').prop('checked', true);
                        });
                    }
                    
                    // ✅ Check the tags
                    if (Array.isArray(response.tags)) {
                        response.tags.forEach(function(tid) {
                            $('input[name="tname[]"][value="' + tid + '"]').prop('checked', true);
                        });
                    }
                } else {
                    console.warn('Failed:', response.message);
                }
            },
        
        });
    }

    // ✅ Edit Product Handler
    $(document).on('click', '.psmEditProduct', function() {
        const row = $(this).closest('tr');
        const id = row.data('id');
        
        // Fill the form with product data
        $("#psm_product_id").val(id);
        $("#psm_product_name").val(row.data('name'));
        $("#psm_stance").val(row.data('stance'));
        $("#psm_product_unit").val(row.data('unit'));
        $("#psm_product_price").val(row.data('price'));
        $("#psm_product_sale_price").val(row.data('sale'));
        $("#psm_product_status").val(row.data('status'));
        
        // Load the companies and tags for this product
        loadProductCompaniesAndTags(id);
        
        // Show the modal
        $("#addProductModal").modal('show');
    });

    // Reset Data
    $(document).on('click', '#resetPdata', function() {
       $("#psmProductForm")[0].reset();
    });
    // ✅ Handle Select All checkbox
    $(document).on('change', '#psmProductSelectAll', function() {
        $('.psmProductCheckbox').prop('checked', $(this).prop('checked'));
    });

    // ✅ Handle individual checkboxes to update Select All
    $(document).on('change', '.psmProductCheckbox', function() {
        const allChecked = $('.psmProductCheckbox:checked').length === $('.psmProductCheckbox').length;
        $('#psmProductSelectAll').prop('checked', allChecked);
    });


  }

  // ===================================================================
  // 🚀 CUSTOMER MANAGEMENT (Table: #customerlist)
  // ===================================================================

  if ($("#customerlist").length) {
    loadCustomers();

    function loadCustomers() {
      $.ajax({
        url: "functions.php",
        type: "POST",
        data: { action: "get_all_customers" },
        dataType: "json",
        success: function(response) {
          if (response.status === "success") {
            const rows = response.data.map(c => `
              <div class="overflow-auto">
              <tr data-row="customer"
                  data-id="${c.id}"
                  data-name="${c.name || ''}"
                  data-phone="${c.phone || ''}"
                  data-email="${c.email || ''}"
                  data-ctype="${c.ctype || ''}"
                  data-address="${c.address || ''}">
                <td><input type="checkbox" class="psmCustomerCheckbox"></td>
                <td>${c.id}</td>
                <td><strong>${c.name}</strong></td>
                <td>${c.phone}</td>
                <td>${c.email || ''}</td>
                <td>${c.ctype || ''}</td>
                <td>${c.address || ''}</td>
                <td>
                    <button class="btn btn-sm btn-info psmEditCustomer" title="Edit">
                        <i class="fa fa-edit"></i>
                    </button>
                    <button class="btn btn-sm btn-danger psmDeleteCustomer" title="Delete">
                        <i class="fa fa-trash"></i>
                    </button>
                </td>
              </tr>
              </div>
            `).join("");
            $("#customerlist tbody").html(rows);

            if ($("#customerlist thead tr th").first().find("#psmCustomerSelectAll").length === 0) {
              $("#customerlist thead tr").prepend('<th><input type="checkbox" id="psmCustomerSelectAll"></th>');
            }
          }
        }
      });
    }

    // ✅ Save or Update Customer
    $("#psmCustomerForm").on("submit", function(e) {
      e.preventDefault();
      $.ajax({
        url: "functions.php",
        type: "POST",
        dataType: "json",
        data: {
          action: "save_customer",
          id: $("#psm_customer_id").val(),
          name: $("#psm_customer_name").val(),
          phone: $("#psm_customer_phone").val(),
          email: $("#psm_customer_email").val(),
          ctype: $("#psm_customer_type").val(),
          address: $("#psm_customer_address").val()
        },
        success: function(response) {
          showMessage(response.status, response.message);
          if (response.status === "success") {
            $("#psmCustomerForm")[0].reset();
            $("#psm_customer_id").val("0");
            $("#addCustomerModal").modal("hide");
            loadCustomers();
          }
        }
      });
    });

    // ✅ Edit Customer
    $(document).on("click", ".psmEditCustomer", function() {
      const row = $(this).closest("tr");
      $("#psm_customer_id").val(row.data("id"));
      $("#psm_customer_name").val(row.data("name"));
      $("#psm_customer_phone").val(row.data("phone"));
      $("#psm_customer_email").val(row.data("email"));
      $("#psm_customer_type").val(row.data("ctype"));
      $("#psm_customer_address").val(row.data("address"));
      $(".modal-title").text("Edit Customer");
      $("#addCustomerModal").modal("show");
    });

    // ✅ Delete Customer
    $(document).on("click", ".psmDeleteCustomer", function() {
      const id = $(this).closest("tr").data("id");

        $.ajax({
        url: "functions.php",
        type: "POST",
        dataType: "json",
        data: { action: "delete_customer", id },
        success: function(response) {
            showMessage(response.status, response.message);
            if (response.status === "success") loadCustomers();
        }
        });
    });

    // ✅ Bulk Delete Customers
    $("#psmCustomerBulkDelete").on("click", function() {
      const ids = $("#customerlist .psmCustomerCheckbox:checked").map(function() {
        return $(this).closest("tr").data("id");
      }).get();

      if (ids.length === 0) {
        showConfirm("Please select at least one customer to delete.", function(){});
        return;
      }
        $.ajax({
        url: "functions.php",
        type: "POST",
        dataType: "json",
        data: { action: "bulk_delete_customer", ids: ids },
        success: function(response) {
            showMessage(response.status, response.message);
            if (response.status === "success") {
            ids.forEach(id => $(`#customerlist tr[data-id="${id}"]`).remove());
            $("#psmCustomerSelectAll").prop("checked", false);
            }
        }
        });
    });

    // ✅ Master checkbox (customers)
    $(document).on("change", "#psmCustomerSelectAll", function() {
      $("#customerlist .psmCustomerCheckbox").prop("checked", $(this).is(":checked"));
    });

    $(document).on("change", ".psmCustomerCheckbox", function() {
      const all = $("#customerlist .psmCustomerCheckbox").length;
      const checked = $("#customerlist .psmCustomerCheckbox:checked").length;
      $("#psmCustomerSelectAll").prop("checked", all > 0 && all === checked);
    });
  }



    let slugEdited = false;
    $('#psm_category_slug').on('input', function () {
        slugEdited = true;
    });
    
    $('#psm_category_name').on('input', function () {
        if (slugEdited) return;
        let name = $(this).val();
    
        let slug = name
            .toLowerCase()
            .trim()
            .replace(/[^a-z0-9\s-]/g, '')
            .replace(/\s+/g, '-')
            .replace(/-+/g, '-');
        $('#psm_category_slug').val(slug);
    });

    $('#psmCustomerSearch, #psmCustomerFilter').on('input change', function () {
        const keyword = $('#psmCustomerSearch').val().toLowerCase();
        const filter = $('#psmCustomerFilter').val(); // all / customer / patient
    
        $('tbody tr[data-row="customer"]').each(function () {
            const rowText = $(this).text().toLowerCase();
            const typeText = $(this).find('td').eq(5).text().toLowerCase(); // 6th column = Type
    
            const matchesSearch = rowText.indexOf(keyword) !== -1;
            const matchesFilter = filter === 'all' || typeText === filter;
    
            $(this).toggle(matchesSearch && matchesFilter);
        });
    });

    // ===================================================================
    // 🚀 CATEGORY MANAGEMENT (Table: #categorieslist)
    // ===================================================================

    if ($("#categorieslist").length) {

    loadCategories();

    function loadCategories() {
        $.ajax({
        url: "functions.php",
        type: "POST",
        data: { action: "get_all_categories" },
        dataType: "json",
        success: function(resp) {
            if (resp.status === "success") {
            const rows = resp.data.map(cat => `
                <tr data-row="category"
                    data-id="${cat.id}"
                    data-name="${cat.name || ''}"
                    data-slug="${cat.slug || ''}"
                    data-status="${cat.ctype || ''}">
                <td><input type="checkbox" class="psmCategoryCheckbox"></td>
                <td>${cat.id}</td>
                <td><strong>${cat.name}</strong></td>
                <td>${cat.slug}</td>
                <td>${cat.ctype}</td>
                <td>
                    <button class="btn btn-sm btn-info psmEditCategory" title="Edit">
                        <i class="fa fa-edit"></i>
                    </button>
                    <button class="btn btn-sm btn-danger psmDeleteCategory" title="Delete">
                        <i class="fa fa-trash"></i>
                    </button>
                </td>
                </tr>
            `).join("");

            $("#categorieslist tbody").html(rows);
            if ($("#categorieslist thead tr th").first().find("#psmCategorySelectAll").length === 0) {
                $("#categorieslist thead tr").prepend('<th><input type="checkbox" id="psmCategorySelectAll"></th>');
            }

            const comList = resp.data.map(com => `
                <input class="form-check-input" type="checkbox" value="${com.name || ''}" id="psm_${com.slug || ''}">
                <label class="form-check-label" for="psm_${com.slug || ''}">${com.name || ''}</label>
            `).join("");

            $("#comList").html(comList);
            }
        }
        });
    }

    $('#psmCategoriesSearch').on('input change', function () {
        const keyword = $('#psmCategoriesSearch').val().toLowerCase();
    
        $('tbody tr[data-row="category"]').each(function () {
            const rowText = $(this).text().toLowerCase();
    
            const matchesSearch = rowText.indexOf(keyword) !== -1;
    
            $(this).toggle(matchesSearch);
        });
    });

    // ✅ Add or Update Category
    $("#psmCategoriesForm").on("submit", function(e) {
        e.preventDefault();
        $.ajax({
        url: "functions.php",
        type: "POST",
        dataType: "json",
        data: {
            action: "save_category",
            id: $("#psm_category_id").val(),
            name: $("#psm_category_name").val(),
            slug: $("#psm_category_slug").val(),
            status: $("#ps_status").val(),
            sub_category: $("#psm_parent_category").val(),
            description: $("#psm_category_description").val()
        },
        
        success: function(response) {
          showMessage(response.status, response.message);
          if (response.status === "success") {
            $("#psmCategoriesForm")[0].reset();
            $("#psm_category_id").val("0");
            loadCategories();
          }
        }
        });
    });

    // ✅ Edit Category
    $(document).on("click", ".psmEditCategory", function() {
        const row = $(this).closest("tr");
        const catbtn = 'Update';
        // const value = $("#psmCategoriesForm")[0].reset();;
        $("#psm_category_id").val(row.data("id"));
        $("#psm_category_name").val(row.data("name"));
        $("#psm_category_slug").val(row.data("slug"));
        $("#ps_status").val(row.data("status"));
        $("#psm_parent_category").val(row.data("sub"));
        $("#psm_category_description").val(row.data("description"));
        
        $("#Catbtn").text(catbtn);
        $("#cCatbtn").show();
    });

    // $(document).on("input", "#psm_category_name", function() {
    //     let value = $(this).val().trim();
    //     if (value !== "") {
    //         $("#psmResetBtn").show();
    //     } else {
    //         $("#psmResetBtn").hide();
    //     }
    // });

    

    $(document).on('click', '#cCatbtn', function() {
        const catbtn = 'Add';
        $("#Catbtn").text(catbtn);
        $("#cCatbtn").hide();
        $("#psmCategoriesForm")[0].reset();
       
    });

    // ✅ Delete Category (Single)
    $(document).on("click", ".psmDeleteCategory", function() {
        const tr = $(this).closest('tr[data-row="category"]');
        const id = tr.data("id");
        $.ajax({
            url: "functions.php",
            type: "POST",
            dataType: "json",
            data: { action: "delete_category", id: id },
            success: function(response) {
                showMessage(response.status, response.message);
                if (response.status === "success") {
                tr.remove();
                $("#psmCategorySelectAll").prop("checked", false);
                }
            }
        });

    });

    // ✅ Bulk Delete Categories
    $("#psmCategoriesBulkDelete").on("click", function() {
        const ids = $("#categorieslist .psmCategoryCheckbox:checked").map(function() {
        return $(this).closest("tr").data("id");
        }).get();

        if (ids.length === 0) {
        showConfirm("Please select at least one category to delete.", function(){});
        return;
        }

        $.ajax({
            url: "functions.php",
            type: "POST",
            dataType: "json",
            data: { action: "bulk_delete_categories", ids: ids },
            success: function(resp) {
                showMessage(resp.status, resp.message);
                if (resp.status === "success") {
                ids.forEach(id => $(`#categorieslist tr[data-id="${id}"]`).remove());
                $("#psmCategorySelectAll").prop("checked", false);
                }
            }
        });


    });

    // ✅ Master checkbox
    $(document).on("change", "#psmCategorySelectAll", function() {
        $("#categorieslist .psmCategoryCheckbox").prop("checked", $(this).is(":checked"));
    });

    $(document).on("change", ".psmCategoryCheckbox", function() {
        const all = $("#categorieslist .psmCategoryCheckbox").length;
        const checked = $("#categorieslist .psmCategoryCheckbox:checked").length;
        $("#psmCategorySelectAll").prop("checked", all > 0 && all === checked);
    });
    }







    // ===================================================================
    // SALES MANAGEMENT
    // ===================================================================
    // if ($("#Invoicelist").length) {

    //     loadInvoices();

    //     function loadInvoices() {
    //         $.ajax({
    //             url: "functions.php",
    //             type: "POST",
    //             data: { action: "get_all_invoices" },
    //             dataType: "json",
    //             success: function(resp) {
    //                 if (resp.status === "success") {
    //                     const rows = resp.data.map(inv => {
    //                         // Format box display with bonus
    //                         const boxDisplay = inv.bonus_box > 0 ? 
    //                             `${inv.box}+${inv.bonus_box}` : 
    //                             inv.box;
                            
    //                         return `
    //                         <tr data-row="invoice"
    //                             data-id="${inv.id}"
    //                             data-invoice_no="${inv.invoice_no || ''}"
    //                             data-pid="${inv.pid || ''}"
    //                             data-box="${inv.box || ''}"
    //                             data-bonus_box="${inv.bonus_box || ''}"
    //                             data-total_amount="${inv.total_amount || ''}"
    //                             data-discount="${inv.discount || ''}"
    //                             data-paid_amount="${inv.paid_amount || ''}"
    //                             data-due_amount="${inv.due_amount || ''}"
    //                             data-created_at="${inv.created_at || ''}">
                            
    //                         <td>${inv.invoice_no}</td>
    //                         <td>${inv.customer_name}</td>
    //                         <td>${inv.customer_phone}</td>
    //                         <td>${boxDisplay}</td>
    //                         <td>${parseFloat(inv.total_amount).toFixed(2)}</td>
    //                         <td>${parseFloat(inv.due_amount).toFixed(2)}</td>
    //                         <td>${inv.created_at}</td>
                            
    //                         </tr>
    //                     `}).join("");

    //                     $("#Invoicelist tbody").html(rows);
    //                     // if ($("#Invoicelist thead tr th").first().find("#psmInvoiceSelectAll").length === 0) {
    //                     //     $("#Invoicelist thead tr").prepend('<th><input type="checkbox" id="psmInvoiceSelectAll"></th>');
    //                     // }
    //                 }
    //             }
    //         });
    //     }

    //     // Generate random invoice number (5 characters)
    //     function generateInvoiceNo() {
    //         const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
    //         let result = '';
    //         for (let i = 0; i < 5; i++) {
    //             result += chars.charAt(Math.floor(Math.random() * chars.length));
    //         }
    //         return result;
    //     }

    //     // Set random invoice number on modal open for new invoices
    //     $('#addInvoiceModal').on('show.bs.modal', function () {
    //         if ($("#psm_Invoice_id").val() == "0") {
    //             $('#invoice_no').val(generateInvoiceNo());
    //         }
    //     });

    //     // Live calculation function
    //     function calculateInvoice() {
    //         const customerId = $('#psm_customer_id').val();
    //         const customerText = $('#psm_customer_id option:selected').text();
    //         const customerName = customerText ? customerText.split(' (')[0] : '';
    //         const box = parseInt($('#total_box').val()) || 0;
    //         const bonusBox = parseInt($('#psm_bonus_box').val()) || 0;
    //         const totalAmount = parseFloat($('#total_amount').val()) || 0;
    //         const discount = parseFloat($('#discount').val()) || 0;
    //         const paidAmount = parseFloat($('#paid_amount').val()) || 0;
            
    //         // Calculate discounted amount and due
    //         const discountedAmount = totalAmount - (totalAmount * discount / 100);
    //         const dueAmount = discountedAmount - paidAmount;
            
    //         // Update due amount hidden field
    //         $('#due_amount').val(dueAmount.toFixed(2));
            
    //         // Format box display with bonus
    //         const boxDisplay = bonusBox > 0 ? `${box}+${bonusBox}` : box;
            
    //         // Update the summary table
    //         let summaryHtml = '';
    //         if (customerId && totalAmount > 0) {
    //             summaryHtml = `
    //                 <tr>
    //                     <td><strong>${customerName}</strong></td>
    //                     <td>${boxDisplay}</td>
    //                     <td>${discountedAmount.toFixed(2)}</td>
    //                     <td>${dueAmount.toFixed(2)}</td>
    //                 </tr>
    //             `;
    //         } else {
    //             summaryHtml = `
    //                 <tr>
    //                     <td colspan="4" class="text-center text-muted">Select customer and enter amount</td>
    //                 </tr>
    //             `;
    //         }
            
    //         $("#InvoiceTB tbody").html(summaryHtml);
    //     }

    //     // Trigger calculation on all input changes
    //     $('#psm_customer_id, #total_amount, #discount, #paid_amount, #total_box, #psm_bonus_box').on('change input', function() {
    //         calculateInvoice();
    //     });

    //     // Search functionality
    //     $('#psmInvoiceSearch').on('input change', function () {
    //         const keyword = $('#psmInvoiceSearch').val().toLowerCase();
        
    //         $('tbody tr[data-row="invoice"]').each(function () {
    //             const rowText = $(this).text().toLowerCase();
    //             $(this).toggle(rowText.indexOf(keyword) !== -1);
    //         });
    //     });

    //     // Add or Update Invoice
    //     $("#psmInvoiceForm").on("submit", function(e) {
    //         e.preventDefault();
            
    //         // Validate form
    //         if (!$('#psm_customer_id').val()) {
    //             showMessage('error', 'Please select a customer');
    //             return;
    //         }
    //         if (!$('#total_amount').val() || parseFloat($('#total_amount').val()) <= 0) {
    //             showMessage('error', 'Please enter valid total amount');
    //             return;
    //         }
            
    //         // Calculate final due amount before submit
    //         calculateInvoice();
            
    //         $.ajax({
    //             url: "functions.php",
    //             type: "POST",
    //             dataType: "json",
    //             data: {
    //                 action: "save_invoice",
    //                 id: $("#psm_Invoice_id").val(),
    //                 pid: $("#psm_customer_id").val(),
    //                 invoice_no: $("#invoice_no").val(),
    //                 box: $("#total_box").val(),
    //                 bonus_box: $("#psm_bonus_box").val() || 0,
    //                 total_amount: $("#total_amount").val(),
    //                 discount: $("#discount").val() || 0,
    //                 paid_amount: $("#paid_amount").val() || 0,
    //                 due_amount: $("#due_amount").val()
    //             },
    //             success: function(response) {
    //                 showMessage(response.status, response.message);
    //                 if (response.status === "success") {
    //                     $("#psmInvoiceForm")[0].reset();
    //                     $("#psm_Invoice_id").val("0");
    //                     $("#due_amount").val("");
    //                     $("#psm_bonus_box").val(""); // Reset bonus box
    //                     $("#InvoiceTB tbody").html('<tr><td colspan="4" class="text-center text-muted">Select customer and enter amount</td></tr>');
    //                     loadInvoices();
    //                     $('#addInvoiceModal').modal('hide');
    //                 }
    //             },
    //             error: function() {
    //                 showMessage('error', 'An error occurred. Please try again.');
    //             }
    //         });
    //     });

    //     // Edit Invoice
    //     $(document).on("click", ".psmEditInvoice", function() {
    //         const row = $(this).closest("tr");
            
    //         $("#psm_Invoice_id").val(row.data("id"));
    //         $("#invoice_no").val(row.data("invoice_no"));
    //         $("#psm_customer_id").val(row.data("pid"));
    //         $("#total_box").val(row.data("box"));
    //         $("#psm_bonus_box").val(row.data("bonus_box"));
    //         $("#total_amount").val(row.data("total_amount"));
    //         $("#discount").val(row.data("discount"));
    //         $("#paid_amount").val(row.data("paid_amount"));
    //         $("#due_amount").val(row.data("due_amount"));
            
    //         $(".modal-title").text("Edit Invoice");
    //         calculateInvoice(); // Update summary table
    //         $('#addInvoiceModal').modal('show');
    //     });

    //     // Delete Invoice (Single)
    //     $(document).on("click", ".psmDeleteInvoice", function() {
    //         if(!confirm('Are you sure you want to delete this invoice?')) return;
            
    //         const tr = $(this).closest('tr[data-row="invoice"]');
    //         const id = tr.data("id");
            
    //         $.ajax({
    //             url: "functions.php",
    //             type: "POST",
    //             dataType: "json",
    //             data: { action: "delete_invoice", id: id },
    //             success: function(response) {
    //                 showMessage(response.status, response.message);
    //                 if (response.status === "success") {
    //                     tr.remove();
    //                     $("#psmInvoiceSelectAll").prop("checked", false);
    //                     loadInvoices(); // Reload to ensure data consistency
    //                 }
    //             }
    //         });
    //     });

    //     // Bulk Delete Invoices
    //     $("#psmInvoiceBulkDelete").on("click", function() {
    //         const ids = $("#Invoicelist .psmInvoiceCheckbox:checked").map(function() {
    //             return $(this).closest("tr").data("id");
    //         }).get();

    //         if (ids.length === 0) {
    //             showMessage('error', 'Please select at least one invoice to delete.');
    //             return;
    //         }

    //         if(!confirm(`Are you sure you want to delete ${ids.length} invoice(s)?`)) return;

    //         $.ajax({
    //             url: "functions.php",
    //             type: "POST",
    //             dataType: "json",
    //             data: { action: "bulk_delete_invoices", ids: ids },
    //             success: function(resp) {
    //                 showMessage(resp.status, resp.message);
    //                 if (resp.status === "success") {
    //                     ids.forEach(id => $(`#Invoicelist tr[data-id="${id}"]`).remove());
    //                     $("#psmInvoiceSelectAll").prop("checked", false);
    //                     loadInvoices(); // Reload to ensure data consistency
    //                 }
    //             }
    //         });
    //     });

    //     // Master checkbox
    //     $(document).on("change", "#psmInvoiceSelectAll", function() {
    //         $("#Invoicelist .psmInvoiceCheckbox").prop("checked", $(this).is(":checked"));
    //     });

    //     $(document).on("change", ".psmInvoiceCheckbox", function() {
    //         const all = $("#Invoicelist .psmInvoiceCheckbox").length;
    //         const checked = $("#Invoicelist .psmInvoiceCheckbox:checked").length;
    //         $("#psmInvoiceSelectAll").prop("checked", all > 0 && all === checked);
    //     });

    //     // Reset modal on close
    //     $('#addInvoiceModal').on('hidden.bs.modal', function () {
    //         $("#psmInvoiceForm")[0].reset();
    //         $("#psm_Invoice_id").val("0");
    //         $("#due_amount").val("");
    //         $("#psm_bonus_box").val("");
    //         $("#InvoiceTB tbody").html('<tr><td colspan="4" class="text-center text-muted">Select customer and enter amount</td></tr>');
    //         $(".modal-title").text("Add Invoice");
    //     });
    // }

if ($("#Invoicelist").length) {
    let selectedProducts = [];
    let productPrices = {};

    loadInvoices();
    loadProducts();

    function loadInvoices() {
        $.ajax({
            url: "functions.php",
            type: "POST",
            data: { action: "get_all_invoices" },
            dataType: "json",
            success: function(resp) {
                if (resp.status === "success") {
                    const rows = resp.data.map(inv => {
                        const boxDisplay = inv.bonus_box > 0 ? 
                            `${inv.box}+${inv.bonus_box}` : 
                            inv.box;
                        
                        // Create products tooltip
                        const productsList = inv.products ? inv.products.map(p => 
                            `${p.product_name}: ${p.box_quantity} boxes`
                        ).join('\n') : 'No products';
                        
                        return `
                        <tr data-row="invoice"
                            data-id="${inv.id}"
                            data-invoice_no="${inv.invoice_no || ''}"
                            data-pid="${inv.pid || ''}"
                            data-box="${inv.box || 0}"
                            data-bonus_box="${inv.bonus_box || 0}"
                            data-total_amount="${inv.total_amount || 0}"
                            data-discount="${inv.discount || 0}"
                            data-paid_amount="${inv.paid_amount || 0}"
                            data-due_amount="${inv.due_amount || 0}"
                            data-created_at="${inv.created_at || ''}"
                            data-products='${JSON.stringify(inv.products || [])}'>
                        
                        <td>${inv.invoice_no}</td>
                        <td>${inv.customer_name || 'N/A'}</td>
                        <td>${inv.customer_phone || 'N/A'}</td>
                        <td title="${productsList}">${boxDisplay}</td>
                        <td>৳${parseFloat(inv.total_amount || 0).toFixed(2)}</td>
                        <td>৳${parseFloat(inv.due_amount || 0).toFixed(2)}</td>
                        <td>${inv.created_at}</td>
                        <td>
                            <button class="btn btn-sm btn-info psmEditInvoice" title="Edit">
                                <i class="fa fa-edit"></i>
                            </button>
                            <button class="btn btn-sm btn-danger psmDeleteInvoice" title="Delete">
                                <i class="fa fa-trash"></i>
                            </button>
                        </td>
                        </tr>
                    `}).join("");

                    $("#Invoicelist tbody").html(rows);
                }
            }
        });
    }

    function loadProducts() {
        $.ajax({
            url: "functions.php",
            type: "POST",
            data: { action: "get_all_products" },
            dataType: "json",
            success: function(resp) {
                if (resp.status === "success") {
                    // Store product sale prices
                    resp.data.forEach(product => {
                        productPrices[product.id] = parseFloat(product.sale_price) || 0;
                    });
                    
                    let options = '';
                    resp.data.forEach(product => {
                        options += `<div class="product-item" data-id="${product.id}" data-name="${product.name}" data-box="${product.unit || 0}" data-price="${product.sale_price || 0}">
                            <div class="form-check">
                                <input class="form-check-input product-checkbox" type="checkbox" value="${product.id}" id="product_${product.id}">
                                <label class="form-check-label" for="product_${product.id}">
                                    ${product.name} 
                                    <span class="badge bg-info">Stock: ${product.unit || 0} boxes</span>
                                    <span class="badge bg-success">৳${parseFloat(product.sale_price || 0).toFixed(2)}/box</span>
                                </label>
                            </div>
                        </div>`;
                    });
                    $("#productList").html(options);
                }
            }
        });
    }

    // Product checkbox change handler
    $(document).on("change", ".product-checkbox", function() {
        const productItem = $(this).closest('.product-item');
        const productId = productItem.data('id');
        const productName = productItem.data('name');
        const boxQuantity = parseInt(productItem.data('box')) || 0;
        const salePrice = parseFloat(productItem.data('price')) || 0;

        if ($(this).is(':checked')) {
            // Add product if not already selected
            if (!selectedProducts.find(p => p.product_id == productId)) {
                selectedProducts.push({
                    product_id: productId,
                    product_name: productName,
                    unit: boxQuantity,
                    sale_price: salePrice
                });
            }
        } else {
            // Remove product
            selectedProducts = selectedProducts.filter(p => p.product_id != productId);
        }
        
        renderProductInputs();
        updateTotalBoxes();
        calculateTotalAmount();
    });

    // Product search
    $("#productSearch").on("input", function() {
        const searchTerm = $(this).val().toLowerCase();
        $(".product-item").each(function() {
            const productName = $(this).data('name').toLowerCase();
            $(this).toggle(productName.includes(searchTerm));
        });
    });

    // Render product input fields
    function renderProductInputs() {
        if (selectedProducts.length === 0) {
            $("#productInputs").html(`
                <div class="text-center text-muted py-4">
                    <i class="fa fa-box-open fa-3x mb-3"></i>
                    <p>No products selected. Check products from the list above.</p>
                </div>
            `);
            return;
        }

        let html = '<div class="row">';
        selectedProducts.forEach((product, index) => {
            const boxQty = parseInt(product.box_quantity) || 0;
            const price = parseFloat(product.sale_price) || 0;
            const subtotal = boxQty * price;
            
            html += `
                <div class="col-md-6 mb-3">
                    <div class="card product-card">
                        <div class="card-body">
                            <div class="d-flex justify-content-between align-items-center mb-2">
                                <h6 class="card-title mb-0">${product.product_name}</h6>
                                <button class="btn btn-sm btn-outline-danger remove-product" data-index="${index}">
                                    <i class="fa fa-times"></i>
                                </button>
                            </div>
                            <div class="mb-2">
                                <small class="text-muted">Price: ৳${price.toFixed(2)}/box</small>
                            </div>
                            <div class="input-group">
                                <span class="input-group-text"><i class="fa fa-cubes"></i></span>
                                <input type="number" class="form-control product-box-input" 
                                       data-index="${index}"
                                       value="${boxQty}" >
                                <span class="input-group-text">boxes</span>
                            </div>
                            <div class="mt-2 text-end">
                                <small class="fw-bold">Subtotal: ৳${subtotal.toFixed(2)}</small>
                            </div>
                        </div>
                    </div>
                </div>
            `;
        });
        html += '</div>';
        
        $("#productInputs").html(html);
        
        // Sync checkboxes
        $(".product-checkbox").prop('checked', false);
        selectedProducts.forEach(p => {
            $(`#product_${p.product_id}`).prop('checked', true);
        });
    }

    // Update box quantity
    $(document).on("input", ".product-box-input", function() {
        const index = $(this).data("index");
        const value = parseInt($(this).val()) || 0;
        
        if (selectedProducts[index]) {
            selectedProducts[index].box_quantity = value;
            
            // Update subtotal display
            const price = parseFloat(selectedProducts[index].sale_price) || 0;
            const subtotal = value * price;
            $(this).closest('.card-body').find('.fw-bold').html(`Subtotal: ৳${subtotal.toFixed(2)}`);
            
            updateTotalBoxes();
            calculateTotalAmount();
        }
    });

    // Remove product
    $(document).on("click", ".remove-product", function() {
        const index = $(this).data("index");
        const productId = selectedProducts[index].product_id;
        
        // Uncheck checkbox
        $(`#product_${productId}`).prop('checked', false);
        
        // Remove from array
        selectedProducts.splice(index, 1);
        
        renderProductInputs();
        updateTotalBoxes();
        calculateTotalAmount();
    });

    // Calculate total boxes
    function updateTotalBoxes() {
        const totalBoxes = selectedProducts.reduce((sum, product) => {
            return sum + (parseInt(product.box_quantity) || 0);
        }, 0);
        $("#total_box").val(totalBoxes);
    }

    // Calculate total amount from products
    function calculateTotalAmount() {
        const total = selectedProducts.reduce((sum, product) => {
            const boxQty = parseInt(product.box_quantity) || 0;
            const price = parseFloat(product.sale_price) || 0;
            return sum + (boxQty * price);
        }, 0);
        
        $("#total_amount").val(total.toFixed(2));
        calculateInvoice(); // Recalculate due amount
    }

    // Generate random invoice number
    function generateInvoiceNo() {
        const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
        let result = '';
        for (let i = 0; i < 5; i++) {
            result += chars.charAt(Math.floor(Math.random() * chars.length));
        }
        return result;
    }

    // Set random invoice number on modal open for new invoices
    $('#addInvoiceModal').on('show.bs.modal', function () {
        if ($("#psm_Invoice_id").val() == "0") {
            $('#invoice_no').val(generateInvoiceNo());
            selectedProducts = [];
            renderProductInputs();
            $(".product-checkbox").prop('checked', false);
            $("#total_box").val('0');
            $("#total_amount").val('0');
            $("#discount").val('0');
            $("#paid_amount").val('0');
            $("#psm_bonus_box").val('0');
            calculateInvoice();
        }
    });

    // Live calculation function
    function calculateInvoice() {
        const customerId = $('#psm_customer_id').val();
        const customerText = $('#psm_customer_id option:selected').text();
        const customerName = customerText ? customerText.split(' (')[0] : 'N/A';
        const totalBoxes = parseInt($('#total_box').val()) || 0;
        const bonusBox = parseInt($('#psm_bonus_box').val()) || 0;
        const totalAmount = parseFloat($('#total_amount').val()) || 0;
        const discount = parseFloat($('#discount').val()) || 0;
        const paidAmount = parseFloat($('#paid_amount').val()) || 0;
        
        // Calculate discounted amount and due
        const discountedAmount = totalAmount - (totalAmount * discount / 100);
        const dueAmount = discountedAmount - paidAmount;
        
        // Update due amount hidden field
        $('#due_amount').val(dueAmount.toFixed(2));
        
        // Format box display with bonus
        const boxDisplay = bonusBox > 0 ? `${totalBoxes}+${bonusBox}` : totalBoxes;
        
        // Update the summary table
        let summaryHtml = '';
        if (totalAmount > 0) {
            summaryHtml = `
                <tr>
                    <td><strong>${customerName}</strong></td>
                    <td>${boxDisplay}</td>
                    <td>৳${discountedAmount.toFixed(2)}</td>
                    <td>৳${dueAmount.toFixed(2)}</td>
                </tr>
            `;
        } else {
            summaryHtml = `
                <tr>
                    <td colspan="4" class="text-center text-muted">Select products to calculate amount</td>
                </tr>
            `;
        }
        
        $("#InvoiceTB tbody").html(summaryHtml);
    }

    // Trigger calculation on all input changes
    $('#psm_customer_id, #discount, #paid_amount, #psm_bonus_box').on('change input', function() {
        calculateInvoice();
    });

    // Search functionality
    $('#psmInvoiceSearch').on('input change', function () {
        const keyword = $('#psmInvoiceSearch').val().toLowerCase();
        $('tbody tr[data-row="invoice"]').each(function () {
            const rowText = $(this).text().toLowerCase();
            $(this).toggle(rowText.indexOf(keyword) !== -1);
        });
    });

    // Save Invoice
    $("#psmInvoiceForm").on("submit", function(e) {
        e.preventDefault();
        
        // Validate form
        if (selectedProducts.length === 0) {
            showMessage('error', 'Please select at least one product');
            return;
        }
        
        if (!$('#total_amount').val() || parseFloat($('#total_amount').val()) <= 0) {
            showMessage('error', 'Invalid total amount');
            return;
        }
        
        calculateInvoice();
        
        // Prepare products data
        const productsData = selectedProducts.map(p => ({
            product_id: p.product_id,
            product_name: p.product_name,
            box_quantity: p.box_quantity
        }));
        
        $.ajax({
            url: "functions.php",
            type: "POST",
            dataType: "json",
            data: {
                action: "save_invoice",
                id: $("#psm_Invoice_id").val(),
                pid: $("#psm_customer_id").val() || '',
                invoice_no: $("#invoice_no").val(),
                box: $("#total_box").val(),
                bonus_box: $("#psm_bonus_box").val() || 0,
                products: JSON.stringify(productsData),
                total_amount: $("#total_amount").val(),
                discount: $("#discount").val() || 0,
                paid_amount: $("#paid_amount").val() || 0,
                due_amount: $("#due_amount").val()
            },
            success: function(response) {
                showMessage(response.status, response.message);
                if (response.status === "success") {
                    resetForm();
                    loadInvoices();
                    $('#addInvoiceModal').modal('hide');
                }
            },
            error: function() {
                showMessage('error', 'An error occurred. Please try again.');
            }
        });
    });

    // Edit Invoice
    $(document).on("click", ".psmEditInvoice", function() {
        const row = $(this).closest("tr");
        const productsData = row.data("products") || [];
        
        $("#psm_Invoice_id").val(row.data("id"));
        $("#invoice_no").val(row.data("invoice_no"));
        $("#psm_customer_id").val(row.data("pid"));
        $("#total_box").val(row.data("box") || 0);
        $("#psm_bonus_box").val(row.data("bonus_box") || 0);
        $("#total_amount").val(row.data("total_amount") || 0);
        $("#discount").val(row.data("discount") || 0);
        $("#paid_amount").val(row.data("paid_amount") || 0);
        $("#due_amount").val(row.data("due_amount") || 0);
        
        // Load products with sale prices
        selectedProducts = productsData.map(p => ({
            product_id: p.product_id,
            product_name: p.product_name,
            box_quantity: parseInt(p.box_quantity) || 0,
            sale_price: productPrices[p.product_id] || 0
        }));
        
        renderProductInputs();
        $(".modal-title").text("Edit Invoice");
        calculateInvoice();
        $('#addInvoiceModal').modal('show');
    });

    // Delete Invoice
    $(document).on("click", ".psmDeleteInvoice", function() {
        if(!confirm('Are you sure you want to delete this invoice?')) return;
        
        const tr = $(this).closest('tr[data-row="invoice"]');
        const id = tr.data("id");
        
        $.ajax({
            url: "functions.php",
            type: "POST",
            dataType: "json",
            data: { action: "delete_invoice", id: id },
            success: function(response) {
                showMessage(response.status, response.message);
                if (response.status === "success") {
                    tr.remove();
                    loadInvoices();
                }
            }
        });
    });

    // Reset function
    function resetForm() {
        $("#psmInvoiceForm")[0].reset();
        $("#psm_Invoice_id").val("0");
        $("#due_amount").val("");
        $("#total_box").val("0");
        $("#psm_bonus_box").val("0");
        $("#total_amount").val("0");
        $("#discount").val("0");
        $("#paid_amount").val("0");
        selectedProducts = [];
        renderProductInputs();
        $(".product-checkbox").prop('checked', false);
        $("#InvoiceTB tbody").html('<tr><td colspan="4" class="text-center text-muted">Select products to calculate amount</td></tr>');
        $(".modal-title").text("Add Invoice");
    }

    // Reset modal on close
    $('#addInvoiceModal').on('hidden.bs.modal', function () {
        resetForm();
    });
}

// Show message function
function showMessage(type, message) {
    const alertClass = type === 'success' ? 'alert-success' : 'alert-danger';
    const html = `<div class="alert ${alertClass} alert-dismissible fade show" role="alert">${message}<button type="button" class="btn-close" data-bs-dismiss="alert"></button></div>`;
    $(".messages").html(html);
    setTimeout(() => $(".alert").alert('close'), 3000);
}



});
