#!/usr/bin/env python3
import subprocess, os, json, socket

BASE      = "/usr/local/etc/chilli/www"
LOGIN_SH  = BASE + "/login.chi.sh"
LANGS_JS  = BASE + "/langs_slim.js"
IMG_DIR   = BASE + "/images"

# ── قراءة الـ config من الداتابيز ──────────────────────────────────────────
r = subprocess.run(
    ["mysql","-u","radius","-pradpass123","radius","-sN","-e",
     "SELECT config_json FROM login_form_config LIMIT 1;"],
    capture_output=True, text=True
)
if not r.stdout.strip():
    print("No config found in DB"); exit(0)

cfg   = json.loads(r.stdout.strip())
style = cfg.get("style", {})
forms = cfg.get("forms", [])

# ── الألوان والفونت ──────────────────────────────────────────────────────────
primary = style.get("primary_color", "#cc0000")
btn     = style.get("btn_color",     "#610000")
bg      = style.get("bg_color",      "#ffffff")
txt     = style.get("text_color",    "#850000")
FONTS   = {
    "Poppins":    "Poppins,sans-serif",
    "Inter":      "Inter,sans-serif",
    "Roboto":     "Roboto,sans-serif",
    "Lato":       "Lato,sans-serif",
    "Montserrat": "Montserrat,sans-serif"
}
font = FONTS.get(style.get("font","Lato"), "Lato,sans-serif")

# ── IP السيرفر ديناميكي ──────────────────────────────────────────────────────
try:
    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    s.connect(('8.8.8.8', 80))
    server_ip = s.getsockname()[0]
    s.close()
except:
    server_ip = '127.0.0.1'

BASE_URL = "/www"

# ── الصور — path فقط، مفيش base64 ────────────────────────────────────────────
def img_url(val):
    if not val: return ''
    fname = val.replace("\\/","/").split('/')[-1]
    if not fname: return ''
    full = os.path.join(IMG_DIR, fname)
    if not os.path.exists(full):
        print(f"  ⚠ image not found: {full}")
        return ''
    return BASE_URL + "/images/" + fname

bg_img   = img_url(style.get("bg_image",""))
logo_img = img_url(style.get("logo_image",""))

bg_css = f'url("{bg_img}") center center/cover no-repeat fixed' if bg_img else bg
logo   = f'<img src="{logo_img}" style="max-width:120px;max-height:80px;object-fit:contain;"/>' if logo_img else '🌐'

# ── Langs block ──────────────────────────────────────────────────────────────
if os.path.exists(LANGS_JS):
    langs_block = f'<script src="{BASE_URL}/langs_slim.js.chi"></script>'
else:
    langs_block = ''

# ── PMS forms ────────────────────────────────────────────────────────────────
COMBOS = {
    0:["__users__"],
    1:["room","first_name","email"],
    2:["room","first_name"],
    3:["room","last_name"],
    4:["room","last_name","email"],
    5:["room","arrival","email"],
    6:["room","arrival"],
    7:["room","departure"],
    8:["room","resv_id"],
    9:["room","phone"],
    10:["room","first_name","last_name"],
    11:["room","first_name","last_name","email"],
    12:["room","first_name","last_name","phone"],
    13:["room","arrival","departure","email"],
    14:["room","first_name","phone"],
    15:["room","last_name","phone"],
    19:["room","arrival","phone"],
    20:["room","resv_id","phone"],
    16:["room","first_name","last_name"],
    17:["room","first_name","last_name","email"],
    18:["room","first_name","last_name","phone"],
    9: ["room","resv_id"],
    10:["room","resv_id","email"],
    11:["room","resv_id","first_name"],
    12:["room","resv_id","last_name"],
    13:["room","arrival","departure","email"],
    14:["room","first_name","phone"],
    15:["room","last_name","phone"],
    21:["room","departure","email"],
    22:["room","departure"]
}
FIELDS = {
    "room":       ("text",  "Room Number",     "e.g. 204",              "roomLabel",      "roomPH"),
    "first_name": ("text",  "First Name",      "e.g. Ahmed",            "firstNameLabel", "firstNamePH"),
    "last_name":  ("text",  "Last Name",       "e.g. Smith",            "lastNameLabel",  "lastNamePH"),
    "email":      ("email", "Email Address",   "e.g. you@email.com",    "emailLabel",     "emailPH"),
    "phone":      ("tel",   "Phone Number",    "e.g. +201001234567",    "phoneLabel",     "phonePH"),
    "resv_id":    ("text",  "Reservation ID",  "e.g. 63483",            "resvIdLabel",    "resvIdPH"),
    "arrival":    ("date",  "Arrival Date",    "",                      "arrivalLabel",   ""),
    "departure":  ("date",  "Departure Date",  "",                      "departureLabel", ""),
}

tabs = ""; secs = ""
for i, form in enumerate(forms):
    fields = COMBOS.get(int(form.get("combination", 1)), COMBOS[1])
    tname  = form.get("tab_name", "Form " + str(i+1))
    act    = " active" if i == 0 else ""

    tabs += f'<button class="pms-tab-btn{act}" onclick="switchPmsTab({i})" id="pms-tab-{i}">{tname}</button>\n'

    inp = ""
    for f in fields:
        if f == "__users__":
            inp += '<div class="inp-wrap"><label class="inp-label">Username</label><input type="text" class="inp-field" data-field="__username__" required/></div>\n'
            inp += '<div class="inp-wrap"><label class="inp-label">Password</label><input type="password" class="inp-field" data-field="__password__" required/></div>\n'
        elif f in FIELDS:
            t2, lbl, ph, lkey, pkey = FIELDS[f]
            if t2 == "date":
                inp += f'<div class="inp-wrap"><label class="inp-label" data-lkey="{lkey}">{lbl}</label><input type="date" class="inp-field" data-field="{f}" required/></div>\n'
            else:
                inp += f'<div class="inp-wrap"><label class="inp-label" data-lkey="{lkey}" data-pkey="{pkey}">{lbl}</label><input type="{t2}" class="inp-field" placeholder="{ph}" data-field="{f}" required/></div>\n'

    secs += (f'<div class="pms-form-section{act}" id="pms-form-{i}">\n'
             + inp
             + f'<div id="pms-status-{i}" class="pms-msg" style="display:none;"></div>'
             + f'<button class="connect-btn" onclick="connectPms({i})" id="pms-btn-{i}">Connect</button>'
             + '</div>\n')

tabs_html = '<div class="pms-tabs">\n' + tabs + "</div>\n" if len(forms) > 1 else ""
pms_block = '<!-- PMS_FORMS_START -->\n<div class="pms-container">' + tabs_html + secs + "</div>\n<!-- PMS_FORMS_END -->"

# ── اقرأ الـ template وحط القيم ─────────────────────────────────────────────
tpl = open(BASE + "/login.chi.sh.tpl").read()
out = (tpl
    .replace("%%PRIMARY%%",    primary)
    .replace("%%BTN%%",        btn)
    .replace("%%BG_CSS%%",     bg_css)
    .replace("%%TXT%%",        txt)
    .replace("%%FONT%%",       font)
    .replace("%%LOGO%%",       logo)
    .replace("%%PMS_BLOCK%%",  pms_block)
    .replace("%%BASE_URL%%",   BASE_URL)
    .replace("%%LANGS_BLOCK%%", langs_block)
)

open(LOGIN_SH, "w").write(out)
os.chmod(LOGIN_SH, 0o755)
subprocess.run(["sudo", "systemctl", "restart", "chilli"])

size = os.path.getsize(LOGIN_SH)
print(f"✅ Done! forms={len(forms)} server={server_ip} size={size} bytes")
print(f"   CSS:  {BASE_URL}/login.css")
print(f"   JS:   {BASE_URL}/login.js")
print(f"   Imgs: {BASE_URL}/images/")
