<?php

ignore_user_abort(true);
set_time_limit(0);

// =========================
// KONFIGURASI
// =========================
$botToken = "8857800780:AAE2bQaPaTvltcHNDQDqBCNZ9RfZgcuIOQU";

// Path ke gambar (relative dari gas.php)
$imagePath = __DIR__ . '/public/assets/og-nusaotp.webp';

$pesan = <<<TEXT
DISKON 15% AWAL AGUSTUS!!
JANGAN SAMPAI KETINGGALAN!!
━━━━━━━━━━━━━━━
🌎 Website : https://nusa-otp.com
🤖 Bot : @nusaotp_bot
📹 Monitoring : @nusaotp_monitoring
📱 Aplikasi : https://nusa-otp.com/download-aplikasi
🛒 Reseller : https://nokos.site
━━━━━━━━━━━━━━━
TEXT;

// =========================
// LOAD .ENV
// =========================
function loadEnv($path)
{
    $env = [];

    if (!file_exists($path)) {
        die(".env tidak ditemukan\n");
    }

    foreach (file($path, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES) as $line) {

        $line = trim($line);

        if ($line === '' || str_starts_with($line, '#')) {
            continue;
        }

        if (!str_contains($line, '=')) {
            continue;
        }

        [$key, $value] = explode('=', $line, 2);

        $env[trim($key)] = trim($value, "\"'");
    }

    return $env;
}

$env = loadEnv(__DIR__ . '/.env');

$dbHost = $env['DB_HOST'] ?? '127.0.0.1';
$dbPort = $env['DB_PORT'] ?? 3306;
$dbName = $env['DB_DATABASE'] ?? '';
$dbUser = $env['DB_USERNAME'] ?? '';
$dbPass = $env['DB_PASSWORD'] ?? '';

// =========================
// KONEKSI DATABASE
// =========================
try {

    $pdo = new PDO(
        "mysql:host={$dbHost};port={$dbPort};dbname={$dbName};charset=utf8mb4",
        $dbUser,
        $dbPass,
        [
            PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
            PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
        ]
    );

} catch (PDOException $e) {

    die("Koneksi database gagal : " . $e->getMessage() . PHP_EOL);

}

// =========================
// LOAD USER DARI DATABASE
// =========================
$stmt = $pdo->query("
    SELECT DISTINCT telegram_id
    FROM users
    WHERE telegram_id IS NOT NULL
      AND TRIM(telegram_id) <> ''
    ORDER BY id ASC
");

$users = $stmt->fetchAll(PDO::FETCH_COLUMN);

$total = count($users);
$berhasil = 0;
$gagal = 0;
$nomor = 0;

echo PHP_EOL;
echo "========================================" . PHP_EOL;
echo "      TELEGRAM BROADCAST START" . PHP_EOL;
echo "========================================" . PHP_EOL;
echo "Total User : {$total}" . PHP_EOL;
echo PHP_EOL;

$start = microtime(true);

// =========================
// BROADCAST
// =========================
foreach ($users as $chatId) {

    $nomor++;

    // Jika gambar ada, kirim gambar dulu
    if (file_exists($imagePath)) {
        $ch = curl_init("https://api.telegram.org/bot{$botToken}/sendPhoto");

        $postFields = [
            "chat_id" => trim($chatId),
            "caption" => $pesan,
            "parse_mode" => "HTML",
        ];

        // Tambahkan gambar sebagai file upload
        $postFields['photo'] = new CURLFile($imagePath);

        curl_setopt_array($ch, [
            CURLOPT_POST => true,
            CURLOPT_POSTFIELDS => $postFields,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_TIMEOUT => 30,
            CURLOPT_CONNECTTIMEOUT => 15,
        ]);
    } else {
        // Jika gambar tidak ada, kirim pesan text
        $ch = curl_init("https://api.telegram.org/bot{$botToken}/sendMessage");

        curl_setopt_array($ch, [
            CURLOPT_POST => true,
            CURLOPT_POSTFIELDS => [
                "chat_id" => trim($chatId),
                "text" => $pesan,
                "parse_mode" => "HTML",
                "disable_web_page_preview" => true,
            ],
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_TIMEOUT => 20,
            CURLOPT_CONNECTTIMEOUT => 10,
        ]);
    }

    $result = curl_exec($ch);

    if (curl_errno($ch)) {

        $gagal++;

        echo sprintf(
            "[%d/%d] ❌ %s | CURL ERROR : %s\n",
            $nomor,
            $total,
            $chatId,
            curl_error($ch)
        );

    } else {

        $json = json_decode($result, true);

        if (!empty($json['ok'])) {

            $berhasil++;

            echo sprintf(
                "[%d/%d] ✅ %s | BERHASIL\n",
                $nomor,
                $total,
                $chatId
            );

        } else {

            $gagal++;

            $error = $json['description'] ?? 'Unknown Error';

            echo sprintf(
                "[%d/%d] ❌ %s | %s\n",
                $nomor,
                $total,
                $chatId,
                $error
            );

        }
    }

    curl_close($ch);

    // Delay 0.1 detik (10 pesan/detik)
    usleep(100000);

    // Progress setiap 50 user
    if ($nomor % 50 === 0) {

        $persen = round(($nomor / $total) * 100, 2);
        $elapsed = round(microtime(true) - $start, 1);

        echo PHP_EOL;
        echo "----------------------------------------" . PHP_EOL;
        echo "Progress : {$persen}%" . PHP_EOL;
        echo "Processed: {$nomor}/{$total}" . PHP_EOL;
        echo "Berhasil : {$berhasil}" . PHP_EOL;
        echo "Gagal    : {$gagal}" . PHP_EOL;
        echo "Runtime  : {$elapsed} detik" . PHP_EOL;
        echo "----------------------------------------" . PHP_EOL;
        echo PHP_EOL;
    }
}

$totalWaktu = round(microtime(true) - $start, 2);

echo PHP_EOL;
echo "========================================" . PHP_EOL;
echo "      BROADCAST SELESAI" . PHP_EOL;
echo "========================================" . PHP_EOL;
echo "Total      : {$total}" . PHP_EOL;
echo "Berhasil   : {$berhasil}" . PHP_EOL;
echo "Gagal      : {$gagal}" . PHP_EOL;
echo "Durasi     : {$totalWaktu} detik" . PHP_EOL;
echo "========================================" . PHP_EOL;