import frappe
from custom_ui.services.email_service import EmailService

def on_submit(doc, method):
    print("DEBUG: On Submit Triggered for Sales Invoice:", doc.name)
    
    # Send invoice email to customer
    try:
        print("DEBUG: Preparing to send invoice email for", doc.name)
        EmailService.send_invoice_email(doc.name)
        print("DEBUG: Invoice email sent successfully for", doc.name)
        frappe.set_value("Project", doc.project, "invoice_status", "Invoice Sent")
    except Exception as e:
        print(f"ERROR: Failed to send invoice email: {str(e)}")
        # Don't raise the exception - we don't want to block the invoice submission
        frappe.log_error(f"Failed to send invoice email for {doc.name}: {str(e)}", "Invoice Email Error")
        
def after_insert(doc, method):
    print("DEBUG: After Insert Triggered for Sales Invoice:", doc.name)
    # Additional logic can be added here if needed after invoice creation
    frappe.set_value("Project", doc.project, "invoice_status", "Invoice Created")
    