import requests
import json
import time
from datetime import datetime

class WhatsAppAutomation:
    def __init__(self, api_key, phone_number_id):
        self.api_key = api_key
        self.phone_number_id = phone_number_id
        self.base_url = f"https://graph.facebook.com/v18.0/{phone_number_id}"
        self.headers = {
            "Authorization": f"Bearer {api_key}",
            "Content-Type": "application/json"
        }
    
    def send_message(self, to_number, message):
        """Send text message"""
        url = f"{self.base_url}/messages"
        payload = {
            "messaging_product": "whatsapp",
            "recipient_type": "individual",
            "to": to_number,
            "type": "text",
            "text": {"body": message}
        }
        
        try:
            response = requests.post(url, headers=self.headers, json=payload)
            return response.json()
        except Exception as e:
            return {"error": str(e)}
    
    def send_template_message(self, to_number, template_name, language="en", components=None):
        """Send template message"""
        url = f"{self.base_url}/messages"
        payload = {
            "messaging_product": "whatsapp",
            "to": to_number,
            "type": "template",
            "template": {
                "name": template_name,
                "language": {"code": language}
            }
        }
        
        if components:
            payload["template"]["components"] = components
        
        try:
            response = requests.post(url, headers=self.headers, json=payload)
            return response.json()
        except Exception as e:
            return {"error": str(e)}
    
    def send_welcome_message(self, to_number, customer_name):
        """Send welcome message to new customer"""
        message = f"""Assalamu Alaikum {customer_name}! 👋

Welcome to Digital Silk Route!

How can we help you today?
1️⃣ View Products/Services
2️⃣ Get a Quote
3️⃣ Speak to Support
4️⃣ Book a Consultation

Reply with the number or type your question."""
        
        return self.send_message(to_number, message)
    
    def send_order_confirmation(self, to_number, customer_name, order_id, amount):
        """Send order confirmation"""
        message = f"""✅ Order Confirmed!

Dear {customer_name},

Your order #{order_id} has been confirmed.
Amount: Rs. {amount}

We'll notify you when it's ready for delivery.

Track: https://digitalsilkroute.com/track/{order_id}

Thank you for choosing us! 🙏"""
        
        return self.send_message(to_number, message)
    
    def send_payment_reminder(self, to_number, customer_name, amount, due_date):
        """Send payment reminder"""
        message = f"""💳 Payment Reminder

Dear {customer_name},

This is a friendly reminder that payment of Rs. {amount} is due on {due_date}.

Please make payment to:
Bank: [Your Bank]
Account: [Your Account]
IBAN: [Your IBAN]

Or pay online: https://digitalsilkroute.com/pay

If already paid, please ignore. Thank you! 🙏"""
        
        return self.send_message(to_number, message)
    
    def send_broadcast(self, numbers, message, delay=1):
        """Send broadcast message to multiple numbers"""
        results = []
        for number in numbers:
            result = self.send_message(number, message)
            results.append({"number": number, "result": result})
            time.sleep(delay)  # Rate limiting
        return results
    
    def setup_auto_reply(self, incoming_message):
        """Auto-reply logic"""
        message_lower = incoming_message.lower()
        
        if any(word in message_lower for word in ["hi", "hello", "assalam", "hey"]):
            return "Assalamu Alaikum! Welcome to Digital Silk Route. How can we help you today?"
        
        elif any(word in message_lower for word in ["price", "cost", "how much", "rate"]):
            return "We have different packages starting from Rs. 25,000/month. Can you tell us what service you need so we can give you an exact quote?"
        
        elif any(word in message_lower for word in ["software", "website", "app", "development"]):
            return "We offer: 1) Website Development 2) Mobile Apps 3) Software Solutions 4) AI Automation. Which one interests you?"
        
        elif any(word in message_lower for word in ["crypto", "trading", "bitcoin", "btc"]):
            return "We have crypto trading bots, portfolio trackers, and educational programs. Visit https://digitalsilkroute.com/programs/crypto-trading for details!"
        
        elif any(word in message_lower for word in ["contact", "phone", "call", "speak"]):
            return "You can reach us at:\n📞 +923019551794\n📧 ali@digitalsilkroute.com\n🌐 https://digitalsilkroute.com\n\nOr we can schedule a call. What time works for you?"
        
        elif any(word in message_lower for word in ["thank", "thanks", "shukria", "jazak"]):
            return "You're welcome! 😊 We're always here to help. Have a great day!"
        
        else:
            return "Thank you for your message. Our team will get back to you within 24 hours. For urgent matters, call +923019551794."

# Example usage
if __name__ == "__main__":
    # Initialize (replace with your actual API credentials)
    wa = WhatsAppAutomation(
        api_key="YOUR_API_KEY",
        phone_number_id="YOUR_PHONE_NUMBER_ID"
    )
    
    # Send welcome message
    result = wa.send_welcome_message("+923001234567", "Ahmed")
    print("Welcome message sent:", result)
    
    # Send order confirmation
    result = wa.send_order_confirmation("+923001234567", "Ahmed", "DSR-2024-001", "50,000")
    print("Order confirmation sent:", result)
    
    # Test auto-reply
    test_messages = [
        "Hi there",
        "How much for a website?",
        "Do you have crypto services?",
        "Thanks for your help"
    ]
    
    for msg in test_messages:
        reply = wa.setup_auto_reply(msg)
        print(f"Incoming: {msg}")
        print(f"Reply: {reply}\n")
