import os
import qrcode
import mysql.connector
from pathlib import Path

# --- Config ---
DB_CONFIG = {
    "host":     "127.0.0.1",
    "user":     "root",
    "password": "",          # ← fixed
    "database": "event_ai"
}

# Output folder
QR_OUTPUT_DIR = r"D:\event-photo-delivery\event-photo-delivery\app\qr"

Path(QR_OUTPUT_DIR).mkdir(parents=True, exist_ok=True)

conn   = mysql.connector.connect(**DB_CONFIG)
cursor = conn.cursor(dictionary=True)
cursor.execute("SELECT id, name, email, mobile_number FROM visitors_registration")
visitors = cursor.fetchall()
cursor.close()
conn.close()

print(f"Found {len(visitors)} visitor(s). Generating QR codes...\n")

for visitor in visitors:
    visitor_id = visitor["id"]
    name       = visitor["name"]
    email      = (visitor["email"] or "").strip()
    mobile     = (visitor["mobile_number"] or "").strip()

    if not email and not mobile:
        print(f"[SKIP] No email or mobile for visitor {visitor_id} ({name})")
        continue

    qr_filename = f"visitor_{visitor_id}.png"
    qr_filepath = os.path.join(QR_OUTPUT_DIR, qr_filename)

    if os.path.exists(qr_filepath):
        print(f"[SKIP] QR already exists for visitor {visitor_id} ({name})")
        continue

    # QR data = email preferred, mobile as fallback
    qr_data = email if email else mobile

    qr = qrcode.QRCode(
        version=1,
        error_correction=qrcode.constants.ERROR_CORRECT_H,
        box_size=10,
        border=4
    )
    qr.add_data(qr_data)
    qr.make(fit=True)

    img = qr.make_image(fill_color="black", back_color="white")
    img.save(qr_filepath)
    print(f"[CREATED] {qr_filename}  →  {qr_data}")

print("\nDone.")