import os
import requests
from django.conf import settings

def send_telegram_message(text):
    token = getattr(settings, 'TELEGRAM_BOT_TOKEN', None)
    chat_id = getattr(settings, 'TELEGRAM_CHAT_ID', None)
    if not token or not chat_id:
        return
    url = f"https://api.telegram.org/bot{token}/sendMessage"
    payload = {'chat_id': chat_id, 'text': text, 'parse_mode': 'HTML'}
    try:
        requests.post(url, data=payload, timeout=5)
    except Exception:
        pass

def notify_contact_message(contact):
    text = f"📩 <b>New Contact Message</b>\n\n<b>Name:</b> {contact.name}\n<b>Email:</b> {contact.email}\n<b>Message:</b> {contact.message}"
    send_telegram_message(text)

def notify_submission(contact):
    text = f"📝 <b>New Article Submission</b>\n\n<b>Name:</b> {contact.name}\n<b>Email:</b> {contact.email}"
    send_telegram_message(text)

def notify_store_order(order):
    from html import escape
    items = ', '.join(f"{i.quantity}× {i.product.title if i.product else 'item'}" for i in order.items.all())
    text = (f"🛍️ <b>New Store Order!</b>\n\n<b>Order ID:</b> {order.id}\n<b>Amount:</b> ৳{order.total_amount}\n"
            f"<b>Name:</b> {escape(order.name)}\n<b>Phone:</b> {escape(order.phone)}"
            f"{' / ' + escape(order.alt_phone) if order.alt_phone else ''}\n"
            f"<b>Address:</b> {escape(order.location)}\n<b>Items:</b> {escape(items)}")
    send_telegram_message(text)

def notify_visitor_stats(total_visitors, active_today, total_time_minutes):
    text = f"📊 <b>Daily Visitor Stats</b>\n\n<b>Total Visitors:</b> {total_visitors}\n<b>Active Today:</b> {active_today}\n<b>Total Time (min):</b> {total_time_minutes:.2f}"
    send_telegram_message(text)
