<?php
header('Content-Type: application/json');
error_reporting(0);

require_once "db.php"; // ONLY DB

$BOT_TOKEN = "7679448689:AAE9LavWq8BadJkyY4ejXEUsXELkVSE042I";
$API_URL = "https://api.telegram.org/bot".$BOT_TOKEN."/sendMessage";

$message = trim($_POST['message'] ?? '');
$offset  = (int)($_POST['offset'] ?? 0);
$limit   = 100;

if ($message === '') {
    echo json_encode(['error'=>'Message empty']);
    exit;
}

$totalUsers = $pdo->query("
  SELECT COUNT(*) FROM user_data WHERE status='ACTIVE'
")->fetchColumn();

$users = $pdo->query("
  SELECT user_id FROM user_data
  WHERE status='ACTIVE'
  ORDER BY user_id ASC
  LIMIT $limit OFFSET $offset
")->fetchAll();

$sent = 0; $failed = 0;

foreach ($users as $u) {
    $ch = curl_init($API_URL);
    curl_setopt_array($ch, [
        CURLOPT_POST => true,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_TIMEOUT => 10,
        CURLOPT_POSTFIELDS => [
            'chat_id' => $u['user_id'],
            'text' => $message
        ]
    ]);
    $res = curl_exec($ch);
    curl_close($ch);
    $res ? $sent++ : $failed++;
}

echo json_encode([
    'sent'=>$sent,
    'failed'=>$failed,
    'has_more'=>count($users)===$limit,
    'next_offset'=>$offset+$limit
]);
