first();
if (! $company) return response()->json(['ok' => false], 404);
$expectedSecret = $telegram->webhookSecretFor($company);
$providedSecret = $request->header('X-Telegram-Bot-Api-Secret-Token');
if ($expectedSecret && $providedSecret !== $expectedSecret) {
Log::warning('telegram.webhook bad secret', ['tenant' => $slug]);
return response()->json(['ok' => false], 401);
}
app(TenantManager::class)->setCurrent($company);
$message = $request->input('message', []);
$chatId = (string) data_get($message, 'chat.id', '');
if (! $chatId) {
return response()->json(['ok' => true]);
}
$contact = data_get($message, 'contact');
$text = trim((string) data_get($message, 'text', ''));
$client = null;
$phoneRaw = null;
if ($contact) {
$phoneRaw = data_get($contact, 'phone_number');
} elseif (preg_match('/(\+?[0-9\-\s\(\)]{7,})/', $text, $m)) {
$phoneRaw = $m[1];
}
if ($phoneRaw) {
$needle = Client::normalizePhone($phoneRaw);
if ($needle) {
$client = Client::whereRaw(
"REPLACE(REPLACE(REPLACE(REPLACE(phone, ' ', ''), '-', ''), '(', ''), ')', '') LIKE ?",
['%' . substr($needle, -9) . '%']
)->first();
}
}
if (! $client && $text === '/start') {
$telegram->sendMessage($company, $chatId,
'Salut! Pentru a primi notificări despre mașina ta, ' .
'apasă butonul „Share contact" sau trimite numărul tău de telefon.'
);
return response()->json(['ok' => true]);
}
if ($client) {
$client->telegram_chat_id = $chatId;
$client->saveQuietly();
$name = $company->display_name ?? $company->name;
$telegram->sendMessage($company, $chatId,
"Te-am identificat — {$client->name}.\n" .
"Vei primi aici notificări despre fișele tale de la {$name}.\n\n" .
"Trimite /stop oricând ca să oprești notificările."
);
return response()->json(['ok' => true]);
}
if ($text === '/stop') {
Client::where('telegram_chat_id', $chatId)->update(['telegram_chat_id' => null]);
$telegram->sendMessage($company, $chatId, 'Notificările au fost oprite.');
return response()->json(['ok' => true]);
}
if ($phoneRaw) {
$telegram->sendMessage($company, $chatId,
"Nu am găsit un client cu acest număr la {$company->name}. " .
"Verifică telefonul sau contactează service-ul."
);
}
return response()->json(['ok' => true]);
}
}