import sqlite3
from http.server import HTTPServer, BaseHTTPRequestHandler
import json
import urllib.parse

PORT = 8083
DB_FILE = 'leads.db'

# Initialize Database
def init_db():
    conn = sqlite3.connect(DB_FILE)
    c = conn.cursor()
    c.execute('''CREATE TABLE IF NOT EXISTS leads
                 (id INTEGER PRIMARY KEY AUTOINCREMENT,
                  nome TEXT,
                  email TEXT,
                  whatsapp TEXT,
                  resumo TEXT,
                  created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP)''')
    conn.commit()
    conn.close()
    print("Banco de dados inicializado.")

class RequestHandler(BaseHTTPRequestHandler):
    def _set_headers(self, status=200):
        self.send_response(status)
        self.send_header('Content-type', 'application/json')
        self.send_header('Access-Control-Allow-Origin', '*') # Allow CORS
        self.send_header('Access-Control-Allow-Methods', 'POST, OPTIONS')
        self.send_header('Access-Control-Allow-Headers', 'Content-Type')
        self.end_headers()

    def do_OPTIONS(self):
        self._set_headers()

    def do_POST(self):
        if self.path == '/submit':
            content_length = int(self.headers['Content-Length'])
            post_data = self.rfile.read(content_length)
            
            try:
                data = json.loads(post_data.decode('utf-8'))
                
                nome = data.get('nome')
                email = data.get('email')
                whatsapp = data.get('whatsapp')
                resumo = data.get('resumo')
                
                if not nome or not email:
                    self._set_headers(400)
                    self.wfile.write(json.dumps({'error': 'Nome e Email são obrigatórios'}).encode('utf-8'))
                    return

                # Save to DB
                conn = sqlite3.connect(DB_FILE)
                c = conn.cursor()
                c.execute("INSERT INTO leads (nome, email, whatsapp, resumo) VALUES (?, ?, ?, ?)",
                          (nome, email, whatsapp, resumo))
                conn.commit()
                conn.close()
                
                print(f"Novo Lead: {nome} ({email})")
                
                self._set_headers(200)
                self.wfile.write(json.dumps({'message': 'Lead salvo com sucesso!'}).encode('utf-8'))
                
            except Exception as e:
                print(f"Erro: {e}")
                self._set_headers(500)
                self.wfile.write(json.dumps({'error': str(e)}).encode('utf-8'))
        else:
            self._set_headers(404)

if __name__ == '__main__':
    init_db()
    server_address = ('0.0.0.0', PORT)
    httpd = HTTPServer(server_address, RequestHandler)
    print(f"Backend Python rodando na porta {PORT}...")
    httpd.serve_forever()
