<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Telegram\Bot\Api;
use Telegram\Bot\Laravel\Facades\Telegram;

class TelegramController extends Controller
{

public function handle(Request $request)
{
    try{
        $telegram = new Api(env('TELEGRAM_BOT_TOKEN'));
        $update = $telegram->getWebhookUpdate();
    
        if ($update->getMessage()) {
            $chatId = $update->getMessage()->getChat()->getId();
            $text   = $update->getMessage()->getText();
            $patientId = null;
            $sampleSourceId = null;
            if ($text && str_starts_with($text, "/start")) {
                $parts = explode(" ", $text);
                $individualType = 'patient';
                if (count($parts) > 1) {
                    $fullText = explode("_", $parts[1]);
                    if(count($fullText) > 1){
                        $sampleSourceId = trim($fullText[1]);
                    }
                    else{
                        $patientId = trim($parts[1]);
                    }
                }
    
                if ($patientId) {
                    // Check if patient already registered
                    $exists = DB::table('patient_telegram')
                        ->where('patient_id', $patientId)
                        ->exists();
    
                    if (!$exists) {
                        DB::table('patient_telegram')->updateOrInsert(
                            ['patient_id' => $patientId],
                            ['chat_id' => $chatId]
                        );
    
                        $telegram->sendMessage([
                            'chat_id' => $chatId,
                            'text' => "✅ Thank you for joining our bot. You will receive future laboratory results here."
                        ]);
                    }
                }
                // for sample source
                if ($sampleSourceId)
                {
                    // Check if patient already registered
                    $exist_sample_source = DB::table('sample_source_telegram')
                        ->where('sample_source_id', $sampleSourceId)
                        ->exists();
    
                    if (!$exist_sample_source) {
                        DB::table('sample_source_telegram')->updateOrInsert(
                            ['sample_source_id' => $sampleSourceId],
                            ['chat_id' => $chatId]
                        );
    
                        $telegram->sendMessage([
                            'chat_id' => $chatId,
                            'text' => "✅ Thank you for joining our bot. You will receive future laboratory results here."
                        ]);
                    }
                }
            }
        }
    
        return response()->json(['status' => 'ok'], 200);
    }
    catch(\Exception $e){
        
    }
}

}


