import os
import json
import urllib.request
import urllib.parse
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from http.server import SimpleHTTPRequestHandler
import socketserver
from datetime import datetime

# Simple .env loader
def load_dotenv():
    env_path = os.path.join(os.path.dirname(__file__), '.env')
    if os.path.exists(env_path):
        with open(env_path, 'r', encoding='utf-8') as f:
            for line in f:
                line = line.strip()
                if line and not line.startswith('#') and '=' in line:
                    key, val = line.split('=', 1)
                    # Strip quotes if present
                    val = val.strip().strip('"').strip("'")
                    os.environ[key.strip()] = val
        print("Loaded environment variables from .env")
    else:
        print("No .env file found, using system environment variables.")

load_dotenv()

PORT = 8000

class DepoStoreHandler(SimpleHTTPRequestHandler):
    def do_OPTIONS(self):
        self.send_response(200)
        self.send_header('Access-Control-Allow-Origin', '*')
        self.send_header('Access-Control-Allow-Methods', 'POST, GET, OPTIONS')
        self.send_header('Access-Control-Allow-Headers', 'Content-Type, Authorization')
        self.end_headers()

    def do_POST(self):
        if self.path == '/api/order':
            content_length = int(self.headers.get('Content-Length', 0))
            post_data = self.rfile.read(content_length)
            
            try:
                order_data = json.loads(post_data.decode('utf-8'))
                print("Received order:", json.dumps(order_data, indent=2, ensure_ascii=False))
                
                # Process notifications
                telegram_ok = self.send_telegram_notification(order_data)
                email_ok = self.send_email_notification(order_data)
                
                # Save order to a local log file as backup
                self.log_order_to_file(order_data)
                
                response_data = {
                    "success": True,
                    "order_id": order_data.get("orderNo"),
                    "telegram_sent": telegram_ok,
                    "email_sent": email_ok
                }
                
                self.send_response(200)
                self.send_header('Content-Type', 'application/json')
                self.send_header('Access-Control-Allow-Origin', '*')
                self.end_headers()
                self.wfile.write(json.dumps(response_data).encode('utf-8'))
            except Exception as e:
                print("Error processing order POST:", e)
                self.send_response(500)
                self.send_header('Content-Type', 'application/json')
                self.send_header('Access-Control-Allow-Origin', '*')
                self.end_headers()
                self.wfile.write(json.dumps({"success": False, "error": str(e)}).encode('utf-8'))
        else:
            self.send_response(404)
            self.end_headers()

    def log_order_to_file(self, order):
        log_path = os.path.join(os.path.dirname(__file__), 'orders.log')
        timestamp = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
        with open(log_path, 'a', encoding='utf-8') as f:
            f.write(f"[{timestamp}] Order #{order.get('orderNo')} - {order.get('name')} - Total: {order.get('total')} {order.get('currency')}\n")
            f.write(json.dumps(order, ensure_ascii=False, indent=2) + "\n")
            f.write("="*50 + "\n")

    def send_telegram_notification(self, order):
        token = os.environ.get('TELEGRAM_BOT_TOKEN')
        chat_id = os.environ.get('TELEGRAM_CHAT_ID')
        
        if not token or token == 'YOUR_TELEGRAM_BOT_TOKEN' or not chat_id or chat_id == 'YOUR_TELEGRAM_CHAT_ID':
            print("Telegram credentials not configured. Skipping Telegram notification.")
            return False
            
        url = f"https://api.telegram.org/bot{token}/sendMessage"
        
        # Format products list
        products_text = ""
        for i, item in enumerate(order.get('items', []), 1):
            products_text += f"{i}. {item.get('title')} ({item.get('size')}) x{item.get('qty')} — {item.get('price')} {order.get('currency')}\n"
            
        payment_text = order.get('paymentMethod')
        if order.get('cardType'):
            payment_text += f" ({order.get('cardType')} - {order.get('cardNumberMasked')})"
            
        message = (
            f"📦 *Новый заказ #{order.get('orderNo')}*\n"
            f"📅 Дата: {order.get('date')}\n"
            f"👤 Клиент: {order.get('name')}\n"
            f"📞 Телефон: `{order.get('phone')}`\n"
            f"📧 Email: {order.get('email')}\n"
            f"📍 Адрес: {order.get('address')}\n"
            f"🚚 Доставка: {order.get('deliveryMethod')}\n"
            f"💳 Оплата: {payment_text}\n\n"
            f"*Товары:*\n{products_text}\n"
            f"💰 *Итого: {order.get('total')} {order.get('currency')}*"
        )
        
        data = urllib.parse.urlencode({
            'chat_id': chat_id,
            'text': message,
            'parse_mode': 'Markdown'
        }).encode('utf-8')
        
        try:
            import ssl
            context = ssl._create_unverified_context()
            req = urllib.request.Request(url, data=data)
            with urllib.request.urlopen(req, timeout=10, context=context) as response:
                res_body = response.read().decode('utf-8')
                res_json = json.loads(res_body)
                if res_json.get("ok"):
                    print("Telegram notification sent successfully.")
                    return True
                else:
                    print("Telegram Bot API returned error:", res_body)
                    return False
        except Exception as e:
            print("Failed to send Telegram notification:", e)
            return False

    def send_email_notification(self, order):
        smtp_host = os.environ.get('SMTP_HOST')
        smtp_port = os.environ.get('SMTP_PORT', '587')
        smtp_user = os.environ.get('SMTP_USER')
        smtp_password = os.environ.get('SMTP_PASSWORD')
        email_from = os.environ.get('EMAIL_FROM', 'hello@depo-store.example')
        
        email_to = order.get('email')
        if not email_to:
            print("No email provided in order. Skipping email notification.")
            return False
            
        if not smtp_host or not smtp_user or not smtp_password or smtp_user == 'your_email@gmail.com':
            print("SMTP credentials not configured. Skipping email notification.")
            return False
            
        # Create message container
        msg = MIMEMultipart('alternative')
        msg['Subject'] = f"Заказ #{order.get('orderNo')} принят на складе DEPO."
        msg['From'] = f"DEPO. Store <{smtp_user}>"
        msg['To'] = email_to
        
        # Build products table rows
        table_rows = ""
        for item in order.get('items', []):
            item_total = item.get('price', 0) * item.get('qty', 0)
            table_rows += f"""
            <tr>
                <td style="padding: 10px; border-bottom: 1px solid #D8D3C6; font-family: 'Courier New', Courier, monospace;">{item.get('title')} ({item.get('size')})</td>
                <td style="padding: 10px; border-bottom: 1px solid #D8D3C6; text-align: center;">{item.get('qty')}</td>
                <td style="padding: 10px; border-bottom: 1px solid #D8D3C6; text-align: right; font-weight: bold;">{item.get('price')} {order.get('currency')}</td>
                <td style="padding: 10px; border-bottom: 1px solid #D8D3C6; text-align: right; font-weight: bold;">{item_total} {order.get('currency')}</td>
            </tr>
            """
            
        payment_info = order.get('paymentMethod')
        if order.get('cardType'):
            payment_info += f" ({order.get('cardType')} {order.get('cardNumberMasked')})"
            
        # Design a beautiful HTML email
        html_content = f"""
        <!DOCTYPE html>
        <html>
        <head>
            <meta charset="utf-8">
            <style>
                body {{
                    font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif;
                    background-color: #F5F3EE;
                    color: #141414;
                    margin: 0;
                    padding: 20px;
                }}
                .container {{
                    max-width: 600px;
                    margin: 0 auto;
                    background: #F5F3EE;
                    border: 4px solid #141414;
                    padding: 30px;
                }}
                .header {{
                    text-align: center;
                    border-bottom: 4px solid #141414;
                    padding-bottom: 20px;
                    margin-bottom: 20px;
                }}
                .logo {{
                    font-size: 28px;
                    font-weight: 900;
                    letter-spacing: 0.05em;
                    text-decoration: none;
                    color: #141414;
                    font-family: "Courier New", Courier, monospace;
                }}
                .logo-dot {{
                    color: #B8341F;
                }}
                .stamp {{
                    display: inline-block;
                    border: 2px solid #B8341F;
                    color: #B8341F;
                    font-weight: bold;
                    text-transform: uppercase;
                    padding: 5px 12px;
                    transform: rotate(-2deg);
                    margin: 15px 0;
                    font-family: "Courier New", Courier, monospace;
                }}
                .info-table {{
                    width: 100%;
                    margin-bottom: 25px;
                    border-collapse: collapse;
                }}
                .info-table td {{
                    padding: 6px 0;
                    font-size: 14px;
                }}
                .info-label {{
                    color: #6B6862;
                    font-family: monospace;
                    width: 140px;
                }}
                .items-table {{
                    width: 100%;
                    border-collapse: collapse;
                    margin-bottom: 25px;
                }}
                .items-table th {{
                    background-color: #141414;
                    color: #F5F3EE;
                    padding: 10px;
                    font-size: 12px;
                    text-transform: uppercase;
                    letter-spacing: 0.05em;
                }}
                .total-row {{
                    font-size: 18px;
                    font-weight: bold;
                    background-color: #B8341F;
                    color: #F5F3EE;
                }}
                .footer {{
                    border-top: 1px dashed #141414;
                    padding-top: 20px;
                    margin-top: 30px;
                    font-size: 12px;
                    color: #6B6862;
                    text-align: center;
                    font-family: monospace;
                }}
            </style>
        </head>
        <body>
            <div class="container">
                <div class="header">
                    <span class="logo">DEPO<span class="logo-dot">.</span></span>
                    <div><span class="stamp">НАКЛАДНАЯ ОТГРУЗКИ #{order.get('orderNo')}</span></div>
                </div>
                
                <h3>Заказ принят в обработку</h3>
                <p>Мы подготовим его к отправке со склада №7 в течение 24 часов.</p>
                
                <table class="info-table">
                    <tr>
                        <td class="info-label">Получатель:</td>
                        <td><strong>{order.get('name')}</strong></td>
                    </tr>
                    <tr>
                        <td class="info-label">Телефон:</td>
                        <td>{order.get('phone')}</td>
                    </tr>
                    <tr>
                        <td class="info-label">Адрес доставки:</td>
                        <td>{order.get('address')}</td>
                    </tr>
                    <tr>
                        <td class="info-label">Способ:</td>
                        <td>{order.get('deliveryMethod')}</td>
                    </tr>
                    <tr>
                        <td class="info-label">Оплата:</td>
                        <td>{payment_info}</td>
                    </tr>
                    <tr>
                        <td class="info-label">Дата заказа:</td>
                        <td>{order.get('date')}</td>
                    </tr>
                </table>
                
                <table class="items-table">
                    <thead>
                        <tr>
                            <th style="text-align: left;">Товар</th>
                            <th>Кол-во</th>
                            <th style="text-align: right;">Цена</th>
                            <th style="text-align: right;">Итого</th>
                        </tr>
                    </thead>
                    <tbody>
                        {table_rows}
                        <tr class="total-row">
                            <td colspan="3" style="padding: 12px 10px;">ИТОГО:</td>
                            <td style="padding: 12px 10px; text-align: right;">{order.get('total')} {order.get('currency')}</td>
                        </tr>
                    </tbody>
                </table>
                
                <div class="footer">
                    <p>© 2026 DEPO. Учебный проект.</p>
                    <p>Ташкент, ул. Складская 7 | {smtp_user}</p>
                </div>
            </div>
        </body>
        </html>
        """
        
        msg.attach(MIMEText(html_content, 'html'))
        
        try:
            if smtp_port == '465':
                server = smtplib.SMTP_SSL(smtp_host, int(smtp_port))
            else:
                server = smtplib.SMTP(smtp_host, int(smtp_port))
                server.ehlo()
                if smtp_port == '587':
                    server.starttls()
                    server.ehlo()
            server.login(smtp_user, smtp_password)
            server.sendmail(smtp_user, [email_to], msg.as_string())
            server.close()
            print(f"Order email notification sent successfully to {email_to}.")
            return True
        except Exception as e:
            print("Failed to send email notification:", e)
            return False

# Custom server execution
if __name__ == '__main__':
    print(f"Starting server on http://localhost:{PORT}")
    socketserver.TCPServer.allow_reuse_address = True
    server = socketserver.TCPServer(("", PORT), DepoStoreHandler)
    try:
        server.serve_forever()
    except KeyboardInterrupt:
        pass
    finally:
        server.server_close()
        print("Server stopped.")
