"""
LeadSquared CRM Integration Module
This module contains functions to send lead data to LeadSquared CRM
"""

import requests
import json


class LeadSquaredAPI:
    """
    LeadSquared API Integration Class
    
    Usage:
        ls = LeadSquaredAPI(access_key="your_access_key", secret_key="your_secret_key")
        ls.send_basic_lead(student_name, parent_name, mobile, email, grade, source)
    """
    
    def __init__(self, access_key, secret_key):
        """
        Initialize LeadSquared API with credentials
        
        Args:
            access_key (str): LeadSquared access key
            secret_key (str): LeadSquared secret key
        """
        self.access_key = access_key
        self.secret_key = secret_key
        self.base_url = "https://api-in21.leadsquared.com/v2/LeadManagement.svc/Lead.Capture"
        self.headers = {
            'Content-Type': 'application/json'
        }
    
    def _send_request(self, payload):
        """
        Send request to LeadSquared API
        
        Args:
            payload (list): List of lead attributes
            
        Returns:
            Response object from requests
        """
        url = f"{self.base_url}?accessKey={self.access_key}&secretKey={self.secret_key}"
        
        try:
            response = requests.post(url, headers=self.headers, data=json.dumps(payload))
            return response
        except Exception as e:
            print(f"Error sending lead to LeadSquared: {e}")
            return None
    
    def send_basic_lead(self, student_name, parent_name, mobile, email, admission_grade, source, academic_year="2025-2026"):
        """
        Send basic lead information to LeadSquared
        
        Args:
            student_name (str): Student's first name
            parent_name (str): Parent's name
            mobile (str): Phone number
            email (str): Email address
            admission_grade (str): Grade/Class for admission
            source (str): Lead source
            academic_year (str): Academic year (default: "2025-2026")
            
        Returns:
            Response object
        """
        payload = [
            {
                "Attribute": "FirstName",
                "Value": student_name
            },
            {
                "Attribute": "mx_Parent_Name",
                "Value": parent_name
            },
            {
                "Attribute": "Phone",
                "Value": mobile
            },
            {
                "Attribute": "EmailAddress",
                "Value": email
            },
            {
                "Attribute": "mx_Admission_for_Grade",
                "Value": admission_grade
            },
            {
                "Attribute": "Source",
                "Value": source
            },
            {
                "Attribute": "SearchBy",
                "Value": "Phone"
            },
            {
                "Attribute": "mx_Academic_Year",
                "Value": academic_year
            }
        ]
        
        return self._send_request(payload)
    
    def send_lead_with_utm(self, student_name, parent_name, mobile, email, admission_grade, 
                          source, gclid=None, campaign=None, content=None, 
                          medium=None, term=None, academic_year="2025-2026"):
        """
        Send lead with UTM tracking parameters to LeadSquared
        
        Args:
            student_name (str): Student's first name
            parent_name (str): Parent's name
            mobile (str): Phone number
            email (str): Email address
            admission_grade (str): Grade/Class for admission
            source (str): Lead source
            gclid (str, optional): Google Click ID
            campaign (str, optional): UTM campaign
            content (str, optional): UTM content
            medium (str, optional): UTM medium
            term (str, optional): UTM term
            academic_year (str): Academic year (default: "2025-2026")
            
        Returns:
            Response object
        """
        payload = [
            {
                "Attribute": "FirstName",
                "Value": student_name
            },
            {
                "Attribute": "mx_Parent_Name",
                "Value": parent_name
            },
            {
                "Attribute": "Phone",
                "Value": mobile
            },
            {
                "Attribute": "EmailAddress",
                "Value": email
            },
            {
                "Attribute": "mx_Admission_for_Grade",
                "Value": admission_grade
            },
            {
                "Attribute": "mx_GCLID",
                "Value": gclid
            },
            {
                "Attribute": "Source",
                "Value": source
            },
            {
                "Attribute": "SourceCampaign",
                "Value": campaign
            },
            {
                "Attribute": "SourceContent",
                "Value": content
            },
            {
                "Attribute": "SourceMedium",
                "Value": medium
            },
            {
                "Attribute": "mx_utm_term",
                "Value": term
            },
            {
                "Attribute": "SearchBy",
                "Value": "Phone"
            },
            {
                "Attribute": "mx_Academic_Year",
                "Value": academic_year
            }
        ]
        
        return self._send_request(payload)


# Standalone function (if you prefer not to use the class)
def send_lead_to_leadsquared(access_key, secret_key, student_name, parent_name, 
                             mobile, email, admission_grade, source, 
                             academic_year="2025-2026"):
    """
    Standalone function to send lead to LeadSquared
    
    Args:
        access_key (str): LeadSquared access key
        secret_key (str): LeadSquared secret key
        student_name (str): Student's first name
        parent_name (str): Parent's name
        mobile (str): Phone number
        email (str): Email address
        admission_grade (str): Grade/Class for admission
        source (str): Lead source
        academic_year (str): Academic year (default: "2025-2026")
        
    Returns:
        Response object
    """
    url = f"https://api-in21.leadsquared.com/v2/LeadManagement.svc/Lead.Capture?accessKey={access_key}&secretKey={secret_key}"
    
    payload = json.dumps([
        {
            "Attribute": "FirstName",
            "Value": student_name
        },
        {
            "Attribute": "mx_Parent_Name",
            "Value": parent_name
        },
        {
            "Attribute": "Phone",
            "Value": mobile
        },
        {
            "Attribute": "EmailAddress",
            "Value": email
        },
        {
            "Attribute": "mx_Admission_for_Grade",
            "Value": admission_grade
        },
        {
            "Attribute": "Source",
            "Value": source
        },
        {
            "Attribute": "SearchBy",
            "Value": "Phone"
        },
        {
            "Attribute": "mx_Academic_Year",
            "Value": academic_year
        }
    ])
    
    headers = {
        'Content-Type': 'application/json'
    }
    
    try:
        response = requests.post(url, headers=headers, data=payload)
        return response
    except Exception as e:
        print(f"Error sending lead to LeadSquared: {e}")
        return None


# Example Usage
if __name__ == "__main__":
    # Replace with your actual credentials
    ACCESS_KEY = "u$r4c361c1c755679105a84d6633d4c6dd9"
    SECRET_KEY = "301aa26e6a57dae1df02182ae50bfd83c254c41a"
    
    # Example 1: Using the class (recommended)
    ls = LeadSquaredAPI(ACCESS_KEY, SECRET_KEY)
    
    response = ls.send_basic_lead(
        student_name="John Doe",
        parent_name="Jane Doe",
        mobile="1234567890",
        email="john@example.com",
        admission_grade="Grade 5",
        source="Website"
    )
    
    if response:
        print(f"Lead sent successfully! Status: {response.status_code}")
        print(f"Response: {response.text}")
    
    # Example 2: Using the class with UTM parameters
    response_utm = ls.send_lead_with_utm(
        student_name="John Doe",
        parent_name="Jane Doe",
        mobile="1234567890",
        email="john@example.com",
        admission_grade="Grade 5",
        source="Google Ads",
        gclid="abc123xyz",
        campaign="summer_admission",
        content="ad_variant_1",
        medium="cpc",
        term="best school"
    )
    
    if response_utm:
        print(f"Lead with UTM sent successfully! Status: {response_utm.status_code}")
    
    # Example 3: Using standalone function
    response_standalone = send_lead_to_leadsquared(
        access_key=ACCESS_KEY,
        secret_key=SECRET_KEY,
        student_name="John Doe",
        parent_name="Jane Doe",
        mobile="1234567890",
        email="john@example.com",
        admission_grade="Grade 5",
        source="Website"
    )
    
    if response_standalone:
        print(f"Standalone function worked! Status: {response_standalone.status_code}")







