import http.server
import socketserver
import json
import sqlite3
import os
import sys
os.chdir(os.path.dirname(os.path.abspath(__file__)))
import smtplib
from email.message import EmailMessage

PORT = 8000

# IMPORTANTE: Para que funcione el envío de correos, debes poner tu correo de Gmail
# y una "Contraseña de Aplicación" (App Password) generada en tu cuenta de Google.
GMAIL_USER = "tu_correo@gmail.com"
GMAIL_PASSWORD = "tu_contraseña_de_aplicacion"

def enviar_correo_bienvenida(destinatario, nombre):
    try:
        msg = EmailMessage()
        msg.set_content(f"Hola {nombre},\n\n¡Gracias por registrarte en Esencia Divina Spa!\n\nTu cuenta ha sido verificada con éxito. Te esperamos pronto para que disfrutes de nuestros servicios y te relajes como mereces.\n\nAtentamente,\nEl equipo de Esencia Divina Spa")
        msg['Subject'] = "¡Bienvenido a Esencia Divina Spa!"
        msg['From'] = f"Esencia Divina Spa <{GMAIL_USER}>"
        msg['To'] = destinatario
        
        server = smtplib.SMTP_SSL('smtp.gmail.com', 465)
        server.login(GMAIL_USER, GMAIL_PASSWORD)
        server.send_message(msg)
        server.quit()
        print(f"Correo de bienvenida enviado exitosamente a {destinatario}")
    except Exception as e:
        print(f"Aviso: No se pudo enviar el correo a {destinatario}. Asegúrate de configurar GMAIL_USER y GMAIL_PASSWORD en server.py. Error: {e}")

# Initialize Database
def init_db():
    conn = sqlite3.connect('spa.db')
    c = conn.cursor()
    c.execute('''
        CREATE TABLE IF NOT EXISTS users (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            name TEXT NOT NULL,
            age INTEGER NOT NULL,
            phone TEXT NOT NULL,
            email TEXT UNIQUE NOT NULL,
            password TEXT NOT NULL
        )
    ''')
    c.execute('''
        CREATE TABLE IF NOT EXISTS appointments (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            name TEXT NOT NULL,
            phone TEXT NOT NULL,
            date TEXT NOT NULL,
            service TEXT NOT NULL
        )
    ''')
    conn.commit()
    conn.close()

def enviar_notificacion_reserva(name, phone, date, service):
    # Opcion 1: Enviar por Correo Electrónico al dueño
    try:
        msg = EmailMessage()
        mensaje = f"¡Nueva Reserva!\n\nNombre: {name}\nTeléfono: {phone}\nFecha: {date}\nTratamiento: {service}"
        msg.set_content(mensaje)
        msg['Subject'] = "Nueva Cita Agendada - Esencia Divina Spa"
        msg['From'] = f"Esencia Divina Spa <{GMAIL_USER}>"
        msg['To'] = GMAIL_USER # Se lo envía al dueño
        
        server = smtplib.SMTP_SSL('smtp.gmail.com', 465)
        server.login(GMAIL_USER, GMAIL_PASSWORD)
        server.send_message(msg)
        server.quit()
        print("Notificación de reserva enviada al dueño.")
    except Exception as e:
        print(f"Error al enviar notificación: {e}")

    # Opcion 2: CallMeBot API (Descomentar para usar bot de WhatsApp)
    # import urllib.request
    # WHATSAPP_PHONE = "tu_numero_aqui"
    # WHATSAPP_APIKEY = "tu_apikey_aqui"
    # url_msg = urllib.parse.quote(mensaje)
    # url = f"https://api.callmebot.com/whatsapp.php?phone={WHATSAPP_PHONE}&text={url_msg}&apikey={WHATSAPP_APIKEY}"
    # try:
    #     urllib.request.urlopen(url)
    # except Exception:
    #     pass

class SpaRequestHandler(http.server.SimpleHTTPRequestHandler):
    def do_POST(self):
        if self.path == '/api/register':
            content_length = int(self.headers['Content-Length'])
            post_data = self.rfile.read(content_length)
            data = json.loads(post_data.decode('utf-8'))
            
            try:
                conn = sqlite3.connect('spa.db')
                c = conn.cursor()
                c.execute("INSERT INTO users (name, age, phone, email, password) VALUES (?, ?, ?, ?, ?)",
                          (data['name'], data['age'], data['phone'], data['email'], data['password']))
                conn.commit()
                conn.close()
                
                # Enviar correo de bienvenida
                enviar_correo_bienvenida(data['email'], data['name'])
                
                self.send_response(200)
                self.send_header('Content-type', 'application/json')
                self.end_headers()
                self.wfile.write(json.dumps({"status": "success", "message": "Usuario registrado exitosamente"}).encode())
            except sqlite3.IntegrityError:
                self.send_response(400)
                self.send_header('Content-type', 'application/json')
                self.end_headers()
                self.wfile.write(json.dumps({"status": "error", "message": "El correo ya está registrado"}).encode())
            except Exception as e:
                self.send_response(500)
                self.send_header('Content-type', 'application/json')
                self.end_headers()
                self.wfile.write(json.dumps({"status": "error", "message": str(e)}).encode())
                
        elif self.path == '/api/login':
            content_length = int(self.headers['Content-Length'])
            post_data = self.rfile.read(content_length)
            data = json.loads(post_data.decode('utf-8'))
            
            conn = sqlite3.connect('spa.db')
            c = conn.cursor()
            c.execute("SELECT id, name, email FROM users WHERE email=? AND password=?", 
                      (data['email'], data['password']))
            user = c.fetchone()
            conn.close()
            
            self.send_response(200)
            self.send_header('Content-type', 'application/json')
            self.end_headers()
            if user:
                self.wfile.write(json.dumps({"status": "success", "user": {"id": user[0], "name": user[1], "email": user[2]}}).encode())
            else:
                self.wfile.write(json.dumps({"status": "error", "message": "Correo o contraseña incorrectos"}).encode())
                
        elif self.path == '/api/book':
            content_length = int(self.headers['Content-Length'])
            post_data = self.rfile.read(content_length)
            data = json.loads(post_data.decode('utf-8'))
            
            # Guardar en base de datos
            conn = sqlite3.connect('spa.db')
            c = conn.cursor()
            c.execute("INSERT INTO appointments (name, phone, date, service) VALUES (?, ?, ?, ?)",
                      (data['name'], data['phone'], data['date'], data['service']))
            conn.commit()
            conn.close()
            
            # Enviar notificación al dueño
            enviar_notificacion_reserva(data['name'], data['phone'], data['date'], data['service'])
            
            self.send_response(200)
            self.send_header('Content-type', 'application/json')
            self.end_headers()
            self.wfile.write(json.dumps({"status": "success", "message": "Reserva enviada"}).encode())
            
        else:
            self.send_response(404)
            self.end_headers()

if __name__ == '__main__':
    init_db()
    with socketserver.TCPServer(("", PORT), SpaRequestHandler) as httpd:
        print(f"Servidor backend y web corriendo en el puerto {PORT}")
        print("Tu página está en vivo en internet. Ábrela aquí: https://nmssaid.uk/pagina.html")
        try:
            httpd.serve_forever()
        except KeyboardInterrupt:
            print("\nServidor detenido.")
