frappe.ui.form.on('Asset', {
    refresh: function(frm) {
        setup_asset_fields(frm);
        update_area_field_label(frm);
        
        // Загружаем данные из Tax Article ТОЛЬКО при первом открытии формы
        if (!frm._tax_validity_loaded) {
            render_tax_validity_fields(frm, 'agricultural');
            render_tax_validity_fields(frm, 'industrial');
            render_tax_validity_fields(frm, 'tax_exempt');
            frm._tax_validity_loaded = true;
        }
        
        if (should_show_calculation_button(frm)) {
            add_calculation_button(frm);
        }
        
        // Применяем ограничения для quality_groups при загрузке формы
        update_quality_groups_options(frm);
    },
    
    land: function(frm) {
        handle_category_checkboxes(frm, 'land');
    },
    
    property: function(frm) {
        handle_category_checkboxes(frm, 'property');
    },
    
    custom_asset_type: function(frm) {
        setup_asset_fields(frm);
        update_area_field_label(frm);
        clear_dependent_fields(frm);
        
        if (should_show_calculation_button(frm)) {
            add_calculation_button(frm);
        } else {
            if (frm.custom_buttons && frm.custom_buttons['Calculate Gross Amount']) {
                frm.remove_custom_button('Calculate Gross Amount');
            }
        }
    },
    
    agricultural_purpose: function(frm) {
        update_area_field_label(frm);
        toggle_calculation_button(frm);
    },
    
    cadastral_district_name: function(frm) {
        if (frm.doc.cadastral_district_name) {
            frappe.call({
                method: 'frappe.client.get',
                args: {
                    doctype: 'Cadastral Valuation District',
                    name: frm.doc.cadastral_district_name
                },
                callback: function(r) {
                    if (r.message && r.message.district_code) {
                        frm.set_value('cadastral_district_code', r.message.district_code);
                    }
                }
            });
        } else {
            frm.set_value('cadastral_district_code', '');
        }
        
        toggle_calculation_button(frm);
    },
    
    area: function(frm) {
        toggle_calculation_button(frm);
    },

    quality_groups: function(frm) {
        toggle_calculation_button(frm);
    },

    agricultural_land_purpose: function(frm) {
        update_quality_groups_options(frm);
        toggle_calculation_button(frm);
    },
    
    territorial_unit_name: function(frm) {
        toggle_calculation_button(frm);
    },

    industrial_land_purpose: function(frm) {
        toggle_calculation_button(frm);
    },
    
    // При выборе Tax Article - рендерим поля
    agricultural_tax_article: function(frm) {
        frm._tax_validity_loaded = false;
        render_tax_validity_fields(frm, 'agricultural');
    },
    
    industrial_tax_article: function(frm) {
        frm._tax_validity_loaded = false;
        render_tax_validity_fields(frm, 'industrial');
    },
    
    tax_exempt_tax_article: function(frm) {
        frm._tax_validity_loaded = false;
        render_tax_validity_fields(frm, 'tax_exempt');
    },
    
    before_save: function(frm) {
        // Собираем данные из динамических полей и отправляем на сервер
        return save_tax_validity_data(frm);
    },
    
    after_save: function(frm) {
        // После успешного сохранения сбрасываем флаг
        frm._tax_validity_loaded = true;
    },
    
    validate: function(frm) {
        if (!frm.doc.land && !frm.doc.property) {
            frappe.msgprint('Please select either Land or Property');
            frappe.validated = false;
            return;
        }
        
        if (!frm.doc.custom_asset_type) {
            frappe.msgprint('Please select an Asset Type');
            frappe.validated = false;
            return;
        }
        
        if (frm.doc.custom_asset_type === "Kənd təsərrüfatı təyinatlı torpaq sahələri") {
            const required_fields = [
                ['agricultural_purpose', 'Purpose'],
                ['cadastral_district_name', 'Name of the Cadastral Valuation District'],
                ['quality_groups', 'Quality Groups'],
                ['agricultural_land_purpose', 'Purpose of the Land Plot']
            ];
            
            for (let [field, label] of required_fields) {
                if (!frm.doc[field]) {
                    frappe.msgprint(`${label} is required for Agricultural Land`);
                    frappe.validated = false;
                    return;
                }
            }
        }
        
        if (frm.doc.custom_asset_type === "Sənaye, tikinti, nəqliyyat, rabitə, ticarət-məişət xidməti və digər xüsusi təyinatlı torpaq sahələri") {
            const required_fields = [
                ['territorial_unit_name', 'Name of the Territorial Unit'],
                ['industrial_land_purpose', 'Purpose of the Land Plot']
            ];
            
            for (let [field, label] of required_fields) {
                if (!frm.doc[field]) {
                    frappe.msgprint(`${label} is required for Industrial/Commercial Land`);
                    frappe.validated = false;
                    return;
                }
            }
        }
        
        if (frm.doc.custom_asset_type === "Vergidən azad olunan əsas vəsaitlər") {
            const required_fields = [];
            
            // tax_exempt_settlements обязателен только для Land
            if (frm.doc.land) {
                required_fields.push(['tax_exempt_settlements', 'Settlements']);
            }
            
            // tax_exempt_tax_article обязателен всегда
            required_fields.push(['tax_exempt_tax_article', 'Tax Article']);
            
            for (let [field, label] of required_fields) {
                if (!frm.doc[field]) {
                    frappe.msgprint(`${label} is required for Tax Exempt Assets`);
                    frappe.validated = false;
                    return;
                }
            }
        }
        
        if (frm.doc.custom_asset_type === "Vergiyə cəlb olunan əsas vəsaitlər") {
            const required_fields = [];
            
            // taxable_settlements обязателен только для Land
            if (frm.doc.land) {
                required_fields.push(['taxable_settlements', 'Settlements']);
            }
            
            // taxable_asset_type обязателен всегда
            required_fields.push(['taxable_asset_type', 'Taxable Asset Type']);
            
            for (let [field, label] of required_fields) {
                if (!frm.doc[field]) {
                    frappe.msgprint(`${label} is required for Taxable Assets`);
                    frappe.validated = false;
                    return;
                }
            }
        }
    }
});

// ===== ФУНКЦИЯ ДЛЯ УПРАВЛЕНИЯ ОПЦИЯМИ QUALITY GROUPS =====

function update_quality_groups_options(frm) {
    const agricultural_land_purpose = frm.doc.agricultural_land_purpose;
    
    if (!agricultural_land_purpose) {
        return;
    }
    
    if (agricultural_land_purpose === 'Biçənək, örüş və otlaqlar') {
        // Ограничиваем только значением "I"
        frm.set_df_property('quality_groups', 'options', '\nI');
        
        // Если выбрано что-то другое, автоматически устанавливаем "I"
        if (frm.doc.quality_groups && frm.doc.quality_groups !== 'I') {
            frm.set_value('quality_groups', 'I');
        }
        // Если ничего не выбрано, тоже устанавливаем "I"
        if (!frm.doc.quality_groups) {
            frm.set_value('quality_groups', 'I');
        }
    } else if (agricultural_land_purpose === 'Əkin, dinc və çoxillik əkmələr') {
        // Показываем все опции
        frm.set_df_property('quality_groups', 'options', '\nI\nII\nIII\nIV\nV');
    }
    
    frm.refresh_field('quality_groups');
}

// ===== DYNAMIC TAX VALIDITY FIELDS WITH FRAPPE CONTROLS =====

function render_tax_validity_fields(frm, type) {
    const tax_article_field = `${type}_tax_article`;
    const html_field = `${type}_validity_html`;
    
    if (!frm.doc[tax_article_field]) {
        // Очищаем контролы и wrapper
        if (frm._tax_validity_controls && frm._tax_validity_controls[type]) {
            delete frm._tax_validity_controls[type];
        }
        if (frm.fields_dict[html_field]) {
            frm.fields_dict[html_field].$wrapper.html('');
        }
        return;
    }
    
    // Предотвращаем повторный рендеринг если уже рендерится
    if (frm[`_rendering_${type}`]) {
        return;
    }
    frm[`_rendering_${type}`] = true;
    
    // Загружаем данные из Tax Article
    frappe.call({
        method: 'frappe.client.get',
        args: {
            doctype: 'Tax Article',
            name: frm.doc[tax_article_field]
        },
        callback: function(r) {
            frm[`_rendering_${type}`] = false;
            
            if (r.message) {
                const tax_article = r.message;
                const tax_article_name = frm.doc[tax_article_field];
                
                // ===== НОВАЯ ПРОВЕРКА: Показываем поля только для определенных Tax Articles =====
                const allowed_tax_articles = [
                    '199.7',
                    '199.9',
                    '199.11',
                    '199.14',
                    '199.15',
                    '199.16',
                    '199.17',
                    '199.19',
                    '199.20',
                    '227.1',
                    '207.4',
                    '207.8',
                    '207.9'
                ];
                
                // Проверяем, содержит ли название Tax Article один из разрешенных номеров
                const is_allowed = allowed_tax_articles.some(pattern => tax_article_name.includes(pattern));
                
                if (!is_allowed) {
                    // Если Tax Article не в списке - очищаем контролы и выходим
                    const $wrapper = frm.fields_dict[html_field].$wrapper;
                    $wrapper.html('');
                    
                    if (frm._tax_validity_controls && frm._tax_validity_controls[type]) {
                        delete frm._tax_validity_controls[type];
                    }
                    
                    return;
                }
                // ===== КОНЕЦ НОВОЙ ПРОВЕРКИ =====
                
                // Очищаем старые контролы
                const $wrapper = frm.fields_dict[html_field].$wrapper;
                $wrapper.html('');
                
                // Удаляем старые ссылки на контролы
                if (frm._tax_validity_controls && frm._tax_validity_controls[type]) {
                    delete frm._tax_validity_controls[type];
                }
                
                // Создаем контейнер с нужными классами Frappe
                const $container = $('<div class="form-section" style="margin-top: 15px; padding-top: 15px; border-top: 1px solid #d1d8dd;">').appendTo($wrapper);
                
                // Проверяем, содержит ли имя Tax Article "207.8" или "207.4"
                if (tax_article_name.includes('207.8')) {
                    // Показываем только текст "75% Azadolma"
                    $('<div class="alert alert-info" style="margin-bottom: 0;">')
                        .html('<i class="fa fa-info-circle"></i> <strong>75% Azadolma</strong>')
                        .appendTo($container);
                    return;
                } else if (tax_article_name.includes('207.4')) {
                    // Показываем только текст "Tam Azadolma"
                    $('<div class="alert alert-success" style="margin-bottom: 0;">')
                        .html('<i class="fa fa-check-circle"></i> <strong>Tam Azadolma</strong>')
                        .appendTo($container);
                    return;
                } else if (tax_article_name.includes('207.9')) {
                    // Для 207.9 показываем только Date To с особым label
                    frm[`_loading_validity_${type}`] = true;
                    
                    let initial_date_to = tax_article.date_to;
                    if (frm._tax_validity_data && frm._tax_validity_data[type]) {
                        initial_date_to = frm._tax_validity_data[type].date_to || initial_date_to;
                    }
                    
                    const $row = $('<div class="row">').appendTo($container);
                    const $col = $('<div class="col-sm-12">').appendTo($row);
                    
                    const court_date_field = frappe.ui.form.make_control({
                        parent: $col,
                        df: {
                            fieldtype: 'Date',
                            label: __('Məhkəmə qərarının qüvvəyə mindiyi tarix'),
                            fieldname: `${type}_court_date_dynamic`,
                            change: function() {
                                handle_court_date_change(frm, type);
                            }
                        },
                        render_input: true
                    });
                    court_date_field.set_value(initial_date_to);
                    
                    $('<div class="text-muted small" style="margin-top: 10px;">')
                        .html('<i class="fa fa-info-circle"></i> ' + __('Changes will be saved to Tax Article when you save this Asset'))
                        .appendTo($container);
                    
                    if (!frm._tax_validity_controls) {
                        frm._tax_validity_controls = {};
                    }
                    frm._tax_validity_controls[type] = {
                        court_date: court_date_field
                    };
                    
                    if (!frm._tax_validity_data) {
                        frm._tax_validity_data = {};
                    }
                    frm._tax_validity_data[type] = {
                        date_to: initial_date_to
                    };
                    
                    setTimeout(() => {
                        frm[`_loading_validity_${type}`] = false;
                    }, 100);
                    
                    return;
                }
                
                // Для всех остальных Tax Articles показываем поля дат
                const $row = $('<div class="row">').appendTo($container);
                
                // Создаем 2 колонки для полей (Date From и Date To)
                const $col1 = $('<div class="col-sm-6">').appendTo($row);
                const $col2 = $('<div class="col-sm-6">').appendTo($row);
                
                // ВАЖНО: Блокируем dirty во время загрузки
                frm[`_loading_validity_${type}`] = true;
                
                // Проверяем, есть ли уже сохраненные данные в памяти (приоритет)
                let initial_date_from = tax_article.date_from;
                let initial_duration = tax_article.duration;
                let initial_date_to = tax_article.date_to;
                
                if (frm._tax_validity_data && frm._tax_validity_data[type]) {
                    initial_date_from = frm._tax_validity_data[type].date_from || initial_date_from;
                    initial_duration = frm._tax_validity_data[type].duration || initial_duration;
                    initial_date_to = frm._tax_validity_data[type].date_to || initial_date_to;
                }
                
                // Создаем Date From поле (редактируемое)
                const date_from_field = frappe.ui.form.make_control({
                    parent: $col1,
                    df: {
                        fieldtype: 'Date',
                        label: __('Date From'),
                        fieldname: `${type}_date_from_dynamic`,
                        change: function() {
                            handle_date_from_change(frm, type);
                        }
                    },
                    render_input: true
                });
                date_from_field.set_value(initial_date_from);
                
                // Создаем скрытое Duration поле (для хранения данных)
                const duration_field = frappe.ui.form.make_control({
                    parent: $('<div style="display:none;">').appendTo($wrapper),
                    df: {
                        fieldtype: 'Int',
                        label: __('Duration (Years)'),
                        fieldname: `${type}_duration_dynamic`,
                        hidden: 1,
                        read_only: 1
                    },
                    render_input: true
                });
                duration_field.set_value(initial_duration);
                
                // Создаем Date To поле (read only)
                const date_to_field = frappe.ui.form.make_control({
                    parent: $col2,
                    df: {
                        fieldtype: 'Date',
                        label: __('Date To'),
                        fieldname: `${type}_date_to_dynamic`,
                        read_only: 1
                    },
                    render_input: true
                });
                date_to_field.set_value(initial_date_to);
                
                // Добавляем информационное сообщение
                $('<div class="text-muted small" style="margin-top: 10px;">')
                    .html('<i class="fa fa-info-circle"></i> ' + __('Changes will be saved to Tax Article when you save this Asset'))
                    .appendTo($container);
                
                // Сохраняем ссылки на контролы
                if (!frm._tax_validity_controls) {
                    frm._tax_validity_controls = {};
                }
                frm._tax_validity_controls[type] = {
                    date_from: date_from_field,
                    duration: duration_field,
                    date_to: date_to_field
                };
                
                // Сохраняем текущие значения
                if (!frm._tax_validity_data) {
                    frm._tax_validity_data = {};
                }
                frm._tax_validity_data[type] = {
                    date_from: initial_date_from,
                    date_to: initial_date_to,
                    duration: initial_duration
                };
                
                // Снимаем блокировку dirty после небольшой задержки
                setTimeout(() => {
                    frm[`_loading_validity_${type}`] = false;
                }, 100);
            }
        },
        error: function() {
            frm[`_rendering_${type}`] = false;
        }
    });
}

function handle_date_from_change(frm, type) {
    // Игнорируем изменения во время загрузки
    if (frm[`_loading_validity_${type}`]) {
        return;
    }
    
    if (!frm._tax_validity_controls || !frm._tax_validity_controls[type]) {
        return;
    }
    
    const controls = frm._tax_validity_controls[type];
    
    const date_from = controls.date_from.get_value();
    const duration = controls.duration.get_value();
    
    if (!date_from || !duration) {
        return;
    }
    
    // Рассчитываем date_to = date_from + duration
    let from_date = frappe.datetime.str_to_obj(date_from);
    let to_date = new Date(from_date);
    to_date.setFullYear(to_date.getFullYear() + duration);
    const calculated_date_to = frappe.datetime.obj_to_str(to_date);
    
    controls.date_to.set_value(calculated_date_to);
    
    // Сохраняем в памяти
    if (!frm._tax_validity_data) {
        frm._tax_validity_data = {};
    }
    frm._tax_validity_data[type] = {
        date_from: date_from,
        date_to: calculated_date_to,
        duration: duration
    };
    
    frm.dirty();
}

function handle_court_date_change(frm, type) {
    // Игнорируем изменения во время загрузки
    if (frm[`_loading_validity_${type}`]) {
        return;
    }
    
    if (!frm._tax_validity_controls || !frm._tax_validity_controls[type]) {
        return;
    }
    
    const controls = frm._tax_validity_controls[type];
    const court_date = controls.court_date.get_value();
    
    if (!court_date) {
        return;
    }
    
    // Сохраняем в памяти
    if (!frm._tax_validity_data) {
        frm._tax_validity_data = {};
    }
    frm._tax_validity_data[type] = {
        date_to: court_date
    };
    
    frm.dirty();
}

function save_tax_validity_data(frm) {
    if (!frm._tax_validity_data) {
        return Promise.resolve();
    }
    
    const promises = [];
    
    // Для каждого типа Tax Article
    ['agricultural', 'industrial', 'tax_exempt'].forEach(type => {
        const tax_article_field = `${type}_tax_article`;
        
        if (frm.doc[tax_article_field] && frm._tax_validity_data[type]) {
            const tax_article_name = frm.doc[tax_article_field];
            
            // Пропускаем сохранение для 207.8 и 207.4 (они не имеют полей дат)
            if (tax_article_name.includes('207.8') || tax_article_name.includes('207.4')) {
                return;
            }
            
            const data = frm._tax_validity_data[type];
            
            // Для 207.9 сохраняем только date_to
            if (tax_article_name.includes('207.9')) {
                promises.push(
                    frappe.call({
                        method: 'jey_erp.asset_events.update_tax_article_from_asset',
                        args: {
                            tax_article_name: tax_article_name,
                            date_to: data.date_to
                        }
                    })
                );
            } else {
                // Для обычных Tax Articles сохраняем все поля
                promises.push(
                    frappe.call({
                        method: 'jey_erp.asset_events.update_tax_article_from_asset',
                        args: {
                            tax_article_name: tax_article_name,
                            date_from: data.date_from,
                            date_to: data.date_to,
                            duration: data.duration
                        }
                    })
                );
            }
        }
    });
    
    if (promises.length > 0) {
        return Promise.all(promises).then(() => {
            frappe.show_alert({
                message: __('Tax Article(s) updated successfully'),
                indicator: 'green'
            }, 3);
        }).catch(() => {
            frappe.msgprint({
                title: __('Error'),
                message: __('Failed to update Tax Article'),
                indicator: 'red'
            });
        });
    }
    
    return Promise.resolve();
}

// ===== ОСТАЛЬНЫЕ ФУНКЦИИ (БЕЗ ИЗМЕНЕНИЙ) =====

function update_area_field_label(frm) {
    let asset_type = frm.doc.custom_asset_type;
    
    if (!asset_type) {
        frm.set_df_property('area', 'label', 'Area');
        frm.set_df_property('area', 'description', 'Select asset type first');
        frm.set_df_property('area', 'hidden', 1);
        frm.refresh_field('area');
        return;
    }
    
    if (asset_type === 'Kənd təsərrüfatı təyinatlı torpaq sahələri') {
        frm.set_df_property('area', 'hidden', 0);
        
        let agricultural_purpose_id = frm.doc.agricultural_purpose;
        
        if (!agricultural_purpose_id) {
            frm.set_df_property('area', 'label', 'Area');
            frm.set_df_property('area', 'description', 'Select agricultural purpose to determine unit (Sq.m or hectares)');
        } else {
            frappe.db.get_value('Agricultural Purpose Type', agricultural_purpose_id, 'purpose_name', function(r) {
                if (r && r.purpose_name) {
                    let purpose_name = r.purpose_name;
                    
                    if (purpose_name === 'Təyinatı üzrə istifadə edilməyən kənd təsərrüfatı torpaqları üzrə hesablanmış vergi məbləği') {
                        frm.set_df_property('area', 'label', 'Sq.m');
                        frm.set_df_property('area', 'description', 'Enter area in square meters for unused agricultural land');
                    } else if (purpose_name === 'Təyinatı üzrə istifadə edilən və ya irriqasiya, meliorasiya və digər aqrotexniki səbəblərdən təyinatı üzrə istifadə edilməsi mümkün olmayan kənd təsərrüfatı torpaqları üzrə verginin məbləği') {
                        frm.set_df_property('area', 'label', 'Hectare');
                        frm.set_df_property('area', 'description', 'Enter area in hectares for used agricultural land');
                    } else {
                        frm.set_df_property('area', 'label', 'Area');
                        frm.set_df_property('area', 'description', purpose_name);
                    }
                    
                    frm.refresh_field('area');
                } else {
                    frm.set_df_property('area', 'label', 'Area');
                    frm.set_df_property('area', 'description', 'Unit could not be determined');
                    frm.refresh_field('area');
                }
            });
        }
        
    } else if (asset_type === 'Sənaye, tikinti, nəqliyyat, rabitə, ticarət-məişət xidməti və digər xüsusi təyinatlı torpaq sahələri') {
        frm.set_df_property('area', 'hidden', 0);
        frm.set_df_property('area', 'label', 'Sq.m');
        frm.set_df_property('area', 'description', 'Enter area in square meters for industrial land');
        frm.refresh_field('area');
        
    } else {
        frm.set_df_property('area', 'hidden', 1);
        frm.set_df_property('area', 'label', 'Area');
        frm.set_df_property('area', 'description', '');
        frm.refresh_field('area');
    }
}

function handle_category_checkboxes(frm, current_field) {
    if (frm.doc[current_field]) {
        const other_field = current_field === 'land' ? 'property' : 'land';
        if (frm.doc[other_field]) {
            frm.set_value(other_field, 0);
        }
    }
    
    setup_asset_type_options(frm);
    setup_asset_fields(frm);
}

function setup_asset_type_options(frm) {
    let options = '\n';
    
    if (frm.doc.land) {
        options += 'Kənd təsərrüfatı təyinatlı torpaq sahələri\nSənaye, tikinti, nəqliyyat, rabitə, ticarət-məişət xidməti və digər xüsusi təyinatlı torpaq sahələri';
    } else if (frm.doc.property) {
        options += 'Vergidən azad olunan əsas vəsaitlər\nVergiyə cəlb olunan əsas vəsaitlər';
    }
    
    frm.set_df_property('custom_asset_type', 'options', options);
    
    if (frm.doc.land || frm.doc.property) {
        frm.set_df_property('custom_asset_type', 'hidden', 0);
        frm.set_df_property('custom_asset_type', 'reqd', 1);
    } else {
        frm.set_df_property('custom_asset_type', 'hidden', 1);
        frm.set_df_property('custom_asset_type', 'reqd', 0);
        frm.set_value('custom_asset_type', '');
    }
}

function show_common_fields(frm) {
    frm.set_df_property('common_land_section', 'hidden', 0);
    
    // Показываем tax_exempt_area только для Land, скрываем для Property
    if (frm.doc.land) {
        frm.set_df_property('tax_exempt_area', 'hidden', 0);
        frm.set_df_property('tax_exempt_area', 'description', 
            'Enter the tax-exempt area in square meters');
    } else if (frm.doc.property) {
        frm.set_df_property('tax_exempt_area', 'hidden', 1);
        frm.set_df_property('tax_exempt_area', 'description', '');
    }
}

function hide_all_conditional_fields(frm) {
    const agricultural_fields = [
        'agricultural_land_section',
        'agricultural_purpose',
        'cadastral_district_name',
        'cadastral_district_code',
        'quality_groups',
        'agricultural_land_purpose',
        'agricultural_column_break',
        'agricultural_tax_article'
    ];
    
    const industrial_fields = [
        'industrial_land_section',
        'territorial_unit_name',
        'territorial_unit_code',
        'industrial_land_purpose',
        'mining_note',
        'industrial_column_break',
        'industrial_tax_article'
    ];
    
    const tax_exempt_fields = [
        'tax_exempt_assets_section',
        'tax_exempt_tax_article',
        'tax_exempt_settlements'
    ];
    
    const taxable_fields = [
        'taxable_assets_section',
        'taxable_settlements',
        'taxable_asset_type'
    ];
    
    [...agricultural_fields, ...industrial_fields, ...tax_exempt_fields, ...taxable_fields].forEach(fieldname => {
        frm.set_df_property(fieldname, 'hidden', 1);
        frm.set_df_property(fieldname, 'reqd', 0);
    });
}

function setup_asset_fields(frm) {
    const asset_type = frm.doc.custom_asset_type;
    
    setup_asset_type_options(frm);
    hide_all_conditional_fields(frm);
    show_common_fields(frm);
    
    if (!asset_type) {
        frm.refresh_fields();
        return;
    }
    
    if (asset_type === "Kənd təsərrüfatı təyinatlı torpaq sahələri") {
        setup_agricultural_fields(frm);
    } else if (asset_type === "Sənaye, tikinti, nəqliyyat, rabitə, ticarət-məişət xidməti və digər xüsusi təyinatlı torpaq sahələri") {
        setup_industrial_fields(frm);
    } else if (asset_type === "Vergidən azad olunan əsas vəsaitlər") {
        setup_tax_exempt_fields(frm);
    } else if (asset_type === "Vergiyə cəlb olunan əsas vəsaitlər") {
        setup_taxable_fields(frm);
    }
    
    frm.refresh_fields();
}

function setup_agricultural_fields(frm) {
    const agricultural_fields = [
        'agricultural_land_section',
        'agricultural_purpose',
        'cadastral_district_name',
        'cadastral_district_code',
        'quality_groups',
        'agricultural_land_purpose',
        'agricultural_column_break',
        'agricultural_tax_article'
    ];
    
    agricultural_fields.forEach(fieldname => {
        frm.set_df_property(fieldname, 'hidden', 0);
    });
    
    const required_agricultural_fields = [
        'agricultural_purpose',
        'cadastral_district_name',
        'quality_groups',
        'agricultural_land_purpose'
    ];
    
    required_agricultural_fields.forEach(fieldname => {
        frm.set_df_property(fieldname, 'reqd', 1);
    });
    
    frm.set_query('agricultural_tax_article', function() {
        return {
            query: "jey_erp.asset.get_land_tax_articles"  
        };
    });
    
    frm.set_df_property('agricultural_purpose', 'description', 
        'Select the purpose for agricultural land taxation');
    frm.set_df_property('cadastral_district_name', 'description', 
        'Select the cadastral valuation district');
    frm.set_df_property('agricultural_tax_article', 'description', 
        'Select the applicable tax article for land');
}

function setup_industrial_fields(frm) {
    const industrial_fields = [
        'industrial_land_section',
        'territorial_unit_name',
        'territorial_unit_code',
        'industrial_land_purpose',
        'mining_note',
        'industrial_column_break',
        'industrial_tax_article'
    ];
    
    industrial_fields.forEach(fieldname => {
        frm.set_df_property(fieldname, 'hidden', 0);
    });
    
    const required_industrial_fields = [
        'territorial_unit_name',
        'industrial_land_purpose'
    ];
    
    required_industrial_fields.forEach(fieldname => {
        frm.set_df_property(fieldname, 'reqd', 1);
    });
    
    frm.set_query('industrial_tax_article', function() {
        return {
            query: "jey_erp.asset.get_land_tax_articles"  
        };
    });
    
    frm.set_df_property('territorial_unit_name', 'description', 
        'Select the appropriate territorial unit');
    frm.set_df_property('industrial_land_purpose', 'description', 
        'Specify the purpose of the industrial/commercial land plot');
    frm.set_df_property('mining_note', 'description', 
        'Check if this relates to mining operations');
    frm.set_df_property('industrial_tax_article', 'description', 
        'Select the applicable tax article for land');
}

function setup_tax_exempt_fields(frm) {
    const tax_exempt_fields = [
        'tax_exempt_assets_section',
        'tax_exempt_tax_article',
        'tax_exempt_settlements'
    ];
    
    tax_exempt_fields.forEach(fieldname => {
        frm.set_df_property(fieldname, 'hidden', 0);
    });
    
    // Скрываем tax_exempt_settlements для Property, так же как для Taxable Assets
    if (frm.doc.property) {
        frm.set_df_property('tax_exempt_settlements', 'hidden', 1);
        frm.set_df_property('tax_exempt_settlements', 'reqd', 0);
        
        // Только tax_exempt_tax_article обязателен для Property
        frm.set_df_property('tax_exempt_tax_article', 'reqd', 1);
    } else {
        // Для Land оба поля обязательны
        frm.set_df_property('tax_exempt_settlements', 'reqd', 1);
        frm.set_df_property('tax_exempt_tax_article', 'reqd', 1);
        
        frm.set_df_property('tax_exempt_settlements', 'description', 
            'Select the settlement type');
    }
    
    frm.set_query('tax_exempt_tax_article', function() {
        return {
            query: "jey_erp.asset.get_tax_exempt_articles"  
        };
    });
    
    frm.set_df_property('tax_exempt_tax_article', 'description', 
        'Select the applicable tax article for tax exempt assets');
}

function setup_taxable_fields(frm) {
    const taxable_fields = [
        'taxable_assets_section',
        'taxable_settlements',
        'taxable_asset_type'
    ];
    
    taxable_fields.forEach(fieldname => {
        frm.set_df_property(fieldname, 'hidden', 0);
    });
    
    // Скрываем taxable_settlements для Property
    if (frm.doc.property) {
        frm.set_df_property('taxable_settlements', 'hidden', 1);
        frm.set_df_property('taxable_settlements', 'reqd', 0);
        
        // Только taxable_asset_type обязателен для Property
        frm.set_df_property('taxable_asset_type', 'reqd', 1);
    } else {
        // Для Land оба поля обязательны
        frm.set_df_property('taxable_settlements', 'reqd', 1);
        frm.set_df_property('taxable_asset_type', 'reqd', 1);
        
        frm.set_df_property('taxable_settlements', 'description', 
            'Select the settlement type');
    }
    
    frm.set_df_property('taxable_asset_type', 'description', 
        'Select the type of taxable asset');
}

function clear_dependent_fields(frm) {
    const conditional_fields = [
        'agricultural_purpose',
        'cadastral_district_name',
        'cadastral_district_code',
        'quality_groups',
        'agricultural_land_purpose',
        'agricultural_tax_article',
        'territorial_unit_name',
        'territorial_unit_code',
        'industrial_land_purpose',
        'mining_note',
        'industrial_tax_article',
        'tax_exempt_tax_article',
        'tax_exempt_settlements',
        'taxable_settlements',
        'taxable_asset_type'
    ];
    
    conditional_fields.forEach(fieldname => {
        frm.set_value(fieldname, '');
    });
}

function should_show_calculation_button(frm) {
    return frm.doc.custom_asset_type === "Kənd təsərrüfatı təyinatlı torpaq sahələri" ||
           frm.doc.custom_asset_type === "Sənaye, tikinti, nəqliyyat, rabitə, ticarət-məişət xidməti və digər xüsusi təyinatlı torpaq sahələri";
}

function can_calculate_agricultural_amount(frm) {
    return frm.doc.custom_asset_type === "Kənd təsərrüfatı təyinatlı torpaq sahələri" &&
           frm.doc.area &&
           frm.doc.cadastral_district_name && 
           frm.doc.quality_groups && 
           frm.doc.agricultural_land_purpose;
}

function can_calculate_industrial_amount(frm) {
    return frm.doc.custom_asset_type === "Sənaye, tikinti, nəqliyyat, rabitə, ticarət-məişət xidməti və digər xüsusi təyinatlı torpaq sahələri" &&
           frm.doc.area &&
           frm.doc.territorial_unit_name && 
           frm.doc.industrial_land_purpose;
}

function can_calculate_amount(frm) {
    return can_calculate_agricultural_amount(frm) || can_calculate_industrial_amount(frm);
}

function add_calculation_button(frm) {
    if (frm.custom_buttons && frm.custom_buttons['Calculate Gross Amount']) {
        return;
    }
    
    frm.add_custom_button('Calculate Gross Amount', function() {
        if (can_calculate_agricultural_amount(frm)) {
            calculate_agricultural_gross_purchase_amount(frm);
        } else if (can_calculate_industrial_amount(frm)) {
            calculate_industrial_gross_purchase_amount(frm);
        }
    }, 'Actions');
    
    update_calculation_button_state(frm);
}

function update_calculation_button_state(frm) {
    const button = frm.custom_buttons && frm.custom_buttons['Calculate Gross Amount'];
    if (button) {
        if (can_calculate_amount(frm)) {
            button.removeClass('btn-default').addClass('btn-primary');
            button.prop('disabled', false);
        } else {
            button.removeClass('btn-primary').addClass('btn-default');
            button.prop('disabled', true);
        }
    }
}

function toggle_calculation_button(frm) {
    if (should_show_calculation_button(frm)) {
        if (!frm.custom_buttons || !frm.custom_buttons['Calculate Gross Amount']) {
            add_calculation_button(frm);
        } else {
            update_calculation_button_state(frm);
        }
    } else {
        if (frm.custom_buttons && frm.custom_buttons['Calculate Gross Amount']) {
            frm.remove_custom_button('Calculate Gross Amount');
        }
    }
}

function calculate_agricultural_gross_purchase_amount(frm) {
    if (!can_calculate_agricultural_amount(frm)) {
        frappe.msgprint('Please fill in all required fields: Area, Cadastral District, Quality Groups, and Purpose of Land Plot');
        return;
    }
    
    frappe.show_alert({
        message: 'Calculating...',
        indicator: 'blue'
    });
    
    frappe.call({
        method: 'jey_erp.asset.calculate_gross_purchase_amount',
        args: {
            area_value: frm.doc.area,
            cadastral_district_name: frm.doc.cadastral_district_name,
            quality_groups: frm.doc.quality_groups,
            agricultural_land_purpose: frm.doc.agricultural_land_purpose,
            agricultural_purpose_name: frm.doc.agricultural_purpose
        },
        callback: function(r) {
            if (r.message) {
                frm.set_value('gross_purchase_amount', r.message.gross_purchase_amount);
                
                const details = r.message.calculation_details;
                let unit_text = details.original_unit || 'units';
                
                frappe.msgprint({
                    title: 'Agricultural Land Calculation Completed',
                    message: `
                        <p><strong>Formula:</strong> ${details.formula}</p>
                        <p><strong>Result:</strong> ${r.message.gross_purchase_amount.toFixed(2)}</p>
                        <hr>
                        <p><strong>Calculation Details:</strong></p>
                        <ul>
                            <li>Original Area: ${details.original_value} ${unit_text}</li>
                            <li>Converted to Hectares: ${details.hectare}</li>
                            <li>Score: ${details.score}</li>
                            <li>Markup: ${details.markup}</li>
                        </ul>
                    `,
                    indicator: 'green'
                });
                
                frm.refresh_field('gross_purchase_amount');
            }
        },
        error: function(r) {
            frappe.msgprint({
                title: 'Calculation Error',
                message: r.message || 'An error occurred during calculation',
                indicator: 'red'
            });
        }
    });
}

function calculate_industrial_gross_purchase_amount(frm) {
    if (!can_calculate_industrial_amount(frm)) {
        frappe.msgprint('Please fill in all required fields: Area, Territorial Unit, and Purpose of Land Plot');
        return;
    }
    
    frappe.show_alert({
        message: 'Calculating...',
        indicator: 'blue'
    });
    
    frappe.call({
        method: 'jey_erp.asset.calculate_industrial_gross_purchase_amount',
        args: {
            area_sqm: frm.doc.area,
            territorial_unit_name: frm.doc.territorial_unit_name,
            industrial_land_purpose: frm.doc.industrial_land_purpose
        },
        callback: function(r) {
            if (r.message) {
                frm.set_value('gross_purchase_amount', r.message.gross_purchase_amount);
                
                const details = r.message.calculation_details;
                let calculation_parts_html = '';
                
                details.calculation_parts.forEach((part, index) => {
                    calculation_parts_html += `<li>Part ${index + 1}: ${part.formula}</li>`;
                });
                
                frappe.msgprint({
                    title: 'Industrial Land Calculation Completed',
                    message: `
                        <p><strong>Formula:</strong> ${details.formula}</p>
                        <p><strong>Result:</strong> ${r.message.gross_purchase_amount.toFixed(2)}</p>
                        <hr>
                        <p><strong>Calculation Details:</strong></p>
                        <ul>
                            <li>Area: ${frm.doc.area} Sq.m</li>
                            <li>Score up to 10,000 Sq.m: ${details.scores_used.up_to_10000}</li>
                            <li>Score above 10,000 Sq.m: ${details.scores_used.above_10000}</li>
                        </ul>
                        <p><strong>Calculation Parts:</strong></p>
                        <ul>
                            ${calculation_parts_html}
                        </ul>
                    `,
                    indicator: 'green'
                });
                
                frm.refresh_field('gross_purchase_amount');
            }
        },
        error: function(r) {
            frappe.msgprint({
                title: 'Calculation Error',
                message: r.message || 'An error occurred during calculation',
                indicator: 'red'
            });
        }
    });
}