/**
 * Purchase Invoice Form and List Configuration
 * Includes Purchase Act sending functionality for Individual suppliers
 */

// ======= ETAXES MODULE (REQUIRED FOR AUTHENTICATION) =======
// This module MUST be included in every JS file that calls E-Taxes API
const ETaxes = {
    // Константы
    PROGRESS_UPDATE_DELAY: 50,
    AUTH_POLL_INTERVAL: 6000,
    AUTH_MAX_ATTEMPTS: 20,

    // Глобальные переменные
    loadingDialog: null,
    cancelLoading: false,
    loadingErrors: [],

    // Кэш
    cache: {
        defaultLogin: null,
        cacheTime: null,
        cacheDuration: 300000 // 5 минут
    }
};

// ======= БАЗОВЫЕ УТИЛИТЫ =======
ETaxes.utils = {
    // Кэшированное получение настроек входа
    getDefaultLogin: function(callback, useCache = true) {
        const now = Date.now();

        if (useCache && ETaxes.cache.defaultLogin && ETaxes.cache.cacheTime &&
            (now - ETaxes.cache.cacheTime) < ETaxes.cache.cacheDuration) {
            callback(ETaxes.cache.defaultLogin);
            return;
        }

        frappe.call({
            method: 'invoice_az.auth.get_default_asan_login',
            callback: function(r) {
                if (r.message) {
                    ETaxes.cache.defaultLogin = r.message;
                    ETaxes.cache.cacheTime = now;
                }
                callback(r.message);
            },
            error: function() {
                callback({found: false, error: 'Network error'});
            }
        });
    },

    // Проверка валидности токена
    checkTokenValidity: function(callback) {
        frappe.call({
            method: 'invoice_az.auth.check_token_validity',
            callback: function(r) {
                callback(r.message && r.message.valid);
            },
            error: function() {
                callback(false);
            }
        });
    },

    // Форматирование валюты
    formatCurrency: function(amount) {
        return new Intl.NumberFormat('az-AZ', {
            style: 'currency',
            currency: 'AZN',
            minimumFractionDigits: 2
        }).format(amount || 0);
    },

    // Очистка кэша
    clearCache: function() {
        ETaxes.cache.defaultLogin = null;
        ETaxes.cache.cacheTime = null;
    }
};

// ======= ДИАЛОГИ ЗАГРУЗКИ =======
ETaxes.dialogs = {
    // Показать диалог загрузки
    showLoading: function(title, message, submessage) {
        if (ETaxes.loadingDialog) {
            this.updateLoading(title, message, submessage);
            return;
        }

        ETaxes.loadingDialog = new frappe.ui.Dialog({
            title: title,
            fields: [{
                fieldname: 'loading_html',
                fieldtype: 'HTML',
                options: this._getLoadingHTML(title, message, submessage)
            }],
            primary_action_label: __('Cancel'),
            primary_action: function() {
                ETaxes.cancelLoading = true;
                ETaxes.loadingDialog.$wrapper.find('.primary-action').prop('disabled', true);
                ETaxes.loadingDialog.$wrapper.find('.primary-action').html(__('Cancelling...'));
                $('#status_message p').text(__('Cancelling the operation.'));
            }
        });

        ETaxes.cancelLoading = false;
        ETaxes.loadingDialog.show();
        ETaxes.loadingDialog.$wrapper.find('.modal-dialog').css('max-width', '450px');
    },

    // Обновить сообщение в диалоге
    updateLoading: function(title, message, submessage) {
        if (!ETaxes.loadingDialog) return;

        if (title) $('#loading_title').text(title);
        if (message) $('#loading_message').text(message);
        if (submessage !== undefined) {
            $('#loading_submessage').text(submessage);
            $('#loading_submessage').toggle(!!submessage);
        }
    },

    // Показать код верификации
    showVerificationCode: function(code) {
        if (ETaxes.loadingDialog && code) {
            $('#verification_code').text(code);
            $('#verification_code_container').show();
        }
    },

    // Установить статус успеха
    setSuccess: function(message, submessage, callback, delay = 2000) {
        if (!ETaxes.loadingDialog) {
            if (callback) callback();
            return;
        }

        ETaxes.loadingDialog.$wrapper.find('.loading-animation').html(`
            <div style="width: 64px; height: 64px; display: flex; align-items: center; justify-content: center;">
                <i class="fa fa-check" style="font-size: 48px; color: #5cb85c;"></i>
            </div>
        `);

        $('#loading_message').text(message);
        if (submessage !== undefined) {
            $('#loading_submessage').text(submessage);
            $('#loading_submessage').toggle(!!submessage);
        }

        $('#verification_code_container').hide();
        ETaxes.loadingDialog.set_primary_action(null);
        ETaxes.loadingDialog.set_secondary_action(null);

        setTimeout(() => {
            this.hide();
            if (callback) callback();
        }, delay);
    },

    // Установить статус ошибки
    setError: function(message, submessage, showCloseButton = true) {
        if (!ETaxes.loadingDialog) return;

        // Update dialog title
        ETaxes.loadingDialog.set_title(__('Error'));

        // Change animation to error icon
        ETaxes.loadingDialog.$wrapper.find('.loading-animation').html(`
            <div style="width: 64px; height: 64px; display: flex; align-items: center; justify-content: center;">
                <i class="fa fa-times" style="font-size: 48px; color: #d9534f;"></i>
            </div>
        `);

        // Clear all existing text elements
        ETaxes.loadingDialog.$wrapper.find('#loading_title').text('');
        ETaxes.loadingDialog.$wrapper.find('#loading_submessage').remove();

        // Set error message
        const $msgElement = ETaxes.loadingDialog.$wrapper.find('#loading_message');
        if ($msgElement.length) {
            $msgElement.css({
                'color': '#d9534f',
                'font-weight': '500',
                'font-size': '14px',
                'margin-top': '15px'
            });

            if (submessage) {
                $msgElement.html(submessage.replace(/\n/g, '<br>'));
            } else {
                $msgElement.text(message);
            }
        }

        $('#verification_code_container').hide();

        if (showCloseButton) {
            ETaxes.loadingDialog.set_primary_action(__('Close'), () => this.hide());
        }
    },

    // Скрыть диалог
    hide: function() {
        if (ETaxes.loadingDialog) {
            try {
                ETaxes.loadingDialog.hide();
            } catch (e) {
                console.error("Error hiding loading dialog:", e);
            }
            ETaxes.loadingDialog = null;
        }
        ETaxes.cancelLoading = false;
    },

    // Получить HTML для диалога загрузки
    _getLoadingHTML: function(title, message, submessage) {
        return `
            <div class="text-center">
                <div class="loading-animation" style="display: inline-block; width: 64px; height: 64px;">
                    <div style="width: 64px; height: 64px; border: 6px solid #4e73df; border-radius: 50%; border-color: #4e73df transparent #4e73df transparent; animation: lds-dual-ring 1.2s linear infinite;"></div>
                </div>
                <style>
                    @keyframes lds-dual-ring {
                        0% { transform: rotate(0deg); }
                        100% { transform: rotate(360deg); }
                    }
                </style>
                <div class="mt-3" id="status_message">
                    <h4 id="loading_title">${title || __('Please wait...')}</h4>
                    <p id="loading_message">${message || __('The operation may take some time')}</p>
                    <p id="loading_submessage" style="${submessage ? '' : 'display:none'}">${submessage || ''}</p>
                </div>
                <div id="verification_code_container" style="display:none; margin-top: 15px;">
                    <div style="background: #f8f9fa; padding: 10px; display: inline-block; border-radius: 5px; font-size: 24px; font-weight: bold; letter-spacing: 2px; color: #333; border: 1px solid #ddd;">
                        <span id="verification_code">----</span>
                    </div>
                    <p style="margin-top: 5px; font-size: 12px; color: #666;">Verification Code</p>
                </div>
            </div>
        `;
    }
};

// ======= МОДУЛЬ АУТЕНТИФИКАЦИИ =======
ETaxes.auth = {
    // Проверить токен и обработать аутентификацию при необходимости
    checkAndProcess: function(callback) {
        ETaxes.utils.checkTokenValidity(function(isValid) {
            if (isValid) {
                callback();
            } else {
                frappe.confirm(
                    __('Your E-Taxes session has expired or authentication is required. Would you like to authenticate now?'),
                    function() {
                        ETaxes.auth.startProcess(callback);
                    },
                    function() {
                        frappe.show_alert({
                            message: __('Authentication canceled. Operation cannot be completed.'),
                            indicator: 'red'
                        }, 5);
                    }
                );
            }
        });
    },

    // Начать процесс аутентификации
    startProcess: function(callback) {
        ETaxes.dialogs.showLoading(
            __('Starting Authentication'),
            __('Getting Asan Login settings...'),
            __('Please wait')
        );

        ETaxes.utils.getDefaultLogin(function(loginData) {
            if (loginData && loginData.found) {
                const asanLoginName = loginData.name;
                ETaxes.dialogs.updateLoading(
                    null,
                    __('Sending authentication request...'),
                    __('This will send a request to your Asan Imza mobile app')
                );

                frappe.call({
                    method: 'invoice_az.auth.handle_authentication',
                    args: { 'asan_login_name': asanLoginName },
                    callback: function(r) {
                        if (r.message && r.message.success) {
                            const bearerToken = r.message.bearer_token;

                            if (r.message.verification_code) {
                                ETaxes.dialogs.showVerificationCode(r.message.verification_code);
                            }

                            ETaxes.dialogs.updateLoading(
                                null,
                                __('Waiting for confirmation on your phone'),
                                __('Please check your phone and confirm the authentication request')
                            );

                            ETaxes.auth.pollStatus(asanLoginName, bearerToken, function(success) {
                                if (success) {
                                    ETaxes.auth.complete(asanLoginName, callback);
                                } else {
                                    ETaxes.dialogs.setError(
                                        __('Authentication Failed'),
                                        __('Could not authenticate with Asan Imza')
                                    );
                                }
                            });
                        } else {
                            ETaxes.dialogs.setError(
                                __('Authentication Error'),
                                r.message ? r.message.message : __('Authentication request failed')
                            );
                        }
                    }
                });
            } else {
                ETaxes.dialogs.setError(
                    __('No Asan Login Settings'),
                    __('Please configure Asan Login settings first')
                );
            }
        }, false); // Не использовать кэш для аутентификации
    },

    // Опрос статуса аутентификации
    pollStatus: function(asanLoginName, bearerToken, callback) {
        let attempts = 0;
        let stopPolling = false;

        function pollStatusStep() {
            if (attempts >= ETaxes.AUTH_MAX_ATTEMPTS || stopPolling) {
                if (attempts >= ETaxes.AUTH_MAX_ATTEMPTS) {
                    ETaxes.dialogs.setError(
                        __('Authentication Timeout'),
                        __('The authentication request has timed out. Please try again.')
                    );
                    callback(false);
                }
                return;
            }

            attempts++;

            ETaxes.dialogs.updateLoading(
                null,
                __('Waiting for confirmation on your phone'),
                __('Please check your phone and confirm the authentication request') +
                ' (' + attempts + '/' + ETaxes.AUTH_MAX_ATTEMPTS + ')'
            );

            frappe.call({
                method: 'invoice_az.auth.poll_auth_status',
                args: {
                    'asan_login_name': asanLoginName,
                    'bearer_token': bearerToken
                },
                callback: function(r) {
                    if (r.message && r.message.success) {
                        if (r.message.authenticated) {
                            stopPolling = true;
                            ETaxes.dialogs.setSuccess(
                                __('Authentication Successful'),
                                __('You are now authenticated with Asan Imza'),
                                function() {
                                    callback(true);
                                }
                            );
                        } else {
                            setTimeout(pollStatusStep, ETaxes.AUTH_POLL_INTERVAL);
                        }
                    } else {
                        stopPolling = true;
                        ETaxes.dialogs.setError(
                            __('Authentication Error'),
                            r.message ? r.message.message : __('An unknown error occurred')
                        );
                        callback(false);
                    }
                },
                error: function(err) {
                    console.error('Error during status check:', err);
                    setTimeout(pollStatusStep, ETaxes.AUTH_POLL_INTERVAL);
                }
            });
        }

        pollStatusStep();
    },

    // Завершение аутентификации
    complete: function(asanLoginName, callback) {
        ETaxes.dialogs.showLoading(
            __('Completing Authentication'),
            __('Getting certificates...'),
            __('Please wait')
        );

        frappe.call({
            method: 'invoice_az.auth.get_auth_certificates',
            args: { 'asan_login_name': asanLoginName },
            callback: function(certR) {
                if (certR.message && certR.message.success) {
                    ETaxes.dialogs.updateLoading(
                        null,
                        __('Certificates retrieved'),
                        __('Selecting certificate and taxpayer')
                    );

                    frappe.call({
                        method: 'frappe.client.get',
                        args: {
                            doctype: 'Asan Login',
                            name: asanLoginName
                        },
                        callback: function(r) {
                            if (r.message && r.message.selected_certificate_json) {
                                try {
                                    const certData = JSON.parse(r.message.selected_certificate_json);
                                    const certName = r.message.selected_certificate;

                                    ETaxes.dialogs.updateLoading(
                                        null,
                                        __('Selecting certificate'),
                                        certName
                                    );

                                    ETaxes.auth._selectCertificate(asanLoginName, certData, certName, callback);
                                } catch (e) {
                                    console.error('Error parsing certificate:', e);
                                    ETaxes.dialogs.hide();
                                    ETaxes.auth._showCertificateSelector(certR.message.certificates, asanLoginName, callback);
                                }
                            } else {
                                ETaxes.dialogs.hide();
                                ETaxes.auth._showCertificateSelector(certR.message.certificates, asanLoginName, callback);
                            }
                        }
                    });
                } else {
                    ETaxes.dialogs.setError(
                        __('Error'),
                        certR.message ? certR.message.message : __('Failed to get certificates')
                    );
                }
            }
        });
    },

    // Выбор сертификата
    _selectCertificate: function(asanLoginName, certData, certName, callback) {
        frappe.call({
            method: 'invoice_az.auth.select_certificate',
            args: {
                'asan_login_name': asanLoginName,
                'certificate_data': certData,
                'certificate_name': certName
            },
            callback: function(r) {
                if (r.message && r.message.success) {
                    ETaxes.dialogs.updateLoading(
                        null,
                        __('Selecting taxpayer'),
                        __('Using certificate: ') + certName
                    );

                    frappe.call({
                        method: 'invoice_az.auth.select_taxpayer',
                        args: { 'asan_login_name': asanLoginName },
                        callback: function(r) {
                            if (r.message && r.message.success) {
                                ETaxes.utils.clearCache(); // Очищаем кэш после успешной аутентификации
                                ETaxes.dialogs.setSuccess(
                                    __('Authentication Complete'),
                                    __('You can now access E-Taxes services'),
                                    callback
                                );
                            } else {
                                ETaxes.dialogs.setError(
                                    __('Error'),
                                    r.message ? r.message.message : __('Failed to select taxpayer')
                                );
                            }
                        }
                    });
                } else {
                    ETaxes.dialogs.setError(
                        __('Error'),
                        r.message ? r.message.message : __('Failed to select certificate')
                    );
                }
            }
        });
    },

    // Показать селектор сертификатов
    _showCertificateSelector: function(certificates, asanLoginName, callback) {
        if (!certificates || !certificates.length) {
            frappe.msgprint(__('No certificates available'));
            return;
        }

        let certHtml = '<div style="max-height: 400px; overflow-y: auto;"><table class="table table-bordered">';
        certHtml += '<thead><tr><th>Type</th><th>Name</th><th>ID</th><th>Position</th><th>Status</th><th></th></tr></thead><tbody>';

        certificates.forEach(function(cert, index) {
            let name = '';
            let id = '';

            if (cert.taxpayerType === 'individual' && cert.individualInfo) {
                name = cert.individualInfo.name || '';
                id = cert.individualInfo.fin || '';
            } else if (cert.legalInfo) {
                name = cert.legalInfo.name || '';
                id = cert.legalInfo.tin || cert.legalInfo.voen || '';
            }

            certHtml += '<tr>' +
                '<td>' + (cert.taxpayerType || '') + '</td>' +
                '<td>' + name + '</td>' +
                '<td>' + id + '</td>' +
                '<td>' + (cert.position || '') + '</td>' +
                '<td>' + (cert.hasAccess ? 'Active' : 'Inactive') + (cert.liquidated ? ' (Liquidated)' : '') + '</td>' +
                '<td><button class="btn btn-xs btn-primary select-cert" data-index="' + index + '">Select</button></td>' +
                '</tr>';
        });

        certHtml += '</tbody></table></div>';

        const dialog = new frappe.ui.Dialog({
            title: __('Select Certificate'),
            fields: [{
                fieldtype: 'HTML',
                fieldname: 'certificates',
                options: certHtml
            }]
        });

        dialog.show();

        dialog.$wrapper.find('.select-cert').on('click', function() {
            const index = $(this).data('index');
            const cert = certificates[index];

            let certName = '';
            if (cert.taxpayerType === 'individual' && cert.individualInfo) {
                certName = `${cert.individualInfo.name} (${cert.individualInfo.fin})`;
            } else if (cert.legalInfo) {
                certName = `${cert.legalInfo.name} (${cert.legalInfo.voen || cert.legalInfo.tin})`;
            } else {
                certName = `Certificate ${index + 1}`;
            }

            dialog.hide();

            ETaxes.dialogs.showLoading(
                __('Selecting Certificate'),
                __('Processing your selection...'),
                certName
            );

            ETaxes.auth._selectCertificate(asanLoginName, cert, certName, callback);
        });
    }
};
// ======= END ETAXES MODULE =======

frappe.ui.form.on('Purchase Invoice', {
    refresh: function(frm) {
        // Check if is_taxes_doc flag is set
        if (frm.doc.is_taxes_doc) {
            // Make all fields read-only
            frm.set_read_only(true);

            // Add visual indicator
            frm.page.set_indicator(__('Tax Document'), 'blue');
        }

        // Toggle visibility of purchase fields
        toggle_purchase_fields_visibility(frm);

        // Add E-Taxes buttons for Purchase Acts (only for Individual suppliers)
        // Only show buttons if purchase_type is checked
        if (frm.doc.docstatus === 1 && frm.doc.purchase_type) {
            add_purchase_act_buttons(frm);
        }

        // Add status indicator based on send status
        add_status_indicator(frm);
    },

    // Make is_taxes_doc field read-only when document loads
    onload: function(frm) {
        frm.set_df_property('is_taxes_doc', 'read_only', 1);

        // Set visibility of purchase fields on load
        toggle_purchase_fields_visibility(frm);
    },

    purchase_type: function(frm) {
        // Toggle visibility of tax_type and purchase_tax_amount fields
        toggle_purchase_fields_visibility(frm);

        // Refresh to show/hide buttons when checkbox changes
        frm.refresh();
    },

    validate: function(frm) {
        // Client-side validation before save
        if (frm.doc.purchase_type && frm.doc.items) {
            // Validate act_kind is selected
            if (!frm.doc.act_kind) {
                frappe.msgprint({
                    title: __('Missing Act Kind'),
                    indicator: 'red',
                    message: __('Please select Act Kind (Agricultural Products Act or Metal Scrap Reception Act)')
                });
                frappe.validated = false;
                return;
            }

            // Validate Tax Type for all items
            let missing_tax_type = [];

            for (let item of frm.doc.items) {
                if (!item.tax_type) {
                    missing_tax_type.push(item.item_code);
                }
            }

            if (missing_tax_type.length > 0) {
                frappe.msgprint({
                    title: __('Missing Tax Type'),
                    indicator: 'red',
                    message: __('Please select Tax Type for items: {0}', [missing_tax_type.join(', ')])
                });
                frappe.validated = false;
            }

            // NOTE: Metal scrap validation removed from client-side to avoid duplicate error messages
            // Server-side validation in send_purchase_api.py will catch this error
        }
    }
});

// Purchase Invoice Item events
frappe.ui.form.on('Purchase Invoice Item', {
    tax_type: function(frm, cdt, cdn) {
        calculate_purchase_tax(frm, cdt, cdn);
    },

    amount: function(frm, cdt, cdn) {
        calculate_purchase_tax(frm, cdt, cdn);
    },

    qty: function(frm, cdt, cdn) {
        calculate_purchase_tax(frm, cdt, cdn);
    },

    rate: function(frm, cdt, cdn) {
        calculate_purchase_tax(frm, cdt, cdn);
    }
});

/**
 * Toggle visibility of purchase fields in items table
 */
function toggle_purchase_fields_visibility(frm) {
    // Get the grid object
    let grid = frm.fields_dict.items.grid;

    if (frm.doc.purchase_type) {
        // Show fields
        grid.update_docfield_property('tax_type', 'hidden', 0);
        grid.update_docfield_property('purchase_tax_amount', 'hidden', 0);
        grid.update_docfield_property('tax_type', 'reqd', 1); // Make required
    } else {
        // Hide fields
        grid.update_docfield_property('tax_type', 'hidden', 1);
        grid.update_docfield_property('purchase_tax_amount', 'hidden', 1);
        grid.update_docfield_property('tax_type', 'reqd', 0); // Not required
    }

    // Refresh grid to apply changes
    grid.refresh();
}

/**
 * Calculate purchase tax amount (5% if Taxable)
 */
function calculate_purchase_tax(frm, cdt, cdn) {
    let item = locals[cdt][cdn];

    // Only calculate if parent has purchase_type checked
    if (!frm.doc.purchase_type) {
        frappe.model.set_value(cdt, cdn, 'purchase_tax_amount', 0);
        return;
    }

    // Calculate 5% if Taxable
    if (item.tax_type === 'Taxable' && item.amount) {
        let tax_amount = item.amount * 0.05;
        frappe.model.set_value(cdt, cdn, 'purchase_tax_amount', tax_amount);
    } else {
        // Tax Free or empty - set to 0
        frappe.model.set_value(cdt, cdn, 'purchase_tax_amount', 0);
    }
}

/**
 * Add status indicator based on E-Taxes send status
 */
function add_status_indicator(frm) {
    if (!frm.doc.etaxes_purchase_send_status) return;

    const status_colors = {
        'Sent and Signed': 'green',
        'Created, not signed': 'orange',
        'Failed': 'red',
        'Not Sent': 'gray'
    };

    const color = status_colors[frm.doc.etaxes_purchase_send_status] || 'gray';

    if (frm.doc.etaxes_purchase_send_status !== 'Not Sent') {
        frm.page.set_indicator(__(frm.doc.etaxes_purchase_send_status), color);
    }
}

/**
 * Add Purchase Act buttons for Individual suppliers
 */
function add_purchase_act_buttons(frm) {
    // CRITICAL: Only show buttons if purchase_type is checked
    if (!frm.doc.purchase_type) {
        return; // Exit early - no buttons shown
    }

    // Check if supplier is Individual type
    if (!frm.doc.supplier) return;

    frappe.db.get_value('Supplier', frm.doc.supplier, 'supplier_type', function(r) {
        if (r && r.supplier_type === 'Individual') {
            // Show buttons based on status

            // Status: Sent and Signed - show details only
            if (frm.doc.etaxes_purchase_send_status === 'Sent and Signed') {
                frm.add_custom_button(__('View E-Taxes Details'), function() {
                    show_act_details(frm);
                }, __('E-Taxes Purchase Act'));
                return;
            }

            // Status: Created, not signed - show sign button
            if (frm.doc.etaxes_purchase_send_status === 'Created, not signed') {
                frm.add_custom_button(__('Sign Act with ASAN Imza'), function() {
                    sign_purchase_act(frm);
                }, __('E-Taxes Purchase Act'));

                frm.add_custom_button(__('Cancel Act on E-Taxes'), function() {
                    cancel_act_on_etaxes(frm);
                }, __('E-Taxes Purchase Act'));

                return;
            }

            // Status: Not sent or Failed - show send button
            if (!frm.doc.etaxes_purchase_send_status ||
                frm.doc.etaxes_purchase_send_status === 'Not Sent' ||
                frm.doc.etaxes_purchase_send_status === 'Failed') {

                // Determine button text based on act_kind
                let send_button_text = __('Send Act to E-Taxes');
                if (frm.doc.act_kind === 'Agricultural Products Act') {
                    send_button_text = __('Send Agricultural Act to E-Taxes');
                } else if (frm.doc.act_kind === 'Metal Scrap Reception Act') {
                    send_button_text = __('Send Metal Scrap Act to E-Taxes');
                } else if (frm.doc.act_kind === 'Tire Products For Disposal Act') {
                    send_button_text = __('Send Tire Disposal Act to E-Taxes');
                } else if (frm.doc.act_kind === 'Plastic Products For Disposal Act') {
                    send_button_text = __('Send Plastic Disposal Act to E-Taxes');
                } else if (frm.doc.act_kind === 'Rawhide Supply') {
                    send_button_text = __('Send Rawhide Supply Act to E-Taxes');
                } else if (frm.doc.act_kind === 'Other Product Receipt Act') {
                    send_button_text = __('Send Other Product Receipt Act to E-Taxes');
                }

                frm.add_custom_button(send_button_text, function() {
                    send_purchase_act(frm);
                }, __('E-Taxes Purchase Act'));

                // Show cancel button if act exists
                if (frm.doc.etaxes_purchase_id) {
                    frm.add_custom_button(__('Cancel Act on E-Taxes'), function() {
                        cancel_act_on_etaxes(frm);
                    }, __('E-Taxes Purchase Act'));
                }
            }
        }
    });
}

/**
 * Send Purchase Act to E-Taxes (Step 1: Create draft)
 */
function send_purchase_act(frm) {
    frappe.confirm(
        __('Send Purchase Act to E-Taxes?') + '<br><br>' +
        __('Purchase Invoice: {0}', [frm.doc.name]) + '<br>' +
        __('Supplier: {0}', [frm.doc.supplier_name]) + '<br><br>' +
        __('This will create a draft act. You will need to sign it with ASAN Imza after creation.'),
        function() {
            // ✅ CRITICAL: Always wrap E-Taxes API calls with authentication check
            ETaxes.auth.checkAndProcess(function() {
                // Show loading
                frappe.show_alert({
                    message: __('Creating purchase act...'),
                    indicator: 'blue'
                }, 3);

                frappe.call({
                    method: 'invoice_az.send_purchase_api.send_purchase_invoice_to_etaxes',
                    args: {
                        purchase_invoice_name: frm.doc.name
                    },
                    callback: function(r) {
                        // Log full response to console for debugging
                        console.log('[PURCHASE_ACT] Full response from server:', r);

                        if (r.message && r.message.success) {
                            // Success
                            console.log('[PURCHASE_ACT] Success! Act created:', r.message);
                            frappe.show_alert({
                                message: __('Draft act created successfully!') + '<br>' +
                                        __('Serial: {0}', [r.message.serial_number]),
                                indicator: 'green'
                            }, 5);

                            // Reload document
                            frm.reload_doc();
                        } else {
                            // Error
                            console.error('[PURCHASE_ACT] Error creating act:', r.message);
                            const errorMsg = r.message ? r.message.message : __('Failed to create purchase act');
                            frappe.msgprint({
                                title: __('Error'),
                                indicator: 'red',
                                message: errorMsg
                            });
                        }
                    },
                    error: function(r) {
                        console.error('[PURCHASE_ACT] Communication error:', r);
                        frappe.msgprint({
                            title: __('Error'),
                            indicator: 'red',
                            message: __('Failed to communicate with E-Taxes service.')
                        });
                    }
                });
            });
        }
    );
}

/**
 * Sign Purchase Act with ASAN Imza (Step 2)
 */
function sign_purchase_act(frm) {
    frappe.confirm(
        __('Sign Purchase Act with ASAN Imza?') + '<br><br>' +
        __('Purchase Invoice: {0}', [frm.doc.name]) + '<br>' +
        __('Serial Number: {0}', [frm.doc.etaxes_purchase_serial_number]) + '<br>' +
        __('E-Taxes Act ID: {0}', [frm.doc.etaxes_purchase_id]) + '<br><br>' +
        __('This will finalize the act and send it to E-Taxes.'),
        function() {
            // ✅ CRITICAL: Always wrap E-Taxes API calls with authentication check
            ETaxes.auth.checkAndProcess(function() {
                // Show loading
                frappe.show_alert({
                    message: __('Signing purchase act...'),
                    indicator: 'blue'
                }, 3);

                frappe.call({
                    method: 'invoice_az.send_purchase_api.retry_signing_act',
                    args: {
                        purchase_invoice_name: frm.doc.name
                    },
                    callback: function(r) {
                        if (r.message && r.message.success) {
                            // Success
                            frappe.show_alert({
                                message: __('Act signed successfully!') + '<br>' +
                                        __('Verification Code: {0}', [r.message.verification_code]),
                                indicator: 'green'
                            }, 5);

                            // Reload document
                            frm.reload_doc();
                        } else {
                            // Error
                            const errorMsg = r.message ? r.message.message : __('Failed to sign purchase act');
                            frappe.msgprint({
                                title: __('Error'),
                                indicator: 'red',
                                message: errorMsg
                            });
                        }
                    },
                    error: function(r) {
                        frappe.msgprint({
                            title: __('Error'),
                            indicator: 'red',
                            message: __('Failed to communicate with E-Taxes service.')
                        });
                    }
                });
            });
        }
    );
}

/**
 * Cancel/Remove draft act from E-Taxes
 */
function cancel_act_on_etaxes(frm) {
    frappe.confirm(
        __('Cancel this purchase act on E-Taxes?') + '<br><br>' +
        __('Purchase Invoice: {0}', [frm.doc.name]) + '<br>' +
        __('E-Taxes Act ID: {0}', [frm.doc.etaxes_purchase_id]) + '<br>' +
        __('Status: {0}', [frm.doc.etaxes_purchase_send_status]) + '<br><br>' +
        __('<strong>Warning:</strong> This will permanently remove the act from E-Taxes system.'),
        function() {
            // ✅ CRITICAL: Always wrap E-Taxes API calls with authentication check
            ETaxes.auth.checkAndProcess(function() {
                // Show loading
                frappe.show_alert({
                    message: __('Removing purchase act...'),
                    indicator: 'orange'
                }, 3);

                frappe.call({
                    method: 'invoice_az.send_purchase_api.cancel_act_on_etaxes',
                    args: {
                        purchase_invoice_name: frm.doc.name
                    },
                    callback: function(r) {
                        if (r.message && r.message.success) {
                            // Success
                            frappe.show_alert({
                                message: __('Act successfully removed from E-Taxes'),
                                indicator: 'green'
                            }, 5);

                            // Reload document
                            frm.reload_doc();
                        } else {
                            // Error
                            const errorMsg = r.message ? r.message.message : __('Failed to cancel act on E-Taxes');
                            frappe.msgprint({
                                title: __('Error'),
                                indicator: 'red',
                                message: errorMsg
                            });
                        }
                    },
                    error: function(r) {
                        frappe.msgprint({
                            title: __('Error'),
                            indicator: 'red',
                            message: __('Failed to communicate with E-Taxes service.')
                        });
                    }
                });
            });
        }
    );
}

/**
 * Show Purchase Act details dialog
 */
function show_act_details(frm) {
    const details = `
        <table class="table table-bordered">
            <tr>
                <th style="width: 40%">${__('Purchase Invoice')}</th>
                <td>${frm.doc.name}</td>
            </tr>
            <tr>
                <th>${__('Supplier')}</th>
                <td>${frm.doc.supplier_name}</td>
            </tr>
            <tr>
                <th>${__('Act Kind')}</th>
                <td>${frm.doc.act_kind || '-'}</td>
            </tr>
            <tr>
                <th>${__('E-Taxes Act ID')}</th>
                <td>${frm.doc.etaxes_purchase_id || '-'}</td>
            </tr>
            <tr>
                <th>${__('Serial Number')}</th>
                <td><strong>${frm.doc.etaxes_purchase_serial_number || '-'}</strong></td>
            </tr>
            <tr>
                <th>${__('Verification Code')}</th>
                <td><strong>${frm.doc.etaxes_purchase_verification_code || '-'}</strong></td>
            </tr>
            <tr>
                <th>${__('Status')}</th>
                <td><span class="indicator ${get_status_color(frm.doc.etaxes_purchase_send_status)}">${frm.doc.etaxes_purchase_send_status || '-'}</span></td>
            </tr>
        </table>
    `;

    frappe.msgprint({
        title: __('E-Taxes Purchase Act Details'),
        message: details,
        wide: true
    });
}

/**
 * Get status indicator color
 */
function get_status_color(status) {
    const colors = {
        'Sent and Signed': 'green',
        'Created, not signed': 'orange',
        'Failed': 'red',
        'Not Sent': 'gray'
    };
    return colors[status] || 'gray';
}

frappe.listview_settings['Purchase Invoice'] = {
    onload: function(listview) {
        // Add field as column (proper way)
        listview.columns.push({
            type: 'Check',
            df: {
                label: __('Tax Doc'),
                fieldname: 'is_taxes_doc'
            },
            width: 120
        });
        
        // Force refresh list with new column
        listview.refresh();
    },
    
    // Format is_taxes_doc field display
    formatters: {
        is_taxes_doc: function(value) {
            return value ? 
                `<span class="indicator-pill green" title="${__('Tax Document')}"></span>` : 
                `<span class="indicator-pill gray" title="${__('Regular Document')}"></span>`;
        }
    }
};