# Файл: jey_erp/custom/sales_order_vat.py

import frappe
import json
from frappe.utils import flt

def set_vat_fields_permissions(doc, method=None):
    """
    Set VAT fields permissions based on Item Tax Template
    Called on Sales Order validate/before_save
    """
    if doc.doctype != "Sales Order":
        return
    
    for item in doc.get("items", []):
        set_item_vat_permissions(item)

def set_item_vat_permissions(item):
    """
    Set VAT field permissions for individual item based on tax template
    """
    if not item.get("item_code"):
        return
    
    # Get item tax template
    item_tax_template = item.get("item_tax_template")
    
    # If no tax template in item row, get from Item master
    if not item_tax_template:
        try:
            item_doc = frappe.get_doc("Item", item.item_code)
            item_tax_template = item_doc.get("item_tax_template")
        except Exception:
            pass
    
    # Default state - all fields disabled
    vat_permissions = {
        'vat_18_percent_with_amount': False,
        'vat_amount': False,
        'vat_0_percent_with_amount': False, 
        'amount_without_vat': False,
        'vat_free_amount': False
    }

    if item_tax_template == "ƏDV 18%":
        # 18% VAT template
        vat_permissions['vat_18_percent_with_amount'] = True
        vat_permissions['vat_amount'] = True  # Показывать VAT Amount только для 18%
    elif item_tax_template == "ƏDV 0%":
        # 0% VAT template
        vat_permissions['vat_0_percent_with_amount'] = True
    elif item_tax_template == "ƏDV-dən azadolma":
        # VAT exempt template
        vat_permissions['vat_free_amount'] = True
    elif not item_tax_template:
        # No tax template - not subject to VAT
        vat_permissions['amount_without_vat'] = True
    else:
        # Any other template - default to amount_without_vat
        vat_permissions['amount_without_vat'] = True
    
    # Apply permissions to item
    apply_vat_permissions_to_item(item, vat_permissions)

def apply_vat_permissions_to_item(item, permissions):
    """
    Apply VAT field permissions to item and clear disabled fields
    """
    # Clear values for disabled fields
    for field, enabled in permissions.items():
        if not enabled and hasattr(item, field):
            setattr(item, field, 0.0)
    
    # Calculate amounts for enabled fields
    item_amount = flt(item.get("amount", 0))
    
    for field, enabled in permissions.items():
        if enabled and hasattr(item, field):
            # Only auto-fill if field is empty (except vat_amount which is always calculated)
            current_value = getattr(item, field, 0)
            if not current_value or current_value == 0 or field == 'vat_amount':
                if field == 'vat_18_percent_with_amount':
                    # For 18% VAT: Amount + 18%
                    vat_amount = item_amount * 1.18
                    setattr(item, field, vat_amount)
                elif field == 'vat_amount':
                    # Calculate VAT Amount: vat_18_percent_with_amount - amount
                    vat_18_total = flt(item.get('vat_18_percent_with_amount', 0))
                    if vat_18_total == 0:
                        # If vat_18_percent_with_amount is not set, calculate it first
                        vat_18_total = item_amount * 1.18
                        setattr(item, 'vat_18_percent_with_amount', vat_18_total)
                    vat_only = vat_18_total - item_amount
                    setattr(item, field, vat_only)
                elif field == 'vat_0_percent_with_amount':
                    # For 0% VAT: just the amount
                    setattr(item, field, item_amount)
                elif field == 'amount_without_vat':
                    # For VAT exempt: auto-fill with item amount
                    setattr(item, field, item_amount)
                elif field == 'vat_free_amount':
                    # For "not subject to VAT": auto-fill with item amount
                    setattr(item, field, item_amount)
    
    # Store permissions in item for client-side use
    item.vat_permissions = json.dumps(permissions)

def calculate_vat_amount(item):
    """
    Calculate VAT Amount whenever vat_18_percent_with_amount or amount changes
    This function can be called from hooks or client-side triggers
    """
    if hasattr(item, 'vat_18_percent_with_amount') and hasattr(item, 'amount'):
        vat_18_total = flt(item.get('vat_18_percent_with_amount', 0))
        item_amount = flt(item.get('amount', 0))
        
        if vat_18_total > 0 and item_amount > 0:
            vat_only = vat_18_total - item_amount
            setattr(item, 'vat_amount', vat_only)
        else:
            setattr(item, 'vat_amount', 0.0)

@frappe.whitelist()
def get_vat_permissions_for_item(item_code, item_tax_template=None):
    """
    API method to get VAT permissions for an item
    Called from client side when item changes
    """
    # Create temporary item object
    temp_item = frappe._dict({
        'item_code': item_code,
        'item_tax_template': item_tax_template
    })
    
    # Calculate permissions
    set_item_vat_permissions(temp_item)
    
    # Return permissions
    if hasattr(temp_item, 'vat_permissions'):
        return json.loads(temp_item.vat_permissions)
    else:
        # Default fallback
        return {
            'vat_18_percent_with_amount': False,
            'vat_amount': False,
            'vat_0_percent_with_amount': False,
            'amount_without_vat': True,
            'vat_free_amount': False
        }

@frappe.whitelist()
def calculate_vat_amount_api(item_data):
    """
    API method to calculate VAT amount from client side
    """
    try:
        if isinstance(item_data, str):
            item_data = json.loads(item_data)
        
        vat_18_total = flt(item_data.get('vat_18_percent_with_amount', 0))
        item_amount = flt(item_data.get('amount', 0))
        
        if vat_18_total > 0 and item_amount > 0:
            vat_only = vat_18_total - item_amount
            return vat_only
        else:
            return 0.0
    except Exception as e:
        frappe.log_error(f"Error calculating VAT amount: {str(e)}")
        return 0.0

# Hook functions for automatic calculation
def on_sales_order_item_validate(doc, method=None):
    """
    Hook to be called on Sales Order Item validate
    Automatically calculates VAT amount when item is saved
    """
    if hasattr(doc, 'vat_18_percent_with_amount') and hasattr(doc, 'amount'):
        calculate_vat_amount(doc)

def on_sales_order_validate(doc, method=None):
    """
    Hook to be called on Sales Order validate
    Ensures all VAT calculations are correct
    """
    if doc.doctype != "Sales Order":
        return
    
    for item in doc.get("items", []):
        # Set permissions first
        set_item_vat_permissions(item)
        
        # Then calculate VAT amount if needed
        if hasattr(item, 'vat_18_percent_with_amount') and hasattr(item, 'amount'):
            calculate_vat_amount(item)