<?php
// poll.php — Telegram Long-Polling Script
// Run this on your LOCAL machine (not needed if using webhooks on a live server)
// Command: php poll.php

require_once __DIR__ . '/config.php';

$last_update_id = 0;
$base_url       = "https://api.telegram.org/bot{$botToken}";

echo "╔══════════════════════════════════════╗\n";
echo "║   GRAY HACKER SECURITY - Polling     ║\n";
echo "╚══════════════════════════════════════╝\n";
echo "[" . date('H:i:s') . "] Bot started. Waiting for messages...\n\n";

while (true) {
    $url      = "{$base_url}/getUpdates?offset=" . ($last_update_id + 1) . "&timeout=30";
    $response = @file_get_contents($url);

    if (!$response) {
        echo "[" . date('H:i:s') . "] ⚠ Could not reach Telegram API. Retrying in 5s...\n";
        sleep(5);
        continue;
    }

    $data = json_decode($response, true);

    if (!$data || !$data['ok']) {
        echo "[" . date('H:i:s') . "] ⚠ Bad response from Telegram. Retrying in 5s...\n";
        sleep(5);
        continue;
    }

    foreach ($data['result'] as $update) {
        $last_update_id = $update['update_id'];

        // Forward update to local bot.php via HTTP
        $ch = curl_init('http://localhost:8000/bot.php');
        curl_setopt_array($ch, [
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_POST           => true,
            CURLOPT_POSTFIELDS     => json_encode($update),
            CURLOPT_HTTPHEADER     => ['Content-Type: application/json'],
            CURLOPT_TIMEOUT        => 10,
        ]);
        curl_exec($ch);
        curl_close($ch);

        $from = $update['message']['from']['username'] ?? $update['message']['from']['first_name'] ?? 'Unknown';
        $type = isset($update['message']['document']) ? 'APK Document' : (isset($update['message']['text']) ? 'Text' : 'Other');
        echo "[" . date('H:i:s') . "] ✅ Update #$last_update_id from @$from | Type: $type\n";
    }

    sleep(1);
}
?>
