"""
Akshay's Mridangam Arangetram Website
"""

import sqlite3
import os
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from flask import (
    Flask, render_template, request, jsonify,
    redirect, url_for, session
)

app = Flask(__name__)

# ── Config ───────────────────────────────────────────────────────────────────
app.secret_key = "change-this-to-a-random-secret-string-before-deploying"

ADMIN_USERNAME = "arangetram.admin"           # ← change this
ADMIN_PASSWORD = "es0M1xzIACFyITYcWv43"  # ← change this to something strong

# Email settings — fill these in to enable confirmation emails
# For Gmail: use an App Password (not your regular password)
# Guide: https://support.google.com/accounts/answer/185833
EMAIL_ENABLED   = True                       # ← set True once configured
EMAIL_FROM      = "mridangam.akshay@gmail.com"       # ← your sending email
EMAIL_PASSWORD  = "zbfj njvq uzcu tgey"   # ← Gmail App Password
EMAIL_SMTP_HOST = "smtp.gmail.com"
EMAIL_SMTP_PORT = 587

# Event details used in confirmation email — update these!
EVENT_NAME    = "Akshay's Mridangam Arangetram"
EVENT_DATE    = "July 25th, 2026"
EVENT_TIME    = "3:00 PM"
EVENT_VENUE   = "East Forsyth High School (8910 Jot Em Down Rd, Gainesville, GA 30506)"
EVENT_CONTACT = "mridangam.akshay@gmail.com"

DB_PATH = os.path.join(os.path.dirname(__file__), "rsvps.db")

# ── Database ──────────────────────────────────────────────────────────────────

def get_db():
    conn = sqlite3.connect(DB_PATH)
    conn.row_factory = sqlite3.Row
    return conn

def init_db():
    with get_db() as conn:
        conn.execute("""
            CREATE TABLE IF NOT EXISTS rsvps (
                id          INTEGER PRIMARY KEY AUTOINCREMENT,
                name        TEXT    NOT NULL,
                email       TEXT    NOT NULL,
                guests      INTEGER NOT NULL DEFAULT 1,
                message     TEXT,
                created_at  DATETIME DEFAULT CURRENT_TIMESTAMP
            )
        """)

# ── Email ─────────────────────────────────────────────────────────────────────

def send_confirmation_email(name, email, guests):
    if not EMAIL_ENABLED:
        return
    subject = f"Thank you for RSVP-ing! {EVENT_NAME}"
    html_body = f"""
<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8"/>
  <meta name="viewport" content="width=device-width, initial-scale=1.0"/>
</head>
<body style="margin:0;padding:0;background:#F2EAD8;font-family:'Georgia',serif;">
  <table width="100%" cellpadding="0" cellspacing="0" style="background:#F2EAD8;padding:40px 20px;">
    <tr><td align="center">
      <table width="100%" style="max-width:580px;background:#ffffff;border:1px solid #e0d4b8;">
        <tr>
          <td style="background:#0F172A;padding:40px 40px 30px;text-align:center;">
            <p style="margin:0 0 8px;font-size:11px;letter-spacing:4px;text-transform:uppercase;color:#60A5FA;">You're Confirmed</p>
            <h1 style="margin:0;font-size:26px;font-weight:300;color:#EFF6FF;line-height:1.2;">{EVENT_NAME}</h1>
            <div style="margin:20px auto 0;width:40px;height:1px;background:#60A5FA;"></div>
          </td>
        </tr>
        <tr>
          <td style="padding:40px 40px 30px;">
            <p style="margin:0 0 20px;font-size:16px;color:#0F172A;line-height:1.7;">Dear <strong>{name}</strong>,</p>
            <p style="margin:0 0 20px;font-size:15px;color:#3B5B8C;line-height:1.8;">
              We are delighted to confirm your RSVP. Your presence will make this celebration truly special!
            </p>
            <table width="100%" style="background:#EFF6FF;border-left:3px solid #2563EB;margin:28px 0;">
              <tr><td style="padding:24px 28px;">
                <p style="margin:0 0 14px;font-size:10px;letter-spacing:3px;text-transform:uppercase;color:#2563EB;">Event Details</p>
                <table>
                  <tr><td style="padding:4px 0;font-size:11px;letter-spacing:2px;text-transform:uppercase;color:#3B5B8C;width:70px;">Date</td><td style="padding:4px 0;font-size:15px;color:#0F172A;">{EVENT_DATE}</td></tr>
                  <tr><td style="padding:4px 0;font-size:11px;letter-spacing:2px;text-transform:uppercase;color:#3B5B8C;">Time</td><td style="padding:4px 0;font-size:15px;color:#0F172A;">{EVENT_TIME}</td></tr>
                  <tr><td style="padding:4px 0;font-size:11px;letter-spacing:2px;text-transform:uppercase;color:#3B5B8C;">Venue</td><td style="padding:4px 0;font-size:15px;color:#0F172A;">{EVENT_VENUE}</td></tr>
                  <tr><td style="padding:4px 0;font-size:11px;letter-spacing:2px;text-transform:uppercase;color:#3B5B8C;">Guests</td><td style="padding:4px 0;font-size:15px;color:#0F172A;">{guests} {'person' if guests == 1 else 'people'}</td></tr>
                </table>
              </td></tr>
            </table>
            <p style="margin:0 0 20px;font-size:14px;color:#3B5B8C;line-height:1.8;">
             If you have any questions/comments please email us at <a href="mailto:{EVENT_CONTACT}" style="color:#2563EB;">{EVENT_CONTACT}</a>
            </p>
            <p style="margin:0;font-size:15px;color:#0F172A;line-height:1.7;font-style:italic;">
              Thank you,<br/>
              <strong style="font-style:normal;">Anand, Gayathri, Akshara, and Akshay</strong>
            </p>
          </td>
        </tr>
        <tr>
          <td style="background:#EFF6FF;padding:20px 40px;text-align:center;border-top:1px solid #DBEAFE;">
            <p style="margin:0;font-size:11px;color:#3B5B8C;letter-spacing:1px;">{EVENT_NAME.upper()}</p>
          </td>
        </tr>
      </table>
    </td></tr>
  </table>
</body>
</html>
"""
    plain_body = f"""Dear {name},

Your RSVP is confirmed!

Event : {EVENT_NAME}
Date  : {EVENT_DATE}
Time  : {EVENT_TIME}
Venue : {EVENT_VENUE}
Guests: {guests} {'person' if guests == 1 else 'people'}

If you have any questions/comments please email us at {EVENT_CONTACT}

Thank you,
Anand, Gayathri, Akshara, & Akshay
"""
    try:
        msg = MIMEMultipart("alternative")
        msg["Subject"] = subject
        msg["From"]    = EMAIL_FROM
        msg["To"]      = email
        msg.attach(MIMEText(plain_body, "plain"))
        msg.attach(MIMEText(html_body, "html"))
        with smtplib.SMTP(EMAIL_SMTP_HOST, EMAIL_SMTP_PORT) as server:
            server.starttls()
            server.login(EMAIL_FROM, EMAIL_PASSWORD)
            server.sendmail(EMAIL_FROM, email, msg.as_string())
    except Exception as e:
        print(f"[Email] Failed to send to {email}: {e}")

# ── Public Routes ─────────────────────────────────────────────────────────────

@app.route("/")
def index():
    return render_template("index.html")

@app.route("/artists")
def artists():
    return render_template("artists.html")

@app.route("/gallery")
def gallery():
    return render_template("gallery.html")

@app.route("/program")
def program():
    return render_template("program.html")

@app.route("/rsvp", methods=["POST"])
def rsvp():
    data    = request.get_json()
    name    = (data.get("name") or "").strip()
    email   = (data.get("email") or "").strip()
    guests  = int(data.get("guests") or 1)
    message = (data.get("message") or "").strip()

    if not name or not email:
        return jsonify({"ok": False, "error": "Name and email are required."}), 400
    if guests < 1 or guests > 20:
        return jsonify({"ok": False, "error": "Guests must be between 1 and 20."}), 400

    with get_db() as conn:
        conn.execute(
            "INSERT INTO rsvps (name, email, guests, message) VALUES (?, ?, ?, ?)",
            (name, email, guests, message)
        )
    send_confirmation_email(name, email, guests)
    return jsonify({"ok": True})

# ── Admin Routes ──────────────────────────────────────────────────────────────

@app.route("/admin", methods=["GET", "POST"])
def admin_login():
    error = None
    if request.method == "POST":
        username = request.form.get("username", "").strip()
        password = request.form.get("password", "").strip()
        if username == ADMIN_USERNAME and password == ADMIN_PASSWORD:
            session["admin"] = True
            return redirect(url_for("admin_rsvps"))
        else:
            error = "Incorrect username or password."
    return render_template("admin_login.html", error=error)

@app.route("/admin/logout")
def admin_logout():
    session.pop("admin", None)
    return redirect(url_for("admin_login"))

@app.route("/admin/rsvps")
def admin_rsvps():
    if not session.get("admin"):
        return redirect(url_for("admin_login"))
    with get_db() as conn:
        rows = conn.execute("SELECT * FROM rsvps ORDER BY created_at DESC").fetchall()
    return render_template("admin_rsvps.html", rsvps=rows)

@app.route("/admin/rsvps/delete/<int:rsvp_id>", methods=["POST"])
def delete_rsvp(rsvp_id):
    if not session.get("admin"):
        return redirect(url_for("admin_login"))
    with get_db() as conn:
        conn.execute("DELETE FROM rsvps WHERE id = ?", (rsvp_id,))
    return redirect(url_for("admin_rsvps"))

# ── Main ──────────────────────────────────────────────────────────────────────

if __name__ == "__main__":
    init_db()
    app.run(debug=True, port=5050)
