const WP_API_CONFIG = { baseUrl: ("file:" === window.location.protocol || !window.location.hostname.endsWith("etx-energylogistic.com") ? "https://etx-energylogistic.com/wp-json" : new URL("/wp-json", window.location.origin).toString() ).replace(/\/$/, ""), authEndpoint: "/etx/v1/login", usersEndpoint: "/wp/v2/users", mediaEndpoint: "/wp/v2/media", logoEndpoint: "/etx/v1/logo", ausstellerEndpoint: "/etx/v1/aussteller", ticketsEndpoint: "/etx/v1/tickets", servicesEndpoint: "/etx/v1/services", badgesEndpoint: "/etx/v1/badges", }; function getAuthHeader() { const e = currentSession.token || (currentSession.wpId ? "cpt_" + currentSession.wpId : ""); return e ? `Bearer ${e}` : wpBasicAuthHeader || null; } async function readApiResponse(e) { return (e.headers.get("content-type") || "").includes("application/json") ? e.json() : e.text(); } function isSuccessfulApiPayload(e) { return ( !(!e || "object" != typeof e) && (!0 === e.success || Number(e.id) > 0) ); } function getErrorMessage(error, fallback) { if (!error) return fallback; if (typeof error === "string") return error; if (error.message) return error.message; if (error.error) return getErrorMessage(error.error, fallback); return fallback; } async function wpRequest(e, t = {}) { const a = new Headers(t.headers || {}); !a.has("Content-Type") && t.body && a.set("Content-Type", "application/json"); const o = getAuthHeader(); o && !a.has("Authorization") && a.set("Authorization", o); let n, r; try { ((n = await fetch(`${WP_API_CONFIG.baseUrl}${e}`, { ...t, headers: a })), (r = await readApiResponse(n))); } catch (e) { throw new Error( "WordPress API nicht erreichbar. Bitte Seite live unter etx-energylogistic.com oeffnen oder Internetverbindung pruefen.", ); } if (!n.ok) { if (isSuccessfulApiPayload(r)) return r; const e = r && r.message ? r.message : `HTTP ${n.status}`; throw new Error(e); } return r; } async function wpLogin(e, t) { try { const a = await wpRequest( `/wp/v2/etx_aussteller?meta_key=email&meta_value=${encodeURIComponent(e)}`, { method: "GET" }, ); if (a && a.length > 0) return { success: !0, user: { email: e, name: stripHtml(a[0].title?.rendered || e), etx_aussteller_id: a[0].id, }, token: "cpt_" + a[0].id, profile: mapWpProfile(a[0], e), }; } catch (a) { return { success: !1, error: a }; } return { success: !1, error: "Kein Aussteller-Konto gefunden." }; } function stripHtml(e) { const t = document.createElement("div"); return ((t.innerHTML = e || ""), t.textContent || t.innerText || ""); } function firstDefined(...e) { return e.find((e) => null != e && "" !== e) || ""; } function mapWpProfile(e, t = "") { const a = e && "object" == typeof e ? e : {}, p = a.profile && "object" == typeof a.profile ? a.profile : {}, o = a.meta || {}, n = a.acf || {}; if (Object.keys(p).length > 0) { const profileMeta = p.meta || {}; return { companyName: firstDefined(p.companyName, profileMeta.firmenname, p.name), contactPerson: firstDefined(p.contactPerson, profileMeta.ansprechpartner), email: firstDefined(p.email, profileMeta.email, t), category: firstDefined(p.category, profileMeta.kategorie), phone: firstDefined(p.phone, profileMeta.telefon), website: firstDefined(p.website, profileMeta.website), description: firstDefined(p.description, profileMeta.beschreibung), logo: firstDefined(p.logoUrl, profileMeta.logo_url), linkedin: firstDefined(p.linkedin, profileMeta.linkedin), instagram: firstDefined(p.instagram, profileMeta.instagram), facebook: firstDefined(p.facebook, profileMeta.facebook), wpId: Number(p.id || a.id) || 0, }; } // title kann String oder Object sein (beim direkten API-Call vs CPT-Archiv) const titleValue = typeof a.title === 'string' ? a.title : (a.title?.rendered || a.title?.raw || ''); return { companyName: firstDefined(o.firmenname, n.firmenname, stripHtml(titleValue)), contactPerson: firstDefined(o.ansprechpartner, n.ansprechpartner), email: firstDefined(o.email, n.email, t), category: firstDefined(o.kategorie, n.kategorie), phone: firstDefined(o.telefon, n.telefon), website: firstDefined(o.website, n.website), description: firstDefined( o.beschreibung, n.beschreibung, a.content?.rendered && stripHtml(a.content.rendered), ), logo: firstDefined(o.logo_url, n.logo_url, o.logo, n.logo), linkedin: firstDefined(o.linkedin, n.linkedin), instagram: firstDefined(o.instagram, n.instagram), facebook: firstDefined(o.facebook, n.facebook), wpId: Number(a.id) || 0, }; } async function uploadLogoToWP(e, t) { const a = String(e || "").match(/^data:(image\/(?:png|jpeg|webp));base64,(.+)$/); if (!a) { const e = new Error("Logo muss als PNG-, JPEG- oder WebP-Data-URL vorliegen."); return { success: !1, id: e, error: e }; } const o = getAuthHeader(); if (!o) { const e = new Error( "Logo-Upload benötigt eine aktive WordPress-Anmeldung.", ); return { success: !1, id: e, error: e }; } const n = a[1], r = a[2], s = atob(r), i = new Array(s.length); for (let e = 0; e < s.length; e += 1) i[e] = s.charCodeAt(e); const l = new Uint8Array(i), c = new Blob([l], { type: n }), u = new FormData(), d = "image/png" === n ? "png" : "image/webp" === n ? "webp" : "jpg"; (u.append("logo", c, t + "." + d), u.append("title", t), u.append("aussteller_id", String(currentSession.wpId || 0))); try { const e = await fetch(WP_API_CONFIG.baseUrl + WP_API_CONFIG.logoEndpoint, { method: "POST", headers: { Authorization: o }, body: u, }), t = await readApiResponse(e); if (!e.ok) throw new Error( t && t.message ? t.message : "Logo-Upload fehlgeschlagen.", ); return { success: !0, id: t.attachment_id || t.id, url: t.url || "" }; } catch (e) { return { success: !1, id: e, error: e }; } } async function wpSaveProfile(e) { try { let t = e.logo; let logoId = 0; let logoUrl = ""; if (t && String(t).startsWith("data:image/")) { const a = await uploadLogoToWP(t, e.companyName || "Aussteller-Logo"); if (!a.success) throw a.error || a.id || new Error("Logo-Upload fehlgeschlagen."); logoId = Number(a.id) || 0; logoUrl = a.url || ""; t = logoUrl || ""; } else if (/^https?:\/\//i.test(String(t || ""))) { logoUrl = t; } const a = { firmenname: e.companyName, ansprechpartner: e.contactPerson, email: e.email, telefon: e.phone, website: e.website, beschreibung: e.description, logo: logoId || undefined, logo_id: logoId || undefined, logo_url: logoUrl || undefined, kategorie: e.category, linkedin: e.linkedin, instagram: e.instagram, facebook: e.facebook, }; // Use PUT for updates, POST for create const isUpdate = e.wpId && e.wpId > 0; const endpoint = isUpdate ? `${WP_API_CONFIG.ausstellerEndpoint}/${e.wpId}` : WP_API_CONFIG.ausstellerEndpoint; const method = isUpdate ? "PUT" : "POST"; const response = await wpRequest(endpoint, { method: method, body: JSON.stringify(a), }); return { success: !0, id: response.id || e.wpId, action: response.action || (isUpdate ? "updated" : "created"), postId: response.post_id || response.postId || 0, message: response.message || "", }; } catch (e) { return { success: !1, error: e }; } } async function wpSubmitAnfrage(e, t) { let endpoint, payload; const basePayload = { aussteller_id: currentSession.wpId || t.aussteller_id || 0, email: currentSession.email || t.email || t.empfaenger_email || "", empfaenger_email: t.empfaenger_email || t.email || currentSession.email || "", nachricht: t.nachricht || t.message || "", }; switch(e) { case 'tickets': endpoint = WP_API_CONFIG.ticketsEndpoint; payload = { ...basePayload, anzahl_tickets: t.anzahl_tickets || 0, }; break; case 'services': endpoint = WP_API_CONFIG.servicesEndpoint; payload = { ...basePayload, anzahl: t.anzahl || 1, leistung: t.leistung || "Zusatzleistungen", }; break; case 'badges': endpoint = WP_API_CONFIG.badgesEndpoint; payload = { ...basePayload, anzahl: t.anzahl, namen: t.namen, }; break; default: return { success: !1, error: 'Unbekannter Anfragetyp: ' + e }; } try { return { success: !0, id: ( await wpRequest(endpoint, { method: "POST", body: JSON.stringify(payload), }) ).id, }; } catch (e) { return { success: !1, error: e }; } } async function wpLoadAnfragen() { const wpId = Number(currentSession.wpId || 0); if (!wpId) return { success: true, anfragen: [] }; try { return await wpRequest(`/etx/v1/aussteller/${wpId}/anfragen`, { method: "GET", }); } catch (e) { return { success: false, error: e, anfragen: [] }; } } async function wpCreateUser(email, company, password) { try { return await wpRequest(WP_API_CONFIG.ausstellerEndpoint, { method: "POST", body: JSON.stringify({ email: email, firmenname: company, ansprechpartner: document.getElementById("reg-contact").value.trim(), telefon: document.getElementById("reg-phone").value.trim(), password: password, }), }); } catch (error) { return { success: !1, error }; } }