frappe.ui.form.on('VAT allocation', {
    refresh: function(frm) {
        // Add button for filling Payment Entries with filters
        if (!frm.is_new()) {
            frm.add_custom_button(__('Fill Payment Entries'), function() {
                show_payment_entry_filters(frm);
            });
            
            // Add button for filling Sales Invoice Items
            frm.add_custom_button(__('Fill Sales Invoice Items'), function() {
                show_sales_invoice_filters(frm);
            });

            // Add button for filling Opening Entries
            frm.add_custom_button(__('Fill Opening Entries'), function() {
                show_opening_entry_filters(frm);
            });
        }
        
        // Setup filter for Journal Entry
        setup_journal_entry_query(frm);

        // Setup filter for Payment Entry
        setup_payment_entry_query(frm);

        // Tax Articles: grid labels + click-to-view popup
        setup_tax_articles_viewer(frm);

    }
});

// Function to show filter dialog for Payment Entries
function show_payment_entry_filters(frm) {
    // Check that year and month are selected
    if (!frm.doc.year || !frm.doc.month) {
        frappe.msgprint(__('Please select Year and Month first'));
        return;
    }
    
    // Create dialog with filters
    let dialog = new frappe.ui.Dialog({
        title: __('Payment Entry Filters'),
        fields: [
            {
                fieldname: 'customers_section',
                fieldtype: 'Section Break',
                label: __('Select Customers (Optional)')
            },
            {
                fieldname: 'customers',
                fieldtype: 'Table',
                label: __('Customers'),
                description: __('Leave empty to get all customers'),
                fields: [
                    {
                        fieldname: 'customer',
                        fieldtype: 'Link',
                        label: __('Customer'),
                        options: 'Customer',
                        in_list_view: 1
                    }
                ]
            },
            {
                fieldname: 'amount_section',
                fieldtype: 'Section Break',
                label: __('Amount Range (Optional)')
            },
            {
                fieldname: 'min_amount',
                fieldtype: 'Currency',
                label: __('Minimum Amount'),
                description: __('Only payments >= this amount')
            },
            {
                fieldname: 'column_break_1',
                fieldtype: 'Column Break'
            },
            {
                fieldname: 'max_amount',
                fieldtype: 'Currency',
                label: __('Maximum Amount'),
                description: __('Only payments <= this amount')
            }
        ],
        primary_action_label: __('Fill Table'),
        primary_action: function(values) {
            fill_payment_entries(frm, values);
            dialog.hide();
        }
    });
    
    dialog.show();
    
    // Hide scrollbar
    setTimeout(function() {
        dialog.$wrapper.find('.frappe-control[data-fieldname="customers"] .grid-scroll-bar').css({
            'visibility': 'hidden',
            'height': '0px'
        });
    }, 100);
}

// Function to show filter dialog for Sales Invoice Items
function show_sales_invoice_filters(frm) {
    // Check that year and month are selected
    if (!frm.doc.year || !frm.doc.month) {
        frappe.msgprint(__('Please select Year and Month first'));
        return;
    }
    
    // Create dialog with filters
    let dialog = new frappe.ui.Dialog({
        title: __('Sales Invoice Items Filters'),
        fields: [
            {
                fieldname: 'customers_section',
                fieldtype: 'Section Break',
                label: __('Select Customers (Optional)')
            },
            {
                fieldname: 'customers',
                fieldtype: 'Table',
                label: __('Customers'),
                description: __('Leave empty to get all customers'),
                fields: [
                    {
                        fieldname: 'customer',
                        fieldtype: 'Link',
                        label: __('Customer'),
                        options: 'Customer',
                        in_list_view: 1
                    }
                ]
            },
            {
                fieldname: 'amount_section',
                fieldtype: 'Section Break',
                label: __('Amount Range (Optional)')
            },
            {
                fieldname: 'min_amount',
                fieldtype: 'Currency',
                label: __('Minimum Amount'),
                description: __('Only grouped amounts >= this amount')
            },
            {
                fieldname: 'column_break_1',
                fieldtype: 'Column Break'
            },
            {
                fieldname: 'max_amount',
                fieldtype: 'Currency',
                label: __('Maximum Amount'),
                description: __('Only grouped amounts <= this amount')
            }
        ],
        primary_action_label: __('Fill Table'),
        primary_action: function(values) {
            fill_sales_invoice_items(frm, values);
            dialog.hide();
        }
    });
    
    dialog.show();
    
    // Hide scrollbar
    setTimeout(function() {
        dialog.$wrapper.find('.frappe-control[data-fieldname="customers"] .grid-scroll-bar').css({
            'visibility': 'hidden',
            'height': '0px'
        });
    }, 100);
}

// Function to fill Payment Entries with filters - UPDATED to include previous months
function fill_payment_entries(frm, filters) {
    // Call server method to get both current and previous payment entries
    frappe.call({
        method: 'taxes_az.taxes_az.doctype.vat_allocation.vat_allocation.get_payment_entries_with_previous',
        args: {
            year: frm.doc.year,
            month: frm.doc.month,
            customers: filters.customers ? JSON.stringify(filters.customers) : null,
            min_amount: filters.min_amount || null,
            max_amount: filters.max_amount || null
        },
        callback: function(r) {
            if (r.message && r.message.length > 0) {
                // Clear existing table
                frm.clear_table('payment_entry_table');
                
                // Add new rows
                r.message.forEach(function(payment) {
                    let row = frm.add_child('payment_entry_table');
                    row.customer = payment.customer;
                    row.payment_entry = payment.payment_entry;
                    row.payment_entry_amount = payment.payment_entry_amount;
                    row.vat_journal_entry = payment.vat_journal_entry || '';
                    row.vat_amount = payment.vat_amount || 0;
                    row.vat_allocated_amount = payment.vat_allocated_amount || 0;
                    row.vat_free_amount = payment.vat_free_amount || payment.payment_entry_amount;
                    row.unallocated_amount = payment.unallocated_amount || 0;
                    row.allocated_amount = payment.allocated_amount || 0;
                    row.vat_allocated_allocated = payment.vat_allocated_allocated || 0;
                    row.vat_free_allocated = payment.vat_free_allocated || 0;
                });
                
                frm.refresh_field('payment_entry_table');
                frappe.msgprint(__('Payment Entries loaded successfully: {0} records', [r.message.length]));
            } else {
                frappe.msgprint(__('No Payment Entries found for selected period'));
            }
        }
    });
}

// Setup query filter for Payment Entry - UPDATED
function setup_payment_entry_query(frm) {
    frm.fields_dict.payment_entry_table.grid.get_field('payment_entry').get_query = function(doc, cdt, cdn) {
        return {
            query: 'taxes_az.taxes_az.doctype.vat_allocation.vat_allocation.get_payment_entry_query',
            filters: {
                year: doc.year,
                month: doc.month
            }
        };
    };
}

// ---- Tax Articles helpers (stored as a JSON list of Tax Article names) ----

// Parse the stored tax_articles value into an array of names.
function parse_tax_articles_value(value) {
    if (!value) return [];
    if (Array.isArray(value)) return value.filter(Boolean);
    if (typeof value === 'string') {
        try {
            let parsed = JSON.parse(value);
            if (Array.isArray(parsed)) return parsed.filter(Boolean);
            return parsed ? [parsed] : [];
        } catch (e) {
            return [value];
        }
    }
    return [String(value)];
}

// Comma-separated label (used inside the allocation dialog).
function format_tax_articles(value) {
    let articles = parse_tax_articles_value(value);
    return articles.length ? frappe.utils.escape_html(articles.join(', ')) : '-';
}

// Short label shown in the grid cell, e.g. "3 articles" (translatable).
function format_tax_articles_count(value) {
    let n = parse_tax_articles_value(value).length;
    return n ? __('{0} articles', [n]) : '';
}

// Read-only popup showing the articles as pills (same look as the Sales Invoice
// "Tax Articles" control). Rendered as plain styled chips so it does not depend on
// the Sales Invoice Tax Article meta being loaded on this form, and cannot be edited.
function show_tax_articles_view(value) {
    let items = parse_tax_articles_value(value);
    let pills = items.length
        ? items.map(function(a) {
            return '<span class="tax-article-pill">' + frappe.utils.escape_html(a) + '</span>';
          }).join('')
        : '<div class="text-muted">' + __('No tax articles') + '</div>';
    let d = new frappe.ui.Dialog({
        title: __('Tax Articles'),
        fields: [{
            fieldtype: 'HTML',
            fieldname: 'body',
            options: '<div class="tax-article-pills">' + pills + '</div>'
        }],
        primary_action_label: __('Close'),
        primary_action() { d.hide(); }
    });
    d.show();
}

// Recompute grid labels for loaded rows and bind the click-to-view handler.
function setup_tax_articles_viewer(frm) {
    ['sales_invoice_table', 'sales_invoice_previous_table'].forEach(function(tbl) {
        (frm.doc[tbl] || []).forEach(function(row) {
            let label = format_tax_articles_count(row.tax_articles);
            if (row.tax_articles_display !== label) {
                row.tax_articles_display = label; // direct set: cosmetic, must not dirty the form
            }
        });
        frm.refresh_field(tbl);
    });

    if (frm.__tax_articles_viewer_bound) return;
    frm.__tax_articles_viewer_bound = true;

    if (!document.getElementById('vat-tax-articles-style')) {
        let style = document.createElement('style');
        style.id = 'vat-tax-articles-style';
        style.textContent =
            '.grid-row [data-fieldname="tax_articles_display"]{cursor:pointer;}' +
            '.grid-row [data-fieldname="tax_articles_display"] input,' +
            '.grid-row [data-fieldname="tax_articles_display"] .like-disabled-input{pointer-events:none;}' +
            // read-only pill chips (same look as the SI Tax Articles control)
            '.tax-article-pills{display:flex;flex-wrap:wrap;gap:6px;padding:4px 0;}' +
            '.tax-article-pill{display:inline-block;background:var(--control-bg,#f4f5f6);' +
            'border:1px solid var(--border-color,#d1d8dd);border-radius:10px;' +
            'padding:4px 10px;font-size:12px;line-height:1.5;color:var(--text-color,#1f272e);}';
        document.head.appendChild(style);
    }

    $(document)
        .off('mousedown.vataa')
        .on('mousedown.vataa', '[data-fieldname="tax_articles_display"]', function(ev) {
            let grid_row = $(this).closest('.grid-row').data('grid_row');
            if (grid_row && grid_row.doc) {
                ev.stopPropagation();
                show_tax_articles_view(grid_row.doc.tax_articles);
            }
        });
}

// Function to fill Sales Invoice Items with filters - UPDATED to fill both tables
function fill_sales_invoice_items(frm, filters) {
    // Call both server methods - current month and previous months
    frappe.call({
        method: 'taxes_az.taxes_az.doctype.vat_allocation.vat_allocation.get_sales_invoice_items',
        args: {
            year: frm.doc.year,
            month: frm.doc.month,
            customers: filters.customers ? JSON.stringify(filters.customers) : null,
            min_amount: filters.min_amount || null,
            max_amount: filters.max_amount || null
        },
        callback: function(r) {
            if (r.message && r.message.length > 0) {
                // Clear existing table
                frm.clear_table('sales_invoice_table');
                
                // Add new rows
                r.message.forEach(function(item) {
                    let row = frm.add_child('sales_invoice_table');
                    row.customer = item.customer;
                    row.item_tax_template = item.item_tax_template;
                    row.tax_articles = item.tax_articles;
                    row.tax_articles_display = format_tax_articles_count(item.tax_articles);
                    row.amount = item.amount;
                    row.unallocated_amount = item.amount; // Default: all amount is unallocated
                });
                
                frm.refresh_field('sales_invoice_table');
                frappe.msgprint(__('Sales Invoice Items loaded successfully: {0} records', [r.message.length]));
            } else {
                frappe.msgprint(__('No Sales Invoice Items found for selected period'));
            }
            
            // Now load previous months items
            load_previous_months_items(frm, filters);
        }
    });
}

// Function to load previous months items
function load_previous_months_items(frm, filters) {
    frappe.call({
        method: 'taxes_az.taxes_az.doctype.vat_allocation.vat_allocation.get_sales_invoice_items_previous_months',
        args: {
            year: frm.doc.year,
            month: frm.doc.month,
            customers: filters.customers ? JSON.stringify(filters.customers) : null,
            min_amount: filters.min_amount || null,
            max_amount: filters.max_amount || null
        },
        callback: function(r) {
            // Clear existing table
            frm.clear_table('sales_invoice_previous_table');
            
            if (r.message && r.message.length > 0) {
                // Add new rows
                r.message.forEach(function(item) {
                    let row = frm.add_child('sales_invoice_previous_table');
                    row.customer = item.customer;
                    row.item_tax_template = item.item_tax_template;
                    row.tax_articles = item.tax_articles;
                    row.tax_articles_display = format_tax_articles_count(item.tax_articles);
                    row.amount = item.amount;
                    row.unallocated_amount = item.unallocated_amount;
                    row.allocated_amount = item.allocated_amount;
                });
                
                frm.refresh_field('sales_invoice_previous_table');
                frappe.show_alert({
                    message: __('Previous months items loaded: {0} records', [r.message.length]),
                    indicator: 'blue'
                });
            } else {
                frm.refresh_field('sales_invoice_previous_table');
                frappe.show_alert({
                    message: __('No unpaid items from previous months'),
                    indicator: 'blue'
                });
            }
        }
    });
}

// Function to show filter dialog for Opening Entries
function show_opening_entry_filters(frm) {
    if (!frm.doc.year || !frm.doc.month) {
        frappe.msgprint(__('Please select Year and Month first'));
        return;
    }

    let dialog = new frappe.ui.Dialog({
        title: __('Opening Entry Filters'),
        fields: [
            {
                fieldname: 'customers_section',
                fieldtype: 'Section Break',
                label: __('Select Customers (Optional)')
            },
            {
                fieldname: 'customers',
                fieldtype: 'Table',
                label: __('Customers'),
                description: __('Leave empty to get all customers'),
                fields: [
                    {
                        fieldname: 'customer',
                        fieldtype: 'Link',
                        label: __('Customer'),
                        options: 'Customer',
                        in_list_view: 1
                    }
                ]
            },
            {
                fieldname: 'amount_section',
                fieldtype: 'Section Break',
                label: __('Amount Range (Optional)')
            },
            {
                fieldname: 'min_amount',
                fieldtype: 'Currency',
                label: __('Minimum Amount'),
                description: __('Only grouped amounts >= this amount')
            },
            {
                fieldname: 'column_break_1',
                fieldtype: 'Column Break'
            },
            {
                fieldname: 'max_amount',
                fieldtype: 'Currency',
                label: __('Maximum Amount'),
                description: __('Only grouped amounts <= this amount')
            }
        ],
        primary_action_label: __('Fill Table'),
        primary_action: function(values) {
            fill_opening_entries(frm, values);
            dialog.hide();
        }
    });

    dialog.show();

    setTimeout(function() {
        dialog.$wrapper.find('.frappe-control[data-fieldname="customers"] .grid-scroll-bar').css({
            'visibility': 'hidden',
            'height': '0px'
        });
    }, 100);
}

// Function to fill Opening Entries table
function fill_opening_entries(frm, filters) {
    frappe.call({
        method: 'taxes_az.taxes_az.doctype.vat_allocation.vat_allocation.get_opening_entries',
        args: {
            year: frm.doc.year,
            month: frm.doc.month,
            customers: filters.customers ? JSON.stringify(filters.customers) : null,
            min_amount: filters.min_amount || null,
            max_amount: filters.max_amount || null
        },
        callback: function(r) {
            frm.clear_table('opening_entry_table');

            if (r.message && r.message.length > 0) {
                r.message.forEach(function(item) {
                    let row = frm.add_child('opening_entry_table');
                    row.customer = item.customer;
                    row.amount = item.amount;
                    row.unallocated_amount = item.amount;
                    row.allocated_amount = 0;
                });

                frm.refresh_field('opening_entry_table');
                frappe.msgprint(__('Opening Entries loaded successfully: {0} records', [r.message.length]));
            } else {
                frm.refresh_field('opening_entry_table');
                frappe.msgprint(__('No Opening Entries found for selected period'));
            }
        }
    });
}

// Setup query filter for Journal Entry
function setup_journal_entry_query(frm) {
    frm.fields_dict.payment_entry_table.grid.get_field('vat_journal_entry').get_query = function(doc, cdt, cdn) {
        let child = locals[cdt][cdn];
        
        return {
            query: 'taxes_az.taxes_az.doctype.vat_allocation.vat_allocation.get_journal_entry_query',
            filters: {
                customer: child.customer,
                year: doc.year,
                month: doc.month
            }
        };
    };
}

// Setup for VAT Journal Entry
frappe.ui.form.on('VAT allocation payment entry', {
    // При изменении Customer - очистить все поля и удалить связанные links
    customer: function(frm, cdt, cdn) {
        let row = locals[cdt][cdn];
        let old_row_name = row.name;
        
        // Очищаем все поля
        frappe.model.set_value(cdt, cdn, 'payment_entry', '');
        frappe.model.set_value(cdt, cdn, 'payment_entry_amount', 0);
        frappe.model.set_value(cdt, cdn, 'vat_journal_entry', '');
        frappe.model.set_value(cdt, cdn, 'vat_amount', 0);
        frappe.model.set_value(cdt, cdn, 'vat_allocated_amount', 0);
        frappe.model.set_value(cdt, cdn, 'vat_allocated_allocated', 0);
        frappe.model.set_value(cdt, cdn, 'vat_free_amount', 0);
        frappe.model.set_value(cdt, cdn, 'vat_free_allocated', 0);
        frappe.model.set_value(cdt, cdn, 'allocated_amount', 0);
        frappe.model.set_value(cdt, cdn, 'unallocated_amount', 0);
        
        // Удаляем все allocation links связанные с этой строкой
        frm.doc.allocation_links = (frm.doc.allocation_links || []).filter(function(link) {
            return link.payment_entry_row !== old_row_name;
        });
        
        frm.refresh_field('allocation_links');
        
        // Пересчитываем totals
        recalculate_totals_manually(frm);
        frm.refresh_field('payment_entry_table');
        frm.refresh_field('sales_invoice_table');
        frm.refresh_field('sales_invoice_previous_table');
        frm.refresh_field('opening_entry_table');
    },

    // При изменении Payment Entry - обновить суммы
    payment_entry: function(frm, cdt, cdn) {
        let row = locals[cdt][cdn];
        let old_row_name = row.name;
        
        // Всегда удаляем allocation links связанные с этой строкой при изменении/очистке Payment Entry
        frm.doc.allocation_links = (frm.doc.allocation_links || []).filter(function(link) {
            return link.payment_entry_row !== old_row_name;
        });
        
        frm.refresh_field('allocation_links');
        
        if (!row.payment_entry) {
            // Если Payment Entry очищен, обнуляем все поля
            frappe.model.set_value(cdt, cdn, 'payment_entry_amount', 0);
            frappe.model.set_value(cdt, cdn, 'vat_allocated_amount', 0);
            frappe.model.set_value(cdt, cdn, 'vat_free_amount', 0);
            frappe.model.set_value(cdt, cdn, 'allocated_amount', 0);
            frappe.model.set_value(cdt, cdn, 'unallocated_amount', 0);
            
            // Пересчитываем totals
            recalculate_totals_manually(frm);
            frm.refresh_field('payment_entry_table');
            frm.refresh_field('sales_invoice_table');
            frm.refresh_field('sales_invoice_previous_table');
            frm.refresh_field('opening_entry_table');

            return;
        }

        // Получаем данные из Payment Entry
        frappe.call({
            method: 'frappe.client.get_value',
            args: {
                doctype: 'Payment Entry',
                filters: { name: row.payment_entry },
                fieldname: ['paid_amount', 'party', 'docstatus']
            },
            callback: function(r) {
                if (r.message) {
                    // Проверяем что Payment Entry submitted
                    if (r.message.docstatus !== 1) {
                        frappe.msgprint(__('Warning: Selected Payment Entry is not submitted'));
                        frappe.model.set_value(cdt, cdn, 'payment_entry', '');
                        return;
                    }
                    
                    // Проверяем что customer совпадает
                    if (row.customer && r.message.party !== row.customer) {
                        frappe.msgprint(__('Payment Entry customer does not match the selected customer'));
                        frappe.model.set_value(cdt, cdn, 'payment_entry', '');
                        return;
                    }
                    
                    // Устанавливаем payment_entry_amount
                    let paid_amount = r.message.paid_amount || 0;
                    frappe.model.set_value(cdt, cdn, 'payment_entry_amount', paid_amount);
                    
                    // Если есть vat_journal_entry, пересчитываем на его основе
                    if (row.vat_journal_entry && row.vat_amount) {
                        let vat_allocated = row.vat_amount / 0.18;
                        frappe.model.set_value(cdt, cdn, 'vat_allocated_amount', vat_allocated);
                        frappe.model.set_value(cdt, cdn, 'vat_free_amount', paid_amount - vat_allocated);
                    } else {
                        // Иначе вся сумма идет в vat_free
                        frappe.model.set_value(cdt, cdn, 'vat_allocated_amount', 0);
                        frappe.model.set_value(cdt, cdn, 'vat_free_amount', paid_amount);
                    }
                    
                    // Обнуляем allocated amounts (так как links удалены)
                    frappe.model.set_value(cdt, cdn, 'allocated_amount', 0);
                    frappe.model.set_value(cdt, cdn, 'vat_free_allocated', 0);
                    frappe.model.set_value(cdt, cdn, 'vat_allocated_allocated', 0);
                    
                    // Unallocated = payment_entry_amount (так как allocated = 0)
                    frappe.model.set_value(cdt, cdn, 'unallocated_amount', paid_amount);
                    
                    // Автоматически заполняем customer, если он не был заполнен
                    if (!row.customer) {
                        frappe.model.set_value(cdt, cdn, 'customer', r.message.party);
                    }
                    
                    // Пересчитываем totals
                    recalculate_totals_manually(frm);
                    frm.refresh_field('payment_entry_table');
                    frm.refresh_field('sales_invoice_table');
                    frm.refresh_field('sales_invoice_previous_table');
                    frm.refresh_field('opening_entry_table');
                }
            }
        });
    },

    // При удалении строки - удалить связанные links
    payment_entry_table_remove: function(frm, cdt, cdn) {
        // Собираем список всех существующих row names из текущей таблицы
        let existing_rows = {};
        for (let pe_row of frm.doc.payment_entry_table || []) {
            existing_rows[pe_row.name] = true;
        }
        
        // Удаляем все allocation links, которые ссылаются на несуществующие строки
        frm.doc.allocation_links = (frm.doc.allocation_links || []).filter(function(link) {
            return existing_rows[link.payment_entry_row];
        });
        
        frm.refresh_field('allocation_links');
        
        // Пересчитываем totals для оставшихся строк
        recalculate_totals_manually(frm);
        frm.refresh_field('payment_entry_table');
        frm.refresh_field('sales_invoice_table');
        frm.refresh_field('sales_invoice_previous_table');
        frm.refresh_field('opening_entry_table');
    },
    
    vat_journal_entry: function(frm, cdt, cdn) {
        let row = locals[cdt][cdn];
        
        if (row.vat_journal_entry) {
            // Get Total Debit from Journal Entry
            frappe.call({
                method: 'frappe.client.get_value',
                args: {
                    doctype: 'Journal Entry',
                    filters: { name: row.vat_journal_entry },
                    fieldname: ['total_debit', 'docstatus']
                },
                callback: function(r) {
                    if (r.message) {
                        // Check if Journal Entry is submitted
                        if (r.message.docstatus !== 1) {
                            frappe.msgprint(__('Warning: Selected Journal Entry is not submitted'));
                            frappe.model.set_value(cdt, cdn, 'vat_journal_entry', '');
                            return;
                        }
                        
                        // Fill vat_amount
                        frappe.model.set_value(cdt, cdn, 'vat_amount', r.message.total_debit);
                        
                        // Calculate vat_allocated_amount
                        let vat_allocated = r.message.total_debit / 0.18;
                        frappe.model.set_value(cdt, cdn, 'vat_allocated_amount', vat_allocated);
                        
                        // Calculate vat_free_amount
                        let vat_free = row.payment_entry_amount - vat_allocated;
                        frappe.model.set_value(cdt, cdn, 'vat_free_amount', vat_free);
                        
                        // allocated_amount remains 0 for now (will be calculated from links)
                        frappe.model.set_value(cdt, cdn, 'allocated_amount', 0);
                    }
                }
            });
        } else {
            // If journal entry is cleared or not selected
            frappe.model.set_value(cdt, cdn, 'vat_amount', 0);
            frappe.model.set_value(cdt, cdn, 'vat_allocated_amount', 0);
            frappe.model.set_value(cdt, cdn, 'vat_free_amount', row.payment_entry_amount);
            frappe.model.set_value(cdt, cdn, 'allocated_amount', 0);
        }
    },
    
    // Setup query filter for vat_journal_entry when form loads
    payment_entry_table_add: function(frm, cdt, cdn) {
        setup_journal_entry_query(frm);
    },
    
    // If payment_entry_amount changes and no journal entry selected
    payment_entry_amount: function(frm, cdt, cdn) {
        let row = locals[cdt][cdn];
        
        if (!row.vat_journal_entry) {
            frappe.model.set_value(cdt, cdn, 'vat_free_amount', row.payment_entry_amount);
            frappe.model.set_value(cdt, cdn, 'unallocated_amount', row.payment_entry_amount);
        }
    },
    
    // Handle Allocate button click
    allocate_button: function(frm, cdt, cdn) {
        let row = locals[cdt][cdn];
        
        // Validate that customer is selected
        if (!row.customer) {
            frappe.msgprint(__('Please select a customer first'));
            return;
        }
        
        // Check if customer is active
        frappe.call({
            method: 'frappe.client.get_value',
            args: {
                doctype: 'Customer',
                filters: { name: row.customer },
                fieldname: ['disabled']
            },
            callback: function(r) {
                if (r.message && r.message.disabled) {
                    frappe.msgprint(__('Cannot allocate to disabled customer'));
                    return;
                }
                // Open allocation dialog - используем idx для несохраненных строк
                show_allocation_dialog(frm, row.idx, row.customer);
            }
        });
    }
});

// Show allocation dialog - работает с несохраненными данными
function show_allocation_dialog(frm, payment_row_idx, customer) {
    // Получаем данные напрямую из формы (не из БД!)
    let payment_row = null;
    for (let row of frm.doc.payment_entry_table || []) {
        if (row.idx === payment_row_idx) {
            payment_row = row;
            break;
        }
    }
    
    if (!payment_row) {
        frappe.msgprint(__('Payment entry row not found'));
        return;
    }
    
    // Получаем sales invoice items для этого клиента из формы
    let vat_free_items = [];
    let vat_items = [];
    let vat_free_items_previous = [];
    let vat_items_previous = [];
    
    // Current month items
    for (let item of frm.doc.sales_invoice_table || []) {
        if (item.customer !== customer) {
            continue;
        }
        
        // Получаем существующие аллокации для этого item от текущего payment row
        let current_allocation = 0;
        for (let link of frm.doc.allocation_links || []) {
            if (link.payment_entry_row === payment_row.name && 
                link.sales_invoice_row === item.name) {
                current_allocation = link.allocated_amount || 0;
                break;
            }
        }
        
        let item_data = {
            name: item.name,
            item_tax_template: item.item_tax_template || '',
            tax_articles: item.tax_articles || '',
            amount: item.amount || 0,
            unallocated_amount: item.unallocated_amount || 0,
            allocated_amount: item.allocated_amount || 0,
            current_allocation: current_allocation
        };
        
        let template = (item.item_tax_template || '').toLowerCase();
        
        if (template.includes('ədv 0%') || template.includes('ədv-dən azadolma')) {
            vat_free_items.push(item_data);
        } else if (template.includes('ədv 18%') || template.includes('ədv daxil 18%')) {
            vat_items.push(item_data);
        }
    }
    
    // Previous months items
    for (let item of frm.doc.sales_invoice_previous_table || []) {
        if (item.customer !== customer) {
            continue;
        }
        
        // Получаем существующие аллокации для этого item от текущего payment row
        let current_allocation = 0;
        for (let link of frm.doc.allocation_links || []) {
            if (link.payment_entry_row === payment_row.name && 
                link.sales_invoice_row === item.name) {
                current_allocation = link.allocated_amount || 0;
                break;
            }
        }
        
        let item_data = {
            name: item.name,
            item_tax_template: item.item_tax_template || '',
            tax_articles: item.tax_articles || '',
            amount: item.amount || 0,
            unallocated_amount: item.unallocated_amount || 0,
            allocated_amount: item.allocated_amount || 0,
            current_allocation: current_allocation
        };
        
        let template = (item.item_tax_template || '').toLowerCase();
        
        if (template.includes('ədv 0%') || template.includes('ədv-dən azadolma')) {
            vat_free_items_previous.push(item_data);
        } else if (template.includes('ədv 18%') || template.includes('ədv daxil 18%')) {
            vat_items_previous.push(item_data);
        }
    }
    
    // Opening entry items
    let opening_entry_items = [];
    for (let item of frm.doc.opening_entry_table || []) {
        if (item.customer !== customer) {
            continue;
        }

        let current_allocation = 0;
        for (let link of frm.doc.allocation_links || []) {
            if (link.payment_entry_row === payment_row.name &&
                link.sales_invoice_row === item.name) {
                current_allocation = link.allocated_amount || 0;
                break;
            }
        }

        opening_entry_items.push({
            name: item.name,
            amount: item.amount || 0,
            unallocated_amount: item.unallocated_amount || 0,
            allocated_amount: item.allocated_amount || 0,
            current_allocation: current_allocation
        });
    }

    // Check if there are items to allocate to
    if (vat_free_items.length === 0 && vat_items.length === 0 &&
        vat_free_items_previous.length === 0 && vat_items_previous.length === 0 &&
        opening_entry_items.length === 0) {
        frappe.msgprint(__('No sales invoice items available for this customer'));
        return;
    }

    // Вычисляем available amounts из текущих данных формы
    let vat_free_amount = payment_row.vat_free_amount || 0;
    let vat_free_allocated = payment_row.vat_free_allocated || 0;
    let vat_allocated_amount = payment_row.vat_allocated_amount || 0;
    let vat_allocated_allocated = payment_row.vat_allocated_allocated || 0;

    let data = {
        payment_row: payment_row,
        vat_free_available: vat_free_amount - vat_free_allocated,
        vat_allocated_available: vat_allocated_amount - vat_allocated_allocated,
        vat_free_items: vat_free_items,
        vat_items: vat_items,
        vat_free_items_previous: vat_free_items_previous,
        vat_items_previous: vat_items_previous,
        opening_entry_items: opening_entry_items
    };

    // Create allocation dialog
    create_allocation_dialog(frm, payment_row_idx, data);
}

function create_allocation_dialog(frm, payment_row_idx, data) {
    let allocation_data_current = {};
    let allocation_data_previous = {};
    let allocation_data_opening = {};

    let dialog = new frappe.ui.Dialog({
        title: __('Allocate Amount'),
        size: 'extra-large',
        fields: [
            {
                fieldname: 'info_section',
                fieldtype: 'Section Break',
                label: __('Payment Entry Information')
            },
            {
                fieldname: 'payment_info_html',
                fieldtype: 'HTML'
            },
            {
                fieldname: 'available_section',
                fieldtype: 'Section Break',
                label: __('Available for Allocation')
            },
            {
                fieldname: 'vat_free_available',
                fieldtype: 'Currency',
                label: __('VAT Free Available (ƏDV 0%, ƏDV-dən azadolma)'),
                read_only: 1,
                default: data.vat_free_available
            },
            {
                fieldname: 'column_break_avail',
                fieldtype: 'Column Break'
            },
            {
                fieldname: 'vat_allocated_available',
                fieldtype: 'Currency',
                label: __('VAT Allocated Available (ƏDV 18%, ƏDV daxil 18%)'),
                read_only: 1,
                default: data.vat_allocated_available
            },
            {
                fieldname: 'tabs_section',
                fieldtype: 'Section Break'
            },
            {
                fieldname: 'tabs_html',
                fieldtype: 'HTML'
            }
        ],
        primary_action_label: __('Save Allocation'),
        primary_action: function() {
            save_allocation_data(frm, payment_row_idx, allocation_data_current, allocation_data_previous, allocation_data_opening, dialog);
        },
        secondary_action_label: __('Auto Allocate'),
        secondary_action: function() {
            // Determine which tab is active
            let active_tab = dialog.$wrapper.find('.nav-tabs .nav-link.active').data('tab');

            // Calculate remaining available amounts
            let available_amounts = calculate_available_amounts(
                data,
                allocation_data_current,
                allocation_data_previous,
                allocation_data_opening
            );

            if (active_tab === 'current') {
                auto_allocate(frm, payment_row_idx, data, data.vat_free_items, data.vat_items,
                    allocation_data_current, dialog, 'current', available_amounts,
                    allocation_data_previous);
            } else if (active_tab === 'opening') {
                auto_allocate(frm, payment_row_idx, data, data.opening_entry_items, [],
                    allocation_data_opening, dialog, 'opening', available_amounts,
                    allocation_data_current);
            } else {
                auto_allocate(frm, payment_row_idx, data, data.vat_free_items_previous, data.vat_items_previous,
                    allocation_data_previous, dialog, 'previous', available_amounts,
                    allocation_data_current);
            }
        }
    });

    // Build payment info HTML
    let info_html = `
        <div style="padding: 10px; background-color: #f8f9fa; border-radius: 5px; margin-bottom: 10px;">
            <div class="row">
                <div class="col-md-6">
                    <strong>Total VAT Free:</strong> ${format_currency(data.payment_row.vat_free_amount)}<br>
                    <strong>VAT Free Spent:</strong> ${format_currency(data.payment_row.vat_free_allocated || 0)}
                </div>
                <div class="col-md-6">
                    <strong>Total VAT Allocated:</strong> ${format_currency(data.payment_row.vat_allocated_amount)}<br>
                    <strong>VAT Allocated Spent:</strong> ${format_currency(data.payment_row.vat_allocated_allocated || 0)}
                </div>
            </div>
        </div>
    `;
    dialog.fields_dict.payment_info_html.$wrapper.html(info_html);

    // Build tabs HTML with Bootstrap
    let html_current = build_allocation_html(data.vat_free_items, data.vat_items, allocation_data_current, 'current');
    let html_previous = build_allocation_html(data.vat_free_items_previous, data.vat_items_previous, allocation_data_previous, 'previous');
    let html_opening = build_allocation_html(data.opening_entry_items, [], allocation_data_opening, 'opening');

    let tabs_html = `
        <style>
            .allocation-tabs .nav-link {
                color: #6c757d;
                font-weight: 400;
                border: none;
                border-bottom: 3px solid transparent;
                padding: 10px 20px;
                cursor: pointer;
                transition: all 0.2s ease;
            }
            .allocation-tabs .nav-link:hover {
                color: #495057;
                background-color: #f8f9fa;
                border-bottom-color: #dee2e6;
            }
            .allocation-tabs .nav-link.active {
                color: #1f272e;
                font-weight: 600;
                border-bottom-color: #2490ef;
                background-color: transparent;
            }
            .allocation-tabs .nav-tabs {
                border-bottom: 1px solid #dee2e6;
            }
        </style>
        <ul class="nav nav-tabs allocation-tabs" role="tablist" style="margin-bottom: 15px;">
            <li class="nav-item">
                <a class="nav-link active" id="tab-link-current" data-tab="current" href="#tab-current" role="tab">
                    ${__('Current Month')}
                </a>
            </li>
            <li class="nav-item">
                <a class="nav-link" id="tab-link-previous" data-tab="previous" href="#tab-previous" role="tab">
                    ${__('Previous Months')}
                </a>
            </li>
            <li class="nav-item">
                <a class="nav-link" id="tab-link-opening" data-tab="opening" href="#tab-opening" role="tab">
                    ${__('Opening Entries')}
                </a>
            </li>
        </ul>
        <div class="tab-content">
            <div class="tab-pane fade show active" id="tab-current" role="tabpanel">
                ${html_current}
            </div>
            <div class="tab-pane fade" id="tab-previous" role="tabpanel">
                ${html_previous}
            </div>
            <div class="tab-pane fade" id="tab-opening" role="tabpanel">
                ${html_opening}
            </div>
        </div>
    `;

    dialog.fields_dict.tabs_html.$wrapper.html(tabs_html);

    // Setup custom tab switching (without Bootstrap's data-toggle)
    dialog.$wrapper.find('.nav-link').on('click', function(e) {
        e.preventDefault();
        e.stopPropagation();

        let $this = $(this);
        let target = $this.attr('href');

        // Update nav links
        dialog.$wrapper.find('.nav-link').removeClass('active');
        $this.addClass('active');

        // Update tab panes
        dialog.$wrapper.find('.tab-pane').removeClass('show active');
        dialog.$wrapper.find(target).addClass('show active');
    });

    // Setup input handlers for all tabs
    setup_allocation_inputs(dialog, allocation_data_current, data.vat_free_available, data.vat_allocated_available, 'current');
    setup_allocation_inputs(dialog, allocation_data_previous, data.vat_free_available, data.vat_allocated_available, 'previous');
    setup_allocation_inputs(dialog, allocation_data_opening, data.vat_free_available, data.vat_allocated_available, 'opening');

    dialog.show();
}

function calculate_available_amounts(data, allocation_data_current, allocation_data_previous, allocation_data_opening) {
    let total_vat_free_current = 0;
    let total_vat_allocated_current = 0;
    let total_vat_free_previous = 0;
    let total_vat_allocated_previous = 0;
    let total_vat_free_opening = 0;
    let total_vat_allocated_opening = 0;

    // Calculate totals from current month
    for (let name in allocation_data_current) {
        let alloc = allocation_data_current[name];
        if (alloc.type === 'vat_free') {
            total_vat_free_current += alloc.value || 0;
        } else {
            total_vat_allocated_current += alloc.value || 0;
        }
    }

    // Calculate totals from previous months
    for (let name in allocation_data_previous) {
        let alloc = allocation_data_previous[name];
        if (alloc.type === 'vat_free') {
            total_vat_free_previous += alloc.value || 0;
        } else {
            total_vat_allocated_previous += alloc.value || 0;
        }
    }

    // Calculate totals from opening entries
    for (let name in (allocation_data_opening || {})) {
        let alloc = allocation_data_opening[name];
        if (alloc.type === 'vat_free') {
            total_vat_free_opening += alloc.value || 0;
        } else {
            total_vat_allocated_opening += alloc.value || 0;
        }
    }

    // Calculate remaining available
    let vat_free_available = data.vat_free_available - total_vat_free_current - total_vat_free_previous - total_vat_free_opening;
    let vat_allocated_available = data.vat_allocated_available - total_vat_allocated_current - total_vat_allocated_previous - total_vat_allocated_opening;

    return {
        vat_free_available: Math.max(0, vat_free_available),
        vat_allocated_available: Math.max(0, vat_allocated_available)
    };
}

function build_allocation_html(vat_free_items, vat_items, allocation_data, tab_type) {
    let html = '<div class="allocation-container" style="max-height: 400px; overflow-y: auto;">';

    // Opening entries tab — simplified table without template/article columns
    if (tab_type === 'opening') {
        if (vat_free_items.length > 0) {
            html += '<h5 style="margin-top: 10px; color: #2490ef;">' + __('Opening Entry Items') + '</h5>';
            html += '<table class="table table-bordered" style="margin-bottom: 20px;">';
            html += '<thead><tr>';
            html += '<th>' + __('Customer') + '</th>';
            html += '<th>' + __('Total Amount') + '</th>';
            html += '<th>' + __('Unallocated') + '</th>';
            html += '<th>' + __('Current Alloc') + '</th>';
            html += '<th style="width: 150px;">' + __('New Allocation') + '</th>';
            html += '</tr></thead><tbody>';

            vat_free_items.forEach(function(item) {
                allocation_data[item.name] = { value: item.current_allocation || 0, type: 'vat_free' };
                html += '<tr>';
                html += '<td>' + (item.customer || '-') + '</td>';
                html += '<td>' + format_currency(item.amount) + '</td>';
                html += '<td>' + format_currency(item.unallocated_amount) + '</td>';
                html += '<td style="background-color: #fff3cd;">' + format_currency(item.current_allocation || 0) + '</td>';
                html += '<td><input type="number" class="form-control allocation-input-' + tab_type + '" data-name="' + item.name + '" data-type="vat_free" data-max="' + (item.unallocated_amount + (item.current_allocation || 0)) + '" value="' + (item.current_allocation || 0) + '" min="0" step="0.01"></td>';
                html += '</tr>';
            });

            html += '</tbody></table>';
        }

        // Summary section for opening tab
        let formatted_zero = $(frappe.format(0, {fieldtype: 'Currency'})).text();
        html += '<div class="allocation-summary-' + tab_type + '" style="margin-top: 20px; padding: 10px; background-color: #f8f9fa; border-radius: 5px;">';
        html += '<div class="row">';
        html += '<div class="col-md-12"><strong>' + __('Total to Allocate') + ':</strong> <span id="total_vat_free_' + tab_type + '" class="text-primary">' + formatted_zero + '</span></div>';
        html += '</div>';
        html += '<div class="row" style="margin-top: 10px;">';
        html += '<div class="col-md-12"><strong>' + __('Total') + ':</strong> <span id="total_allocated_' + tab_type + '" class="text-success">' + formatted_zero + '</span></div>';
        html += '</div>';
        html += '</div>';

        html += '</div>';
        return html;
    }

    // VAT Free items section
    if (vat_free_items.length > 0) {
        html += '<h5 style="margin-top: 10px; color: #2490ef;">VAT Free Items (ƏDV 0%, ƏDV-dən azadolma)</h5>';
        html += '<table class="table table-bordered" style="margin-bottom: 20px;">';
        html += '<thead><tr>';
        html += '<th>Item Tax Template</th>';
        html += '<th>Tax Articles</th>';
        html += '<th>Total Amount</th>';
        html += '<th>Unallocated</th>';
        html += '<th>Current Alloc</th>';
        html += '<th style="width: 150px;">New Allocation</th>';
        html += '</tr></thead><tbody>';

        vat_free_items.forEach(function(item) {
            allocation_data[item.name] = { value: item.current_allocation || 0, type: 'vat_free' };
            html += '<tr>';
            html += '<td>' + (item.item_tax_template || '-') + '</td>';
            html += '<td>' + format_tax_articles(item.tax_articles) + '</td>';
            html += '<td>' + format_currency(item.amount) + '</td>';
            html += '<td>' + format_currency(item.unallocated_amount) + '</td>';
            html += '<td style="background-color: #fff3cd;">' + format_currency(item.current_allocation || 0) + '</td>';
            html += '<td><input type="number" class="form-control allocation-input-' + tab_type + '" data-name="' + item.name + '" data-type="vat_free" data-max="' + (item.unallocated_amount + (item.current_allocation || 0)) + '" value="' + (item.current_allocation || 0) + '" min="0" step="0.01"></td>';
            html += '</tr>';
        });

        html += '</tbody></table>';
    }
    
    // VAT 18% items section
    if (vat_items.length > 0) {
        html += '<h5 style="margin-top: 10px; color: #f56b00;">VAT 18% Items (ƏDV 18%, ƏDV daxil 18%)</h5>';
        html += '<table class="table table-bordered">';
        html += '<thead><tr>';
        html += '<th>Item Tax Template</th>';
        html += '<th>Tax Articles</th>';
        html += '<th>Total Amount</th>';
        html += '<th>Unallocated</th>';
        html += '<th>Current Alloc</th>';
        html += '<th style="width: 150px;">New Allocation</th>';
        html += '</tr></thead><tbody>';
        
        vat_items.forEach(function(item) {
            allocation_data[item.name] = { value: item.current_allocation || 0, type: 'vat_allocated' };
            html += '<tr>';
            html += '<td>' + (item.item_tax_template || '-') + '</td>';
            html += '<td>' + format_tax_articles(item.tax_articles) + '</td>';
            html += '<td>' + format_currency(item.amount) + '</td>';
            html += '<td>' + format_currency(item.unallocated_amount) + '</td>';
            html += '<td style="background-color: #fff3cd;">' + format_currency(item.current_allocation || 0) + '</td>';
            html += '<td><input type="number" class="form-control allocation-input-' + tab_type + '" data-name="' + item.name + '" data-type="vat_allocated" data-max="' + (item.unallocated_amount + (item.current_allocation || 0)) + '" value="' + (item.current_allocation || 0) + '" min="0" step="0.01"></td>';
            html += '</tr>';
        });
        
        html += '</tbody></table>';
    }
    
    // Summary section
    let formatted_zero = $(frappe.format(0, {fieldtype: 'Currency'})).text();

    html += '<div class="allocation-summary-' + tab_type + '" style="margin-top: 20px; padding: 10px; background-color: #f8f9fa; border-radius: 5px;">';
    html += '<div class="row">';
    html += '<div class="col-md-6"><strong>Total VAT Free to Allocate:</strong> <span id="total_vat_free_' + tab_type + '" class="text-primary">' + formatted_zero + '</span></div>';
    html += '<div class="col-md-6"><strong>Total VAT to Allocate:</strong> <span id="total_vat_allocated_' + tab_type + '" class="text-warning">' + formatted_zero + '</span></div>';
    html += '</div>';
    html += '<div class="row" style="margin-top: 10px;">';
    html += '<div class="col-md-12"><strong>Total:</strong> <span id="total_allocated_' + tab_type + '" class="text-success">' + formatted_zero + '</span></div>';
    html += '</div>';
    html += '</div>';
    
    html += '</div>';
    
    return html;
}

function setup_allocation_inputs(dialog, allocation_data, max_vat_free, max_vat_allocated, tab_type) {
    // Ищем wrapper по ID вкладки в общем wrapper диалога
    let $wrapper = dialog.$wrapper.find('#tab-' + tab_type);
    
    // Initial calculation
    setTimeout(function() {
        $wrapper.find('.allocation-input-' + tab_type).first().trigger('input');
    }, 100);
    
    $wrapper.find('.allocation-input-' + tab_type).on('input', function() {
        let $input = $(this);
        let name = $input.data('name');
        let type = $input.data('type');
        let max_value = parseFloat($input.data('max'));
        let value = parseFloat($input.val()) || 0;
        
        // Validate against item's max
        if (value > max_value) {
            value = max_value;
            $input.val(value.toFixed(2));
        }
        
        if (value < 0) {
            value = 0;
            $input.val(value.toFixed(2));
        }
        
        allocation_data[name] = {
            value: value,
            type: type
        };
        
        // Calculate totals for this tab only
        let total_vat_free = 0;
        let total_vat_allocated = 0;
        
        $wrapper.find('.allocation-input-' + tab_type).each(function() {
            let item_type = $(this).data('type');
            let item_value = parseFloat($(this).val()) || 0;
            
            if (item_type === 'vat_free') {
                total_vat_free += item_value;
            } else {
                total_vat_allocated += item_value;
            }
        });
        
        // Validate totals against available amounts (with tolerance)
        const TOLERANCE = 0.01;
        
        if (total_vat_free > max_vat_free + TOLERANCE) {
            frappe.show_alert({
                message: __('Total VAT Free allocation exceeds available amount'),
                indicator: 'red'
            });
            // Reset this input
            allocation_data[name] = { value: 0, type: type };
            $input.val(0);
            total_vat_free -= value;
        }
        
        // Update summary for this tab
        $wrapper.find('#total_vat_free_' + tab_type).text($(frappe.format(total_vat_free, {fieldtype: 'Currency'})).text());
        $wrapper.find('#total_vat_allocated_' + tab_type).text($(frappe.format(total_vat_allocated, {fieldtype: 'Currency'})).text());
        $wrapper.find('#total_allocated_' + tab_type).text($(frappe.format(total_vat_free + total_vat_allocated, {fieldtype: 'Currency'})).text());
    });
}

function auto_allocate(frm, payment_row_idx, data, vat_free_items, vat_items, allocation_data, dialog, tab_type, available_amounts, other_allocation_data) {
    // Use calculated available amounts
    frappe.call({
        method: 'taxes_az.taxes_az.doctype.vat_allocation.vat_allocation.calculate_auto_allocation',
        args: {
            vat_free_available: available_amounts.vat_free_available,
            vat_allocated_available: available_amounts.vat_allocated_available,
            vat_free_items: JSON.stringify(vat_free_items),
            vat_items: JSON.stringify(vat_items)
        },
        callback: function(r) {
            if (r.message) {
                let allocations = r.message;
                let $wrapper = dialog.$wrapper.find('#tab-' + tab_type);
                
                // Reset all inputs for this tab
                $wrapper.find('.allocation-input-' + tab_type).val(0);
                
                // Update allocation data
                for (let key in allocation_data) {
                    allocation_data[key].value = 0;
                }
                
                // Apply auto allocations
                allocations.forEach(function(alloc) {
                    allocation_data[alloc.name].value = alloc.allocated;
                    $wrapper.find('.allocation-input-' + tab_type + '[data-name="' + alloc.name + '"]').val(alloc.allocated.toFixed(2));
                });
                
                // Trigger input event to update summary
                $wrapper.find('.allocation-input-' + tab_type).first().trigger('input');
                
                // Update available amounts in dialog fields
                let new_available = calculate_available_amounts(data,
                    tab_type === 'current' ? allocation_data : other_allocation_data,
                    tab_type === 'previous' ? allocation_data : other_allocation_data,
                    tab_type === 'opening' ? allocation_data : {}
                );
                
                dialog.set_value('vat_free_available', new_available.vat_free_available);
                dialog.set_value('vat_allocated_available', new_available.vat_allocated_available);
                
                frappe.show_alert({
                    message: __('Auto allocation completed'),
                    indicator: 'green'
                });
            }
        }
    });
}

// Сохранение allocation - работает с несохраненным документом
function save_allocation_data(frm, payment_row_idx, allocation_data_current, allocation_data_previous, allocation_data_opening, dialog) {
    // Prepare allocations array - combine all tabs
    let allocations = [];

    // Add allocations from current month tab
    for (let name in allocation_data_current) {
        let data = allocation_data_current[name];
        allocations.push({
            name: name,
            allocated: data.value,
            type: data.type
        });
    }

    // Add allocations from previous months tab
    for (let name in allocation_data_previous) {
        let data = allocation_data_previous[name];
        allocations.push({
            name: name,
            allocated: data.value,
            type: data.type
        });
    }

    // Add allocations from opening entries tab
    for (let name in (allocation_data_opening || {})) {
        let data = allocation_data_opening[name];
        allocations.push({
            name: name,
            allocated: data.value,
            type: data.type
        });
    }

    // Найдем payment row по idx
    let payment_row = null;
    for (let row of frm.doc.payment_entry_table || []) {
        if (row.idx === payment_row_idx) {
            payment_row = row;
            break;
        }
    }

    if (!payment_row) {
        frappe.msgprint(__('Payment entry row not found'));
        return;
    }

    // Удаляем старые links для этого payment row
    frm.doc.allocation_links = (frm.doc.allocation_links || []).filter(function(link) {
        return link.payment_entry_row !== payment_row.name;
    });

    // Добавляем новые links
    let total_vat_free = 0;
    let total_vat_allocated = 0;

    allocations.forEach(function(alloc) {
        if (alloc.allocated > 0) {
            let link = frm.add_child('allocation_links');
            link.payment_entry_row = payment_row.name;
            link.sales_invoice_row = alloc.name;
            link.allocated_amount = alloc.allocated;
            link.allocation_type = alloc.type;

            if (alloc.type === 'vat_free') {
                total_vat_free += alloc.allocated;
            } else {
                total_vat_allocated += alloc.allocated;
            }
        }
    });

    // Пересчитываем totals вручную (так как validate еще не вызван)
    recalculate_totals_manually(frm);

    frm.refresh_field('allocation_links');
    frm.refresh_field('payment_entry_table');
    frm.refresh_field('sales_invoice_table');
    frm.refresh_field('sales_invoice_previous_table');
    frm.refresh_field('opening_entry_table');

    // Помечаем документ как измененный
    frm.dirty();

    dialog.hide();
}

// Функция для пересчета totals без сохранения в БД - UPDATED
function recalculate_totals_manually(frm) {
    // Reset all allocated amounts
    for (let pe_row of frm.doc.payment_entry_table || []) {
        pe_row.vat_free_allocated = 0;
        pe_row.vat_allocated_allocated = 0;
        pe_row.allocated_amount = 0;
    }

    for (let si_row of frm.doc.sales_invoice_table || []) {
        si_row.allocated_amount = 0;
    }

    for (let si_row of frm.doc.sales_invoice_previous_table || []) {
        si_row.allocated_amount = 0;
    }

    for (let oe_row of frm.doc.opening_entry_table || []) {
        oe_row.allocated_amount = 0;
    }

    // Calculate from links
    for (let link of frm.doc.allocation_links || []) {
        let allocated = link.allocated_amount || 0;
        if (allocated <= 0) continue;

        // Update payment entry row
        for (let pe_row of frm.doc.payment_entry_table || []) {
            if (pe_row.name === link.payment_entry_row) {
                pe_row.allocated_amount = (pe_row.allocated_amount || 0) + allocated;

                if (link.allocation_type === 'vat_free') {
                    pe_row.vat_free_allocated = (pe_row.vat_free_allocated || 0) + allocated;
                } else {
                    pe_row.vat_allocated_allocated = (pe_row.vat_allocated_allocated || 0) + allocated;
                }
                break;
            }
        }

        // Update sales invoice row - check all three tables
        let found = false;
        for (let si_row of frm.doc.sales_invoice_table || []) {
            if (si_row.name === link.sales_invoice_row) {
                si_row.allocated_amount = (si_row.allocated_amount || 0) + allocated;
                found = true;
                break;
            }
        }

        if (!found) {
            for (let si_row of frm.doc.sales_invoice_previous_table || []) {
                if (si_row.name === link.sales_invoice_row) {
                    si_row.allocated_amount = (si_row.allocated_amount || 0) + allocated;
                    found = true;
                    break;
                }
            }
        }

        if (!found) {
            for (let oe_row of frm.doc.opening_entry_table || []) {
                if (oe_row.name === link.sales_invoice_row) {
                    oe_row.allocated_amount = (oe_row.allocated_amount || 0) + allocated;
                    break;
                }
            }
        }
    }

    // Calculate unallocated amounts
    for (let pe_row of frm.doc.payment_entry_table || []) {
        let total = pe_row.payment_entry_amount || 0;
        let allocated = pe_row.allocated_amount || 0;
        pe_row.unallocated_amount = Math.max(0, total - allocated);
    }

    for (let si_row of frm.doc.sales_invoice_table || []) {
        let total = si_row.amount || 0;
        let allocated = si_row.allocated_amount || 0;
        si_row.unallocated_amount = Math.max(0, total - allocated);
    }

    for (let si_row of frm.doc.sales_invoice_previous_table || []) {
        let total = si_row.amount || 0;
        let allocated = si_row.allocated_amount || 0;
        si_row.unallocated_amount = Math.max(0, total - allocated);
    }

    for (let oe_row of frm.doc.opening_entry_table || []) {
        let total = oe_row.amount || 0;
        let allocated = oe_row.allocated_amount || 0;
        oe_row.unallocated_amount = Math.max(0, total - allocated);
    }

    // Calculate tax template totals
    calculate_tax_template_totals(frm);
}

// Новая функция для расчета итогов по tax templates
function calculate_tax_template_totals(frm) {
    // Reset allocated totals
    frm.doc.total_edv_daxil_18 = 0;
    frm.doc.total_edv_azadolma = 0;
    frm.doc.total_edv_0 = 0;
    frm.doc.total_edv_18 = 0;
    frm.doc.total_allocated_sum = 0;

    // Reset unallocated totals
    frm.doc.total_edv_daxil_18_unallocated = 0;
    frm.doc.total_edv_azadolma_unallocated = 0;
    frm.doc.total_edv_0_unallocated = 0;
    frm.doc.total_edv_18_unallocated = 0;
    frm.doc.total_unallocated_sum = 0;

    // Calculate totals from sales invoice table (only current month)
    for (let si_row of frm.doc.sales_invoice_table || []) {
        let allocated = si_row.allocated_amount || 0;
        let unallocated = si_row.unallocated_amount || 0;

        let template = (si_row.item_tax_template || '').trim();

        // Match by template name prefix (template may have company suffix like "ƏDV 18% - js")
        if (template.startsWith('ƏDV daxil 18%')) {
            if (allocated > 0) {
                frm.doc.total_edv_daxil_18 += allocated;
            }
            if (unallocated > 0) {
                frm.doc.total_edv_daxil_18_unallocated += unallocated;
            }
        } else if (template.startsWith('ƏDV-dən azadolma')) {
            if (allocated > 0) {
                frm.doc.total_edv_azadolma += allocated;
            }
            if (unallocated > 0) {
                frm.doc.total_edv_azadolma_unallocated += unallocated;
            }
        } else if (template.startsWith('ƏDV 0%')) {
            if (allocated > 0) {
                frm.doc.total_edv_0 += allocated;
            }
            if (unallocated > 0) {
                frm.doc.total_edv_0_unallocated += unallocated;
            }
        } else if (template.startsWith('ƏDV 18%')) {
            if (allocated > 0) {
                frm.doc.total_edv_18 += allocated;
            }
            if (unallocated > 0) {
                frm.doc.total_edv_18_unallocated += unallocated;
            }
        }

        // Add to total sums
        if (allocated > 0) {
            frm.doc.total_allocated_sum += allocated;
        }
        if (unallocated > 0) {
            frm.doc.total_unallocated_sum += unallocated;
        }
    }

    // Add opening entry rows to totals (no VAT template, contribute to totals only)
    for (let oe_row of frm.doc.opening_entry_table || []) {
        let allocated = oe_row.allocated_amount || 0;
        let unallocated = oe_row.unallocated_amount || 0;
        if (allocated > 0) {
            frm.doc.total_allocated_sum += allocated;
        }
        if (unallocated > 0) {
            frm.doc.total_unallocated_sum += unallocated;
        }
    }

    // Refresh the allocated total fields
    frm.refresh_field('total_edv_daxil_18');
    frm.refresh_field('total_edv_azadolma');
    frm.refresh_field('total_edv_0');
    frm.refresh_field('total_edv_18');
    frm.refresh_field('total_allocated_sum');

    // Refresh the unallocated total fields
    frm.refresh_field('total_edv_daxil_18_unallocated');
    frm.refresh_field('total_edv_azadolma_unallocated');
    frm.refresh_field('total_edv_0_unallocated');
    frm.refresh_field('total_edv_18_unallocated');
    frm.refresh_field('total_unallocated_sum');

    // Refresh opening entry table
    frm.refresh_field('opening_entry_table');
}

function format_currency(value) {
    return frappe.format(value, {fieldtype: 'Currency'});
}