function escapeHtml(value = '') {
return String(value)
.replace(/&/g, '&')
.replace(//g, '>')
.replace(/"/g, '"')
.replace(/'/g, ''')
.slice(0, 1200);
}
function normalizePhone(value = '') {
return String(value).replace(/[^+\d]/g, '').slice(0, 20);
}
function getBody(req) {
if (!req.body) return {};
if (typeof req.body === 'string') {
try {
return JSON.parse(req.body);
} catch {
return {};
}
}
return req.body;
}
export default async function handler(req, res) {
if (req.method !== 'POST') {
res.setHeader('Allow', 'POST');
return res.status(405).json({
ok: false,
error: 'Method not allowed'
});
}
const token = process.env.TELEGRAM_BOT_TOKEN;
const chatId = process.env.TELEGRAM_CHAT_ID;
if (!token || !chatId) {
return res.status(500).json({
ok: false,
error: 'Telegram environment variables are not configured'
});
}
const body = getBody(req);
if (body.company) {
return res.status(200).json({ ok: true });
}
const name = escapeHtml(body.name);
const phone = normalizePhone(body.phone);
const service = escapeHtml(body.service);
const date = escapeHtml(body.date || 'Nav norādīts / не указано');
const address = escapeHtml(body.address || 'Nav norādīta / не указан');
const details = escapeHtml(body.details || 'Nav / нет');
const lang = escapeHtml(body.lang || 'lv');
const page = escapeHtml(body.page || 'Website');
if (!name || !phone || !service) {
return res.status(400).json({
ok: false,
error: 'Missing required fields'
});
}
const message = `🚨 JAUNS PIETEIKUMS A2B
👤 Vārds / имя: ${name}
📞 Telefons: ${phone}
🎯 Pakalpojums / услуга: ${service}
🕐 Kad / когда: ${date}
📍 Adrese / адрес: ${address}
📝 Detaļas / детали: ${details}
🌐 Valoda: ${lang}
🔗 Lapa: ${page}
⏰ Laiks: ${new Date().toLocaleString('lv-LV', { timeZone: 'Europe/Riga' })}
👉 Zvanīt klientam / позвонить клиенту`;
try {
const response = await fetch(`https://api.telegram.org/bot${token}/sendMessage`, {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
chat_id: chatId,
text: message,
parse_mode: 'HTML',
disable_web_page_preview: true
})
});
const data = await response.json();
if (!response.ok || !data.ok) {
return res.status(502).json({
ok: false,
error: data.description || 'Telegram request failed'
});
}
return res.status(200).json({ ok: true });
} catch (error) {
return res.status(500).json({
ok: false,
error: 'Server error'
});
}
}