<?php

namespace App\Http\Controllers;

use App\Models\Central\Company;
use App\Models\Tenant\Client;
use App\Services\Notifications\TelegramService;
use App\Tenancy\TenantManager;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;

/**
 * Receives Telegram updates per tenant. URL: /telegram/webhook/{slug}
 *
 * To link a Telegram account to a Client record, the bot expects the user
 * to share their phone via Telegram's contact share button (Telegram lets
 * users send their own phone with one tap). We match the shared phone (or
 * the message text fallback) to clients.phone and persist chat_id.
 */
class TelegramWebhookController extends Controller
{
    public function handle(Request $request, string $slug, TelegramService $telegram)
    {
        $company = Company::where('slug', $slug)->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 — <b>{$client->name}</b>.\n" .
                "Vei primi aici notificări despre fișele tale de la <b>{$name}</b>.\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]);
    }
}
