export async function onRequestPost(context) { const { request, env } = context; try { if (!env.DB) { return json({ success: false, error: "D1 binding DB not found" }, 500); } const body = await request.json().catch(() => ({})); await env.DB.prepare(` INSERT INTO clicks ( link_name, target_url, page_url, referrer, ip, country, user_agent ) VALUES (?, ?, ?, ?, ?, ?, ?) `).bind( String(body.link_name || "unknown").slice(0, 100), String(body.target_url || "").slice(0, 500), String(body.page_url || "").slice(0, 500), String(body.referrer || "").slice(0, 500), request.headers.get("CF-Connecting-IP") || "", request.cf?.country || "", request.headers.get("User-Agent") || "" ).run(); return json({ success: true }); } catch (err) { return json({ success: false, error: err.message }, 500); } } function json(data, status = 200) { return new Response(JSON.stringify(data), { status, headers: { "Content-Type": "application/json; charset=utf-8", "Access-Control-Allow-Origin": "*" } }); }