import os
from flask import Flask, request, jsonify
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
import smtplib
import requests
from dotenv import load_dotenv

load_dotenv()

app = Flask(__name__)

# Load environment
RECAPTCHA_SECRET = os.getenv("RECAPTCHA_SECRET")
EMAIL_USER = os.getenv("EMAIL_USER")
EMAIL_PASSWORD = os.getenv("EMAIL_PASSWORD")
OWNER_EMAIL = os.getenv("OWNER_EMAIL")
SMTP_SERVER = os.getenv("SMTP_SERVER", "smtp.gmail.com")
SMTP_PORT = int(os.getenv("SMTP_PORT", 587))

def verify_recaptcha(token, remote_ip=None):
    if not token:
        return False
    url = "https://www.google.com/recaptcha/api/siteverify"
    data = {"secret": RECAPTCHA_SECRET, "response": token}
    if remote_ip:
        data["remoteip"] = remote_ip
    try:
        r = requests.post(url, data=data, timeout=5)
        return r.json().get("success", False)
    except:
        return False

@app.route("/send-incentive", methods=["POST"])
def send_incentive():
    # Získání dat z form
    name = (request.form.get("name") or "").strip()
    email = (request.form.get("email") or "").strip()
    message_body = (request.form.get("message") or "").strip()
    recaptcha_token = request.form.get("g-recaptcha-response")
    honeypot = request.form.get("website")  # skryté pole

    # Honeypot kontrola
    if honeypot:
        return jsonify({"error": "Spam detected"}), 400

    # reCAPTCHA kontrola
    if not verify_recaptcha(recaptcha_token, request.remote_addr):
        return jsonify({"error": "reCAPTCHA failed"}), 400

    # Základní validace
    if not name or not email or not message_body:
        return jsonify({"error": "Missing fields"}), 400

    # Vytvoření emailu
    msg = MIMEMultipart()
    msg["From"] = EMAIL_USER
    msg["To"] = OWNER_EMAIL
    msg["Subject"] = f"Pobídka od {name}"
    body = f"Od: {name} <{email}>\n\n{message_body}"
    msg.attach(MIMEText(body, "plain"))

    try:
        server = smtplib.SMTP(SMTP_SERVER, SMTP_PORT)
        server.starttls()
        server.login(EMAIL_USER, EMAIL_PASSWORD)
        server.sendmail(EMAIL_USER, OWNER_EMAIL, msg.as_string())
        server.quit()
        return jsonify({"status": "Email sent"}), 200
    except Exception as e:
        return jsonify({"error": str(e)}), 500

if __name__ == "__main__":
    app.run(debug=True, host="0.0.0.0", port=5000)
