import frappe

@frappe.whitelist(allow_guest=True)  # allow_guest=True if you want unauthenticated access
def lead_magnet(email,subject,content):
    try:
        # Check if a Lead with the given email exists
        lead = frappe.db.get_value("Lead", {"email_id": email}, "name",)

        if not lead:
            # Create a new Lead if not found
            lead_doc = frappe.get_doc({
                "doctype": "Lead",
                "first_name": "Unknown",
                "email_id": email,
                "status": "Open"
            })
            lead_doc.insert(ignore_permissions=True)
            frappe.db.commit()
            lead = lead_doc.name  # Get the newly created lead name

        # Create a Communication linked to the Lead
        communication = frappe.get_doc({
            "doctype": "Communication",
            "subject": subject,
            "content": content,
            "sender": email,
            "sent_or_received": "Received",
            "reference_doctype": "Lead",
            "reference_name": lead  # Link to the existing or new lead
        })
        communication.insert(ignore_permissions=True)
        frappe.db.commit()

        return {"success": True, "message": "Lead and communication recorded successfully", "lead": lead}

    except Exception as e:
        frappe.log_error(f"Lead Creation Error: {str(e)}", "Lead API Error")
        return {"success": False, "error": str(e)}




@frappe.whitelist(allow_guest=True)
def contact_form():
    try:
        # Extract data from the form submission
        data = frappe.form_dict  # Get request parameters
        first_name = data.get("first_name")
        last_name = data.get("last_name")
        business_name = data.get("business_name")
        email = data.get("email")
        phone = data.get("phone")
        subject = data.get("subject")
        content = data.get("content")
        department = data.get("department")

        if not email or not subject or not content:
            return {"success": False, "error": "Missing required parameters"}

        reference_doctype = "Contact"
        reference_name = None

        if department and department.lower() == "sales":
            # Look for a Lead with the given email
            lead_name = frappe.db.get_value("Lead", {"email_id": email}, "name")
            if lead_name:
                # Update Lead status to 'Open'
                frappe.db.set_value("Lead", lead_name, "status", "Open")
                reference_doctype = "Lead"
                reference_name = lead_name
            else:
                # Create a new Lead if not found
                lead_doc = frappe.get_doc({
                    "doctype": "Lead",
                    "first_name": first_name or "Unknown",
                    "last_name": last_name or "",
                    "company_name": business_name or "",
                    "email_id": email,
                    "phone": phone or "",
                    "status": "Open"
                })
                lead_doc.insert(ignore_permissions=True)
                reference_doctype = "Lead"
                reference_name = lead_doc.name
        
        if not reference_name:
            # Check if a Contact with the given email exists by querying the Contact Email doctype
            contact_email = frappe.db.get_value("Contact Email", {"email_id": email}, "parent")

            if not contact_email:
                # Create a new Contact if not found
                contact_doc = frappe.get_doc({
                    "doctype": "Contact",
                    "first_name": first_name or "Unknown",
                    "status": "Open",
                    "email_ids": [
                        {
                            "email_id": email,
                        }
                    ]
                })
                contact_doc.insert(ignore_permissions=True)
                reference_name = contact_doc.name
            else:
                # If contact exists, we ensure the email is linked, but only if it isn't already
                contact_doc = frappe.get_doc("Contact", contact_email)
                existing_email = frappe.db.exists("Contact Email", {"parent": contact_doc.name, "email_id": email})

                if not existing_email:
                    contact_doc.append("email_ids", {
                        "email_id": email,
                        "is_primary": 1  # Optional: Make it the primary email if needed
                    })
                    contact_doc.save(ignore_permissions=True)

                reference_name = contact_doc.name
        
        if department and department.lower() == "support":
            # Create an Issue and link it to the Contact
            issue_doc = frappe.get_doc({
                "doctype": "Issue",
                "subject": subject,
                "description": content,
                "raised_by": email,
                "contact": reference_name
            })
            issue_doc.insert(ignore_permissions=True)
            
            reference_doctype = "Issue"
            reference_name = issue_doc.name

        # Create a Communication linked to the determined reference doctype
        communication = frappe.get_doc({
            "doctype": "Communication",
            "subject": subject,
            "content": content,
            "sender": email,
            "sent_or_received": "Received",
            "reference_doctype": reference_doctype,
            "reference_name": reference_name
        })
        communication.insert(ignore_permissions=True)

        return {"success": True, "message": "Lead, Contact, or Issue and communication recorded successfully", "reference_doctype": reference_doctype, "reference_name": reference_name}

    except Exception as e:
        frappe.log_error(f"Contact Form Error: {str(e)}", "Contact Form API Error")
        return {"success": False, "error": str(e)}
