<?php
session_start();
header('Content-Type: application/json');

if (!isset($_SESSION['admin_id'])) {
    echo json_encode(['success' => false, 'error' => 'Unauthorized']);
    exit;
}

require_once __DIR__ . '/../../../config/db.php';
require_once __DIR__ . '/../../../includes/helpers.php';

$database = new Database();
$db = $database->getConnection();

$botToken = getSetting($db, 'telegram_bot_token', '');

if (empty($botToken)) {
    echo json_encode(['success' => false, 'error' => 'Telegram Bot Token not set in settings.']);
    exit;
}

$url = "https://api.telegram.org/bot$botToken/getUpdates";
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
$response = curl_exec($ch);
curl_close($ch);

if (!$response) {
    echo json_encode(['success' => false, 'error' => 'Failed to connect to Telegram API.']);
    exit;
}

$data = json_decode($response, true);

// Check for Webhook conflict (409)
if (isset($data['error_code']) && $data['error_code'] == 409) {
    // Attempt to delete webhook
    $delUrl = "https://api.telegram.org/bot$botToken/deleteWebhook";
    $ch = curl_init($delUrl);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_TIMEOUT, 10);
    $delRes = curl_exec($ch);
    curl_close($ch);
    
    // Try getUpdates again
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_TIMEOUT, 10);
    $response = curl_exec($ch);
    curl_close($ch);
    
    if ($response) {
        $data = json_decode($response, true);
    }
}

if (!$data || !isset($data['result'])) {
    echo json_encode(['success' => false, 'error' => 'Invalid response from Telegram: ' . $response]);
    exit;
}

$newGroups = 0;
foreach ($data['result'] as $update) {
    $chat = null;
    if (isset($update['message']['chat'])) {
        $chat = $update['message']['chat'];
    } elseif (isset($update['my_chat_member']['chat'])) {
        $chat = $update['my_chat_member']['chat'];
    }

    if ($chat && ($chat['type'] === 'group' || $chat['type'] === 'supergroup')) {
        $chatId = $chat['id'];
        $chatTitle = $chat['title'] ?? 'Unknown Group';

        // Check if group exists
        $stmt = $db->prepare("SELECT id FROM telegram_groups WHERE chat_id = :chat_id");
        $stmt->execute([':chat_id' => $chatId]);
        if (!$stmt->fetch()) {
            $ins = $db->prepare("INSERT INTO telegram_groups (group_name, chat_id) VALUES (:name, :chat_id)");
            $ins->execute([':name' => $chatTitle, ':chat_id' => $chatId]);
            $newGroups++;
        }
    }
}

echo json_encode(['success' => true, 'new_groups' => $newGroups]);
?>
